WebRequest.GetResponse() throwing SSL secure channel error

Problem Statement:

WebRequest.GetResponse() is one of the most common ways we adopt to perform a HTTPWebRequest from our server side. This case was a specific one, although the error appeared to be more generic in nature. In fact it happened only in SharePoint and not in my .Net application.

The error observed in the GetResponse() method was:

“The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel”

One of the root cause of this problem is due to the certificate issue. And to be more precise the certificate validation has failed.


The solution to this problem, more or less i would call it a decent workaround is to use the ServerCertificateCallbackValidation method from the HttpWebRequest class and forcefully return true.

Create a static method for validating the certificate

private static bool ValidateFbCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
return true;

Just before u make your HttpWebRequest try using this.

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(ValidateFbCertificate);

HttpWebRequest …..;

This should skip any certificate errors.

Happy Coding!!!

Generate JSON string output in C#

This is one of the most widely used and very useful script that you could use in your web services/ WCF services/ Handlers or any place wherein you require a JSON string to be passed to the client/ consumer.

We make use of the Serialize method in JavaScriptSerializer class in C# under the following namespace:

using System.Web.Script.Serialization;

The code snippet below show how its done:

//Namespace for the JavascriptSerializer object

using System.Web.Script.Serialization;

public string GenerateJSONString(List<myObject> myCustomList)


//Initialize the JavascriptSerializer object   

JavaScriptSerializer serializer = new JavaScriptSerializer();

//Initialize a stringbuilder object to hold the final JSON output     

StringBuilder jsonBuilder = new StringBuilder();

//Generate the JSON string

serializer.Serialize(myCustomList, jsonBuilder);

//Return the JSON string

return Convert.ToString(jsonBuilder);


This code is just a framework to get to know that the JavascriptSerializer could help you generate JSON string with ease.

In the client side, you could use jQuery.parseJSON(JSONstring); and then parse this JSON string using the myObject properties. Remeber that parseJSON was added in jQuery v1.4.1.

__doPostBack and Object expected error

The best way to understand the working of the __doPostBack function is to dissect the function into small pieces and explore each piece one at a time.  Let us take a look at the function.

<input type=”hidden” name=”__EVENTTARGET” id=”__EVENTTARGET” value=”” />
<input type=”hidden” name=”__EVENTARGUMENT” id=”__EVENTARGUMENT” value=”” />
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;

The __doPostBack function takes two arguments, eventTarget and eventArgument.  The eventTarget contains the ID of the control that causes the postback and the eventArgument contains any additional data associated with the control.  Note that the two hidden fields, “__EVENTTARGET” and “__EVENTARGUMENT,” are automatically declared.  The value of the eventTarget and eventArgument are stored in the hidden fields.  The two hidden variables can be accessed from the code behind using the forms/params collection.

Let me clarify a common problem that we miss out here.

__doPostBack() is a script that gets written into your html, by ASP .Net, during any postback event and not any load event. Hence it would be meaningful to use this method in postback events.

Now let me go through some of the possible causes for this error:

  • Case is not right: Check the spelling of __doPostBack() – there are two underscores followed by ‘doPostBack’
  • __EVENTTARGET is not Id, instead its the name of the object. For ex. if a button id is ‘ctl00_cpMain_btnSubmit’, its name will be ‘ctl00$cpMain$btnSubmit’. This happens normally when you are on a child page or usercontrol inheriting from a master page. Best option would be to view the source of the page and get the button Name (I would recommend you to use IE developer toolbar to view source).
  • __EVENTTARGET argument not right: The object itself is not present on the page.
  • You must be calling this method, on a html button. In this case, there would be no __doPostBack() method in the page itself.

By the way its browser independent. These are some quick notes that i had faced, in my projects. Hope it was useful. Feel free to add on more.

ASP .Net Menu using ordered list – ul, li concept

I give a different approach to menu creation, in my ASP .Net project. The main wins being the performance and ease of use. Asp menu is pretty messy when you look at the code behind and the page size it adds. But use this concept only if performance is a critical factor.
•    Use of ordered list (ul and li) and css smartly to construct the menu’s. Check any standard sites (www.apple.com) They use this concept.
•    Aspx design with divs only. ASP menu create Tables that are pretty messy and affects the page performance.


•    Page is light weight
•    No table structure, only divs
•    The page menu loads like a normal html and is pretty cool and fast. It does not have any server tags also… eh except for the one div into which I have to add the codebehind menu result.

•    Setup a usercontrol for this. Add it to master page.
•    Basic concept is to create the <ul> <li> <a> sections through codebehind. Use template concept, as defined below:

•    Use string.Format : string liSbTemp = string.Format(liTemplate, “link1”, “’active’”, “|”));
•    Use stringbuilder.append and so on…
•    Use for-loops effectively along with the above template(string.format({0}{1})), stringbuilder, LINQ(for querying through the list returned by the db) and structure a menu as below:

•    ‘ctl100_nvgMenu_divNavigator’ is the div with runat=server, into which I add my stringbuilder result.
•    ‘GlobalNav’ div is a wrapper to the full menu.
•    ‘mainNav’ <ul> has the main navigation tab anchor tags(<a>), with its own <li>
•    ‘subNav’ <ul> has the sub menu sections, with its own <li>
•    At the end, add the stringbuilder result to a div-divNavigator(which has a runat server attribute… only 1 runat server or do findcontrol and add it to a div on the page)
•    Use innerHtml (ctl100_nvgMenu_divNavigator.innerHtml ) to add it to the ‘divNavigator’ or else you will have some issue with the EnableEventValidation attribute in the page directive, during navigation.

Css: I am sharing the full css selector list here
#header #globalNav
padding-left: 8px;
padding-right: 8px;

#header #globalNav ul
padding: 1px 0px 0px 0px;
margin: 0;
list-style: none;

#header #globalNav ul li
float: left;

/* Start – Main Nav */

#globalNav ul#mainNav
font-size: 14px;
height: 27px;

ul#mainNav li a
color: #ffffff;
text-decoration: none;
line-height: 27px;
padding: 0 10px 0 9px;

ul#mainNav li.active
background: url(../../Resources/images/mainNav_left.gif) no-repeat;

ul#mainNav li.active a
background: url(../../Resources/images/mainNav_rt.gif) no-repeat right;
display: block;
color: #0D8695;
cursor: default;

/* End – Main Nav */

/* Start – Sub Nav */

#globalNav ul.subNav
border-bottom: 1px solid #C2CEDA;
height: 23px;
ul.subNav li
padding-right: 10px;
ul.subNav li a
color: #666666;
text-decoration: none;
line-height: 23px;
margin: 0 10px 0 0;

ul.subNav li a:hover
color: #0D8695;

ul.subNav li.active a
color: #0D8695;
cursor: default;

ul.subNav li.active a:hover
color: #0D8695;
text-decoration: none;

Voila… you have a light weight and powerful menu to boast off…

I totally respect the asp:Menu’s, but I am totally against using tables in any site… they are really primitive…  Hope Microsoft introduce div designs for the asp:Menu…

NB: To get a good head start, check the html source of apple site menu…..

How to determine whether Javascript is enabled?

There are a lot of approaches to this. Lets take them one at a time:

  • Using NOSCRIPT tag: You can write a noscript tag just before your script tag to display the user a warning message. Check the code below, wherein the user will be redirected to another page if javascript is disabled:


<noscript><meta http-equiv=”refresh” content=”0; url=whatyouwant.html”></noscript>

<!–this javascript ensures that anybody that doesnt use javascript wont see the menu–>
<script type=”text/javascript”>
<!–hide script from older browsers
document.write(‘<select name=”whatever”><option>1</option><option>2</option></select>’);

  • Check out this interesting article on 15 seconds,  Creating a Server Control for JavaScript Testing by George Masselli. It explains how to create a control that verifies whether Javascript is supported and enabled. Apparently it is not easy to determine if a user disabled Javascript support for security reasons.
  • A simple concept of hiding the always visible warning message through javascript. In this case, if your browser has javascript enabled, the script will hide the message. However, if it has javascript disabled, the message will be visible always. Check the snippet below:

<body onload=”valid()”>
<form id=”form1″ runat=”server”>
<label Id=”lblWarning”>Your Browser has Disabled Scripting</label>
<script type=”text/jscript”>
function valid()
var lbl=document.getElementById(‘lblWarning’);
lbl.style.display = ‘none’;


Hope this was useful. Feel free to add on more options.

Difference between Convert.ToString() and .ToString()

The main difference between these both are the fact that Convert.ToString() can handle NULL and avoid ObjectReferenceNullException, while .ToString() would break in such case.

It is always good to use the Convert object than the ToString()

Let’s have a look into the Convert.ToString() method. Using a reflector, i got hold of the Convert object below:

public static string ToString(object value, IFormatProvider provider)
IConvertible convertible = value as IConvertible
if(convertible != null)
return convertible.ToString(provider)
if(value != null)
return value.ToString();
return string.Empty

Well I guess this would clear up the reason for using the Convert object in you type conversion operations.