Asynchronous Programming in .NET

“Performance” is a term that is used a lot when talking about apps, but it’s actually a pretty vague term. There are at least two aspects of performance that most people think about: app launch time and throughput. Both of these can be measured and described with actual numbers. The true test of an app, however, is end-user perception.

Asynchronous programming is a means of parallel programming in which a unit of work runs separately from the main application thread and notifies the calling thread of its completion, failure or progress. You may be wondering when you should use asynchronous programming and what are its benefits and problem points.

The main benefits one can gain from using asynchronous programming are improved application performance and responsiveness. One particularly well suited application for the asynchronous pattern is providing a responsive UI in a client application while running a computationally or resource expensive operation.

Async and Await

The async and await keywords in C# are the heart of asynchronous programming. By using those two keywords, you can use resources in the .NET Framework or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. Asynchronous methods that you define by using async and await are referred to as async methods.

The following example shows an async method. Almost everything in the code should look completely familiar to you.

async Task AccessTheWebAsync()
{
    HttpClient client = new HttpClient();
    Task getStringTask = client.GetStringAsync("http://www.haidermrizvi.com");
    DoIndependentWork();
    string urlContents = await getStringTask;
    return urlContents.Length;
}

GetStringAsync returns a Task. That means that when you await the task you’ll get a string (urlContents).

The await operator suspends AccessTheWebAsync.

AccessTheWebAsync can’t continue until getStringTask is complete.
Meanwhile, control returns to the caller of AccessTheWebAsync.
Control resumes here when getStringTask is complete.
The await operator then retrieves the string result from getStringTask.

The following characteristics summarize what makes the previous example an async method.

  • The method signature includes an async modifier.
  • The name of an async method, by convention, ends with an “Async” suffix.
    • The return type is one of the following types:

    • Task if your method has a return statement in which the operand has type TResult.
    • Task if your method has no return statement or has a return statement with no operand.
      • The method usually includes at least one await expression, which marks a point where the method can’t continue until the awaited asynchronous operation is complete. In the meantime, the method is suspended, and control returns to the method’s caller. The next section of this topic illustrates what happens at the suspension point.

      Summary

      The new async and await keywords enable you to provide significant user experience improvements in your apps without much effort on your part. This term does not mean multithreaded code. By default, code written with async and await is single-threaded. But threaded code works well here.

Validating FileUpload control for specific file type and required field.

In this article I am going to explain how we can check and validate user for uploading only certain files and making uploading of file to be must for submission of form.

For validating for required field we have to use RequiredFieldValidator and for validating for file types we’ll have to use RegularExpressionValidator. But, before starting we should have brief idea about the controls required.

Before starting about validating FileUpload we must have brief idea about FileUpload control and Validation Controls of ASP.Net

FileUpload Control:

FileUpload control is used for uploading file to the server from the client side.

For detailed reading about FileUpload visit: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.aspx

RequiredFieldValidator:

With this control, the validation fails if the input value does not change from its initial value. By default, the initial value is an empty string (“”).

For more details visit: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.requiredfieldvalidator.aspx

RegularExpressionValidator:

The RegularExpressionValidator control is used to ensure that an input value matches a specified pattern. The validation will not fail if the input control is empty. Use the RequiredFieldValidator control to make the field required.

For more details about RegularExpressionValidator visit following link: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.regularexpressionvalidator.aspx

Validating FileUpload Control in ASP.Net

Validating File Upload Control for certain file types. Here in the example below I am using RegularExpressionValidator to accomplish my task.

<asp:FileUpload ID="FileUpload1" runat="server" />

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only .doc , .docx or .txt files are allowed." 
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.txt)$" ControlToValidate="FileUpload1">*</asp:RegularExpressionValidator>

Here, regular expression for .doc, .docx, .txt files is:

"^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.txt)$"

If you want some more or other files type to be uploaded then you can replace or add more extension with the above mentioned extensions. Suppose you want your user to upload only .pdf file then you Regular expression for that will be:

"^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.pdf)$"

But, this does not mean that user will be forced to upload file, this validation is only performed if user tries to upload file. If you want to make uploading of file mandatory then you have to use RequiredFieldValidator.

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="You have not uploaded your file" ControlToValidate="FileUpload1">*</asp:RequiredFieldValidator>

The code above will validate FileUpload1 for required field.

Case statement in SQL Server

The SQL Server CASE statement is a conditional statement that returns a single value based on the evaluation of a statement. CASE expressions can be used in SQL anywhere an expression can be used like SELECT list, WHERE clause, HAVING clause, IN list, DELETE and UPDATE statements. CASE statement can also be nested. This provides a lot of pliability for evaluating multiple expressions.

SQL Case statement can be used in 2 forms:

  1. SQL CASE statement with simple expression to compare and get results.
  2. SQL CASE statement with search or comparison expression to get results.
  1. SQL CASE statement with simple expression to compare and get results

    A simple CASE expression operates by comparing the first expression to the expression in each WHEN clause for equivalency.

    Syntax

    CASE expression
        WHEN expression1 THEN expression1
        [[WHEN expression2 THEN expression2] [...]]
        [ELSE expression N]
    END
    

    Example

    SELECT CASE [Section]
        WHEN 1 THEN 'One'
        WHEN 2 THEN 'Two'
        WHEN 3 THEN 'Three'
        WHEN 4 THEN 'Four'
        WHEN 5 THEN 'Five'
        ELSE 'Greater than Five'
    END as [Sec_Word] FROM [Table_Test]
    
  2. SQL CASE statement with search or comparison expression to get results

    A search or comparison CASE expression allows comparison operators, and the use of AND and/or OR between each Boolean expression.

    Syntax

    CASE
        WHEN Boolean_expression1 THEN expression1
        [[WHEN Boolean_expression2 THEN expression2] [...]]
        [ELSE expression N]
    END
    

    Example

    SELECT CASE
        WHEN [Section] < 5 THEN 'Less than Five'
        WHEN [Section] = 5 THEN 'Equal to Five'
        WHEN [Section] > 5 THEN 'Greater than Five'
    END as [Sec_Word] FROM [Table_Test]
    

Hope you will find this post helpful. For any suggestion or query please feel free to post your valuable comments. Thanks.

Introduction to JOINs in SQL Server

The nature of relational database design shows that we will have related data that is stored in different tables. To retrieve data from two or more tables we use JOINS.

The JOIN clause tells the database how the data in the two tables is related so that it can return a correct representation of the related data.

Before entering into JOINs concept in SQL Server first design two tables in database, which I will be using to give you a better understanding of JOINs.

Table1Table2

In this blog I am going to discuss about two JOIN type:

  1. INNER JOIN
  2. OUTER JOIN

INNER JOIN

The INNER JOIN keyword return rows when there is at least one match in both tables.

inner-join

Example of Inner Join in SQL Server

SELECT * FROM Table1 t1
INNER JOIN Table2 t2
ON t1.ID = t2.ID

Output of Inner Join in SQL Server
Inner-Join

OUTER JOIN

There are three types of OUTER JOIN’s in SQL Server

  • LEFT OUTER JOIN
  • RIGHT OUTER JOIN
  • FULL OUTER JOIN

LEFT OUTER JOIN

LEFT OUTER JOIN in SQL Server returns all the rows from the left table in conjunction with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values.

left-join

Example of Left Outer Join in SQL Server

SELECT * FROM Table1 t1
LEFT OUTER JOIN Table2 t2
ON t1.ID = t2.ID

Output of Left Outer Join in SQL Server
Left-Outer-Join

RIGHT OUTER JOIN

RIGHT OUTER JOIN returns all the rows from the right table in conjunction with the matching rows from the left table. If there are no columns matching in the left table, it returns NULL values.

right-join

Example of Right Outer Join in SQL Server

SELECT * FROM Table1 t1
RIGHT OUTER JOIN Table2 t2
ON t1.ID = t2.ID

Output of Right Outer Join in SQL Server
RIGHT-OUTER-JOIN

FULL OUTER JOIN

FULL OUTER JOIN returns rows from either table when the conditions are met and returns null value when there is no match.

outer-join

Example of Full Outer Join in SQL Server

SELECT * FROM Table1 t1
FULL OUTER JOIN Table2 t2
ON t1.ID = t2.ID

Output of Full Outer Join in SQL Server
FULL-OUTER-JOIN