Monday, 24 October 2016

View State Management ASP.Net

View State Management ASP.Net
 
ASP.Net is stateless , that means when we submit page to server , server generate new HTML for that page and deliver us.The value we entered  , get loss .For Example we have entered some information of student and send it to Server , when server return the page , the data i have entered losses.

To solve the problem , different framework introduced different technique .In ASP.Net , there are two type of technique , server Based & Client Based . 


View State is a good technique to handle State Management .View State is actually a hidden field which hold data in base 64 encrypted format.If you go to view HTML of the page , you will notice

It is always recomended to use  as little as possible , view state make extra overhead on perfoemance ,but little .We can enable/disable bu enter enableViewState=true/false.


Now we will discuss how , view state overhead effect .We have data and running two mode  
enableViewState=true/false .Let us see the performance.





Now , notice size of page increase , that means , it will take more time with View State , that means View State has a effect on Page performance.An extra overload make a page little bit slow in loading.

Now , can we control page level view state & control level view state ? can we do disable page view state and enable control view state , the answer is 'yes' , Asp.Net offer this solution also .In the page top just write enableViewState=false , this makes , page view state off , now we can turn on control of ASP.Net ViewStatemode enable disable will enable / disable will enable /disable control by control basis.

Some point to remember

  •   View State Loaded after page_init.
  •   View State created after page_prerender.
  •   View State is encrypted base 64 algorithm.                                                                                                     There are also encryption  option on View State , we can do it elthier page level
  •  
   OR 

Three Option are
Always  : Always encrypt view state.
Auto :encryption if the control on thre page request it.
Never :Recommended not use
  
                                         






Friday, 21 October 2016

ASP.Net State Management

ASP.Net State Management
                   We know any web page are state less, means when we post a page to server , server will not return the same state as it was send . The reason is , when we post a form /page to the server , server process the page and generate new html and send to browser .For example a web page is taking student information , student name , date of birth ,country ,state .We enter student name , date of birth , now we have Select student country “Say” India , page need to go server and get state list of India .When it posted to server for state information , the whole html is created again and when comes to browser , student name , date of birth not data is not there .Input fields are empty.

                To over come this problem , Asp.Net introduced State Management . State Management is a technique to keep data while post back occur , that means , when student page with student data will be posted to the server , and server will return  student page with student data.

              There are several way to maintain State in ASP.Net , such as View State ,Hidden Fields ,
Cookies ,  Query String , Control State . Some are Clint Site and Some are Server Site.


  View State : View state is the technique that the ASP.NET page  uses to preserve page and control  values when post back . The working of View State can be controlled by C# code , by default view state enabled . View state is a hidden filed with serialized into base64-encoded strings.We van enable /disable code from page level


%@ Page Language="C#"  CodeFile="Default2.aspx.cs" Inherits="Default2"  EnableViewState="false"

We can encrypt view state


%@ Page Language="C#"  CodeFile="Default2.aspx.cs" Inherits="Default2" EnableViewState="true ViewStateEncryptionMode="Always" 

There is also Option for enable/disable at control level

asp:TextBox EnableViewState=true

We can also do enable/disable  the whole page and enable/disable on or more control.
We can also use View State variable as follow


protected void Page_Load(object sender, EventArgs e)

    {

        if (ViewState["NameOfStudent"] != null)

            txtStudentName.Text = ViewState["NameOfUser"].ToString();

        else

            txtStudentName.Text = "Not set yet...";

    } 

    protected void SubmitForm_Click(object sender, EventArgs e)

    {
        ViewState["NameOfUser"] = txtStudentName.Text;
        txtStudentName.Text = NameField.Text;
    }
 

We can see view state value , to see the value , please write click on mouse and go to "View source" , here is the example
Hidden field : Hidden field is control , which is not displayed in the front end .This field are use to hold control value , here is an example


<body>
    <form id="form1" runat="server">
    <div>
      <asp:HiddenField ID="hiddn_1" runat="server" />
      <asp:TextBox ID="txtStudent" runat="server" ></asp:TextBox>
        <asp:Button ID="Button1" runat="server" oncommand="Button1_Command"
            Text="Button" />
        <br />
    </div>
    </form>
</body>

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        txtStudent.Text = hiddn_1.Value;
    }
    protected void Button1_Command(object sender, CommandEventArgs e)
    {
        hiddn_1.Value = txtStudent.Text;
    }
}

Here , hidden field hold the value of "txtStudent" , while page load , the process  is reverse

Cookies : Cookies are small text to stored some value .This is like key pair combination.
Cookies are associated with a Web site, not with a specific page, so the browser and server will exchange cookie information no matter what page the user requests from your site.

 protected void Page_Load(object sender, EventArgs e)
    {       
     Response.Cookies["LoggedUsere"].Value = "MyUser";
     Response.Cookies["LoggedUser"].Expires = DateTime.Now.AddDays(1);
    }
    protected void Button1_Command(object sender, CommandEventArgs e)
    {
        HttpCookie obj = new HttpCookie("LoggedUser");
        string loggedUser = Request.Cookies["LoggedUser"].Values.ToString();

    }

Here ,  user values stored in cookies and later retrieved in a sting.

Context.Handler
Context handler just return the immediate previous web page when Server.transfer occure , this does not works for Response.redirect.


public partial class MyContext1 : System.Web.UI.Page
{
    internal string value
    {
        get
        {
            return TextBox1.Text;
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Server.Transfer("MyContext1.aspx");
    }
}

public partial class MyContext2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        MyContext1 largePare;
        largePare = (MyContext1)Context.Handler;
        this.textBox1.Text = largePare.value;
    }
}

Query String 
       This is popularly used in ASP.Net Application . A  string of query can be generated before posting and later while loading field value can be retrive from query .this works for both Server.Transfer and Request.Response.


   protected void Button1_Click(object sender, EventArgs e)
    {
        Server.Transfer("MyContext1.aspx?mText=20");
    }
 

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["mText"] != null)
        {
            this.Textbox1.Text = Request.QueryString["mText"].ToString();
        }
    }

Session State
Asp.net offer a unique key to each user when a new session begin , this is called session id/ Session key.This key is stored is cookie.In each request client send the key to Server .Session State maintained by Globax.aspx


<%@ Application Language="C#" %>

<script runat="server">

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Session["MyNumber"] = 100;
    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.

    }
      
</script>

Application State
As ASP.Net is stateless protocal ,it is application state which can hold some value , we can use during page load event to show the value to client .Application variable inisialised when application starts only.


<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        Application["MyAppVarable"] = "100";

    } 
</script>

Catching
Catching is a technique to deliver the same Web Page which is frequently   used without rebuild the page HTML.For I am using page A , after 3 second I called same page A to browser , server will return page A to browse from cache memory.But the question is how many time cache hold the page , which page will hold by cache , there are several caching technique output caching , data catching ,object catching.

Tuesday, 18 October 2016

Interface

Interface

Interface are implemented by class or structure , it is a contract , how a class or structure will behave .Any object implement interface will make sure of implement property defined in the interface . An interface property have to define in the same data type , parameter and same property .For example an interface A has property calculateAge with return type integer .Now I am implementing interface A on class B , I have to declare calculateAge  with return type integer . either compiler will through error  “does not implement interface member Interfaceimplement.A.calcualtedag int”

A simple interface with no method

public interface MyInterface
{

}

A Simple class with Interface

public class MyClass : MyInterface
{

}
Now I am writing a interface with method

public interface MyInterface
{
    void MySuv(int x)
    {
    }
}
Now a class with Interface implementation

public class Myclass : MyInterface
{
    public void MySub (int x)
    {
    //do you own logic
    }
}
Some points to remember


  • Interface is a point where two point , organization subject together
  • Interface can not have a definition , that is we can not write body of Interface member
  • We ca not declare variable in interface
  • Interface  can not have fields
  • All interface method have to define in implemented class
  • We can not define access modifier on interface method
  • We can implement interface to Abstract class
  • We can apply access modifier on interface
What is use of Interface then ?
    Generally developer write class method different name with same implementation . For example a developer has declared a method name "Save" to class A , later he is writing "SaveData" in class B.But both purpose is same .Interface allow to overcome this problem.


Implementation Interface –Now we are discussing how method of Interface is implemented in class or structure , the first step define method with same name and signature in the class and do implementation.

public interface MyInterface
{
    void calculateAge(DateTime Date_of_Birth)
    {
    }
}
public class student : MyInterface
{
    public void calculateAge(DateTime Date_of_Birth)
    {
        int t_year=;//calculation logig here
    }
}

Multiple Interface Implementation : In.Net , it is not possible to implement multiple inheritance ,but it is possible to implement multiple Interface .


public interface MyInterface1
{
    void calculateAge(DateTime Date_of_Birth)
    {
    }
}

public interface MyInterface2
{
    void calculateMarks()
    {
    }
}


public class student : MyInterface1, MyInterface2
{
    public void calculateAge(DateTime Date_of_Birth)
    {
        int t_year=;//calculation logig here
    }
     public void calculateMarks()
    {
        int t_year=;//calculation logig here
    }
}

You need to declared all construct of the both interface .What happen when Multiple Interfece has same named  method , for example Interface1 and Interface2 has same name method A , what will happen when both has same parameter & same signature.C# provide us the way to tell compiler , with method to use.During calling , tell compiler the Interface name , then method name , for Example


public interface A
{
    void method1(DateTime Date_of_Birth)
    {
    }
}

public interface B
{
    void method1(DateTime Date_of_Birth)
    {
    }
}


public class student : A,B
{
    public void A.method1(DateTime Date_of_Birth)
    {
        int t_year=;//calculation logig here
    }
     public void B.method1(DateTime Date_of_Birth)
    {
        int t_year=;//calculation logig here
    }
}


Now the common question is what is the difference between Abstract Class and Interface .Why we should use Abstract Class and why we should Interface ?  here is the points .A class can inherits only single Abstract Class but a class can inherits multiple Interface In Abstract can contain contact , method , sub , but Interface can contain method ,sub.In Abstract Class , we can access modifier public , private , protected but Interface can not have such option.


Friday, 14 October 2016

016 Weekend Tour Dooars,Murti,Garumara National Park

Murti is named after the name of beautiful river Murti , beautiful scenic beauty and light flow of water greenly all around made Murti attractive for tourist , mainly from West Bengal . It is very well connected by Air, road, rail.You can reach Murti from Bagdogra Airport, By Rail it is 73 km from Siliguri,18kms from New MAL Junction , you can come from New Jalpauguri also.







In Murti you will find several private hotels/lodge , there is a guest house of WBFDC named "Banani", location of this guest house is awesome , just beside the river Murti .If you are lucky , you may notice wild animal just at the bank of Murti from your room .you can visit Gorumara National Park, Chapramari Forest , Metali watch tour as Site Seeing .








 You can take either elephant ride or Zipsy car to visit Garumara .You can see Barking Deer , Rhino ,Bison ,Elephant , plenty of peacock in Garumara National Park . During visit you need to purchase ticket , guide ect . Each ticket allowed for 2 hours only . Deep forest , wild animal make a trilling for tourist.If you are going to visit Metali watch tour , you need to hire bull cart , purchase ticket .You will feel excited while riding bull cart .






In the afternoon you can visit Lataguri Bazar , Chalsa Bazar arear. Most of the road side are either deep forest of beautiful  tea garden , full of lush green , people are pulking tea leaves from the Garden.



Connection pooling

Connection pooling is a technique to maintain database connection in cache .This reduce overhead on connection open and close again and again .In an application where large number of user is there , connection open for one user do not closed or released , instead it is being pooled for next user or request, where next user ask for connection , pooled connection is offered .This reduced overhead on connection open and close and also speed of performance of the application. In case all connection is in use , and new connection is asked , a new connection is opened and put into the pool again. When a connection is open , what actually happen ? the answer is , a named pipe or socket established with handshake mechanism .But in connection pooling is created based on an extra machine algorithm , that associated the pool with connection string when a new pool called and does not match the existing pool , a new pool created .Here is example of connection pooling.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
          string sqlConnectString = "Data Source= xxx.xxx.xxx.xxx; initial catalog=MyDatabaseName;Connect Timeout=6000; User ID=MyUserID;Password=MyPassword";
          SqlConnection connection = new SqlConnection();
          connection.ConnectionString = sqlConnectString + "Connection Timeout=30;Connection Lifetime=0;Min Pool Size=0;Max Pool Size=100;Pooling=true;";
          connection.Open();

          //for command executing
          SqlCommand cmd = new SqlCommand("select * from tbl_myTable");
          cmd.Connection = connection;
          SqlDataReader dr = cmd.ExecuteReader();
         
          //for data set
          SqlDataAdapter da = new SqlDataAdapter("select * from tbl_myTable", connection);
        


    }
}

There are several property of connection pooling , we can set maximum pooling size or Minimum pooling size for a connection pool.We can run sql query to identify how many active connection is currently active


SELECT 

    DB_NAME(dbid) as Data_Base_Name, 
    COUNT(dbid) as Number_Of_Connections,
    loginame as Login_uSER_Name
FROM
    sys.sysprocesses
WHERE  dbid
GROUP BY  dbid, loginame


Result
----------------------------------------
database1    3            user1

database2    4            user1
  

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...