I recently ran into an interesting issue when developing a connector for a third-party API. When trying to connect to the API endpoint, I received the following error message:

“An error occurred while making the HTTP request to https://<API endpoint>. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.” Inner exception was “Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Not very informative at first glance, right?

However, after some digging around I realized that the error message was correct, at least in the following part: “This could also be caused by a mismatch of the security binding between the client and the server.” I checked my SOAP bindings, and everything seemed to be correct: server required SSL connection, and I had TransportLevelSecurity specified in my binding:

var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);

After I read more about SSL and Transport Level Security (TLS), I understood that “not all HTTPSs are created equal.” HTTPS relies on a family of lower level security protocol implementations called transport level security (TLS), each using different cryptographic algorithms. TLS standards keep developing and improving. At the moment TLS 1.2 is a latest encryption standard powering SSL and TLS 1.3 is in works. In general, anything that is using TLS standard below TLS 1.2 is considered to be non secure because these older encryption algorithms are known to be cracked.

Apparently, the provider of the API I was trying to call disabled all other security protocols except for TLS 1.2. That was reason I was getting the error.

So, why didn’t .NET framework support TLS 1.2 in my case? Well, that was because my application was using .NET 4.0. In .NET 4.0 default transport level security standard is TLS 1.1. The solution for my problem was to upgrade my application to the latest .NET framework: 4.6.1. In this framework version TLS 1.2 is a default cryptographic standard.

But what if you can’t upgrade your application to latest .NET framework and still want to use TLS 1.2? Solutions exist, but they vary depending on the framework version:

  1. .NET 4.6 and above. You don’t need to do any additional work to support TLS 1.2, it’s supported by default.
  2. .NET 4.5. TLS 1.2 is supported, but it’s not a default protocol. You need to opt-in to use it. The following code will make TLS 1.2 default, make sure to execute it before making a connection to secured resource:

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

  3. .NET 4.0. TLS 1.2 is not supported, but if you have .NET 4.5 (or above) installed on the system then you still can opt in for TLS 1.2 even if your application framework doesn’t support it. The only problem is that SecurityProtocolType in .NET 4.0 doesn’t have an entry for TLS1.2, so we’d have to use a numerical representation of this enum value:

   ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

  1. .NET 3.5 or below. TLS 1.2 is not supported and there is no workaround. Upgrade your application to more recent version of the framework.

P.S. For scenario #3 there is also a registry hack which forces 4.5 to use TLS 1.2 by default without enforcing it programmatically.


Basically, you have to run:

sc sidtype ftpsvc unrestricted

And then restart the FTP service:

net stop ftpsvc & net start ftpsvc

The .Net framework has a number of technologies that allow you to create HTTP services such as Web Service, WCF and now Web API. There are a lot of articles over the internet which may describe to whom you should use. Now a days, you have a lot of choices to build HTTP services on .NET framework.

Web Service

  1. It is based on SOAP and return data in XML form.
  2. It support only HTTP protocol.
  3. It is not open source but can be consumed by any client that understands xml.
  4. It can be hosted only on IIS.

WCF

  1. It is also based on SOAP and return data in XML form.
  2. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
  3. The main issue with WCF is, its tedious and extensive configuration.
  4. It is not open source but can be consumed by any client that understands xml.
  5. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest

  1. To use WCF as WCF Rest service you have to enable webHttpBindings.
  2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
  3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
  4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
  5. It support XML, JSON and ATOM data format.

Web API

  1. This is the new framework for building HTTP services with easy and simple way.
  2. Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
  3. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
  4. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
  5. It can be hosted with in the application or on IIS.
  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.
  7. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

To whom choose between WCF or WEB API

  1. Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
  2. Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
  3. Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
  4. Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

 


Recently I had to recreate an old service module from an old website, which outputted XML. There was a requirement to meet a certain format, which was without xml namespaces (XMLNS) and declarations.

Our project team decided to use object serialization and I quickly ran into the problem that the .Net serializers likes to output namespaces and declarations. There is however a way to avoid this

Here is how I did it:

 public string ToXml()
{
   //this avoids xml document declaration
   XmlWriterSettings settings = new XmlWriterSettings() {
                   Indent = false, OmitXmlDeclaration = true };
   var stream = new MemoryStream();
   using (XmlWriter xw = XmlWriter.Create(stream, settings))
   {
      //this avoids xml namespace declaration
      XmlSerializerNamespaces ns = new XmlSerializerNamespaces(
                         new[] { XmlQualifiedName.Empty });
      XmlSerializer x = new XmlSerializer(GetType(), "");
      x.Serialize(xw, this, ns);
   }
   return Encoding.UTF8.GetString(stream.ToArray());
 }

Enjoy!


Deprecated
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

The Window.showModalDialog() creates and displays a modal dialog box containing a specified HTML document.

This feature is going away. Please fix your Web sites and applications.

Support has been removed in Chrome 37. But they have  added a temporary Enterprise Policy setting to re-enable showModalDialog. In May 2015 this setting will be removed andshowModalDialog() will be completely removed from Chrome.

Mozilla has announced that it will remove support for this method (bug 981796). Regarding timing, it shouldn’t be before Firefox 39. This means that the function will be around until around mid-June 2015. It also means that for enterprise you can switch to using ESR 38 builds, which will have the function into mid 2016.

Solution:

  // fix for deprecated method
    if (!window.showModalDialog) {
        window.showModalDialog = function(arg1, arg2, arg3) {

            var w;
            var h;
            var resizable = "no";
            var scroll = "no";
            var status = "no";

            // get the modal specs
            var mdattrs = arg3.split(";");
            for (i = 0; i < mdattrs.length; i++) {
                var mdattr = mdattrs[i].split(":");

                var n = mdattr[0];
                var v = mdattr[1];
                if (n) { n = n.trim().toLowerCase(); }
                if (v) { v = v.trim().toLowerCase(); }

                if (n == "dialogheight") {
                    h = v.replace("px", "");
                } else if (n == "dialogwidth") {
                    w = v.replace("px", "");
                } else if (n == "resizable") {
                    resizable = v;
                } else if (n == "scroll") {
                    scroll = v;
                } else if (n == "status") {
                    status = v;
                }
            }

            var left = window.screenX + (window.outerWidth / 2) - (w / 2);
            var top = window.screenY + (window.outerHeight / 2) - (h / 2);
            var targetWin = window.open(arg1, arg1, 'toolbar=no, location=no, directories=no, status=' + status + ', menubar=no, scrollbars=' + scroll + ', resizable=' + resizable + ', copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
            targetWin.focus();
        };
    }

 

 


In the Visual Studio 2012 IDE, a new feature is introduce to convert XML document into C# classes as a Serializable type.

In the .NET framework 4.5 there is another Paste Special option is exists in the Edit menu which enables you to copy the XML as C# Classes.

Paste-xml-as-classes.png

Copy the XML  you want to create a class/classes for, place the cursor in a class file on the location you want the code to be added and select the following menu items:

  • Edit.
  • Paste Special.
  • Paste XML as Classes.

And you’re done.

Suppose you have following XML File.
xml-in-vs-2012.jpg

And when you paste the above XML using Paste XML as classes. It will looks like that.

xml-as-classes.jpg


Locate the code that hooks up the slider. It should look something like the following:


You could use jQuery to dynamically update the mapping

function drawMap() {
 // remove image overlays used during transition
 $('.nivo-slice, .nivo-box').remove();
 var current_title = $('.nivoSlider').data('nivo:vars').currentImage.attr('title'); 
// set usemap attribute for current image
 $('.nivo-main-image').attr("useMap", current_title + "_map"); }

 

Then just call that function after load and after each transition

$('.nivoSlider').nivoSlider({
 // slider config
 afterLoad: drawMap,
 afterChange: drawMap
));

2013 in review

Posted: January 1, 2014 in Asp.net

The WordPress.com stats helper monkeys prepared a 2013 annual report for this blog.

Here’s an excerpt:

A San Francisco cable car holds 60 people. This blog was viewed about 900 times in 2013. If it were a cable car, it would take about 15 trips to carry that many people.

Click here to see the complete report.


To select one radio button at a time in datalist, please follow below steps

Step 1: Write this Past below JavaScript in the aspx source code 

<script type=”text/javascript” language=”javascript”>
function CheckOnes(spanChk)
{
var oItem = spanChk.children;
var theBox= (spanChk.type==”radio”) ? spanChk : spanChk.children.item[0];

xState=theBox.unchecked;
elm=theBox.form.elements;

for(i=0;i<elm.length;i++)
if(elm[i].type==”radio” && elm[i].id!=theBox.id)
{
elm[i].checked=xState;
}
}
</script>

Step 2: Now data list as

<asp:DataList ID=”dlExample” runat=”server” RepeatDirection=”Vertical” RepeatColumns=”4″ OnItemDataBound=”dlExample_ItemDataBound” >
<ItemTemplate>
<table> <tr> <td> <asp:RadioButton ID=”rdb” runat=”server” /> </td> </tr> </table>
</ItemTemplate>
</asp:DataList>

Step 3: In code behind

protected void dlExample_ItemDataBound(object sender, DataListItemEventArgs e)
{
RadioButton rdb;
rdb = (RadioButton)e.Item.FindControl(“rdb”);
if(rdb != null)
rdb.Attributes.Add(“onclick”, “CheckOnes(this);”);
}