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
  

Thursday, 13 October 2016

014 Weekend Tour Dooars,Paren,Bindu,Jhalong

Parent is a tourist spot in the district of Darjeeling and in the state of West Bengal .It is situated very closed to Bhutan and Jaldhaka . The main place of stay here WBFDC guest house . You need to do prior booking of the guest house before reaching paren . Location is very good , far from crowded city and situated in the jungle .








All around it , green jungle, Location wise its very rewarding with sunrise from beyond the Bhutan hills with thick greenery all around , there is a small mountain stream just beside the resort .One can reach Paren by going Siliguri or New Jalpai guri , from there you can reach Chalsa and Jhalong . Another two destination of Dooars Bingdu and Jhalong is very closed to paren.In Jhalong , two small mountain stream in coming from hills and meeting together , beside this WBFDC guest house is situated . A beautifully scenic beauty created by nature.









Bindu is very close to Parent , just opposite it , there is Bhutan .You can spend a few hour by playing with water over stone . You can enjoy  Bindu Dam - Built on the Jaldhaka River. Rare view of the Bhutan Himalayas and snow peak mountains in the winters.Jaldhaka Hydel Project - The hydroelectric project ,you  can be visited with the prior permission of the WBSEB authorities.







Inheritance


Inheritance is the feature of the .Net framework , which allow to create a new class with all the member of previously defined class .For example ,we have defined class A ,, now inherited class B . All member of class A will come to Clasas B automatically.The first class is called Base class an second class is called derived class . In other object oriented programming language allow unlimited level of inheritance  , but .Net frame work allow only 2nd level inheritance . The main advantage of inheritance is just copy/implement common functionality of Base class to derived clasas . Now I am creating an class
public class parent //base class
{
    public int public_member;
    public int public_method(int a, int b)
    {
        return (a + b);
    }
}

public class child : parent
{
    //derived class
}

Notice that , child class do not have any method .Now I am creating instance of the clind class.
        child obj = new child();

obj.public_member;
obj.public_method();
We get both member of the parent class in child class . Noticed that , member of the parent class declared public ,so that we can inherit it , only public , protected access modifier will be available during Inheritance .Here is an example ,

public class Parent
{
    private void Method1()
    {
    }
    protected void Method2()
    {
    }

}

public class child : Parent
{
    public void method_call()
    {
        this.method1();//compliler through error-inacccable due to protection level
        this.Method2.method2();//will compile & work
    }
}

Is there any way , that we can define a class that can not be Inherited ?
Yes . there is , the keyword called “sealed” , seal keyword tells compiler that , this class can not be inherted  . For example
public sealed class  Myclass
{

}
Now , I am trying to Inherit the clasas “MyClasas”
public class MyChild : Myclass
{
}
//error MyChild': cannot derive from sealed type 'Myclass'

An error will shown , sealed class can not be inherited , but we can create instance of the seal class .The question is , what is the use of sealed class ?
Sealed class is mainly used for security features, so that class cannot be modified.

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

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