Monday, 21 October 2013

Difference between Asp.Net WebForm and Asp.Net MVC

Asp.net framework is a part of .net platform for building, deploying and running web applications. Now, we can develop a web application by using Asp.Net Web Form and Asp.Net MVC. In this article, I am going to expose the main difference between Asp.Net Web Form and Asp.Net MVC.


Difference between Asp.Net MVC and Web Forms
Asp.Net Web Forms
1.    Asp.Net Web Form follow a traditional event driven development model.
2.    Asp.Net Web Form has server controls.
3.    Asp.Net Web Form has state management (like as view state, session) techniques.
4.    Asp.Net Web Form has file-based URLs means file name exist in the URLs must have its physically existence.
5.    Asp.Net Web Form follows Web Forms Syntax
6.    In Asp.Net Web Form, Web Forms(ASPX) i.e. views are tightly coupled to Code behind(ASPX.CS) i.e. logic.
7.    Asp.Net Web Form has Master Pages for consistent look and feels.
 8.    Asp.Net Web Form has User Controls for code re-usability.
9.    Asp.Net Web Form has built-in data controls and best for rapid development with  powerful data access.
10.Asp.Net Web Form is not Open Source.
11.Visual studio and Visual web developer(free) are tools for developing Asp.Net Web Forms.


Asp.Net MVC
1.    Asp.Net MVC is a lightweight and follow MVC (Model, View, Controller) pattern based development model.
2.    Asp.Net MVC has html helpers.
3.    Asp.Net MVC has no automatic state management techniques.
4.    Asp.Net MVC has route-based URLs means URLs are divided into controllers and actions and moreover it is based on controller not on physical file.
5.    Asp.Net MVC follow customizable syntax (Razor as default)
6.    In Asp.Net MVC, Views and logic are kept separately.
7.    Asp.Net Web Form has Layouts for consistent look and feels.

8.    Asp.Net MVC has Partial Views for code re-usability.
9.    Asp.Net MVC is lightweight, provide full control over markup and support many features that allow fast & agile development. Hence it is best for developing interactive web application with latest web standards.
10.Visual studio and Visual web developer(free) are tools for developing Asp.Net MVC application.
11.Asp.Net Web MVC is an Open Source.

What is the difference between ASP and ASP.NET?

1. ASP is interpreted, ASP.NET is compiled. 

2. Classic ASP uses a technology called ADO to connect and work with databases. ASP.NET uses the ADO.NET technology 

3. ASP has Mixed HTML and coding logic where in asp.net html and coding part are separated by code behind files. 

4. ASP.NET purely object oriented whereas ASP is partially object oriented. 

5. For ASP No in-built support for XML whereas in ASP.NET full XML Support for easy data exchange.

1. ASP: Code is Interpreted
ASP.NET: Code is Compiled

2. ASP: Business Logic and  Presentation Logic are in a sindle file
ASP.NET: Business Logic and Presentation Logic are in separate files (.cs or .vb) and (.aspx) respectively.
3. ASP: No Web Server Controls
ASP.NET: Web Server Controls supported by strong .NET Framework
4. ASP: No RAD in Classic ASP
ASP.NET: Supports RAD

1.Asp is interpreted
Asp.net is compiled which is faster than asp.
2 Asp.net maintains its own CLR and is managed as it runs by CLR
Where as asp is unmanaged
3 We can maintain sessions in state server and sql server which is Outproc,
where in asp sessions will be last if we restart webserver or make changes.
4 In asp.net we can configure each application using web.config file which is available in application itself and we have machine.config where we can configure all applications.
In asp we cannot configure single application
5 Asp.net we have autopostback event which is not in asp
6 In asp.net we have global.asax where can handle some global things which is not in asp.
7 We have well built GUI to work in asp.net
8 We have ado.net and as well as disconnected architecture in asp.net
9 We have Xcopy deployment in asp.net
10. We can work with any language as code behind technique in asp.net that supports .net frame work

a) asp.net is compiled but ASP is a interpreter or script only.
b) asp.net is supported more control then the asp.
c) asp.net is more supported even control then the asp.
d) In asp.net if update any component then no need to shutdown the computer but in asp if loaded any component then need to be shutdown the computer.
d) So lastly an asp.net is faster then asp .

Asp.net Difference between DataReader and DataSet and DataAdapter in C#, VB.NET


Description:
Now I will explain difference between datareader, dataset and dataadapter in ASP.NET
DataReader
DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch the data from database. DataReader is used to iterate through resultset that came from server and it will read one record at a time because of that memory consumption will be less and it will fetch the data very fast when compared with dataset. Generally we will use ExecuteReader object to bind data to datareader.
Sample code of datareader will be like this
C# Code
// This method is used to bind gridview from database
protected void BindGridview()
{
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName,LastName,Location FROM UserInformation", con);
SqlDataReader dr = cmd.ExecuteReader();
gvUserInfo.DataSource = dr;
gvUserInfo.DataBind();
con.Close();
}
}
VB.NET Code
This method is used to bind gridview from database
Protected Sub BindGridview()
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("Select UserName,LastName,Location FROM UserInformation", con)
Dim dr As SqlDataReader = cmd.ExecuteReader()
gvUserInfo.DataSource = dr
gvUserInfo.DataBind()
con.Close()
End Using
End Sub

DataSet
DataSet is a disconnected orient architecture that means there is no need of active connections during work with datasets and it is a collection of DataTables and relations between tables. It is used to hold multiple tables with data. You can select data form tables, create views based on table and ask child rows over relations. Also DataSet provides you with rich features like saving data as XML and loading XML data.

C# Code
// This method is used to bind gridview from database
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select UserName,LastName,Location from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
VB.NET Code
//This method is used to bind gridview from database
Protected Sub BindGridview()
Dim con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("select UserName,LastName,Location from UserInformation", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
gvUserInfo.DataSource = ds
gvUserInfo.DataBind()
End Sub
DataAdapter
DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to read the data from database and bind that data to dataset. Dataadapter is a disconnected oriented architecture. Check below sample code to see how to use DataAdapter in code

C# Code

// This method is used to bind gridview from database
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select UserName,LastName,Location from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
VB.NET Code
//This method is used to bind gridview from database
Protected Sub BindGridview()
Dim con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("select UserName,LastName,Location from UserInformation", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
gvUserInfo.DataSource = ds
gvUserInfo.DataBind()
End Sub

Difference Between DataReader, DataSet, DataAdapter and DataTable in C#

DataReader
DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch the data from database. DataReader will fetch the data very fast when compared with dataset. Generally we will use ExecuteReader object to bind data to datareader.
To bind DataReader data to GridView we need to write the code like as shown below:

Protected void BindGridview()
{
using (SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
SqlDataReader sdr = cmd.ExecuteReader();
gvUserInfo.DataSource = sdr;
gvUserInfo.DataBind();
conn.Close();
}
}
  • Holds the connection open until you are finished (don't forget to close it!).
  • Can typically only be iterated over once
  • Is not as useful for updating back to the database
DataSet
DataSet is a disconnected orient architecture that means there is no need of active connections during work with datasets and it is a collection of DataTables and relations between tables. It is used to hold multiple tables with data. You can select data form tables, create views based on table and ask child rows over relations. Also DataSet provides you with rich features like saving data as XML and loading XML data.
protected void BindGridview()
{
    SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}
DataAdapter
DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to read the data from database and bind that data to dataset. Dataadapter is a disconnected oriented architecture. Check below sample code to see how to use DataAdapter in code:
protected void BindGridview()
{
    SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}
  • Lets you close the connection as soon it's done loading data, and may even close it for you automatically
  • All of the results are available in memory
  • You can iterate over it as many times as you need, or even look up a specific record by index
  • Has some built-in faculties for updating back to the database.
DataTable 

DataTable represents a single table in the database. It has rows and columns. There is no much difference between dataset and datatable, dataset is simply the collection of datatables.
protected void BindGridview()
{
     SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
     conn.Open();
     SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
     SqlDataAdapter sda = new SqlDataAdapter(cmd);
     DataTable dt = new DataTable();
     da.Fill(dt);
     gridview1.DataSource = dt;
     gvidview1.DataBind();

}

Code for uploading in all formts:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;

public partial class Default2 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=YESTK-PC;Initial Catalog=test;Integrated Security=True");
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
      

        // Read the file and convert it to Byte Array
        string filePath = FileUpload1.PostedFile.FileName;
        string filename = Path.GetFileName(filePath);
        string ext = Path.GetExtension(filename);
        string contenttype = String.Empty;

        //Set the contenttype based on File Extension
        switch (ext)
        {
            case ".doc":
                contenttype = "application/vnd.ms-word";
                break;
            case ".docx":
                contenttype = "application/vnd.ms-word";
                break;
            case ".xls":
                contenttype = "application/vnd.ms-excel";
                break;
            case ".xlsx":
                contenttype = "application/vnd.ms-excel";
                break;
            case ".jpg":
                contenttype = "image/jpg";
                break;
            case ".png":
                contenttype = "image/png";
                break;
            case ".gif":
                contenttype = "image/gif";
                break;
            case ".pdf":
                contenttype = "application/pdf";
                break;
        }
        if (contenttype != String.Empty)
        {
            con.Open();
            Stream fs = FileUpload1.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            Byte[] bytes = br.ReadBytes((Int32)fs.Length);

            //insert the file into database
         


            SqlCommand cmd = new SqlCommand("insert into upload(name, filetype, data) values (@name, @filetype, @data)",con);
           


            cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = filename;
            cmd.Parameters.Add("@filetype", SqlDbType.VarChar).Value
              = contenttype;
            cmd.Parameters.Add("@data", SqlDbType.Binary).Value = bytes;
            //SqlDataReader dr = cmd.ExecuteReader();
            //if (dr.Read())
            //{
                Response.Write("saved");
            //}
                cmd.ExecuteNonQuery();
          
            Label1.ForeColor = System.Drawing.Color.Green;
            Label1.Text = "File Uploaded Successfully";
            con.Close();
        }
        else
        {
            Label1.ForeColor = System.Drawing.Color.Red;
            Label1.Text = "File format not recognised." +
              " Upload Image/Word/PDF/Excel formats";
        }
       
    }

}

Monday, 23 September 2013

Interview questions for C#.Net


Interview questions for C#.Net
1. What’s the top .NET class that everything is derived from?
  • System.Object.
2. Does C# support multiple-inheritance?
  • No. It supports only user interfaces.
3. Who is a protected class-level variable available to?
  • It is available to any sub-class (a class inheriting this class).
4. Are private class-level variables inherited?
  • Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.
5. Describe the accessibility modifier "protected internal" ?
  • It is available to classes that are within the same assembly and derived from the specified base class.
6. What does the term immutable mean?
  • The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
7. What’s the difference between System. String and System.Text.StringBuilder classes?
  • System. String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
8. What’s the advantage of using System.Text.StringBuilder over System. String?
  • String Builder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.
9. Can you store multiple data types in System.Array?
  • No.
10. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
  • The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The Copy To () method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identical object.
11. How can you sort the elements of the array in descending order?
  • By calling Sort() and then Reverse() methods.
12. What’s the .NET collection class that allows an element to be accessed using a unique key?
  • HashTable.
13. What class is underneath the Sorted List class?
  • A sorted Hash Table.
14. Will the finally block get executed if an exception has not occurred?
  • Yes.
15. What’s the C# syntax to catch any possible exception?
  • A catch block that catches the exception of type System. Exception. You can also omit the parameter data type in this case and just write catch {}.
16. Can multiple catch blocks be executed for a single try statement?
  • No. Once the proper catch block processed, control is transferred to the finally block (if there are any).
17. Explain the three services model commonly know as a three-tier application.
  • Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).
Questions on Classes
18. What is the syntax to inherit from a class in C#?
  • Place a colon and then the name of the base class.
    Example: Class MyNewClass : MyBaseClass
19. Can you prevent your class from being inherited by another class?
  • Yes. The keyword “sealed” will prevent the class from being inherited.
20. Can you allow a class to be inherited, but prevent the method from being over-ridden?
  • Yes. Just leave the class public and make the method sealed.
21. What’s an abstract class?
  • A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.
22. When do you absolutely have to declare a class as abstract?
  • 1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
    2. When at least one of the methods in the class is abstract.
23. What is an interface class?
  • Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.
24. Why can’t you specify the accessibility modifier for methods inside the interface?
  • They all must be public, and are therefore public by default.
25. Can you inherit multiple interfaces?
  • Yes. .NET does support multiple interfaces.
26. What happens if you inherit multiple interfaces and they have conflicting method names?
  • It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
27. What’s the difference between an interface and abstract class?
  • In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.
28. What is the difference between a Struct and a Class?
  • Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit.