July 3, 2015

Asp.Net - UpdatePanel Time Out

I was working with an asp.net applcation and one of the pages was producing errors. After going through the error, I realise it was failing with a timeout error. So, I went ahead and increased the timeout value for both WCF service and also the SqlCommand that's being called by the Wcf service, however, even though there was no exception, the data was not displaying on the site.

So, to test the issue, I started inspecting the issue in Chrome and under the Network tab, there was an error "Sys.WebForms.PageRequestManagerTimeoutException", which meant some kind of error with the UpdatePanel. After this, I increased the timeout value for the UpdatePanel by setting the "AsyncPostBackTimeout" property on "ScriptManager" and then it got fixed.

June 24, 2015

I have this Sql table setup in Sql Server that contains a XML field and I need to count the number of times a xml node appears in the xml. In practice, it could be the table contains user data and the xml contains a list of cities the user has visited and we need to find out how many cities the user has visited.

June 19, 2015

I have sometimes seen WCF services that times out. The easiest way to fix it is to increase the timeout value within the config file. Here is an example of this can be done.

  1. <binding name="WSHttpBinding_ILoanService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00">  
  2. </binding>


Okay, so there are four different timeouts - what do they mean.

How to Increase SQL Command Timeout

Sometimes I have seen while running a sql script from .NET code that the Sql Command times out. The solution is simple - we just need to increase the timeout. However, we should really think on why the timeout increase is needed and whether we should change the query - like, by reducing the number of rows returned - to minimise the time taken.

Before starting the discussion, what is Sql Command? It's a call to the database to get data or to update data. We can either directly execute the sql script or call a stored procedure by passing in the relevant parameters. In case, we figure we cannot change the sql query and our only option is to increase the timeout, then we can write the following code.

I was running an application using Visual Studio and for not so apparent reason the web service was not working. Since I was debugging the web site connecting to a web service within visual studio - it was not apparent as to why it was failing. When I started debugging the web service, I figured it resulting in an error - Memory gates checking failed because the free memory (296964096 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element..

Practically there are no differences between int and System.Int32 (except while using enums). C# allows for certain aliases and it is one of those. Both int and System.Int32 are compiled to System.Int32 in the Intermediate Language (IL). C# contains a number of aliases that allows for quick typing of the variable types. Here is a full list of the aliases.

May 22, 2015

Recently, I had to login to a SQL Server to get some data but the pain was I had to login to remote desktop using a different windows username and then opening Sql Server Management Studio and then opening connection to the Sql Server in a different server. I was thinking this is just crazy and I would simply just want to connect to the sql server using my local Sql Server Management Studio.

May 18, 2015

C# Different ways to create a string

Strings, in C#, represents text as a series of Unicode characters. A string can be referenced as both "string" and "String" - string is basically an alias of System.String.  It can be created in a number of ways. In the simplest form, it can just be assigned or alternatively it can be created using the String's constructors. String, like other objects in .NET, can be assigned to null. Strings might look like and can be used like other variables like int or double but one important characteristics is that it is immutable - that is, once a String is created, it cannot be changed (so, when a string variable is re-assigned, behind the scenes, a new string is created and assigned to the variable).

The main difference between nvarchar and varchar column is in the character set of data that it can store. Varchar is single byte whereas nvarchar is double-byte and therefore nvarchar can store Unicode characters while varchar cannot.

May 15, 2015

To escape a single quote in Sql Server, use two single quotes. Note, don't use a double quote.

For example, the following SQL Script will give error.

All these methods Int32.Parse(), Convert.ToInt32(), and Int32.TryParse() ultimately does the same thing - convert a string to an integer. The main difference lies in what happens if the conversion does not succeed. With Int32.Parse(), exceptions are thrown if conversion does not work. With Convert.ToInt32() methods 0 is returned while parsing null, otherwise exceptions are thrown. With Int32.TryParse() method, no exception is thrown - it sets the correct value to an integer variable if conversion succeeds and at the same time returns a boolean value suggesting if conversion has succeeded.

 

February 18, 2015

Another new feature of C# 6.0 is Exception Filters which allows catching all exceptions except for some. We can basically write an if statement before entering the catch block meaning that we can and cannot enter the catch block. For example, we can catch all exceptions except for say ArithMatic exception or we can check the value of a property before entering the catch block.

Here is an example of how this would work.

private void GetData()
{
    try
    {
        //do something
    }
    catch(Exception ex)
    if(ex.GetType() != typeof(ArithmeticException) && ex.GetType() != typeof(SqlException) && ex.InnerException != null)
    {
        //handle exception
    }
    finally
    {
        //do something
    }
}

Read on other new features of C# 6.0.

One of the new features introduced in C# 6.0 is Conditional Access Operator. This really means that we can use the ? and ?? operators while checking if a property of an object exists. Previously, we had to write if(object != null) and so on but now there is a shorthand of writing this using the conditional operators.

Here's an example of how it works.

private string GetName(NewStuff stuff)
{
    string ans = "";
    //old way
    if (stuff != null && stuff.Name != null)
        ans = stuff.Name.ToUpper();
    else
        ans = "no name";


    //new way
    ans = stuff?.Name? .ToUpper() ?? "no name";

    return ans;
}

Read on other new features of C# 6.0.

February 17, 2015

C# 6.0 has introduced a new feature that allows specifying Static Classes in the using statement. For example, previously we would have written System.Console.WriteLine("some message") or Console.WriteLine("some message") but now we can just write WriteLine("some message") and specify the class name in the using statement. Note that the syntax has recently changed from using StaticClass to using static StaticClass. Here's an example of how to use the static class.

using System;
using static System.Console;
using static System.Math;

 

public static void LogMessage(string message)
{
    WriteLine(message);
}

public static void GetArea(int radius)
{
    //the old way
    Console.WriteLine(Math.PI * Math.Pow(radius, 2));

    //the new way
    WriteLine(PI * Pow(radius, 2));
}

 

As part of the example, just note how much less typing we would need while using static.

Read on other new features of C# 6.0.

This is a new feature in C# 6.0. There is no syntax improvement but a feature improvement and this is new feature allows await keyword to be called within the catch section of a try-catch block. This allows for async exception handling when async results in an exception.

Here is an example of how to use the code.

  1. //await within a catch block
  2. async void DoSomething()
  3. {
  4.     try
  5.     {
  6.         NewStuff stuff = new NewStuff();
  7.         Task<bool> task = stuff.BuggyMethod();
  8.     }
  9.     catch (Exception ex)
  10.     {
  11.         await Logger.Log(ex.StackTrace);
  12.     }
  13.  
  14. }

Read on other new features of C# 6.0.

With the Auto Property initialization feature, properties can be initialized without using private setter or a local variable. Previously, we used to set the properties within the constructors, with C# 6, the properties can be initialised within the properties' get-set section. A constructor is not required.

Here is an example of how this can be achieved.

Property Initializer
  1. class NewStuff
  2. {
  3.     public long ID { get; } = -1;
  4.     public string Name { get; } = "John";
  5.     public string Email { get; protected set; } = "example@domain.com";
  6. }
  7.  
  8. class OldStuff
  9. {
  10.     private string email = "example@domain.com";
  11.     public OldStuff()
  12.     {
  13.         //initialiser
  14.         ID = -1;
  15.         Name = "John";
  16.     }
  17.  
  18.     public long ID { get; set; }
  19.  
  20.     public string Name { get; set; }
  21.  
  22.     public string Email
  23.     {
  24.         get { return email; }
  25.         protected set
  26.         {
  27.             email = value;
  28.         }
  29.     }
  30. }

 

Read on other new features of C# 6.0.

January 30, 2015

I have a website that I configured to use https using IIS and have setup the links to point to the https version of the site. However, IIS does not automatically redirect the http version of the site to https and instead display error messages on the screen. This is bad as other sites had linked to the http version of prior to setting up https.

January 8, 2015

HTML - Pattern Matching

From HTML5, a pattern attribute has been introduced which allows validation of an input field using regular expression. The validation is carried out by the browser and no javascript is required. This is great news for developers as sometimes javascript validation becomes a tedious and repetitive task.

In this post, I will show how to use patterns in html forms with examples and then list a few common regular expression. Note that, in the example, I have not included a regular expression for email address. It's actually not required to validate email using regular expression and instead we can directly use the input type as email.

In this post, I will show how to read a single file from a password protected zip file and then display it on a web browser. This scenario might be more required in a windows application but since the focus is to read from the zip file than to display it on the web browser, I will go ahead with browser.

To read from the zip file, I am using a NuGet package - SharpZipLib. This library can ne used to read a password protected zip file. If you are not familiar on how to add or manage NuGet packages, then check the NuGet Docs. After the package is added, I will use the ICSharpCode.SharpZipLib.Zip to read the zip file.

Reference: Shahed Kazi at AspNetify.com