Tuesday, March 31, 2015

skin file in asp.net

Skins are files with .skin extensions that contain common property settings for buttons, labels, text boxes, and other controls. Skin files resemble control markups ,but contain only the properties you want to define as part of the theme to be applied across pages.

Example
add skin file in your website
add code like(this code id for asp:Button)

<asp:Button runat="server" Font-Size="Large" ForeColor="Red" Text="Button" />

add .aspx file
write Theme="SkinFileName" in page tab(first line)
now add asp button it will come with some style which is specify in skin file for every button.



for specify different style for different button set SkinId property in skin file like
<asp:Button SkinId="1" runat="server" Font-Size="Large" ForeColor="Red" Text="Button" />
<asp:Button SkinId="2" runat="server" Font-Size="Large" ForeColor="Blue" Text="Button" />

for use that style in aspx file write code like
<asp:Button SkinID="1" ID="Button5" runat="server" Text="Button" /> 
<asp:Button SkinID="2" ID="Button6" runat="server" Text="Button" />

Master Page in ASP.NET

An ASP.NET Provide the template called master page that is for define
the core layout of the pages in your site. This information is common to all
pages that use the same master page.

Advantage

They allow you to centralize the common functionality of your pages so that you can make updates in just one place. They make it easy to create one set of controls and code and apply the results to a set of pages.

For example, you can use controls on the master page to create a menu that applies to all pages. They give you fine-grained control over the layout of the final pages by llowing you to control how the placeholder controls are rendered. They provide object models that allow you to customize the
master pages from individual content pages.

A master page is defined with the file extension .master. Master pages are very similar to regular.aspx pages. They contain text, HTML, and server controls; they even have their own codebehind files.

One difference is that a master page inherits from the Master Page class. Another is that instead of an @ Page directive at the top of the page source, master pages contain an @ Master directive. Following this are the common things you would expect to

Master Page can be nested.


State Management in ASP.NET

There are two types of state management techniques: client side and server side.

Client side

  1. Hidden Field
  2. View State
  3. Cookies
  4. Control State
  5. Query Strings

Server side

  1. Session
  2. Application

Client side methods

1. Hidden field

Hidden field is a control provided by ASP.NET which is used to store small amounts of data on the client. It store one value for the variable and it is a preferable way when a variable's value is changed frequently. Hidden field control is not rendered to the client (browser) and it is invisible on the browser. A hidden field travels with every request like a standard control’s value.
Let us see with a simple example how to use a hidden field. These examples increase a value by 1 on every "No Action Button" click. The source of the hidden field control is.

<asp:HiddenField ID="HiddenField1" runat="server"  />


protected void Page_Load(object sender, EventArgs e)
{
   if (HiddenField1.Value != null)
   {
    int val= Convert.ToInt32(HiddenField1.Value) + 1;
    HiddenField1.Value = val.ToString();
    Label1.Text = val.ToString();
   }
}
protected void Button1_Click(object sender, EventArgs e)
{
  //this is No Action Button Click
}

2. View state

View state is another client side state management mechanism provided by ASP.NET to store user's data, i.e., sometimes the user needs to preserve data temporarily after a post back, then the view state is the preferred way for doing it. It stores data in the generated HTML using hidden field not on the server. 
View State provides page level state management i.e., as long as the user is on the current page, state is available and the user redirects to the next page and the current page state is lost. View State can store any type of data because it is object type but it is preferable not to store a complex type of data due to the need for serialization and deserilization on each post back. View state is enabled by default for all server side controls of ASP.NET with a property EnableviewState set to true.
Let us see how ViewState is used with the help of the following example. In the example we try to save the number of postbacks on button click.
protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        if (ViewState["count"] != null)
        {
            int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;
            Label1.Text = ViewstateVal.ToString();
            ViewState["count"]=ViewstateVal.ToString();
        }
        else
        {
            ViewState["count"] = "1";
        }
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
       Label1.Text=ViewState["count"].ToString();
}

3. Cookies

Cookie is a small text file which is created by the client's browser and also stored on the client hard disk by the browser. It does not use server memory. Generally a cookie is used to identify users.
A cookie is a small file that stores user information. Whenever a user makes a request for a page the first time, the server creates a cookie and sends it to the client along with the requested page and the client browser receives that cookie and stores it on the client machine either permanently or temporarily (persistent or non persistence). The next time the user makes a request for the same site, either the same or another page, the browser checks the existence of the cookie for that site in the folder. If the cookie exists it sends a request with the same cookie, else that request is treated as a new request. 

Types of Cookies

1. Persistence Cookie: Cookies which you can set an expiry date time are called persistence cookies. Persistence cookies are permanently stored till the time you set.
Let us see how to create persistence cookies. There are two ways, the first one is:   
Response.Cookies["nameWithPCookies"].Value = "This is A Persistance Cookie";
Response.Cookies["nameWithPCookies"].Expires = DateTime.Now.AddSeconds(10); 
And the second one is:  
HttpCookie aCookieValPer = new HttpCookie("Persistance");
aCookieValPer.Value = "This is A Persistance Cookie";
aCookieValPer.Expires = DateTime.Now.AddSeconds(10);
Response.Cookies.Add(aCookieValPer);
2. Non-Persistence Cookie: Non persistence cookies are not permanently stored on the user client hard disk folder. It maintains user information as long as the user accesses the same browser. When user closes the browser the cookie will be discarded. Non Persistence cookies are useful for public computers.
Let us see how to create a non persistence cookies. There are two ways, the first one is:
Response.Cookies["nameWithNPCookies"].Value = "This is A Non Persistance Cookie";
And the second way is:
HttpCookie aCookieValNonPer = new HttpCookie("NonPersistance");
aCookieValNonPer.Value = "This is A Non Persistance Cookie;
Response.Cookies.Add(aCookieValNonPer);how to create cookie : 
How to read a cookie:
if (Request.Cookies["NonPersistance"] != null)
Label2.Text = Request.Cookies["NonPersistance"].Value;

Limitation of cookies: The number of cookies allowed is limited and varies according to the browser. Most browsers allow 20 cookies per server in a client's hard disk folder and the size of a cookie is not more than 4096 bytes or 4 KB of data that also includes name and value data. 

4. Control State

Control State is another client side state management technique. Whenever we develop a custom control and want to preserve some information, we can use view state but suppose view state is disabled explicitly by the user, the control will not work as expected. For expected results for the control we have to use Control State property. Control state is separate from view state.
How to use control state property: Control state implementation is simple. First override the OnInit()method of the control and add a call for the Page.RegisterRequiresControlState() method with the instance of the control to register. Then override LoadControlState and SaveControlState in order to save the required state information.


Server side

session

Session is use for mention current user state on the server side , by which we can get and Live user  information session is generated by the server when we un any application server will generate the session that is default session WE use our custom session Session variable we can access in whole application the default time of session will be 20 min. we can increase and decrease it by code

Create session variable

Session[“user”]=“SomeText”

Access session variable

Txtusernaem.Text=session[“user”].Tostring();


Define session time using timeout property
Timeout=“5” // this session will be for 5 min

Destroy session

Session.Abendan()
this method will destroy all the session in this application

Session.clear();
it will remove session value


Session.Remove(“user”)
it will remove particular session

Check session is available or not on page load

If(session["user"]!=null)
{
lblname.Text= session["user"].Tostring();
}
Else
{
Response.Redirect("login.aspx");
}



2. Application

Application state is a server side state management technique. The date stored in application state is common for all users of that particular ASP.NET application and can be accessed anywhere in the application. It is also called application level state management. Data stored in the application should be of small size.  
How to get and set a value in the application object:


Application["Count"] = Convert.ToInt32(Application["Count"]) + 1; //Set Value to The Application Object
Label1.Text = Application["Count"].ToString(); //Get Value from the Application Object

Application_start: The Application_Start event is raised when an app domain starts. When the first request is raised to an application then the Application_Start event is raised. Let's see the Global.asax file. 

void Application_Start(object sender, EventArgs e)
{
    Application["Count"] = 0;
}

difference between Response.Redirect and Server.Transfer

  • Response.Redirect can redirect out of application
  • Server.Transfer can’t redirect out of application




  • Response.Redirect maintain browser history
  • Server.Transfer can’t maintain browser history

Friday, March 27, 2015

How to access session at Outside of Web Forms page class

HttpContext.Current.Session["user"].ToString();


////
string firstName = "Jeff";
string lastName = "Smith";
string city = "Seattle";

// Save to session state in a Web Forms page class.
Session["FirstName"] = firstName;
Session["LastName"] = lastName;
Session["City"] = city;

// Read from session state in a Web Forms page class.
firstName = (string)(Session["FirstName"]);
lastName = (string)(Session["LastName"]);
city = (string)(Session["City"]);

// Outside of Web Forms page class, use HttpContext.Current.
HttpContext context = HttpContext.Current;
context.Session["FirstName"] = firstName;
firstName = (string)(context.Session["FirstName"]);

Wednesday, March 25, 2015

Upload Multiple file

It’s new inbuld feature of fileupload control in .net framework 4.5
Place file upload control and set propert allow multiple file
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="True"
/>
protected void Button1_Click(object sender, EventArgs e)
{
      if (FileUpload1.HasFiles)
      {
// Iterate over files
              foreach (HttpPostedFile file in FileUpload1.PostedFiles)
             {
                     file.SaveAs(Server.MapPath("~/files/") + file.FileName);
             }
              lblMsg.Text = "Uploaded " + FileUpload1.PostedFiles.Count + " files!";
       }
}

The File Upload Control

The File Upload Control
The following properties give you flexible ways to access the uploaded file:
File Bytes The file is exposed as a byte array.

File Content The file is exposed as a stream.

Posted File The file is exposed as an object of type Http PostedFile. This object has properties, such as Content Type and Content Length.

Methods
Save as()

Program
using System.IO;
public partial class _Default : System.Web.UI.Page
{
string Uppath;
protected void Page_Load(object sender, EventArgs e)
{
Label1.Visible = false;
Uppath = Server.MapPath(“~/MyUploads");
if (!Directory.Exists(Uppath))
{
Directory.CreateDirectory(Uppath);
}
}

protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fname = FileUpload1.FileName;
string dpath = Server.MapPath(“~/MyUploads");
string concate = dpath + "//" + fname;
FileUpload1.SaveAs(concate);
lblContent.Text = "Content Type:" + FileUpload1.PostedFile.ContentType;
lblFname.Text = "File Name is:" + fname;
lblsize.Text = "File size in byte is:" + FileUpload1.PostedFile.ContentLength;
lblPath.Text = "File save at location:" + concate;
lblExtension.Text = Path.GetExtension(fname);
} else
{
Label1.Visible = true;
Label1.Text = "Please select a file to upload";
}
}
}

Upload Multiple file

Tuesday, March 24, 2015

JIT Compilation

Dynamically compiles IL code to managed native code that is optimized for execution on a target Operating System

For optimization reasons, JIT compilation occurs only the first time a method is invoked.

The compiled native code lies in memory until process shuts down and garbage-collection takes place.

What CLR Gives to Your applications
Platform Independent
Hardware Independent
Language Independent

Intermediate Language (IL)

.NET languages are not compiled to machine code. They are compiled to an Intermediate Language (IL).

CLR accepts the IL code and recompiles it to machine code. The recompilation is just-in-time (JIT) meaning it is done as soon as a function or subroutine is called.

The JIT code stays in memory for subsequent calls. In cases where there is not enough memory it is discarded thus making JIT process interpretive.

Jargon Buster

Managed Code: code that is written to target the services of the managed runtime execution environment (like CLR)

Why managed??? Managed refers to a method of exchanging information between the program and the runtime environment

Then Unmanaged Code???

Code that is directly executed by the Operating System is known as unmanaged
code.

Common Language Runtime (CLR)


  • The Common Language Runtime which manages the code which is executing
  • Memory Management
  • Thread Management
  • Exception handling
  • Garbage collection
  • Security
  • The Middle-Man

.Net Framework Architecture


Common Language Runtime


  • The core runtime engine in the Microsoft .NET Framework for executing applications.
  • .NET equivalent of the Java Virtual Machine, although JVM currently supports only the Java language.
  • Activates objects, performs security checks on them, lays them out in memory, executes them, and garbage-collects them.
  • Code running in CLR is referred to as “managed code”.
  • Traditional compilers target a specific processor
  • .NET compiler produces binary files containing Common Intermediate language (CIL), and metadata.
  • CLR uses metadata for execution



CTS stands for Common Type System. It defines the rules which Common Language Runtime follows when declaring, using, and managing types.

CLS stands for Common Language Specification and it is a subset of CTS. It defines a set of rules and restrictions that every language must follow which runs under .NET framework. The languages which follows these set of rules are said to be CLS Compliant. In simple words, CLS enables cross- language integration.

example- one rule is that you cannot use multiple inheritance within .NET Framework. As you know C++ supports multiple inheritance but; when you will try to use that C++ code within C#, it is not possible because C# doesn’t supports multiple inheritance.

.Net Framework


About dotnet


  • .NET is Microsoft's new Internet and Web strategy
  • .NET is NOT a new operating system
  • .NET is a new Internet and Web based infrastructure
  • .NET delivers software as Web Services
  • .NET is a framework for universal services
  • .NET is a server centric computing model
  • .NET will run in any browser on any platform
  • .NET is based on the newest Web standards

What Are Programs?

A program is a sequence of written instructions which is compiled and executed by a
computer
A script is a program which runs directly without pre-compilation
Web pages can be thought of as scripts which are interpreted by web browsers

Programs Vs Scripts



About DotNet

DotNet is Technologies developed by Microsoft it’s provide platform independence for any application.

We can create any application in .Net like-
-Web application
-Window application
- Mobile Application
-Web Services
- Console Application