Translate

Wednesday 21 May 2014

Assembly

What is a .NET assembly?

An assembly is the primary building block of a .NET application and can take the form of a dynamic link library (DLL) or executable file (EXE). An assembly is a collection of functionality that is built, versioned, and deployed as a single implementation unit.

What does an assembly contain?

A .NET assembly may contain the following elements:
  1. Assembly Manifest – Metadata that describes the assembly and its contents (see below)
  2. Source Code – Compiled into Microsoft intermediate language (MSIL)
  3. Type Metadata – Defines all types, their properties and methods,classes, interfaces, enums, structs and most importantly, public types exported from this assembly
  4. Resources – Icons, images, text strings and other resources
The assembly manifest is required; the other elements are optional.

What is an assembly manifest?

An assembly manifest is metadata inside an assembly that describes everything there is to know about the assembly and its contents. The manifest contains:
  • Strong Name – The assembly’s name, version, culture, optional processor architecture, and public key (for shared assemblies)
  • File Contents – Name and hash of all files in the assembly
  • Type List - Types defined in the assembly, including public types that are exported from the assembly
  • Resource List – Icons, images, text strings and other resources contained in the assembly
  • Dependencies – Compile-time dependencies on other assemblies
  • Security – Permissions required for the assembly to run properly
MISL code is executed through CLR (it cannot be directly executed)
 .NET 3 types of Assemblies are available,

it is classified as,

1. Private Assemblies
2. Shared Assemblies (public Assembly)
3. Satellite Assembly

Private Assemblies

A private assembly is used only by a single application and is stored in that application's directory other wise in the application's sub directory.

There is no version constraint in private assembly.


If an assembly is copied in to the respective application in which we would like to use is known as local assembly. if any changes made to the copy that will not reflect the copies in other applications.


 Public Assemblies


  • It resides in GAC, so that anyone can use this assembly. Public assemblies are always share the common.
  • It has version constraint.
  • This public assembly is stored inside the global assembly cache or GAC.GAC contains a collection of shared assemblies.
  • If an assembly is copied into the global place and reference is used from all other applications then this is called public or global assembly..if we want to copy assembly in global place we have to create strong name by using sn.exe.
Satellite Assembly

A satellite assembly is defined as an assembly with resources only, no executable code.

Satellite assemblies are used to build multi-linguistic applications. Application which has built in supportive of more than one human readable language is known as multi-linguistic applications.
  • Satellite Assemblies doesn’t contain any Data
  • Satellite assembly is containing cultural information.
  • Satellite assembly mainly used for to display information based on the Cultural setting of browser or region.

What is the difference between a private and shared assembly?

A private assembly is used only by a single application and is stored in that application's directory other wise in the application's sub directory. The name of a private assembly name must be unique within the application that uses it. There is no version constraint in private assembly. 
A shared assembly is used by multiple applications and is typically stored in a global folder known as the Global Assembly Cache (GAC). When building an assembly, a developer must specifically choose to build it as a shared assembly by giving it a cryptographically strong name. For example, the .NET Framework is a collection of shared assemblies.

What is the difference between an assembly and a namespace?

Namespaces are logical, whereas assemblies are physical.
A namespace is a logical naming scheme to group related types. Namespaces can contain other namespaces to form a hierarchy. The “fully qualified name” of a type is its namespace followed by its type name, separated by a period (for example, System.Windows.Forms.Button). Type names must be unique within a namespace, but the same type name can be used in different namespaces.
An assembly is a physical deployment scheme to group related types. An assembly can contain one or many namespaces. A namespace can exist in one or many assemblies.

What is the Difference between Assembly and DLL?

DLL is a dynamically linked library. Although, assemblies are physically equal to DLLs, they are very different internally. It is not possible to maintain consistency between a set of DLLs, but the CLR can maintain consistency between a set of assemblies, because assemblies are self-describing (they contain the list of dependencies internally). Unlike for DLLs, versioning information is enforced for assemblies (by the CLR). Side-by-side deployment (different applications using different versions) is possible with assemblies.








ASP.NET

How to use mode "Windows"?

Change the authentication mode to Windows.
Windows Authentication mode provides the developer to authenticate a user based on Windows user accounts. This is the default authentication mode provided by ASP.Net. You can easily get the Identity of the user by using User.Identity.Name. This will return the computer name along with the user name. Windows authentication also provides IsInRole method to find the role of the user and than you can give permissions to the user depending on the role.
<authentication mode="Windows">
  <forms name=" AuthenticationDemo" loginUrl="logon.aspx" protection="All" path="/" timeout="30"/>
</authentication>

Deny access to the anonymous user in the <authorization> section as follows:

<authorization>
     <deny users ="?" />
    <allow users = "*" />
</authorization>

Other you can make a special client to access you project with windows authentication. Code like this (this case you can get value using 'User.Identity.Name', then you can use it to do other work you like.):

<authorization>
     <deny users ="?" />
</authorization>

How to use mode "Forms"?
Change the authentication mode to Forms.
Insert the <Forms> tag, and fill the appropriate attributes. (For more information about these attributes, refer to the MSDN documentation)
First you should specify a page and make sure all clients can found it. Code like this
<authentication mode="Forms">
    <forms name=" AuthenticationDemo" loginUrl="logon.aspx" protection="All" path="/" timeout="30"/>
</authentication>

Deny access to the anonymous user in the <authorization> section as follows:

<authorization>
    <deny users ="?" />
</authorization>

Second in that page you to validate the user's Id and Password. Code like this:
You can use one of two methods to generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event. Sample code is provided for both scenarios. Use either of them according to your requirement.
(1). Call the RedirectFromLoginPage method to automatically generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event:
private void cmdLogin_ServerClick(object sender, System.EventArgs e)
{

     If (ValidateUser(txtUserName.Value,txtUserPass.Value) )
     {
          FormsAuthentication.RedirectFromLoginPage(txtUserName.Value, false);
     }
     else
     {
          Response.Redirect("logon.aspx"true);
     }
}

(2). Generate the authentication ticket, encrypt it, create a cookie, add it to the response, and redirect the user. This gives you more control in how you create the cookie. You can also include custom data along with the FormsAuthenticationTicket in this case.

Private void cmdLogin_ServerClick(object sender, System.EventArgs e)
{
    if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
    {
        FormsAuthenticationTicket tkt;
        string cookiestr;
        HttpCookie ck;
        tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
        cookiestr = FormsAuthentication.Encrypt(tkt);
        ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
       
        if (chkPersistCookie.Checked)
        ck.Expires=tkt.Expiration;   
        ck.Path = FormsAuthentication.FormsCookiePath;
        Response.Cookies.Add(ck);
        string strRedirect;
        strRedirect = Request["ReturnUrl"];
       
        if (strRedirect==null)
        strRedirect = "default.aspx";
        Response.Redirect(strRedirect, true);
    }
    else
    Response.Redirect("logon.aspx"true);
}


Windows Authentication 

Windows Authentication provider is the default authentication provider for ASP.NET applications. When a user using this authentication logs in to an application, the credentials are matched with the Windows domain through IIS. 

There are 4 types of Windows Authentication methods: 
1) Anonymous Authentication - IIS allows any user 
2) Basic Authentication - A windows username and password has to be sent across the network (in plain text format, hence not very secure). 
3) Digest Authentication - Same as Basic Authentication, but the credentials are encrypted. Works only on IE 5 or above 
4) Integrated Windows Authentication - Relies on Kerberos technology, with strong credential encryption 

Forms Authentication - This authentication relies on code written by a developer, where credentials are matched against a database. Credentials are entered on web forms, and are matched with the database table that contains the user information. 
-----------------------------------------------------------------------------------
  • Session is used to store per-user information for the current Web session on the server. It supports using a database server as the back-end store.
  • Cookie should be used to store per-user information for the current Web session or persistent information on the client, therefore client has control over the contents of a cookie.
  • Cache object is shared between users in a single application. Its primary purpose is to cache data from a data store and should not be used as a primary storage. It supports automatic invalidation features.
  • Application object is shared between users to store application-wide state and should be used accordingly.
Cookies:

There two type of cookies in ASP.NET

 Persistent cookies:
cookies are stored on your computer hard disk. They stay on your hard disk and can be accessed by web servers until they are deleted or have expired.

Non-persistent cookies:
cookies are saved only while your web browser is running. They can be used by a web server only until you close your browser. They are not saved on your disk.
------------------------------------------------------------------------------------


The default Global.asax file template includes five methods within a server-side <script> tag:
  • Application_Start executes when the web application first starts
  • Application_End runs when the application is shutting down
  • Application_Error executes whenever an unhandled exception reaches the application
  • Session_Start executes when a new session is created
  • Session_End runs when a session is expired or abandoned
-------------------------------------------------------------------------------------

Difference between response.redirect and server.transfer 

Response.Redirect should be used when:
  • we want to redirect the request to some plain HTML pages on our server or to some other web server
  • we don't care about causing additional roundtrips to the server on each request
  • we do not need to preserve Query String and Form Variables from the original request
  • we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if its necessary)
Server.Transfer should be used when:

Wednesday 14 May 2014

Upload CSV file to SQL server (Bulk Upload)

In general you can achieve it in two steps
1) step is to read the CSV file and hold it as a DataTable.
2) step Store the retrieved file into SQL Table as a Bulk Entry
This is a function that returns CSV File Data as a Datatable. call and get it, and in the end do whatever you want
This function is going to return CSV Read file into DataTable.
private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
    {
        DataTable csvData = new DataTable();
        try
        {
          using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
             {
                csvReader.SetDelimiters(new string[] { "," });
                csvReader.HasFieldsEnclosedInQuotes = true;
                string[] colFields = csvReader.ReadFields();
                foreach (string column in colFields)
                {
                    DataColumn datecolumn = new DataColumn(column);
                    datecolumn.AllowDBNull = true;
                    csvData.Columns.Add(datecolumn);
                }
                while (!csvReader.EndOfData)
                {
                    string[] fieldData = csvReader.ReadFields();
                    //Making empty value as null
                    for (int i = 0; i < fieldData.Length; i++)
                    {
                        if (fieldData[i] == "")
                        {
                            fieldData[i] = null;
                        }
                    }
                    csvData.Rows.Add(fieldData);
                }
            }
        }
        catch (Exception ex)
        {
        }
        return csvData;    
  }
SQLBulkCopy - Use this function to insert the Retrieved DataTable into Sql Table
protected void InsertDataIntoSQLServerUsingSQLBulkCopy(DataTable csvFileData)
{    
         Con.Open();
         using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
         {
             s.DestinationTableName = "Your table name";
             foreach (var column in csvFileData.Columns)
             s.ColumnMappings.Add(column.ToString(), column.ToString());
             s.WriteToServer(csvFileData);
         }
        Con.Close();
 }
Ref:http://www.morgantechspace.com/2013/10/import-csv-file-into-sql-server-using.html