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:




Friday, February 27, 2015

REMAINDER SCHEDULAR ALERT USING JQUERY TIMER

Add the following jquery files 

You need to  download the following files

  <link type="text/css" rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>

    <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

    <script src="jquery.timers.js"></script>
    
    <script type="text/javascript">

        $(document).everyTime(10000, function (i) {
            $.ajax({
                type: "POST",
                url: "popup.aspx/GetUserInfoData",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert("Failure Details : " + response.d);
                },
                error: function (response) {
                    alert("Error Details: " + response.d);
                }
            });
        });
        function OnSuccess(response) {
            var xmlDoc = $.parseXML(response.d);
            var xml = $(xmlDoc);
            var users = xml.find("Table");
            if (users.length >= 1) {
                $("#div1").dialog({
                    title: "Hi Welcome",
                    width: 600,
                    height: 400,
                    modal: true,
                    buttons: {
                        Close: function() {
                            $(this).dialog('close');
                        }
                    }
                });
            }
        }

    </script>









Design:


<body>
    <form id="form1" runat="server">
        <div>
            <div id="div1" style="display: none">
                <b>Welcome to this World</b>
            </div>
        </div>
    </form>

</body>


protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static string GetUserInfoData()
    {

        SqlConnection con = new SqlConnection("    ");
        SqlCommand cmd = new SqlCommand("select * from fdfd", con);
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        return ds.GetXml();

    }






Output:

Wait for 15 seconds, then the pop up will be displayed automatically.




Kubernetes

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