Tuesday, 16 June 2015

Constructor and its types

Constructor

  1. It is a method of the class which automatically invoked when an instance of the class is created.
  2. Used for initializing private fields of the class while creating an instance for the class.
  3. If Constructor not created then compiler automatically create a default constructor in the class.
  4. Default constructor initializes all numeric fields in the class to zero and all string and object to null.
Key points of constructor are:
  1. A class can have any number of constructors.
  2. A constructor doesn't have any return type, not even void.
  3. A static constructor can not be a parametrized constructor.
  4. Within a class you can create only one static constructor. 
Types of Constructor are :
  1. Default constructor
  2. Parametrized constructor
  3. Copy Constructor
  4. Static Constructor
  5. Private constructor

Default Constructor

  1. Constructor without any parameters.
  2. Every instance of the class initialized to the same values.
  3. All numeric fields in the class initialized to zero.
  4. All string and objects fields initialized to null.
Example :

using System;
namespace
 DefaultConstractor
 {
    class addition
    {
        int a, b; 
        public addition()   //default contructor
        {
            a = 100;
            b = 175;
        }
        public static void Main()
        {
            addition obj = new addition(); //an object is created , constructor is called
            Console.WriteLine(obj.a);
            Console.WriteLine(obj.b);
            Console.Read();
        }
      }
    }

  Parametrized Constructor

  1. A Constructor with at least one parameter.
  2. We can initialize each instance of the class to different values.
Example:
using System;

namespace Constructor

{
    class paraconstrctor    {
      public  int a, b;
      public paraconstrctor(int x, int y)  // decalaring Paremetrized Constructor with passing x,y parameter

        {
            a = x;
            b = y;
        }
   }
    class MainClass
    {
        static void Main()
        {
            paraconstrctor v = new paraconstrctor(100, 175);   // Creating object of Parameterized Constructor and passing values 
            Console.WriteLine("-----------parameterized constructor example by vithal wadje---------------");
            Console.WriteLine("\t");
            Console.WriteLine("value of a=" + v.a );
            Console.WriteLine("value of b=" + v.b);
            Console.Read();
        }
    }
}

Copy Constructor

  1. This Constructor creates an object by copying variables from another object.
  2. Copy constructor  initializes a new instance to the values of an existing instance.
Syntax
public employee(employee emp)
{
name=emp.name;
age=emp.age;
}

The copy constructor is invoked by instantiating an object of type employee and passing it the object to be copied.

Example
employee emp1=new  employee (emp2); Now, emp1 is a copy of emp2. 

So let us see its practical implementation.
using System;

namespace copyConstractor

{
    class employee
    {
        private string name;
        private int age;
        public employee(employee emp)   // declaring Copy constructor.
        {
            name = emp.name;
            age = emp.age;
        }
        public employee(string name, int age)  // Instance constructor.
        {
            this.name = name;
            this.age = age;
        }
        public string Details     // Get deatils of employee
        {
            get
            {
                return  " The age of " + name +" is "+ age.ToString();
            }
        }
    }
    class empdetail
    {
        static void Main()
        {
            employee emp1 = new employee("Vithal", 23);  // Create a new employee object.

            employee emp2 = new employee(emp1);          // here is emp1 details is copied to emp2.

            Console.WriteLine(emp2.Details);
            Console.ReadLine();
        }
    }
}

Static Constructor

  1. A static constructor does not have parameters.
  2. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  3. A static constructor cannot be called directly.
Syntax
class employee
 {// Static constructor
  static employee(){}
 }

Now let us see it with practically
using System;
namespace staticConstractor
{
public class employee
{
    static employee() // Static constructor declaration{Console.WriteLine("The static constructor ");
}
public static void Salary()
 {
    Console.WriteLine();
    Console.WriteLine("The Salary method");
 }
}
class details
{
    static void Main()
    {
        Console.WriteLine("----------Static constrctor example by vithal wadje------------------");
        Console.WriteLine();
        employee.Salary();
        Console.ReadLine();
    }
  }
}

Private Constructor

  1. When a constructor is created with a private specifier, it is not possible for other classes to drive from this class,neither is it possible to create an instance of this class.
  2. They are used in classes that contain static members only.
  3. We can create instance of this class by creating one public constructor.
  4. It provides an implementation of a singleton class pattern.
Example : 
using System;
namespace defaultConstractor
{
    public class Counter
    {
        private Counter()   //private constrctor declaration
        {
        }
        public static int currentview;
        public static int visitedCount()
        {
            return ++ currentview;
        }
    }
    class viewCountedetails
    {
        static void Main()
        {
            // Counter aCounter = new Counter();   // Error
            Console.WriteLine("-------Private constructor example by vithal wadje----------");
            Console.WriteLine();
            Counter.currentview = 500;
            Counter.visitedCount();
            Console.WriteLine("Now the view count is: {0}", Counter.currentview);
            Console.ReadLine();
        }
    }
}














Sunday, 14 June 2015

SqlCommand Object


SqlCommand Object

  1. A SqlCommand object allows you to specify what type of interaction you want to perform with a database.
  2. For example insert, update, delete and get commands on rows in a database table.
  3. SqlCommand object can be used with the disconnected and connected approach.

Creating a SqlCommand object

SqlCommand cmd = new SqlCommand("Select Category from Categories", conn);

It takes string parameter that holds the command you want to execute and a reference to a SqlConnection object.

Querying Data

When using a SQL select command, you retrieve a data set for viewing.
To get the results send by the query we can use the sqlCommand object's function ExecuteReader which returns the SqlDataReader object.

// 1. Instantiate a new command with a query and connection
SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);

// 2. Call Execute reader to get query results
SqlDataReader rdr = cmd.ExecuteReader();



Inserting Data

To insert data into database use the ExecuteNonQuery  method of the SqlCommand object.

 
// prepare command string
 
string insertString = @"
     insert into Categories
     (CategoryName, Description)
     values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')";

 // 1. Instantiate a new command with a query and connection
 
SqlCommand cmd = new SqlCommand(insertString, conn);

 // 2. Call ExecuteNonQuery to send command
 
cmd.ExecuteNonQuery();


 
ExecuteNonQuery method returns number of affected records.

 
Updating data

The executeNonQuery method is also used for updating data.

// prepare command string
 
string updateString = @"
     update Categories
     set CategoryName = 'Other'
     where CategoryName = 'Miscellaneous'";
 
 // 1. Instantiate a new command with command text only
 
SqlCommand cmd = new SqlCommand(updateString);
 
 // 2. Set the Connection property
 
cmd.Connection = conn;
 
 // 3. Call ExecuteNonQuery to send command
 
cmd.ExecuteNonQuery();


Deleting Data


You can also used ExecuteNonQuery method for deleting data.
// prepare command string
 
string deleteString = @"
     delete from Categories
     where CategoryName = 'Other'";
 
 // 1. Instantiate a new command
 
SqlCommand cmd = new SqlCommand();
 
 // 2. Set the CommandText property
 
cmd.CommandText = deleteString;
 
 // 3. Set the Connection property
 
cmd.Connection = conn;
 
 // 4. Call ExecuteNonQuery to send command
 
cmd.ExecuteNonQuery();


This example uses the SqlCommand constructor with no parameters. Instead, it explicitly sets the CommandText and Connection properties of the SqlCommand object, cmd.


Getting Single values
  1. Sometimes we need single value from the database which could be a count, Sum, average, or other aggregated value.
  2. For getting single value from the database you can use ExecuteScaler method of the sqlCommand object.

// 1. Instantiate a new command
 
SqlCommand cmd = new SqlCommand("select count(*) from Categories", conn);
 
 // 2. Call ExecuteNonQuery to send command
 
int count = (int)cmd.ExecuteScalar();



Putting it All Together


 using System;
 using System.Data;
 using System.Data.SqlClient;

 /// <summary>
 ///
Demonstrates how to work with SqlCommand objects
 
/// </summary>
 
class SqlCommandDemo
 {
     SqlConnection conn;
 
 
    public SqlCommandDemo()
     {
         // Instantiate the connection
 
        conn = new SqlConnection(
            "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
     }
 
 
    // call methods that demo SqlCommand capabilities
 
    static void Main()
     {
         SqlCommandDemo scd = new SqlCommandDemo();

         Console.WriteLine();
         Console.WriteLine("Categories Before Insert");
         Console.WriteLine("------------------------");
 
 
        // use ExecuteReader method
 
        scd.ReadData();
 
 
        // use ExecuteNonQuery method for Insert
 
        scd.Insertdata();
         Console.WriteLine();
         Console.WriteLine("Categories After Insert");
         Console.WriteLine("------------------------------");

        scd.ReadData();

         // use ExecuteNonQuery method for Update
 
        scd.UpdateData();

         Console.WriteLine();
         Console.WriteLine("Categories After Update");
         Console.WriteLine("------------------------------");

         scd.ReadData();

         // use ExecuteNonQuery method for Delete
 
        scd.DeleteData();

         Console.WriteLine();
         Console.WriteLine("Categories After Delete");
         Console.WriteLine("------------------------------");

         scd.ReadData();

         // use ExecuteScalar method
 
        int numberOfRecords = scd.GetNumberOfRecords();

         Console.WriteLine();
         Console.WriteLine("Number of Records: {0}", numberOfRecords);
     }

     /// <summary>
 
    /// use ExecuteReader method
 
    /// </summary>
 
    public void ReadData()
     {
        SqlDataReader rdr = null;
 
 
        try
 
        {
             // Open the connection
 
            conn.Open();
 
 
            // 1. Instantiate a new command with a query and connection
 
            SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);
 
 
            // 2. Call Execute reader to get query results
 
            rdr = cmd.ExecuteReader();

             // print the CategoryName of each record
 
            while (rdr.Read())
             {
                 Console.WriteLine(rdr[0]);
             }
         }
         finally
 
        {
             // close the reader
 
            if (rdr != null)
             {
                 rdr.Close();
             }
 
 
            // Close the connection
 
            if (conn != null)
             {
                 conn.Close();
             }
         }
     }

     /// <summary>
 
    /// use ExecuteNonQuery method for Insert
 
    /// </summary>
 
    public void Insertdata()
     {
         try
 
        {
             // Open the connection
 
            conn.Open();
 
 
           // prepare command string
 
           string insertString = @"
                 insert into Categories
                 (CategoryName, Description)
                 values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')";
 
 
            // 1. Instantiate a new command with a query and connection
 
            SqlCommand cmd = new SqlCommand(insertString, conn);
 
 
            // 2. Call ExecuteNonQuery to send command
 
            cmd.ExecuteNonQuery();
         }
         finally
 
        {
             // Close the connection
 
            if (conn != null)
             {
                 conn.Close();
             }
         }
     }
 
 
    /// <summary>
 
    /// use ExecuteNonQuery method for Update
 
    /// </summary>
 
    public void UpdateData()
     {
         try
 
        {
             // Open the connection
 
           conn.Open();
 
 
            // prepare command string
 
            string updateString = @"
                 update Categories
                 set CategoryName = 'Other'
                 where CategoryName = 'Miscellaneous'";
 
 
           // 1. Instantiate a new command with command text only
 
            SqlCommand cmd = new SqlCommand(updateString);

             // 2. Set the Connection property
 
            cmd.Connection = conn;
 
 
            // 3. Call ExecuteNonQuery to send command
 
            cmd.ExecuteNonQuery();
        }
         finally
 
        {
             // Close the connection
 
           if (conn != null)
             {
                 conn.Close();
             }
         }
     }
 
 
    /// <summary>
 
    /// use ExecuteNonQuery method for Delete
 
    /// </summary>
 
    public void DeleteData()
     {
         try
 
       {
             // Open the connection
 
            conn.Open();
 
 
            // prepare command string
 
            string deleteString = @"
                 delete from Categories
                 where CategoryName = 'Other'";
 
 
            // 1. Instantiate a new command
 
            SqlCommand cmd = new SqlCommand();
 
 
           // 2. Set the CommandText property
 
            cmd.CommandText = deleteString;
 
 
           // 3. Set the Connection property
 
            cmd.Connection = conn;
 
 
            // 4. Call ExecuteNonQuery to send command
 
            cmd.ExecuteNonQuery();
         }
         finally
 
        {
             // Close the connection
 
            if (conn != null)
             {
                 conn.Close();
             }
         }
     }

     /// <summary>
 
    /// use ExecuteScalar method
 
    /// </summary>
 
    /// <returns>number of records</returns>
 
    public int GetNumberOfRecords()
     {
         int count = -1;
 
 
       try
 
       {
             // Open the connection
 
            conn.Open();
 
 
            // 1. Instantiate a new command
 
            SqlCommand cmd = new SqlCommand("select count(*) from Categories", conn);
 
 
            // 2. Call ExecuteScalar to send command
 
            count = (int)cmd.ExecuteScalar();
         }
         finally
 
        {
            // Close the connection
 
            if (conn != null)
             {
                 conn.Close();
             }
         }
         return count;
     }
 }








 

ADO.NET Introduction and SqlConnection Object

ADO.NET is an object-oriented set of libraries that allows to interact with the data sources.
Data source are mostly data based but it could be an excel sheet, text file or xml file.

Data providers

  1. ADO.NET provides a common way to interact with the data sources.
  2. It comes in different sets of libraries and these libraries are called Data Providers.

Examples of Data providers
  1. ODBC Data provider -- used in older databases
  2. OleDB Data provider -  used in MS Access  or Excel
  3. Oracle Data provider -  used for oracle databases
  4. SQL    Data provider - used for Microsoft sql server
  5. Borland Data provider - Generic access to many databases such as interbase, Sql Server, IBM DB2, and Oracle.

SqlConnection object

  1. SqlConnection object is used to create a connection with the database which can be located over the LAN or over the internet.
  2. Sql connection object enable other ADO.NET code to work with the database.
  3. Other ADO.NET objects us connection object as parameter.

The sequence of operations occur in the llfe of sqlConnection are as follows :
  1.  Instantiate the sql connection
  2.  Open the connection
  3.  pass the connection to other ADO.NET objects.
  4.  Perform the database operations
  5.  Close the connection.

Connection string

  1. Connection string is a key value pairs for specifying how to make a database connection.
  2. It includes the location, Name of the database and security credentials.

Connection string parameters
  1. Data source - Identifies the server
  2. Initial Catalog - Database name
  3. Integrated security - set to sspi to make connection with user's windows login
  4. User ID - Name of user configured in sql server
  5. Password - Password matching SQL Server User Id
Integrated security

Integrated security is secure when we are on a single machine doing development.

   SqlConnection conn = new SqlConnection(
        "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");

 Sql server security

Sql server security is secure when database located on a different machine, over a LAN, or over the internet. User ID and password replace the integrated security parameters

SqlConnection conn = new SqlConnection(
        "Data Source=DatabaseServer;Initial Catalog=Northwind;User ID=YourUserID;Password=YourPassword");

Example :

using System;
using System.Data;
using System.Data.SqlClient;

/// <summary>
///
Demonstrates how to work with SqlConnection objects
/// </summary>
class SqlConnectionDemo
{
    static void Main()
    {
        // 1. Instantiate the connection
        SqlConnection conn = new SqlConnection(
            "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");

        SqlDataReader rdr = null;

        try
        {
            // 2. Open the connection
            conn.Open();

            // 3. Pass the connection to a command object
            SqlCommand cmd = new SqlCommand("select * from Customers", conn);

            //
            // 4. Use the connection
            //

            // get query results
            rdr = cmd.ExecuteReader();

            // print the CustomerID of each record
            while (rdr.Read())
            {
                Console.WriteLine(rdr[0]);
            }
        }
        finally
        {
            // close the reader
            if (rdr != null)
            {
                rdr.Close();
            }

            // 5. Close the connection
            if (conn != null)
            {
                conn.Close();
            }
        }
    }
}







Saturday, 13 June 2015

CTE, Temp table, Global temp table, Table variable


CTE
  1. CTE is Common table expression
  2. Temporary result set
  3. Used for storing result of complex queries
  4. This table available only for the current query
When to use
To store result of complex queries
To create recursive query
Example:
    ;With CTE1(Name, Roll, Age)--Params are optional AS ( SELECT Student.Name, Student.Roll, Student.Age from Student ) SELECT * FROM CTE1 --Using CTE WHERE CTE1.Age > 50 ORDER BY CTE1.NAME

Local Temp Table

  1. This table available only for one sql server session or connection that created this table.
  2. Drop automatically when session ends or connection close.
  3. These tables are available to one tab only once created
  4. These table starts with # sign
Example:
    CREATE TABLE #LclTmp ( ID int, Name varchar(50), Address varchar(150) ) GO insert into #LclTmp values ( 1, 'Tejpal','jammu'); GO Select * from #LclTmp

Global Temp table

  1. This table available for all sql server sessions or connections.
  2. Drop automatically when all sessions have been closed.
  3. These tables are available to all tabs of sql server once created.
  4. These table starts with Double ## sign.
Example:
        CREATE TABLE ##GblTmp
        (
        UserID int,
        Name varchar(50),
        Address varchar(150)
        )
        GO
        insert into ##GblTmp values ( 1, 'Tejpal','jammu');
        GO
        Select * from ##GblTmp

Table variable

  1. This table available for a group of query execution.
  2. Drop automatically when all the queries of the group are executed
  3. These tables are declared with @ sign
Example:
        GO
        DECLARE @TableVariable TABLE
        (
        Id INT IDENTITY(1,1),
        GoodsID INT,
        Quantity INT
        )
        --Insert data to Table variable @Tablevariable
        INSERT INTO @TableVariable(GoodsId,Quantity)
        SELECT DISTINCT ID, Quantity FROM GoodsSales ORDER BY GoodsID ASC
        --Select data
        Select * from @Tablevariable

        --Next batch
        GO
        Select * from @TableVariable--gives error in next batch  


Saturday, 4 April 2015

Ajax helpers


  1. Ajax helpers are used to create ajax enabled elements same as we create ajax enabled forms and links which perform requests asynchronously.
  2. Ajax helpers are extension methods of Ajax helper class which exists in System.Web.Mvc namespace.
  3. Ajax enabled means based on controller and action.
For Example :

@Ajax.ActionLink("Load Goods", "GetGoods", new AjaxOptions {UpdateTargetId = "Goods-container", HttpMethod = "GET" }) 

HTML Output

<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#Goods-container" href="/Home/GetGoods">Load Goods</a>

Properties for AJAX Helpers


Url
Specify the URL that will be requested from the server.
 
Confirm 
Specify a message that will be displayed in a confirm dialog to the end user. When user clicks on OK button in the confirmation dialog, the Ajax call performs.
 
OnBegin
Specify a JavaScript function name which is called at the beginning of the Ajax request.
 
OnComplete
Specify a JavaScript function name which is called at the end of the Ajax request.
 
OnSuccess
Specify a JavaScript function name which is called when the Ajax request is successful.
 
OnFailure
Specify a JavaScript function name which is called if the Ajax request fails.
 
LoadingElementId
Specify progress message container’s Id to display a progress message or animation to the end user while an Ajax request is being made.
 
LoadingElementDuration
Specify a time duration in milliseconds that controls the duration of the progress message or animation.
 
UpdateTargetId
Specify the target container’s Id that will be populated with the HTML returned by the action method.
 
InsertionMode
Specify the way of populating the target container. The possible values are InsertAfter, InsertBefore and Replace (which is the default).





MVC Html Helpers



  1. In Mvc html helpers are much like ASP.NET web form controls.
  2. Html helpers are used to modify HTML But these helpers are very light weight.
  3. Html helpers does not have a view state and a event modal but we have in web form controls.
  4. Html helper basically a method that returns a string.
  5. In MVC we can the inbuild html helpers or we can create our own helpers.

Standard HTML Helpers

  1. HTML Links
  •  The standard way to use the HTML link in MVC is by using the HTML.ActionLink() helper. 
  • With MVC Action Link create a link to the controller Action. 
  For example :
@Html.ActionLink("About this Project", "About")

HTML output
<a href="/Home/About">About this Project</a>

Also we can pass the parameter value to the action
@Html.ActionLink("Delete Record", "Delete", new {Id=2})

HTML Output
<a href="/Home/Delete/3">Delete Record</a>

HTML Form Elements

The following html heplers are used to render(modify and output) html form elements : 

  • BeginForm()
  • EndForm()
  • TextArea()
  • TextBox()
  • CheckBox()
  • RadioButton()
  • ListBox()
  • DropDownList()
  • Hidden()
  • Password()
ASP.NET Syntax C#:

<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()){%>

<label for="FirstName">First Name:</label>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>

<label for="LastName">Last Name:</label>
<%= Html.TextBox("LastName") %>
<%= Html.ValidationMessage("LastName", "*") %>

<label for="Password">Password:</label>
<%= Html.Password("Password") %>
<%= Html.ValidationMessage("Password", "*") %>

<label for="Password">Confirm Password:</label>
<%= Html.Password("ConfirmPassword") %>
<%= Html.ValidationMessage("ConfirmPassword", "*") %>

<label for="Profile">Profile:</label>
<%= Html.TextArea("Profile", new {cols=60, rows=10})%>

<%= Html.CheckBox("Receiveletter") %>
<label for="Receiveletter" style="display:inline">Receive letter?</label>

<input type="submit" value="Register" />

<%}%>



 



Thursday, 26 March 2015

Difference between MVC1, MVC2, MVC3, MVC4, MVC5 and MVC6



MVC 1

  1. Launched on 13 March 2009
  2. MVC 1 runs on .Net framework 3.5 and with visual studio 2008
  3. It has MVC pattern Architecture with web form engine
  4. HTML Helpers ( Reference Link)
  5. Ajax Helpers (Reference Link)
  6. Routing (Reference Link)
  7. We can do Unit Testing on it

MVC 2

  1.  Launched on 10 March 2010
  2.  MVC 2 runs on .Net framework 3.5,4.0 and with visual studio 2008,2010
  3.  Lamda expression Html helpers which are strongly typed. (Reference Link)
  4. Templated helpers (Reference Link)
  5. Data annotation attribute support 
  6. Client side validation
  7. UI helpers for automatic scaffolding and customizable template
  8. For both client and server attribute based modal validation
  9. Override the HTTP Method Verb including GET, PUT, POST, and DELETE
  10. Area for partitioning a large application into modules
  11. Asynchronous controllers

 MVC 3

  1.  Launched on 13 Jan 2011
  2.  MVC3 Runs on .Net 4.0 and with Visual Studio 2010
  3.  Razor view engine
  4. Data Annotation support is improved
  5. Remote validation
  6. Compare attribute
  7. Sessionless controller
  8. Child Action output caching
  9. Dependency Resolver
  10. Entity framework code first support
  11. Partial page output caching
  12. ViewBag dynamic property for passing data from controller to view
  13. Global Action Filters
  14. Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding
  15. Use of NuGet to deliver software and manage dependencies throughout the platform
  16. Good Intellisense support for Razor into Visual Studio

 For more details go to the following links :

 http://www.dotnet-tricks.com/Tutorial/mvc/XWX7210713-A-brief-history-of-Asp.Net-MVC-framework.html

http://www.dotnetinterviewquestions.in/article_what-is-the-difference-between-each-version-of-mvc-2-3-4-5-and-6-mvc-interview-questions_247.html