While we are developing Web API, we might expect the caller to pass in either an object or array of object. Of course it would be best to handle array of object as the API paramter. But, we are not always have the luck to change the API parameter type since the existing system is connected by many third party apps.
Basically, the existing code is handling the incoming parameter that is string type, a JSON formatted value. We are parse it correctly if we know that type:
using Newtonsoft.Json.Linq;
string s = @"{'name': 'MIKE', 'age':'23'}";
JObject jobj = JObject.Parse(s);
string s2 = @"[{'name': 'MIKE', 'age':'23'}, {'name': 'MICKEY', 'age':'25'}]";
JArray jarr = JArray.Parse(s2);
Let's say, we modified our Web API to handle array of object while the existing code is only handling object, it will crash:
try
{
// let's crash it
JObject jobj2 = JObject.Parse(s2);
}
catch (Exception x)
{
Console.WriteLine(x.Message);
}
In this case, you have to parse the incoming text into JToken.
JToken jt = JToken.Parse(s);
JToken jt2 = JToken.Parse(s2);
To identify whether it is JObject or JArray:
bool b = jt is JObject;
bool b2 = jt is JArray;
Showing posts with label System Development. Show all posts
Showing posts with label System Development. Show all posts
Thursday, November 28, 2019
Sunday, May 27, 2018
HttpWebRequest and automatic decompression
Continue from our previous post "Posting compressed data in JSON format to the ASP.NET website using WinForm", in HttpWebRequest, there is a property called "AutomaticDecompression" (boolean) which is able to decompress the server response without extra codes.
Now, the question is that if we set this property to true, does it compress the data before sending it to the web server? After research and confirm that it does not compress the data before sending.
Below is the sample code to upload the data after
string url = "http://localhost:30000/myHandler.ashx";
System.Net.HttpWebRequest req = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
req.ContentType = "text/json";
req.Method = "POST";
req.AutomaticDecompression = System.Net.DecompressionMethods.GZip
| System.Net.DecompressionMethods.Deflate;
// generate dummy data.
string s = "";
for (int i = 0; i < 100; i++)
{
s += Guid.NewGuid().ToString();
}
using (System.IO.StreamWriter w = new System.IO.StreamWriter(req.GetRequestStream()))
{
w.WriteLine("helo me.." + s);
}
In the ASHX handler, you may verify the content length that has been submitted from the client:
public class myHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
System.Diagnostics.Debug.WriteLine(string.Format("{0}-header=>"
+ context.Request.ContentLength.ToString(),
DateTime.Now.ToString("d/MMM/yy @ HH:mm:ss.fff")));
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
Now, the question is that if we set this property to true, does it compress the data before sending it to the web server? After research and confirm that it does not compress the data before sending.
Below is the sample code to upload the data after
string url = "http://localhost:30000/myHandler.ashx";
System.Net.HttpWebRequest req = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
req.ContentType = "text/json";
req.Method = "POST";
req.AutomaticDecompression = System.Net.DecompressionMethods.GZip
| System.Net.DecompressionMethods.Deflate;
// generate dummy data.
string s = "";
for (int i = 0; i < 100; i++)
{
s += Guid.NewGuid().ToString();
}
using (System.IO.StreamWriter w = new System.IO.StreamWriter(req.GetRequestStream()))
{
w.WriteLine("helo me.." + s);
}
In the ASHX handler, you may verify the content length that has been submitted from the client:
public class myHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
System.Diagnostics.Debug.WriteLine(string.Format("{0}-header=>"
+ context.Request.ContentLength.ToString(),
DateTime.Now.ToString("d/MMM/yy @ HH:mm:ss.fff")));
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
Labels:
.Net,
AJAX,
ASHX,
ASP.NET,
Networking,
System Design,
System Development
Saturday, July 22, 2017
Decoupling the code with "notification" design
In C#, there are many different ways to decouple the program and the most common ways of doing so is to use one of the following:
The core of this strategy - the publisher & subscriber + multi-threaded object. Let's call it NotificationServer. This core object allows the publisher to send the notification messages into the message pool. It also allows the subscriber to subscribe and listen to the notification messages that they are interested. You will find tons of example on how to implement the publisher & subscriber + multi-threaded in the Internet.
The notification message object contains the following properties:
- event - it's multicasting. You listen to what you need.
- interface - it's dynamic. You can incorporate the interface into any of your class.
- callback using Action<T> or Func<T> - you handle what you are interested.
The core of this strategy - the publisher & subscriber + multi-threaded object. Let's call it NotificationServer. This core object allows the publisher to send the notification messages into the message pool. It also allows the subscriber to subscribe and listen to the notification messages that they are interested. You will find tons of example on how to implement the publisher & subscriber + multi-threaded in the Internet.
The notification message object contains the following properties:
- message ID - the ID that allows the subscriber to identify the purpose of it.
- session ID - it's GUID type and it's used in conjunction with broadcast flag.
- data - it's an object to be passing around.
- broadcast - it's a flag which tells the NotificationServer whether it should send the message to a specific subscriber or all subscribers. This can be very useful if you are implementing a TCP NotificationServer.
- should feedback - it's a flag that indicate whether it waits for the NotificationServer's respond. This can be very useful if you are implementing a TCP NotificationServer.
- Embedded NotificationServer- the implementation is to have a publisher & subscriber + multi-threaded object.
- The fun does not stop here - you can embed the NotificationServer class into a TCP server class and all communications are done through TCP communication. In this case, you will have a TCP NotificationServer which is able to run as a Windows Service. The publisher and subscribers can be any program, ASP.Net web page or another Windows Service. The publisher and subscribers could be running from the same computer or different computer.
Labels:
.Net,
C#,
Class,
Enhancement,
Integration,
Multi-threading,
Networking,
Reusable,
System Design,
System Development,
TCP
Monday, May 15, 2017
A better way to configure Intelli-sense for Javascript in VS2015
Now, I'm moving toward the direction of developing fat client using Javascript (JS) and I need a
better way of enable the intelli-sense support for Javascript in the fat client.
Earlier, I found out that we can include the reference in each JS file by adding the following line.
When the number of JS files that you are developing are increasing, added this reference line might be headache.
/// <reference path="jquery-1.7.js" />
Here is a better way:
1. Add a "_references.js" file into "js" folder (let says you are keeping all your JS files in a folder call "js" instead of "scripts").
2. In the Quick Launch bar (located at top right corner), key in "Javascript" and look for "IntelliSense -> References" option. Clicks on it.
3. Choose "Implicit (Web)" option.
4. In the "Add a reference to current group" field, key in "~/js/_references.js".
5. Click Add button.
6. Click OK.

7. Back to the Solution Explorer. Right click on _references.js and you will find two new options.
- Auto-sync- means that VS will add all the JS files automatically.
- Update Javascript References - this is manually sync the JS files.

better way of enable the intelli-sense support for Javascript in the fat client.
Earlier, I found out that we can include the reference in each JS file by adding the following line.
When the number of JS files that you are developing are increasing, added this reference line might be headache.
/// <reference path="jquery-1.7.js" />
Here is a better way:
1. Add a "_references.js" file into "js" folder (let says you are keeping all your JS files in a folder call "js" instead of "scripts").
2. In the Quick Launch bar (located at top right corner), key in "Javascript" and look for "IntelliSense -> References" option. Clicks on it.
3. Choose "Implicit (Web)" option.
4. In the "Add a reference to current group" field, key in "~/js/_references.js".
5. Click Add button.
6. Click OK.
7. Back to the Solution Explorer. Right click on _references.js and you will find two new options.
- Auto-sync- means that VS will add all the JS files automatically.
- Update Javascript References - this is manually sync the JS files.
Labels:
.Net,
ASP.NET,
JQuery,
System Development,
Visual Studio
Subscribe to:
Posts (Atom)