Pass null value to ASP.NET web service using HTTP POST? - asp.net

How do I pass a null value to an ASP.NET web service when accessing it via HTTP POST?
[WebMethod]
public string GetResult(DateTime date, int foo)
{
//do stuff here
}
When calling this method using HTTP POST, how do I pass a null parameter? Passing empty string just makes the server throw an exception trying to convert the string parameter to a DateTime. Making the DateTime parameter nullable (i.e. DateTime? date) seems to disallow calling it via HTTP.

Neither of these can have null values. They are both value types and can't be set to null even if you attempted to do it using code. I would recommend sending DateTime.MinValue and 0.

Related

what is the function of HttpContext.Current.Request?

1)When exactly we need to use HTTPContext (exclusively), please elaborate with an example if possible.
2)What does the following code do
internal string QueryString( string name )
{
if ( HttpContext.Current.Request.QueryString[name] == null )
return string.Empty;
else {
return HttpContext.Current.Request.QueryString[name].ToString();
}
3)Is there any other alternative way where we avoid using HttpContext
Q1:
HttpContext is an object which encapsulates all HTTP-specific information about an individual HTTP request. So, if you need to get any information about receiving HTTP request (for example in order to get the query string parameter values, referral urls, User's IP address etc), you need to use HttpContext object. Further more, this object contains information of current Request, Response, Server, Session, Cache, User and etc.
More information
Usage and examples
Get current session Id: HttpContext.Session.SessionID
Get Timestamp of current request: HttpContext.Timestamp.ToString()
Q2:
In your code sample, you are trying get the value of query string parameter 'name'.
Your dummy request Url looks like - http://www.yourdomain.com/something?name=queryStringValue
QueryString parameter = name
QueryString parameter value = queryStringValue
Hope this helps.

TypeMock to fake DateTime.Parse

I need a way to fake DateTime.Parse with Typemock and have it return the same date when called with any parameters.
I have a DB field that stores an encrypted string that is parsed as date when loaded. The class that holds the data has a Load() method where it copies DB data into its properties, decrypts what's encrypted and does some basic validation, such as:
public class BusinessObject{
public DateTime ImportantDate{get;set;}
...
public void Load(DBObject dbSource){
...
ImportantDate = DateTime.Parse(DecryptionService.Decrypt(dbSource.ImportantDate));
}
}
Runtime all works well.
I'm trying to write a unit test using TypeMock to load some fake data into BusinessObject using its Load method. BusinessObject has way too many properties and can not be deserialized from XML, but DBObject can, so I've stored some XMLs that represent valid data.
It all works well until DecryptionService is called to decrypt the data - it doesn't work because my dev machine doesn't have the DB certificates used in the encryption process. I can't get those on my machine just for testing, that would be a security breach.
I added this to my unit test:
Isolate.Fake.StaticMethods<DecryptionService>(Members.ReturnRecursiveFakes);
Isolate.WhenCalled(() => DecryptionService .Decrypt(null)).WillReturn("***");
Isolate.Fake.StaticMethods<DateTime>(Members.ReturnNulls);
Isolate.WhenCalled(() => DateTime.Parse("***" /*DateStr*/)).WillReturn(DateTime.Now.AddYears(2));
The first part where DecryptionService is faked works, social security and other sensitive strings are "decrypting", but no matter what parameters I give to DateTime I still get one exception or another (ArgumentNullException: String reference not set to an instance of an object if DateStr is null, FormatException when it's "*")
How (if) can I override DateTime.Parse with typemock so that it returns valid DateTime with any invalid paramters passed?
My name is Nofar and i'm from Typemock's support team.
DateTime.Parse is not supported in the WhenCalled API, so in order to fake it's returned value you need to wrap it with a method from your class, for example:
public class BusinessObject
{
public DateTime Load (string s)
{
return DateTime.Parse(s);
}
}
And you test will look like this:
[TestMethod]
public void TestMethodDateTime()
{
BusinessObject b = new BusinessObject();
DateTime now= DateTime.Now.AddYears(2);
Isolate.WhenCalled(()=>b.Load(null)).WillReturn(now);
Assert.AreEqual(now, b.Load(null));
}
Supporting DateTime.Parse in the WhenCalled API is in our backlog.
Please feel free to contact us via mail at support#typemock.com
Nofar
Typemock Support

asp.net return data in Page_Load

If a query string param exists in my page request I want to query the database on the server in the Page_Load and then return the result to the client. I can do the query string param check and query the DB but how do I return the data to the page and on the javascript side how do I access that data?
Ideally I would return JSON of an object structure and it would be returning an array of them.
Yes, returning JSON would be the best option. I'm not sure how you query your database (Do you use LINQ or ADO.NET DataTables, etc)
If you don't have custom object of type you want to send, I recommend you create one. Then you should get an array of them.
Example:
public class Person {
string Name { get; set; }
int Age { get; set; }
}
Person[] pArr = new Person[5];
Then you can use a third party library like this to create an string representaion of that array in JSON.
string json = JsonConvert.SerializeObject(product);
Then you write that json string to the Response object so its sent down to the client, by overriding the Render method of the page.
// Don't expect this code to work as it is, but take this as a guidance
Response.Clear();
Response.Write(json);
Response.Close();
on the client side use jQuery library send a request to page, and process the JSON response for you.
$.getJSON('url', function(data) {
//process data
});
Here is my suggestion if you don't want to use an AJAX request for this:
Use the objects as you would normally do in the page_load, and convert it to a JSON string as explained above.
Then use ClientScriptManager to create an JavaScript variable on the client side when it loaded.
ClientScript.RegisterClientScriptBlock(typeof(Page), "unique_key", "var myObjectList = " + json, true);
After this when the page loads you will have an variable named "myObjectList" with the list of objects without having to make a different AJAX call.
You can directly refer that variable in your javascript and do necessary processing.
Hope this helps.

How to pass a NULL value to a WCF Data Services' service operation?

I have a WCF data services' service operation such as
[WebGet(UriTemplate = "GetData")]
public IQueryable<string> GetData(int code, int deviceid, int groupId, DateTime dateTimeFrom, DateTime dateTimeTo)
{ ...
}
I am calling this service operation by sending a HTTP request to the server in this format:
http://localhost:6000/GetData?code=0&deviceId=1&groupId=0L&dateTimeFrom=datetime'2013-01-31T15:36:50.904'&dateTimeTo=datetime'2012-02-01T15:36:50.904'
and it is working like a charm.
Now I want to pass a NULL value as one of the parameters. How do I do that? Do I need to use nullable types such as "Int?" in the service operation declaration? How do I encode the NULL value in the URI?
Yes - you need to declare the parameter as nullable. Then you can simply omit the parameter (if it's nullable it will be treated as null then).

Can GetHandler return null when implementing IHttpHandlerFactory?

Will this code throw an exception:
public class MyHttpHandlerFactory : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
if (...)
return null;
...
return new MyHttpHandler();
}
}
If you take a look at this article on MSDN, you'll see that in their example they return null from GetHandler. However, they only return null if the request is not a GET or a POST, which should never happen based on the way they have set up the factory in the web.config.
I set up a quick sample using the code from the article using ASP.NET 4.0/IIS 7.5/Integrated Pipeline and if you do return null from a call to GetHandler all that appears to happen is an empty 200/OK response is returned from the server (I checked using Fiddler). So it seems that ASP.NET 4.0 (at least) handles this condition gracefully. To answer the question as asked, no it does not appear that there is a runtime limitation to returning null. In practice, however, you may want to limit the requests that your HandlerFactory is receiving so that it never returns null, or at least consider how the other parts of your application will react to a request to this handler factory returning an empty 200/OK response.

Resources