Tuesday, March 3, 2015

View State in Asp.net

View State:

View State which is used to maintain the State at a page level. 

i.e the the information is being stored for a specific page and until that specific page is active (i.e. the page which we are currently viewing). if we are redirected to some other page, the information stored in the View State will be lost. 

It uses "Dictionary Object" to store data, here the information is stored in key and value pair. It stores that information in a Hidden field on the page itself in a hashed format. 


It can store a string value upto specific length. If the length is exceeded then the excess information will be stored into another hidden field.

It maintains the state of controls during page postback and if we save any control values or anything in the viewstate than we can access that values throughout the page whenever it is required.

viewstate values are by default sent to the client browser and it returned  to the server in the form of a hidden input control on your page

Basic Example of View State:


In, this example i am going to save the view state values, and retrieving it on PageLoad



.cs page:


 protected void btnSave_Click(object sender, EventArgs e)

    {
        ViewState["FirstName"] = Convert.ToString(txtFirstName.Text);
        ViewState["LastName"] = Convert.ToString(txtLastName.Text);
        ViewState["Salary"] = Convert.ToString(txtSalary.Text);
        txtFirstName.Text = "";
        txtLastName.Text = "";
        txtSalary.Text = "";

    }

    protected void btnRead_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Convert.ToString(ViewState["FirstName"])))
        {
            txtFirstName.Text = Convert.ToString(ViewState["FirstName"]);
        }
        if (!string.IsNullOrEmpty(Convert.ToString(ViewState["LastName"])))
        {
            txtLastName.Text = Convert.ToString(ViewState["LastName"]);
        }
        if (!string.IsNullOrEmpty(Convert.ToString(ViewState["Salary"])))
        {
            txtSalary.Text = Convert.ToString(ViewState["Salary"]);
        }

    }

.In this example, i am saving the values in ViewState and Reteriving the saved values from viewstate , when we click on Read button.





When Click on Read Button. again the values are populated.



we can see below I am retrieving the value from the View State, 

View State Information is stored in a Hashed Format

In html view source ,we can see this






View Source we can see this as,In html view source ,we can see this



<div class="aspNetHidden">

 <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="vkITvu/CexBloorOExhQydean8rSPGP8ZyiqbLqc71XNJYBLyVpWe1Fow2yFyEN43Bwh8RNard1nTm7ZZkCx99VvcjCcPGn7Y0DPvMO3WgzFbk3Xduw3HTi/aQZF6UYkd+m/nYsjvNnzVWd4b8USvmkNzAgz8ZxcCWL8v8LAJLcwiGo74HqrKcsQwKcmKBzfIfjovSysuFpRQEDa+Syk1Q==" />
</div>

-----------------------------------------------------------------------------------------

View State can be applied at the following places.

  • Application Level
  • Page Level 
  • Control Level 

Page Level.

If we dont want the page to use viewstate,then we can disable view state at page level.
we can disable or enable viewstate by using EnableViewState 


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3"  EnableViewState="false"%>


Example:

 In the below example i am saving the values in ViewState, and when i am trying to Read those values from Viewstate , we can see the ViewState Values are null.







Output:




At Control Level 



Application Level 

In web.config 




If View State set to off. Textbox values still Existings

They are few controls which retain there values even after disabling the ViewState?

The controls which implements IPostBackEventHandler (Textbox, Checkbox) will retain the state even though if  disable the  viewstate.  That is during the Load Postback Data phase, that controls will get state information from Posted back form.
Where as controls like label will not implement IPostBackEventHandler will not get any state information from posted back data and hence they depend on viewstate to maintain the state .

To make  view state secure?

There are two ways :
"EnableViewStateMAC=true"  (MAC Stands for "Message Authentication Code")




ViewStateEncryptionMode="Always" , which will encrypt the view state data.

ViewStateEncryptionMode.Auto
It will Encrypt the ViewState.

ViewStateEncryptionMode.Never
It will not encrypt the ViewState

ViewStateEncryptionMode.Always
ViewState is always encrypted




The following are list of controls which dont maintain state if we disable viewstate also. That is because they implement IPostBackDataHandler


TextBox
CheckBox
CheckBoxList
DropDownList
ImageButton
ListBox
RadioButtonList
HtmlInputCheckBox
HtmlInputFile
HtmlInputHidden
HtmlInputImage
HtmlInputRadioButton
HtmlInputText
HtmlSelect
HtmlTextArea





Monday, March 2, 2015

Method OverLoading In WCF

A method can be overloaded on the basis of type of parameters, no of parameters, and an order of parameters.


Let, us consider the below example:

File->New Project-wcf service application



Delete the two Files




Add->New Item




Write the following code in Iservice1.cs

namespace WcfService2

{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        void DoWork();

        [OperationContract]

        string Display();

        [OperationContract]

        string Display(string name);
    }

}




Service1.cs




public class Service1 : IService1

    {
        public void DoWork()
        {

        }



        public string Display()

        {
            return "Welcome";
        }

        public string Display(string name)

        {
            return string.Format("Welcome {0}", name);
        }

    }




Build the service, and Go to .svc file, and view in browser 





and select your browser and see the output as  shown below.






Now, modify the below code by using Name Attribute as shown below:

namespace WcfService2

{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        void DoWork();

        [OperationContract(Name = "Dispaly")]

        string Display();

         [OperationContract(Name = "Display name")]

        string Display(string name);
    }

}


Now, run and see the output 






By default WSDL does not support operational overloading, but this can be done using  the Name property of OperationContract.




Example 2:


Iservice1.cs





Service1.cs


namespace WcfService2

{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        public void DoWork()
        {

        }

        public int Addition(int x, int y)
        {
            return x + y;
        }

        public double Addition(double x, double y)

        {
            return  Convert.ToDouble(x) + Convert.ToDouble(y);
        }
    }
}


Build the service. and see the output.




Consuming the WCF Service.


Add the service Reference first as shown below.

Add->Service Reference




and Click on Ok Button.


Design the Form as Follows:





.cs page:


public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client();
        int a=Convert.ToInt32(txtFirstNumber.Text);
        int b = Convert.ToInt32(txtLastNumber.Text);
        dynamic result=obj.SumUsingInt(a, b);
        lblmessage.Text = Convert.ToString(result);
    }

}


output:




Sunday, March 1, 2015

Dynamic keyword in c sharp Example

Example: 

Below example to save data.( I am going to use the following concepts) in this example.

1 JQuery

2 Ajax
3 dynamic keyword
4 JSON 


Design the form  as shown below:


<table>

        <tr>
            <td>First Name</td>
            <td> <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td> Last Name</td>
            <td> <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Salary</td>
            <td> <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td colspan="2">
                <fieldset>
                    <legend> Address Details</legend>
                    Plot No:
                    <asp:TextBox ID="txtPlotNo" runat="server"></asp:TextBox>
                    Area Name:
                    <asp:TextBox ID="txtAreaName" runat="server"></asp:TextBox>
                    Phone Number:
                    <asp:TextBox ID="txtPhoneNumber" runat="server"></asp:TextBox>
                </fieldset>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <fieldset>
                    <legend>Skill Details</legend>
                    SkillSet
                  <asp:DropDownList ID="drpSkillSet" runat="server">
                      <asp:ListItem Value="0">Select </asp:ListItem>
                      <asp:ListItem Value="1">DOTNET</asp:ListItem>
                      <asp:ListItem Value="2">JAVA</asp:ListItem>
                      <asp:ListItem Value="3">SAP</asp:ListItem>
                      <asp:ListItem Value="4">PHP</asp:ListItem>
                      <asp:ListItem Value="5">ANDROID</asp:ListItem>
                    </asp:DropDownList>
                   Rating
                    <asp:TextBox ID="txtRating" runat="server"></asp:TextBox>
                    Lastly Used:
                    <asp:TextBox ID="txtLastUsed" runat="server"></asp:TextBox>
                </fieldset>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <fieldset>
                    <legend>Experience Details</legend>
                    CompanyName
                  <asp:TextBox ID="txtCompanYname" runat="server"></asp:TextBox>
                    Address
                    <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
                    Lastly WorkingYear:
                   <asp:DropDownList ID="drpLastWorkingYear" runat="server">
                       <asp:ListItem Value="0">Select </asp:ListItem>
                       <asp:ListItem Value="1">2010</asp:ListItem>
                       <asp:ListItem Value="2">2011</asp:ListItem>
                       <asp:ListItem Value="3">2013</asp:ListItem>
                       <asp:ListItem Value="4">2014</asp:ListItem>
                       <asp:ListItem Value="5">2015</asp:ListItem>
                   </asp:DropDownList>
                </fieldset>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <fieldset>
                    <legend>Project Details</legend>
                   Project Name
                  <asp:TextBox ID="txtProjectName" runat="server"></asp:TextBox>
                    ClientName
                    <asp:TextBox ID="txtClientName" runat="server"></asp:TextBox>
                    Duration IN Months
                   <asp:DropDownList ID="drpMonths" runat="server">
                       <asp:ListItem Value="0">Select </asp:ListItem>
                       <asp:ListItem Value="1">1</asp:ListItem>
                       <asp:ListItem Value="2">2</asp:ListItem>
                       <asp:ListItem Value="3">3</asp:ListItem>
                       <asp:ListItem Value="4">4</asp:ListItem>
                       <asp:ListItem Value="5">5</asp:ListItem>
                   </asp:DropDownList>
                </fieldset>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input id="btnSave" type="button" value="Save"  onclick="saveDetails()"/>
            </td>
        </tr>
    </table>



javascript Code:


 <script type="text/javascript">
        var Dataxml = new Object();
        function saveDetails() {
            Dataxml.EmployeeXML = CreateEmployeeXML();
            Dataxml.AddressXML = CreateAddressXml();
            Dataxml.SkillXml = CreateSkillXml();
            Dataxml.ExperienceXml = CreateExperienceXml();
            Dataxml.ProjectXml = CreateProjectXml();
            var _saveResult = Default.SaveData(JSON.stringify(Dataxml));
        }

        function CreateAddressXml() {

            var _addressData = '';
            _addressData += "<Address> <AddressHeader";
            _addressData += " Plotno=\"" + $('#txtPlotNo').val();
         
            if ($('#txtAreaName') != undefined)
                _addressData += "\" AreaName=\"" + $('#txtAreaName').val();

            if ($('#txtPhoneNumber') != undefined)

                _addressData += "\" PhoneNumber=\"" + $('#txtPhoneNumber').val().replace(/,/g, "") + "\">";

            _addressData += "</AddressHeader>";

            _addressData += "</Address>";
            return _addressData
        }
        function CreateSkillXml() {
            var _skilldata = '';
            _skilldata += "<Skills> <SkillsHeader";
            _skilldata += " Rating=\"" + $('#txtRating').val();
            _skilldata += "\" SkillSet=\"" + $('#drpSkillSet').val();

            if ($('#txtLastUsed') != undefined)

                _skilldata += "\" LastUsed=\"" + $('#txtLastUsed').val().replace(/,/g, "") + "\">";

            _skilldata += "</SkillsHeader>";

            _skilldata += "</Skills>";
            return _skilldata
            
        }
        function CreateEmployeeXML() {
            var _skilldata = '';
            _skilldata += "<Skills> <SkillsHeader";
            _skilldata += " Rating=\"" + $('#txtRating').val();
            _skilldata += "\" SkillSet=\"" + $('#drpSkillSet').val();

            if ($('#txtLastUsed') != undefined)

                _skilldata += "\" LastUsed=\"" + $('#txtLastUsed').val().replace(/,/g, "") + "\">";

            _skilldata += "</SkillsHeader>";

            _skilldata += "</Skills>";
            return _skilldata
        }
        function CreateExperienceXml() {
            var _experiencedata = '';
            _experiencedata += "<Experience> <ExperienceHeader";
            _experiencedata += " CompanYname=\"" + $('#txtCompanYname').val();
            _experiencedata += "\" WorkingYear=\"" + $('#drpLastWorkingYear').val();

            if ($('#txtAddress') != undefined)

                _experiencedata += "\" Address=\"" + $('#txtAddress').val().replace(/,/g, "") + "\">";

            _experiencedata += "</ExperienceHeader>";

            _experiencedata += "</Experience>";
            return _experiencedata
        }
        function CreateProjectXml() {
            var _projectdata = '';
            _projectdata += "<Projects> <ProjectsHeader";
            _projectdata += " ProjectName=\"" + $('#txtProjectName').val();
            _projectdata += "\" DurationMonths=\"" + $('#drpMonths').val();

            if ($('#txtClientName') != undefined)

                _projectdata += "\" ClientName=\"" + $('#txtClientName').val().replace(/,/g, "") + "\">";

            _projectdata += "</ProjectsHeader>";

            _projectdata += "</Projects>";
            return _projectdata
        }
        function CreateEmployeeXML() {
            var _employeedata = '';
            _employeedata += "<Employee> <EmployeeHeader";
            _employeedata += " FirstName=\"" + $('#txtFirstName').val();
            _employeedata += "\" LastName=\"" + $('#txtLastName').val();

            if ($('#txtSalary') != undefined)

                _employeedata += "\" Salary=\"" + $('#txtSalary').val().replace(/,/g, "") + "\">";

            _employeedata += "</EmployeeHeader>";

            _employeedata += "</Employee>";
            return _employeedata
        }

    </script>














Add Ajax Reference dll.




You can see the values here in debugging mode.

Output in Debugging Mode:








Dynamic KeyWord in C sharp

It is the new feature introduced in 4.0

A dynamic variable or parameter or field it can have any type. 


Its type can be changed during runtime.


dynamic type variables should be initialized when declared.



Changing type of value assigned to var cannot be changed after assigned to it.

Means , if we assign a int value to var then we cannot assign a string value. this is because on assigning the int value, it will treat as int type thereafter no other type value can assign to it.


Example:



If, i assign a value to integer it wont show any error.



using dynamic keyword




Initially it was assign with integer variable, and again i am reassigning the value to string data type.



output:





Advantages of var keyword

1 We can assign the value to same data type.
var a = 4;
        a = 52;
        Response.Write(a);
2 Intellisense support

Advantages of dynamic keyword.

1 We cannot assign the value to different data type
dynamic a = 9;
        a = "Hi";
        Response.Write(a);
2 No Intellisense support



Example:





output:


We can call any function  or property, if it is not declared also , your code will still compile but you will get runtime exception.





Dynamic types can also be converted explicitly to any other data types 



output:



Saturday, February 28, 2015

Consuming WCF Service USING jquery/ajax

First, we need to Add New Service as shown below.





Click on Add Button







Iservice.cs





using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
[ServiceContract]
public interface IService
{
    [OperationContract]
    void DoWork();

    [OperationContract]
    [System.ServiceModel.Web.WebInvoke(Method = "POST",
        ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
    string GetEmployees(string result);

}


Service.cs









[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service : IService
    {
        public void DoWork()
        {
        }

        public string GetEmployees(string result)
        {
            List<object> emp = new List<object>();
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "select Firstname,Lastname from emp where " +
            "Firstname like @result + '%'";
            cmd.Parameters.AddWithValue("@result", result);
            cmd.Connection = con;
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                emp.Add(new
                        {
                            FirstName = dr["Firstname"],
                            Lastname = dr["Lastname"]
                        });
            }
            con.Close();
            return (new JavaScriptSerializer().Serialize(emp));
        }

    }


Now, the service is ready. and we need to consume the service.

Now, add new form and design the form as shown below

<body>
    <form id="form1" runat="server">
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <input id="btnsearch" type="button" value="Search" />
        <div id="results"></div>
    </form>

</body>

web.config

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="Service">
        <endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="ServiceAspNetAjaxBehavior">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
  </system.serviceModel>


Javascript Code:

    <script src="jquery-1.7.min.js"></script>
    <script type="text/javascript">
        $("#btnsearch").live("click", function () {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '<%=ResolveUrl("~/Service.svc/GetEmployees") %>',
                data: '{"result": "' + $("#TextBox1").val() + '"}',
                processData: false,
                dataType: "json",
                success: function (response) {
                    var employees = eval(response.d);
                  
                    var html = "";
                    $.each(customers, function () {
                        html += "<span>FirstName: " + this.FirstName + " Lastname: " + this.Lastname + "</span><br />";
                    });
                    $("#results").html(html == "" ? "No Records Found" : html);
                },
                error: function (a, b, c) {
                    alert(a.responseText);
                }
            });
        });

    </script>


Here ResolveUrl : will get the application folder Name

Output:




Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...