Tuesday, 29 October 2013

C#.NET - Custom Extension Methods Step By Step

Extension methods are introduced in .NET Framework 3.5. These are the special kind of static methods. Extension methods are mainly useful when you want to extend an existing type like Integer, String e.t.c. You can implement any type using extension methods.

Now i will show you an example on extension methods. In this example i will show you how to extend the DateTime type to get custom date format.

1. Create a new console application.

2. Create a static class with name "ExtensionMethods"

     public static class ExtensionMethods
     {

     }

3. Inside ExtensionMethods class create an extension method
    -- Remember the first parameter of the extension method must be preceded with "this" keyword

    public static string GetCustomDate(this DateTime value)
    {

  }

4. Now write the following statement to return the date in "MMM dd, yyyy" (Ex: Oct 30, 2013) format.

    return value.ToString("MMM dd, yyyy");

5. Finally your extension class looks as follows.

    public static class ExtensionMethods
    {
          public static string GetCustomDate(this DateTime value)
          {
              return value.ToString("MMM dd, yyyy");
          }
    }

6. Now go to Main method and call the DateTime extension method as follows

    class Program
     {
            static void Main(string[] args)
            {
                string value = DateTime.Now.GetCustomDate(); // Called like an instance method.
                Console.WriteLine(value);
            }
    }

7. Here the extension method will return the output in custom date time format like "Oct 30, 2013".


Complete Code


using System;
namespace CustomExtensions
{
    //Extension methods must be defined in static class
    public static class ExtensionMethods
    {
        // The first parameter of the extension method
        //should be preceded with this keyword
        public static string GetCustomDate(this DateTime value)
        {
            return value.ToString("MMM dd, yyyy");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //Pass the date time value to the extension method
            string value = DateTime.Now.GetCustomDate();
            // Extension method returns "Oct 30, 2013"
            Console.WriteLine(value);
        }
    }
}

Friday, 25 October 2013

Trick - How to get Database Connection String using NotePad

1. Create new file in Notepad. Save the file as "myconnection.udl"  (Microsoft Data Link File) with double quotes.

2. Open "myconnection.udl" file and provide correct details SQL Server name , Select Use windows NT Integrated Security radiobutton, select the database fro the dropdown list. Now click on the Test Connection button if you are provided the correct details you will get Test connection succeed message.

3. Now open "myconnection.udl" with notepad

4. Now you will get the connection string in the file.






Wednesday, 23 October 2013

C#.NET - Standard DateTime formats with examples

using System;

class Program
{
    static void Main(string[] args)
    {

        string str = string.Empty;

       //A standard date and time format string uses a single format specifier
      //to define the text representation of a date and time value.
      //The following examples describes the standard date and time format specifiers.

        //d Short date Pattern
        str = DateTime.Now.ToString("d");  
        //10/23/2013

        //d Long date Pattern
        str = DateTime.Now.ToString("D");  
        //Wednesday, October 23, 2013

        //f Full date time (short time) Pattern
        str = DateTime.Now.ToString("f");  
        //Wednesday, October 23, 2013 5:59 PM

        //F Full date time (long time) Pattern
        str = DateTime.Now.ToString("F");  
        //Wednesday, October 23, 2013 5:59:39 PM

        //g General date time (short time) Pattern
        str = DateTime.Now.ToString("g");  
        //10/23/2013 5:59 PM

        //G General date time (long time) Pattern
        str = DateTime.Now.ToString("G");  
        //10/23/2013 5:59:56 PM

        //m or M Month day Pattern
        str = DateTime.Now.ToString("m");  
        //October 23
        str = DateTime.Now.ToString("M");  
        //October 23

        //r or R RFC1123 Pattern
        str = DateTime.Now.ToString("r");  
        //Wed, 23 Oct 2013 18:01:02 GMT
        str = DateTime.Now.ToString("R");
        //Wed, 23 Oct 2013 18:01:02 GMT

        //s Sortable date time pattern
        str = DateTime.Now.ToString("s");  
        //2013-10-23T18:01:22

        //t Short time pattern
        str = DateTime.Now.ToString("t");  
        //6:01 PM

        //T Long time pattern.
        str = DateTime.Now.ToString("T");  
        //6:05:25 PM

        //u Universal sortable date time pattern
        str = DateTime.Now.ToString("u");  
        //2013-10-23 18:06:25Z

        //U Universal full date/time pattern
        str = DateTime.Now.ToString("U");  
        //Wednesday, October 23, 2013 12:36:50 PM  

        //y or Y Year month pattern.
        str = DateTime.Now.ToString("y");  
        //October, 2013
        str = DateTime.Now.ToString("Y");  
        //October, 2013

    }
}

C#.NET - Custom DateTime formats with examples


using System;
class Program
{
    static void Main(string[] args)
    {
        string str = string.Empty;
        //There are following custom format specifiers

        //y Year
        str = String.Format("{0:y yy yyy yyyy}", DateTime.Now);
        //13 13 2013 2013

        //M Month
        str = String.Format("{0:M MM MMM MMMM}", DateTime.Now);
        //10 10 Oct October

        //d Day
        str = String.Format("{0:d dd ddd dddd}", DateTime.Now);
        //23 23 Wed Wednesday

        //h 12-Hours, H 24-Hours
        str = String.Format("{0:h hh H HH}", DateTime.Now);
        //3 03 15 15

        //m Minute
        str = String.Format("{0:m mm}", DateTime.Now);
        //0 00

        //s Second
        str = String.Format("{0:s ss}", DateTime.Now);
        //22 22

        //f Second Fraction
        str = String.Format("{0:f ff fff ffff}", DateTime.Now);
        //4 47 473 4737

        //t A.M or P.M
        str = String.Format("{0:t tt}", DateTime.Now);
        //P PM

        //z Time Zone
        str = String.Format("{0:z zz zzz}", DateTime.Now);
        //+5 +05 +05:30
    }
}

Tuesday, 22 October 2013

How to create dynamic DataTable in C#.NET?

using System;
using System.Data;

class Program
{
    static void Main(string[] args)
    {
        DataTable table = GetTable();
    }
    static DataTable GetTable()
    {
        //Create new DataTable instance
        DataTable table = new DataTable("Indian Cricket Team");

        // Add Columns to table
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));
        table.Columns.Add("Batting style", typeof(string));
        table.Columns.Add("Bowling style", typeof(string));

        //Add Rows to Table
        table.Rows.Add("Mahendra Singh Dhoni", 32, "Right-handed", "Right medium");
        table.Rows.Add("Virat Kohli", 24, "Right-handed", "Right medium");
        table.Rows.Add("Virender Sehwag", 34, "Right-handed", "Off break");
        table.Rows.Add("Suresh Raina", 26, "Left-handed", "Off break");
        //.............
        //.............

        //Return the DataTable
        return table;
    }
}

Friday, 18 October 2013

C#.NET - How to use OUTPUT clause in Stored Procedures to retrieve new identity values from SQL Server


SQL Server 2005 introduced the OUTPUT clause in DML statements.
We can use this in an INSERT ... SELECT statement to capture all the inserted identity values.

1. Create an Employee table
 CREATE TABLE [dbo].[tbl_employee]
  (
     [serial]      [INT] IDENTITY(1, 1) NOT NULL,
     [empname]     [VARCHAR](50) NULL,
     [empsal]      [VARCHAR](50) NULL,
     [emplocation] [VARCHAR](50) NULL
  )     
2. Create a stored procedure to get the identity value
 CREATE PROCEDURE [dbo].[Temp]
 AS
  BEGIN
      -- Declare table variable to hold results
      DECLARE @Temp TABLE
        (
           serial INT
        )

      -- Insert into table with IDENTITY column      
      INSERT INTO [Temp].[dbo].[tbl_employee]
                  ([empname],
                   [empsal],
                   [emplocation])
      -- Use OUTPUT clause to retrieve new value 
      output      inserted.serial
      INTO @Temp(serial)
      VALUES      ('emp1',
                   '15000',
                   'Hyderabad')

      --Select the identity value
      SELECT serial
      FROM   @Temp
  END     
3. Open web.config file and set connection string as follows
<connectionStrings>
   <add name="SiteSqlServer" connectionString="Data Source=ADMIN-PC;Initial Catalog=Temp;User ID=sa;Password=sql@121"
      providerName="System.Data.SqlClient" />
</connectionStrings>
4. Open code behind file and add following namespaces
using System.Data.SqlClient;
using System.Collections.Generic;
5. Write the following method to retrieve data from Stored Procedure.
public static object UsingTheOutputClauseExecuteCommandAndRetriveNewIdentity(string storedProcedureName, List<SqlParameter> sqlParameters)
    {
        string outputParameterValue = string.Empty;
        SqlConnection connection = new SqlConnection(sqlConnectionString);
        SqlCommand command = new SqlCommand(storedProcedureName, connection);
        command.CommandType = CommandType.StoredProcedure;
        if (sqlParameters.Count > 0)
        command.Parameters.AddRange(sqlParameters.ToArray());        
        using (connection)
        {
            connection.Open();
            object num = command.ExecuteScalar();           
            connection.Close();
        }
        return outputParameterValue;
    }
    
6. Finally use the following code to retrieve new identity values from SQL Server.
List<SqlParameter> sqlparams = new List<SqlParameter>();
object str = UsingTheOutputClauseExecuteCommandAndRetriveNewIdentity("Temp",sqlparams);  

Stored Procedures - How to use OUTPUT clause to retrieve new identity values from SQL Server 2008

SQL Server 2005 introduced the OUTPUT clause in DML statements.
We can use this in an INSERT ... SELECT statement to capture all the inserted identity values.

Create an Employee table

CREATE TABLE [dbo].[tbl_employee]
  (
     [serial]      [INT] IDENTITY(1, 1) NOT NULL,
     [empname]     [VARCHAR](50) NULL,
     [empsal]      [VARCHAR](50) NULL,
     [emplocation] [VARCHAR](50) NULL
  ) 


Create a stored procedure to get the identity value

CREATE PROCEDURE [dbo].[Temp]
AS
  BEGIN
      -- Declare table variable to hold results
      DECLARE @Temp TABLE
        (
           serial INT
        )

      -- Insert into table with IDENTITY column      
      INSERT INTO [Temp].[dbo].[tbl_employee]
                  ([empname],
                   [empsal],
                   [emplocation]) 


      -- Use OUTPUT clause to retrieve new value 
      output      inserted.serial
      INTO @Temp(serial)
      VALUES      ('emp1',
                   '15000',
                   'Hyderabad')

      --Select the identity value
      SELECT serial
      FROM   @Temp
  END  


If you execute the above stored procedure you will get the identity of the last inserted row.

EXEC [dbo].[Temp]  

Serial
------------------------------------------------------------
  1

EXEC [dbo].[Temp]  

Serial
------------------------------------------------------------
  2

EXEC [dbo].[Temp]  

Serial
------------------------------------------------------------
  3




Thursday, 17 October 2013

How to check string is number or not in C#


Method
public static Boolean IsNumeric(string stringToTest)
{
    int result;
    return int.TryParse(stringToTest, out result);
}

Usage
bool result = IsNumeric("value"); //result is false
bool result = IsNumeric("1234"); //result is true


Tuesday, 8 October 2013

No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.

How to Resolve No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type error in C#.NET?

You will get this type of problems when you pass Direct control ( TextBox ) as SQLParameter value.

EX:

 protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = WebConfigurationManager.AppSettings["ConnectionString"];
        SqlCommand cmd=new SqlCommand("insert into register values(@name,@address,@password,@confirmpassword)",con);  
        cmd.Parameters.AddWithValue("@name",TextBox1);
        cmd.Parameters.AddWithValue("@address", TextBox2);
        cmd.Parameters.AddWithValue("@password", TextBox3);
        cmd.Parameters.AddWithValue("@confirmpassword", TextBox4);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }

If you observe the above code you are passing the TextBoxes as SQLParameter values.

You should pass the values of the Controls to SQLParameter as follows. 

 protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = WebConfigurationManager.AppSettings["ConnectionString"];
        SqlCommand cmd=new SqlCommand("insert into register values(@name,@address,@password,@confirmpassword)",con);  
        cmd.Parameters.AddWithValue("@name",TextBox1.Text);
        cmd.Parameters.AddWithValue("@address", TextBox2.Text);
        cmd.Parameters.AddWithValue("@password", TextBox3.Text);
        cmd.Parameters.AddWithValue("@confirmpassword", TextBox4.Text);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }