Monday, 27 March 2017

async keyword in C#

What is an async Method?

An async method is a method that returns to the calling method before completing all its work, and then completes its work while the calling method continues its execution.
An async method has the following characteristics:
  • An async method must have the async keyword in its method header, and it must be before the return type.
  • This modifier doesn’t do anything more than signal that the method contains one or more await expressions.
  • It contains one or more await expressions. These expressions represent tasks that can be done asynchronously.
  • It must have one of the following three return types.
    − void :If the calling method just wants the async method to execute, but doesn’t need any further interaction with it
    − Task : If the calling method doesn’t need a return value from the async method, but needs to be able to check on the async method’s state
    − Task<T> :If the calling method is to receive a value of type T back from the call, the return type of the async method must be Task
  • An async method can have any number of formal parameters of any types but it cannot be out or ref parameters.
  • The name of an async method should end with the suffix Async.
  • Otherthan Methods, lambda expressions and anonymous methods can also act as async objects.

Using an async method that returns a Task<int> object:

class Program
  {
      static void Main()
      {
          Task<int> value = DoAsyncWork.CalculateSumAsync(10, 11);
          //Do Other processing
          Console.WriteLine("Value: {0}", value.Result);      
      }
  }

    static class DoAsyncWork
    {
        public static async Task<int> CalculateSumAsync(int i1,int i2)
        {
            int sum = await Task.Run(() => GetSum(i1,i2));
            return sum;
        }

        private static int GetSum(int i1, int i2)
        {
        return i1+i2;
        }
    }

Output:

Using an async method that returns a Task object:

class Program
  { 
     static void Main()
      {  
        Task value = DoAsyncWork.CalculateSumAsync(10, 11); 
         //Do Other processing 
         value.Wait();  
        Console.WriteLine("Async stuff is done"); 
              } 
 }    
 static class DoAsyncWork 
   { 
       public static async Task CalculateSumAsync(int i1,int i2)
         { 
           int sum = await Task.Run(() => GetSum(i1,i2));
            Console.WriteLine("Value: {0}", sum);
        }
         private static int GetSum(int i1, int i2)
        { 
       return i1+i2;
        } 
   }
 Value: 21
Async stuff is done

Using an async method that returns a void object:

class Program
  {
      static void Main()
      {
           DoAsyncWork.CalculateSumAsync(10, 11);
          //Do Other processing
           Thread.Sleep(200);
          Console.WriteLine("Program Exiting");      
      }
  }

    static class DoAsyncWork
    {
        public static async void CalculateSumAsync(int i1,int i2)
        {
            int sum = await Task.Run(() => GetSum(i1,i2));
            Console.WriteLine("Value: {0}", sum);
        }

        private static int GetSum(int i1, int i2)
        {
        return i1+i2;
        }
    }
 Output:
Value: 21
Program Exiting

The Flow of Control in an Async Method :

The body of an async method has divided mainly into three sections.
  • Before the first await expression : This includes all the code at the beginning of the method up until the first await expression. This section contains very minimal code that doesn’t require too much processing.
  • The await expression: This expression represents the task to be performed asynchronously.
  • Continuation: This is the rest of the code in the method, following the await expression. This includes the information about which thread it’s on, the values of the variables currently in scope, and other things it’ll need in order to resume execution later, after the await expression completes

Thursday, 9 March 2017

msdb.dbo.sp_send_dbmail

Sends an e-mail message to the specified recipients. The message may include a query result set, file attachments, or both. When mail is successfully placed in the Database Mail queue, sp_send_dbmail returns the mailitem_id of the message. This stored procedure is in the msdb database.

Syntax
sp_send_dbmail [ [ @profile_name = ] 'profile_name' ]  
    [ , [ @recipients = ] 'recipients [ ; ...n ]' ]  
    [ , [ @copy_recipients = ] 'copy_recipient [ ; ...n ]' ]  
    [ , [ @blind_copy_recipients = ] 'blind_copy_recipient [ ; ...n ]' ]  
    [ , [ @from_address = ] 'from_address' ]  
    [ , [ @reply_to = ] 'reply_to' ]   
    [ , [ @subject = ] 'subject' ]   
    [ , [ @body = ] 'body' ]   
    [ , [ @body_format = ] 'body_format' ]  
    [ , [ @importance = ] 'importance' ]  
    [ , [ @sensitivity = ] 'sensitivity' ]  
    [ , [ @file_attachments = ] 'attachment [ ; ...n ]' ]  
    [ , [ @query = ] 'query' ]  
    [ , [ @execute_query_database = ] 'execute_query_database' ]  
    [ , [ @attach_query_result_as_file = ] attach_query_result_as_file ]  
    [ , [ @query_attachment_filename = ] query_attachment_filename ]  
    [ , [ @query_result_header = ] query_result_header ]  
    [ , [ @query_result_width = ] query_result_width ]  
    [ , [ @query_result_separator = ] 'query_result_separator' ]  
    [ , [ @exclude_query_output = ] exclude_query_output ]  
    [ , [ @append_query_error = ] append_query_error ]  
    [ , [ @query_no_truncate = ] query_no_truncate ]   
    [ , [ @query_result_no_padding = ] @query_result_no_padding ]   
    [ , [ @mailitem_id = ] mailitem_id ] [ OUTPUT ]  

@profile_name= ] 'profile_name'
Is the name of the profile to send the message from. The profile_name is of type sysname, with a default of NULL. The profile_name must be the name of an existing Database Mail profile. When no profile_name is specified, sp_send_dbmail uses the default private profile for the current user. If the user does not have a default private profile, sp_send_dbmail uses the default public profile for the msdb database. If the user does not have a default private profile and there is no default public profile for the database, @profile_name must be specified.
@recipients= ] 'recipients'
Is a semicolon-delimited list of e-mail addresses to send the message to. The recipients list is of type varchar(max). Although this parameter is optional, at least one of @recipients@copy_recipients, or @blind_copy_recipients must be specified, or sp_send_dbmail returns an error.
@copy_recipients= ] 'copy_recipients'
Is a semicolon-delimited list of e-mail addresses to carbon copy the message to. The copy recipients list is of type varchar(max). Although this parameter is optional, at least one of @recipients@copy_recipients, or @blind_copy_recipients must be specified, or sp_send_dbmail returns an error.
@blind_copy_recipients= ] 'blind_copy_recipients'
Is a semicolon-delimited list of e-mail addresses to blind carbon copy the message to. The blind copy recipients list is of type varchar(max). Although this parameter is optional, at least one of @recipients@copy_recipients, or @blind_copy_recipients must be specified, or sp_send_dbmail returns an error.
@from_address= ] 'from_address'
Is the value of the 'from address' of the email message. This is an optional parameter used to override the settings in the mail profile. This parameter is of type varchar(MAX). SMTP security settings determine if these overrides are accepted. If no parameter is specified, the default is NULL.
@reply_to= ] 'reply_to'
Is the value of the 'reply to address' of the email message. It accepts only one email address as a valid value. This is an optional parameter used to override the settings in the mail profile. This parameter is of type varchar(MAX). SMTP security settings determine if these overrides are accepted. If no parameter is specified, the default is NULL.
@subject= ] 'subject'
Is the subject of the e-mail message. The subject is of type nvarchar(255). If no subject is specified, the default is 'SQL Server Message'.
@body= ] 'body'
Is the body of the e-mail message. The message body is of type nvarchar(max), with a default of NULL.
@body_format= ] 'body_format'
Is the format of the message body. The parameter is of type varchar(20), with a default of NULL. When specified, the headers of the outgoing message are set to indicate that the message body has the specified format. The parameter may contain one of the following values:
  • TEXT
  • HTML
Defaults to TEXT.
@importance= ] 'importance'
Is the importance of the message. The parameter is of type varchar(6). The parameter may contain one of the following values:
  • Low
  • Normal
  • High
Defaults to Normal.
@sensitivity= ] 'sensitivity'
Is the sensitivity of the message. The parameter is of type varchar(12). The parameter may contain one of the following values:
  • Normal
  • Personal
  • Private
  • Confidential
Defaults to Normal.
@file_attachments= ] 'file_attachments'
Is a semicolon-delimited list of file names to attach to the e-mail message. Files in the list must be specified as absolute paths. The attachments list is of type nvarchar(max). By default, Database Mail limits file attachments to 1 MB per file.
@query= ] 'query'
Is a query to execute. The results of the query can be attached as a file, or included in the body of the e-mail message. The query is of type nvarchar(max), and can contain any valid Transact-SQL statements. Note that the query is executed in a separate session, so local variables in the script calling sp_send_dbmail are not available to the query.
@execute_query_database= ] 'execute_query_database'
Is the database context within which the stored procedure runs the query. The parameter is of type sysname, with a default of the current database. This parameter is only applicable if @query is specified.
@attach_query_result_as_file= ] attach_query_result_as_file
Specifies whether the result set of the query is returned as an attached file. attach_query_result_as_file is of type bit, with a default of 0.
When the value is 0, the query results are included in the body of the e-mail message, after the contents of the @body parameter. When the value is 1, the results are returned as an attachment. This parameter is only applicable if @query is specified.
@query_attachment_filename= ] query_attachment_filename
Specifies the file name to use for the result set of the query attachment. query_attachment_filename is of type nvarchar(255), with a default of NULL. This parameter is ignored when attach_query_result is 0. When attach_query_result is 1 and this parameter is NULL, Database Mail creates an arbitrary filename.
@query_result_header= ] query_result_header
Specifies whether the query results include column headers. The query_result_header value is of type bit. When the value is 1, query results contain column headers. When the value is 0, query results do not include column headers. This parameter defaults to 1. This parameter is only applicable if @query is specified.
@query_result_width = ] query_result_width
Is the line width, in characters, to use for formatting the results of the query. The query_result_width is of type int, with a default of 256. The value provided must be between 10 and 32767. This parameter is only applicable if @query is specified.
@query_result_separator= ] 'query_result_separator'
Is the character used to separate columns in the query output. The separator is of type char(1). Defaults to ' ' (space).
@exclude_query_output= ] exclude_query_output
Specifies whether to return the output of the query execution in the e-mail message. exclude_query_output is bit, with a default of 0. When this parameter is 0, the execution of the sp_send_dbmail stored procedure prints the message returned as the result of the query execution on the console. When this parameter is 1, the execution of the sp_send_dbmail stored procedure does not print any of the query execution messages on the console.
@append_query_error= ] append_query_error
Specifies whether to send the e-mail when an error returns from the query specified in the @query argument. append_query_error is bit, with a default of 0. When this parameter is 1, Database Mail sends the e-mail message and includes the query error message in the body of the e-mail message. When this parameter is 0, Database Mail does not send the e-mail message, and sp_send_dbmail ends with return code 1, indicating failure.
@query_no_truncate= ] query_no_truncate
Specifies whether to execute the query with the option that avoids truncation of large variable length data types (varchar(max)nvarchar(max)varbinary(max)xmltextntextimage, and user-defined data types). When set, query results do not include column headers. The query_no_truncate value is of type bit. When the value is 0 or not specified, columns in the query truncate to 256 characters. When the value is 1, columns in the query are not truncated. This parameter defaults to 0.
@query_result_no_padding ] @query_result_no_padding
The type is bit. The default is 0. When you set to 1, the query results are not padded, possibly reducing the file size.If you set @query_result_no_padding to 1 and you set the @query_result_width parameter, the @query_result_no_padding parameter overwrites the @query_result_width parameter.
In this case no error occurs.
If you set the @query_result_no_padding to 1 and you set the @query_no_truncate parameter, an error is raised.
@mailitem_id= ] mailitem_id [ OUTPUT ]
Optional output parameter returns the mailitem_id of the message. The mailitem_id is of type int.
Ref:- https://msdn.microsoft.com/en-in/library/ms190307.aspx

Tuesday, 24 January 2017

REST Design Principles

    Everything is a Resource

  • Everything that needs to be identified on web should be treated as Resource and be uniquely identified.
  •  Resource is usually Noun and not verb
  •  Each piece of data available on the Internet has a format that could be described by a content type
  • Example: “http://Csharpstar.com/Employee/1234
  • Each resource is identifiable by a unique identifier (URI)

  • The Internet contains so many different resources, they all should be accessible via URIs and should be identified uniquely
  • The URI keeps the data self-descriptive and eases further development on it.
  • The URIs helps you to reduce the risk of logical errors in your programs to a minimum.
  • URIs expose different types of resources in a straightforward manner
  • Example:
    – Images (http://Csharpstar.com/Images)  
    – Videos (http://Csharpstar.com/Videos)  
    – XML documents (http://Csharpstar.com/Archieves)

    Use the standard HTTP methods

       Use standard Http methods to operate on identified resources
        – Get : Request an existing Resource
        – Post :Update an existing Resource
        – Put : Create or Update a Resource
        – Delete:Remove/Delete a Resource

    Allow multiple representations for same Resource

  •  A key feature of a resource is that they may be represented in a different form than the one it is stored. so, it can be requested or posted in different representations.As long as the specified format is supported, the REST-enabled endpoint should use it
  • The resource should be presented to client in multiple formats as the client desire. The format can be anything like XML,JSON,JPG,PDF,HTML etc..
  • Communication should be always stateless   

  • REST services are stateless by nature. So, the clients state can not be stored on the server.However, the client can still maintain state and pass it to the service with each request
  • In a production environment, it is likely that incoming requests are served by a load balance, ensuring availability and high availability. Once exposed via a load balance, the idea of keeping your application state at server side gets compromised. This doesn’t mean that you are not allowed to keep the state of your application. It just means that you should keep it in a RESTful way.

Friday, 30 December 2016

C# 7.0

Visual studio 2017 RC which was released on November 16, 2016. Let us see some of the new features of C# 7.0, which is the default language of this version.

the new C# 7.0 features coming down the pipeline. Although C# 7.0 is still in development, most of the new features noted by Microsoft have been enabled in Visual Studio 15 Preview 5.
According to Mads Torgersen, Microsoft program manager for C#; the biggest features are tuples, which make it easy to have multiple results, and pattern matching, which simplifies code that is conditional on the shape of data.
Current features and beyond can be followed at Roslyn on GitHub.
Some of the new features in C# 7.0 are
  • Out variables
  • Pattern matching
  • Tuples
  • Deconstruction
  • Local functions
  • Ref returns and locals
  • Generalized async return types

Tuesday, 31 May 2016

SQL Query for generating matrix in SQL Server

We have a table like that:
























We need result of query in MATRIX form like this:
















We can use SQL Server's PIVOT operator

;WITH Q AS (
  SELECT  [Vehicle] = 'Scooter' , [Employee] = 'Anas', [Amount] = 80115.50
  UNION ALL SELECT 'Scooter', 'Ross', 36571.85
  UNION ALL SELECT 'Scooter', 'Michelle', 39571.97
  UNION ALL SELECT 'Car', 'Peterson', 82658.23
  UNION ALL SELECT 'Car', 'Ross', 68998.85
  UNION ALL SELECT 'Car', 'Anas', 63598.75
  UNION ALL SELECT 'Car', 'Smith', 58950.53
  UNION ALL SELECT 'Car', 'Andrew', 57890.21
  UNION ALL SELECT 'Van', 'Andrew', 82658.23
  UNION ALL SELECT 'Van', 'Smith', 13400.65
  UNION ALL SELECT 'Van', 'Deniss', 15430.10
  UNION ALL SELECT 'Bus', 'Anas', 95867.55
  UNION ALL SELECT 'Bus', 'Bob', 98222.85
  UNION ALL SELECT 'Bus', 'Ronald', 98547.52
  UNION ALL SELECT 'Bus', 'Eric', 57880.65
  UNION ALL SELECT 'Bus', 'Smith', 6430.35
  UNION ALL SELECT 'Truck', 'Ross', 29560.10
  UNION ALL SELECT 'Truck', 'Andrew', 25780.30
  UNION ALL SELECT 'Truck', 'Taniya', 25054.44
 
)
SELECT  Employee,
        Scooter = ISNULL( Scooter, 0 ),
        Car = ISNULL( Car, 0 ),
        Van = ISNULL( Van, 0 ),
        Bus = ISNULL( Bus, 0 ),
        Truck = ISNULL( Truck, 0 ),
        Total = ISNULL( Scooter, 0 )+ ISNULL( Car, 0 ) + ISNULL( Van, 0 )+ ISNULL( Bus, 0 )  + ISNULL( Truck, 0 )
FROM    (
          SELECT  FROM  Q
        ) AB
PIVOT   ( SUM(Amount ) FOR [Vehicle] IN ([Scooter],[Car], [Van], [Bus], [Truck] )) PVT_table


Monday, 1 June 2015

Automatic Page Refresh in ASP.NET

To refresh a page automatically at a time interval. Doing this is pretty simple, using META tags.

    <meta http-equiv="refresh" content="45">


    <meta http-equiv="refresh" content="45;url=home.aspx">

But if you used Master Pages, the META tag then all pages that use this master page will be refreshed, which is not desired, to accomplish this, add the following c# code in the code behind of, the particular page you want to refresh:
Response.AppendHeader("Refresh", 45 + "; URL=home.aspx");

Where, 45 is the time interval in seconds.

There are many other ways of doing auto refreshing , like using JavaScript and J Queries, but this is simplest way. 

Wednesday, 25 March 2015

SQL:- Multiple rows to a single comma-separated value

Sample Data
DECLARE @MyTable1 TABLE(ID INT, Value Varchar(50))
INSERT INTO @MyTable1 VALUES (1,'John'),(1,'Tom'),(1,'Sajan'),(1,'Ram')
Sql Query
SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(200)) [text()]
        FROM @MyTable1
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') Name
FROM @MyTable1 t
GROUP BY ID
Results
ID Names
1 John, Tom, Sajan, Ram