Tag Archives: c#

System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

I have a helper method below that uses the new HttpClient Class introduced in .NET 4.5 as shown below.

public static async Task<HttpResponseMessage> GetWebRequestAsync(string uri)
{
    using (var httpClient = new HttpClient())
    {
         //set Accept headers
         httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml,application/json");
         //set User agent
         httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; EN; rv:11.0) like Gecko");
         httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");
         return = await httpClient.GetAsync(uri); 
    }
}

I tested it in both http and https scenarios with different URLs and they passed with flying colors. Satisfied, I pointed my URL to one of my production websites for final testing. The production website uses https protocol. Of course, my expectation should be no different from my testing but boom, I got this error!

GetWebRequestAsyncTest threw exception: 
System.AggregateException: One or more errors occurred. --->
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> 
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. --->
System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> 
System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

Switching to http protocol did not threw any exception so I was able to isolate that the culprit was https protocol. However, It worked for other website using https and not in my production website. And that made me googling for a day without resolving the problem.

The next day, I turned my attention to my production website and reviewed all the configurations done with the web server particularly interested with https protocol. I noticed that my web server was configured to accept TLS 1.2 only. It was configured this way for PCI compliance.

That gave me a hint that led me to find out that HttpClient is connecting  using TLS 1.0.  I cannot find any documentation that this is the default but I suspect it is because SSL 3.0 and below is already deprecated.

Armed with this information, I now have to force my HttpClient to connect using TLS 1.2 first then TLS 1.1 then TLS 1.0 so that it can support three versions of TLS. And that gave me the ServicePointManager.SecurityProtocol configuration. So, simply with a single line of code, it worked!. See code below

public static async Task<HttpResponseMessage> GetWebRequestAsync(string uri)
{
    using (var httpClient = new HttpClient())
    {
          //make sure to use TLS 1.2 first before trying other version
          ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

         //set Accept headers
         httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml,application/json");
         //set User agent
         httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; EN; rv:11.0) like Gecko");
         httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");
         return = await httpClient.GetAsync(uri); 
    }
}

I hope you will find this helpful for your next use of HttpClient class. Happy coding!

Don’t forget that Response.End()

While adding some few enhancement on an old project, ASP.NET webform-based API, I was having problem removing the HTML tag output from the API. I have written this project five years ago and I know that you can write a response from an ASPX page without the HTML tags. I simply should use the Response.Clear() or Response.ClearContent(). Response.Clear() is not working?!?!?!

Here is the code that does not output what I want.

protected void Page_Load(object sender, EventArgs e)
{
     //Erases any buffered HTML output
     Response.Clear();
     Response.Write("Hello, API.");
}

If you view the source of the output,

Hello, API.


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>
<form method="post" action="NewApi.aspx" id="form1">
<div class="aspNetHidden">
                <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="YpQKYTR2RvrptiLm1lmMsAJwJ//a75ZBpZNGl/rMG5KPseJDjWPtzsRumtqz2U5cLtK9ilxYWrQxgjcxR9VyjfQzP4W4MK8Xgdd753gdoh4=" />
            </div>
<div></div>
<div class="aspNetHidden">
                <input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="F48D0FAC" />
            </div>
        </form>
        <!-- Visual Studio Browser Link -->
        <script type="application/json" id="__browserLink_initializationData">
    {"appName":"Chrome","requestId":"dacea9113ab74bf7a121e7e8599c93a5"}
</script>
        <script type="text/javascript" src="http://localhost:52028/b08ad1d741774013a9875e2b2003daf7/browserLink" async="async"></script>
        <!-- End Browser Link -->
    </body>
</html>

Using my old arsenal of restarting and clearing cache did not work. So I did look up my old code and sure enough I forgot to write the most important line of code. The Response.End()

The working code

protected void Page_Load(object sender, EventArgs e)
{
     //Erases any buffered HTML output
     Response.Clear();
     Response.Write("Hello, API.");
     //Sends all currently buffered output
     //and stops the execution of the page
     Response.End();
}

And I got the correct output.

Hello, API.

So, don’t forget that Response.End();

C# Extension Methods

As defined by MSDN: Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. It was introduced in .NET 3.5 at the same time with LINQ – which in turn uses Extensions. That’s why all of a sudden, you can now use LINQ against Enumerables even though those objects where never modified.

As defined by me: A very powerful feature that sometimes new developers forget, doesn’t care or doesn’t know about it or don’t quite understand how to create one.

Consider the following scenario. To secure your application credentials at runtime, you decided to use System.Security.SecureString. The content of the SecureString is encrypted while in memory. Read the documentation about SecureString. You cannot assign a string directly to SecureString. It only has a method of AppendChar that accepts one character at a time. So to assign a string, you have to do this.

string s = "MyPassword";
System.Security.SecureString secureString = 
  new System.Security.SecureString();
foreach(char c in s)
{
    secureString.AppendChar(c);
}

Imagine you have to do this over and over in different classes in your code. So you decided to create a public static method and call it every time like this.

public static System.Security.SecureString GetSecureString(string s)
{
    System.Security.SecureString secureString = new System.Security.SecureString();
    foreach (char c in s)
    {
        secureString.AppendChar(c);
    }
    return secureString;
}
static void Main(string[] args)
{
    string unsecuredPassword = "Password123";
    var securePassword = GetSecureString(unsecuredPassword);
}

How about doing it in a more elegant way. Like for example, when you convert the string into lower case, you would do this.

string myString = "Hello World";
string lower = myString.ToLower();

And to convert to SecureString, you would do this.

string unsecuredPassword = "Password123";
var securePassword = unsecuredPassword.ToSecureString();

If you add ToSecureString() into your existing string, it will not compile. Because ToSecureString() is not a method or extension of string by default. We have to create an extension method to be able to do this.

To create an extension

  1. Create a public static class
  2. Create a public static method with the parameter you wish to extend. In this example,  the string object.
  3. Put the this keyword before the object you are extending.
  4. Don’t forget the this

See example below.


public static class StringExtension
{
   public static System.Security.SecureString ToSecureString(this String s)
   {
       System.Security.SecureString secureString = 
       new System.Security.SecureString();
       foreach(char c in s)
       {
           secureString.AppendChar(c);
       }
       return secureString;
   }
 }

And now, to use it…

    

 class Program
 {
     static void Main(string[] args)
     {
         string unsecuredPassword = "Password123";
         var securePassword = unsecuredPassword.ToSecureString();
         Console.Read();
     }
 }
        

Creating extension methods is easy after all. But don’t overdo it! Enjoy coding!

C# 5.0 Asynchronous Programming with async and await

The introduction of async and await in C# 5.0 makes asynchronous programming a breeze. In contrast with traditional asynchronous technique that is complicated. However, you need to understand how the new technique works and how to implement it properly.

First, lets see the code snippet below. A method that returns something.

        async Task<int> GetTotalCustomerAsync()
        {
            //the data to be returned
            int result = 0;
            using (SqlConnection conn = new SqlConnection("..."))
            {
                using (SqlCommand cmd = new SqlCommand("....", conn))
                {
                    //open the connection asynchronously
                    await conn.OpenAsync();
                    //execute the query
                    Object obj = await cmd.ExecuteScalarAsync();
                    //convert the result
                    if(obj!=null)
                    {
                        int.TryParse(obj.ToString(), out result);
                    }                    
                }
            }
            //return the result
            return result;
        }

Pointers:

  1. The method signature includes an async modifier
  2. The method must not return void. Except when you’re writing an async event handler.
  3. The method must return Task<TResult> or Task if it returns nothing.
  4. The method must have at least one await operator.
  5. By convention, the method ends with Async suffix. So that you will easily identify that the method is asynchronous and can be awaitable as you can see in the succeeding example.
  6. await can only be used to an asynchronous method provided by the type. e.g. SqlCommand.ExecuteNonQueryAsync(). Hence, you cannot await SqlCommand.ExecuteNonQuery();

Just follow the pointers and method signature above and you can implement an asynchronous programming technique easily. As stated in Pointers #4, there must be at least one await operator. The next question now is what if I have my own method but I can’t use the await operator inside because there is nothing asynchronous inside that I can call and I want that my method to be asynchronous? An example would be:

        double Compute()
        {
            double result = 0;
            //very extensive computation with I/O and it may take a while
            //the computed value is stored to result
            return result;
        }

        void MyMethod()
        {
            double finalResult = Compute();
        }

        //decorating with async and await like this
        //will not compile at all as noted in the pointers above
        //because Compute is not async and awaitable
        async Task MyMethod()
        {
            double finalResult = await Compute();
        }


TaskCompletionSource to the rescue. As defined by MSDN, “Represents the producer side of a Task unbound to a delegate, providing access to the consumer side through the Task property.” It is a little bit hard to understand but applying it in the example, I hope you can grasp the idea.

        Task<double> ComputeAsync()
        {
            double result = 0;

            //create a task completion source
            //the type of the result value should be the same
            //as the type in the returning Task            
            TaskCompletionSource<double> taskCompletionSource = new TaskCompletionSource<double>();

            //create and run the extenstive computation in background task
            //to complete taskCompletionSource.Task
            Task.Run(() =>
              {
                  try
                  {
                      //very extensive computation with I/O and it may take a while
                      //the computed value is stored to result
                      //....                      
                      //set the result to TaskCompletionSource
                      taskCompletionSource.SetResult(result);
                  }
                  catch (Exception ex)
                  {
                      //pass the exception to TaskCompletionSource
                      //for proper handling
                      taskCompletionSource.SetException(ex);
                  }
              }
            );
            //return the Task
            return taskCompletionSource.Task;
        }

Implementing an asynchronous programming is now easier than before. Likewise, you can make your own method to run asynchronously easily, too. However, it doesn’t mean that you have to convert all your methods to run asynchronously. In my own experience, I only convert those methods that require I/O and CPU extensive tasks that may complete for more than 50 milliseconds.

I passed the Microsoft Exam 70-483: Programming in C#

Passing the Microsoft Exam 70-483 is a validation of my skills in programming in C#. Although I’ve been programming in C# since C# 2.0, taking the exam was not easy for me. It is because technology is constantly evolving and so is C# which at the time of this posting, the current version of C# is 6.0 (released just two months ago.) However, the exam I toke covers up to C# 5.0.

The exam covers the following:

  1. Manage program flow (25%)
  2. Create and use types (24%)
  3. Debug applications and implement security (25%)
  4. Implement data access (26%)

Microsoft Specialist

Pointers

Hello World!

“Hello World” is the most common example to teach a programming language. It shows the basic structure and syntax to print the word “Hello World”. This is the first step towards a bigger, interesting and yet challenging world of software development.

using System;

namespace HelloWorld
{
    class Program
    {
        ///<summary>
        ///Main entry to the program.
        ///</summary>
        ///<param name="args">Arguments to be passed.</param>
        static void Main(string[] args)
        {
            //Write to output window
            Console.WriteLine("Hello World!");
        }
    }
}

Above code shows the most basic structure and syntax in programming C#.

Line 1: Declaration for importing namespaces
Line 3: Namespace of the current assembly
Line 4: Start of namespace
Line 5: Class declaration
Line 6: Start of class
Line 7-10: Describes the type or type member. It is used in automatic documentation and used by Visual Studio IntelliSense to display the description of the said type or type member during development.
Line 11: Method declaration
Line 12: Start of a method
Line 13: Comment – a one line comment. You should always document your source code well.
Line 14: Statement
Line 15: End of method
Line 16: End of class
Line 17: End of namespace

Pointers:

  • statements are terminated with semi-colon ;
  • opening curly bracket { must always have a corresponding closing curly bracket }

Now let’s keep learning and challenging ourselves – and it has just begun.