Archive for the ‘c#’ Category


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.


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!


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


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);”);
}

Class vs Object vs Instance

Posted: September 6, 2013 in c#
Tags: , ,

In OO Programming, we often hear of terms like “Class”, “Object” and “Instance”;

but what actually is a Class / Object / Instance?

In short,

An object is a software bundle of related state and behavior.

A class is a blueprint or prototype from which objects are created.

An instance is a single and unique unit of a class.

Example, we have a blueprint (class) represents student (object) with fields like name, age, course (class member). And we have

2 students here, Foo and Bob. So, Foo and Bob is 2 different instances of the class

(Student class) that represent object (Student people).

Let me go into details…

Object

Real world objects shares 2 main characteristics, state

and behavior. Human have state (name, age) and behavior (running, sleeping).

Car have state (current speed, current gear) and state (applying brake, changing

gear). Software objects are conceptually similar to real-world objects: they too

consist of state and related behavior. An object stores its state in fields

and exposes its behavior through methods.

Class

Class is a “template” / “blueprint” that is used to create objects. Basically,

a class will consists of field, static field, method, static method and constructor.

Field is used to hold the state of the class (eg: name of Student object). Method

is used to represent the behavior of the class (eg: how a Student object going to

stand-up). Constructor is used to create a new Instance of the Class.

Instance

An instance is a unique copy of a Class that representing an Object. When a new

instance of a class is created, the JVM will allocate a room of memory for that

class instance.


I came across this problem over the holiday period. The full error was:

Warning    4    Custom tool warning: Cannot import wsdl:portType

Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.DataContractSerializerMessageContractImporter
Error: Type 'Newtonsoft.Json.Linq.JToken' is a recursive collection data contract which is not supported. Consider modifying the definition of collection 'Newtonsoft.Json.Linq.JToken' to remove references to itself.
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:portType[@name='Ixxxxx']    C:\projects\Tyrannt RPG\Tyrannt\Tyrannt.Client.Web\Service References\CodexUpdateServiceReference\Reference.svcmap    1    1    Tyrannt.Client.Web

After doing a bit of searching I found the way to fix it was to remove the Newtonsoft.Json.Linq.JToken from the “Resue Types”:

Right click the service reference…

Service Reference

Select the Reuse Types in Selected References option and tick all the boxes except the Newtonsoft.Json package.

This was the blogpost that helped me solve it “Type ‘Newtonsoft.Json.Linq.JToken’ is a recursive collection data contract” While Adding Service Reference in VS2012


This content is password protected. To view it please enter your password below: