2014/09/17

How to get the value of Textbox, CheckBoxlist, RadioButtonList, ListBox, DropDownList in javascript


Introduction

This Article explains you how to Raise Client Click Events for Server Controls
usage:
1.Attribute 'OnClientClick':-The OnClientClick property is used to sets a client side script or Method to be run when the Button control is clicked.
eg:OnClientClick ="return javascriptMethod()"
2.getElementById():-It is used to get the Elements in a form.This method takes an argument to access elements with a unique id attribute.
eg:document.getElementById ("textbox1");
3)getElementsByTagName():-This method takes in as argument the name of a tag element and returns an array of all matching tags elements found in the document.
eg:document.getElementsByTagName("Label");
How to get the value of textbox in javascript ?
in .aspx source code
<head runat="server">
    <title>Untitled Page</title>
    <script type ="text/javascript">
    function getTxt()
    {
     var txt=document.getElementById("TextBox1");
     alert(txt.value);
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server" Height="16px" Style="z-index: 100; left: 176px;position: absolute; top: 32px" Width="96px"></asp:TextBox>
  <asp:Button ID="Button1" runat="server" Font-Bold="True" Style="z-index:101;left:184px;position:absolute; top:64px" Text="Click" Width="56px"
 OnClientClick ="return  getTxt()"/>
        <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="0.8em" Style="z-index: 103;left: 96px; position: absolute; top: 32px" Text="User Name:"></asp:Label>
    </div>
    </form>
</body>
</html>
 Image of textbox

 How to get the text of CheckBoxList in Javascript?

<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    function chkboxMeth()
    {
      var chkbox = document.getElementById("CheckBoxList1");
      var inputArr = chkbox.getElementsByTagName('input');
      var labelArr = chkbox.getElementsByTagName('label');
      var sum="";
     for (var i=0; i
     {
      if (inputArr[i].checked == true)
{
sum = sum + labelArr[i].innerText;
}
    }
alert(sum);
return false;
  }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True" BackColor="#00CC99" Font-Bold="True" ForeColor="#FF0066">
            <asp:ListItem Value="1">Apple</asp:ListItem>
            <asp:ListItem Value="2">Banana</asp:ListItem>
            <asp:ListItem Value="3">Grapes</asp:ListItem>
        </asp:CheckBoxList>
        <asp:Button ID="Button1" runat="server" Style="position: absolute; z-index: 102; left: 400px; top: 48px;" Text="Click" OnClientClick =" return chkboxMeth()" BackColor="#CCCC66" Font-Bold="True" Width="64px"/>
    </div>
    </form>
</body>
</html>
 
Image of CheckBoxlist
How to get the value or text of radioButtonList in javascript?

<head runat="server">
    <title>Untitled Page</title>
    <script type ="text/javascript">            
  function GetRadioButtonSelectedValue()
  {
      var radio = document.getElementById('radiobuttonlist1');
      var inputArr = radio.getElementsByTagName('input');
      var labelArr = radio.getElementsByTagName('label');
     for (var i=0; i
     {
        if (inputArr[i].checked )
         {
          alert("Selected Value:"+inputArr[i].value+" 
Selected Text :"+labelArr[i].innerText);
          inputArr[i].checked =false  
         }
     }
  } 
    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
  
    <asp:RadioButtonList ID="radiobuttonlist1" runat="Server" RepeatLayout="flow" ForeColor="Blue" BackColor="#E0E0E0" Font-Bold="True" Font-Names="Verdana" Font-Size="Small">
          <asp:ListItem Text="ASP.NET" Value="1" ></asp:ListItem>
          <asp:ListItem Text="SilverLight" Value="2"></asp:ListItem>
          <asp:ListItem Text="C#.NET" Value="3"></asp:ListItem>
   </asp:RadioButtonList>
   <asp:Button ID="Button1" runat="server" Style="position: static;" Text="Select"
     OnClientClick =" return GetRadioButtonSelectedValue(); " />
</div>
    </form>
</body>
</html>
Image of RadioButton List
How to get the selected value or text  of dropdown in javascript?
 <head runat="server">
    <title>Untitled Page</title>
     <script type ="text/javascript">
      function ddlmeth()
      {
var ddl=document.getElementById("DropDownList1");
     alert("Selected Value: "+ddl.value +"  "+"Selected Text: "+ddl[ddl.selectedIndex].innerText);
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
<asp:Button ID="Button1" runat="server" Style="position: absolute; z-index: 103; left: 200px; top: 120px;" Text="click" OnClientClick ="return ddlmeth()" ForeColor="#FF0066" Width="72px"  />
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" Style="z-index: 102;
            left: 208px; position: absolute; top: 8px">
            <asp:ListItem Value="1">ASP.NET</asp:ListItem>
            <asp:ListItem Value="2">VB.NET</asp:ListItem>
            <asp:ListItem Value="3">C#.NET</asp:ListItem>
        </asp:DropDownList>
   
    </div>
    </form>
</body> 

Image of dropdownlist

How to get the text or value of ListBox in JavaScript?
<head runat="server">
    <title>Untitled Page</title>
    <script type ="text/javascript">
    function getListBox()
    {
     var listbox=document.getElementById("ListBox1");
 
     alert("Selected Value:"+listbox.value+"  
            Selected Text:"+listbox[listbox.selectedIndex].innerText);
    }
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="ListBox1" runat="server" BackColor="#FFFFFF" Font-Bold="True" Font-Names="Verdana"ForeColor="#660066" Height="80px" Style="z-index: 100; left: 240px; position: absolute; top: 48px" Width="80px">
            <asp:ListItem Value="1">SilverLight</asp:ListItem>
            <asp:ListItem Value="2">Ajax</asp:ListItem>
            <asp:ListItem Value="3">JQuery</asp:ListItem>
        </asp:ListBox>
 
        <asp:Button ID="Button1" runat="server" Font-Bold="True" Style="z-index: 102; left: 336px; position: absolute; top: 72px" Text="Click" Width="56px"  
   OnClientClick ="return getListBox();"/>
    
    </div>
    </form>
</body>
</html>
Image of ListBox

Display Popup message before session expiry time and Extend Session if they want to extend in asp.net C#

Write below java script function in .aspx page if u are not using master page..other wise write this function Master page .aspx page

<script language=JavaScript>


    var secondsPassed = 0;
    var minutesBeforeLoggedOut = 0;
    var minutesToWarning = 0;

    function ShowTimePassed() {

        minutesBeforeLoggedOut = parseInt(minutesBeforeLoggedOut);
        secondsPassed += 1;

        if (minutesBeforeLoggedOut == -1) {
            if (secondsPassed == 30) {
                var img = new Image(1, 1);
                img.src = 'KeepAlive.aspx?date=' + escape(new Date());
                secondsPassed = 0;
            }
        }
        else {
            if (secondsPassed == minutesToWarning * 60) {
                var answer;

                var currentTime = new Date();
                var expiredTime = new Date();
                var minutes = expiredTime.getMinutes();
                minutes += minutesBeforeLoggedOut;
                expiredTime.setMinutes(minutes);

                if (minutesBeforeLoggedOut == 1) {

                    answer = confirm("It is now " + currentTime.toLocaleTimeString() + " You have " + minutesBeforeLoggedOut + " minute left before getting logged out. Do you want to extend the session?");

                }
                else {

                    answer = confirm("It is now " + currentTime.toLocaleTimeString() + " You have " + minutesBeforeLoggedOut + " minutes left before getting logged out. Do you want to extend the session?");


                } if (answer) {
                    var img = new Image(1, 1);
                    img.src = 'KeepAlive.aspx?date=' + escape(new Date());
                    secondsPassed = 0;
                    currentTime = new Date();
                    if (currentTime > expiredTime) {
                        alert("You've exceeded the time needed to extend the session. You will be logged out now");
                        window.location = loginUrl;
                    }
                }
            }
        }
    }

    window.setInterval('ShowTimePassed()', 1000);
 

</script>


write below two function is .aspx.cs file


  private void keepAlive()
    {

        //figure out the full url of the logout page configured in web.config + the return url which is the current page

        String logoutUrl = FormsAuthentication.LoginUrl + "?ReturnUrl=" + Request.Url;

         String minutesToWarning = "";
        //figure out how many minutes before time out the user wants to get warned.

        String minutesBeforeLoggedOut = "1";
        if (minutesBeforeLoggedOut == null || minutesBeforeLoggedOut == "")
        {
            minutesBeforeLoggedOut = "1";
        }

        //if the user selected "-1", then it never gets timedout. If not, figure out, how many minutes after the page loaded, give the user the warning
        if (!minutesBeforeLoggedOut.Equals("-1"))
        {
            int formsTimeout = GetFormsTimeout();
         //   int formsTimeout = Session.Timeout;
            minutesToWarning = Convert.ToString(formsTimeout - Convert.ToInt32(minutesBeforeLoggedOut));
        }

       String script = @"
                  

<script language=JavaScript>
                        var minutesToWarning = " + minutesToWarning + @";
                        var minutesBeforeLoggedOut = " + minutesBeforeLoggedOut + @";
                        var loginUrl  = '" + logoutUrl + @"';
                   

</script>
                    ";

        if (!Page.ClientScript.IsClientScriptBlockRegistered("WarnTimeOut"))
            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "WarnTimeOut", script);

    }


    private int GetFormsTimeout()
    {
        System.Xml.XmlDocument x = new System.Xml.XmlDocument();
        x.Load(Request.PhysicalApplicationPath + "/web.config");
        System.Xml.XmlNode node = x.SelectSingleNode("/configuration/system.web/authentication/forms");
        int Timeout = int.Parse(node.Attributes["timeout"].Value, System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
        return Timeout;
    }

and call  keepAlive(); function in Page_Load

 protected void Page_Load(object sender, EventArgs e)
    {
             keepAlive();
    }

and in web.config dont forget to add these lines of code

< authentication mode="Forms">
            <forms timeout="20"/>
        </authentication>


           
       

If your project contains more than one folder and more than one master page..do the same procedure for every master page in every folder in your project

Thanks & Regards

Sathish Sirikonda

Disable Right Click Button on aspx page

Disable Right Click Button on aspx page

If u want to restrict any user  not to copy ur website content so you use this script in tag 
<script language=JavaScript>
var message = "Right Click not allowed!";
function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}
function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}
document.oncontextmenu=new Function("alert(message);return false")
</script>

Web Services and standard web protocols

Web Services and standard web protocols

Web services gain more popularity from last few years in developers and companies. So there are good reasons to understand internals of Web Services.



What are Web Services?
 
Web Service is an application designed to directly interact with other applications all over the world on internet. It describes a standardized way of integrating web based applications. Web services allow different applications from different sources to communicate with each other.
 
Web Services provides an important way for business to communicate with clients and with each other. It provides business logic processes and data through a programmatic interface instead of any traditional user interface. User interface is then added to this application interface to provide specific functionality to users. The basic purpose of Web Service is to provide some functionality from the owner to its clients so that they can use it.
Web Services publish their methods to the world and these methods, when invoked, perform some actions and provide some data in result. Web services sometimes called Application Services.
 
Independent of Operating System and Language
 
Web Services are XML based applications that use XML to communicate with other applications so Web Services are independent of Operating System and Programming Language.  An application using a Web Service is not concerned about the operating system or programming language of that Web Service as all communication is in XML. For example, A Web Service created in Java can be used by an application created in Visual Basic or Windows application can be called by a UNIX application.
 
 
Web Services Protocols
 
Web services use XML based web protocols that include HTTP, XML, SOAP, WSDL and UDDI. XML is used to tag the data, SOAP is used to transfer data, WSDL is used to describe available Web Services and UDDI is used to list the available Web Services.
 
HTTP
 
Hypertext Transfer Protocol (HTTP) is the standardized protocol of communication on the internet by the World Wide Web Consortium (W3C). It is responsible for requesting and transmitting data over the internet. It provides safe recognition of network web server and encrypted communication.
 
XML
 
Extensible Markup Language (XML) is the markup language that is designed to transport and store data in a format that is readable by both human and machine. It enables the transmission, validation and interpretation of data between applications. . XML is used to tag, format and display the data. It allows developers to create their own customized tags. It mainly designed for documents but it is extensively used in Web Services. It is the most common markup language in which the information is written.
 
SOAP
 
Simple Object Access Protocol (SOAP) is the XML based protocol to transfer the data in Web Services. It is the language and platform independent protocol that allows applications in Web Services to communicate via standard internet HTTP. It is the center piece of Web Services and complements all other protocols (XML, WSDL and UDDI). In a simple way, we can say that SOAP is the way in which web services method calls are translate into XML format and sent via HTTP and it allows applications to exchange information over HTTP. SOAP is standardized and recommended by W3C.
 
WSDL
 
Web Services Description language (WSDL) is a standard format to describe and locate web services. It is the XML based language that UDDI uses for Web Services. Every client application that is connected to Web Service can read the WSDL to determine what functions are available on the Web Service. Any special data types are embedded in the WSDL. URL from which Web Service methods can be accessed and communication protocols used by web services are also in the WSDL file. So it contains every detail to allow users to build client applications to use Web Services. WSDL is the W3C recommendation.
 
UDDI
 
Universal Description, Discovery and Integration (UDDI) is the web based directory or registry for listing web services. It enables businesses to list themselves on the internet and discover each other. It allows clients to find Web Services to use them. It is a public library where we can publish Web Services and inquire about Web Services. UDDI includes several ways to find Web Services that client needs to built their application.
 
UDDI registry manages information about service providers and service implementations. Service providers can use UDDI to publicize web services they offer and service clients can use UDDI to discover Web Services according to their requirements. UDDI is based on XML and SOAP standards.
 
 
Criticism on Web Services
 
Web services are often criticized because of security issues. It is the application to application interaction instead of human-application interaction. Issues like authentication, privacy and data integrity are main concerns when using Web Services. Another criticism on Web Services is the complexity in Web Services.
 
 
Benefits of Web Services
 
Although there are some criticisms on Web services but benefits of Web Services have overpowered these criticisms. The communication between applications is easier with Web Services. Information distribution to different clients and consumers is relatively simple task for companies. Web services can be reused when needed and from the past few years there is rapid development in Web Services. 
 
SOAP is a standard for exchanging XML-based messages over a computer network, normally using HTTP.
Purpose of using SOAP:
For many Web services, you need only a combination of XML, HTTP, and an application-specific message protocol. To be sure, SOAP has its uses. But, in my opinion, SOAP’s role is overstated in the early stages of a Web service’s development. Using SOAP for the wrong tasks can easily hijack a Web service development project, because SOAP introduces a large set of problems that are orthogonal to the challenges of building a Web service. SOAP-related issues tend to consume the majority of the development effort.
The most common purpose of Web services today is to exchange XML data. For instance, more than 200 Web services listed on XMethods share that purpose. The classic examples of a stock quote service, weather service, or postal code lookup service are all about sending an XML query message, and receiving an XML reply. That pattern dominates more complex Web services as well: the UDDI registry service or the Liberty Alliance single sign-on and identity federation Web services are all defined in terms of XML-based query-response message exchanges.
At best, SOAP introduces a level of indirection to such XML message exchanges by embedding an XML message in a SOAP envelope. Since the SOAP envelope can carry metadata about the original XML message, such as processing instructions, the envelope can aid a Web service in processing that message. At worst, SOAP makes it difficult, if not impossible, to verify the validity of an XML message traversing between two Web services.
Example:
Here is an example of how a client might format a SOAP message requesting product information from a fictional warehouse web service. The client needs to know which product corresponds with the ID DEVASP123:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
     <getProductDetails xmlns="http://warehouse.example.com/ws">
       <productID> DEVASP123</productID>
     </getProductDetails>
   </soap:Body>
 </soap:Envelope> 
Here is how the warehouse web service might format its reply message with the requested product information:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
     <getProductDetailsResponse xmlns="http://warehouse.example.com/ws">
       <getProductDetailsResult>
         <productName>Toptimate 3-Piece Set</productName>
         <productID> DEVASP123</productID>
         <description>3-Piece luggage set. Black Polyester.</description>
         <price>96.50</price>
         <inStock>true</inStock>
       </getProductDetailsResult>
     </getProductDetailsResponse>
   </soap:Body>
 </soap:Envelope>
How to create and use a Web Service in ASP.NET Visual Studio 2010
 
What is Web Service?
Web Service is an application that is designed to interact with other applications on the internet. Web Services allow a server to expose its functionality that clients can utilize. Web services can publish their methods or messages to the world and these methods, when invoked, perform some action and return some data or result.
Web services allow different applications from different sources to communicate with each other. As all communication in a web service is in XML so it is independent of language, platform and protocol.
 
Create a Web Service

To create a web service in visual studio 2010, follow these steps:
  1. Open New Project
  2. Select .NET Framework 3.5
  3. Select ASP.NET Web Service Application in web either in Visual C# or in Visual Basic
  4. A HelloWorld web method is already in the Service1 class. Write another web method in class Service1 as below

    C#

    [WebMethod]
    public int AddNumbers(int firstNum, int secondNum) {
                int thirdnum = firstNum + secondNum;
                return thirdnum;
     }
     
    VB.NET

    <WebMethod()> _
    Public Function AddNumbers(ByVal firstNum As Integer, ByVal secondNum As Integer)   As Integer
                Dim thirdnum As Integer = firstNum + secondNum
                Return thirdnum
    End Function
     
  5. See web service in browser and copy the URL to add reference of the service when you have to use the service. Select Web Method to see result in XML.

Use Web Service
 
When a web service is created the next step is to use this service. It is also called consuming the Web Service.
 
To use a web service, follow these steps in visual studio 2010:
 
  1. Open New Web Site
  2. Select .NET Framework 3.5
  3. Create an ASP.NET Empty Website either in Visual Basic or Visual C#
  4. Right click on the Website in Solution Explorer
  5. Select Add Service Reference
  6. Select Advanced option in Add Service Reference window
  7. Select Add Web Reference in Service Reference Settings
  8. Enter the copied URL in Add Web Reference window
  9. Change the Web reference name and click Add Reference
  10. Import namespace for the Web Service

    C#
     
    using WebServiceTest;
     
    VB.NET

    Imports WebServiceTest
     
  11. Now drag and drop two labels in aspx page and write below code in Page_Load method of code behind file. Create the instance of the Service1 class and call the method of that class.

    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    <br />

     
    <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

     


  12.  
  13. Write below code in Page_Load method of code behind file. Create the instance of the Service1 class and call the method of that class.

    C#

    Service1 service = new Service1();
    Label1.Text = service.HelloWorld();
    int num = service.AddNumbers(3, 4);
    Label2.Text = "The result is: " + num.ToString();

    VB.NET

    Dim service As New Service1()
    Label1.Text = service.HelloWorld()
    Dim num As Integer = service.AddNumbers(3, 4)
    Label2.Text = "The result is: " & num.ToString()
     
  14. View website in browser, you will see the result of both web methods of Web Service
A web Service created in any ASP.NET language can be consumed in application written in any other ASP.NET language.

How to bind data to Web Service and use this Web Service in ASP.NET


Web Services are created to bind data because these are used by consumers to work with data. You can see articles on DevASP.NET about Web Services. In this article, I will show you simple example of data binding to web service. This data binding procedure can be complex but this example is just for learning purposes.
Follow below steps to create a web service and bind data to it.
  1. Create New Web Site in Visual Studio 2010
  2. Select .NET Framework 3.5
  3. Select ASP.NET Web Service either in Visual C# or in Visual Basic
  4. Add a Class and rename it as ProductsClass
  5. Import namespaces in ProductsCass
    C#
     
    using System.Data;
    using System.Data.SqlClient;
     
    VB.NET
     
    Imports System.Data
    Imports System.Data.SqlClient
     
     
  6. Write below function in ProductsClass to get data
     
    C#
     
    public static DataSet ProductsData() {
        string sqlQuery = "Select * From Products";
        string connString = "Data Source=Local;Initial Catalog=NORTHWND;Integrated Security=True";
        SqlConnection connection = new SqlConnection(connString);
        SqlCommand command = new SqlCommand(sqlQuery, connection);
        SqlDataAdapter da = new SqlDataAdapter(command);
        DataSet ds = new DataSet();
        da.Fill(ds);
        return ds;
    }
     
    VB.NET
     
    Public Shared Function ProductsData() As DataSet
        Dim sqlQuery As String = "Select * From Products"
        Dim connString As String = "Data Source=Local;Initial Catalog=NORTHWND;Integrated Security=True"
        Dim connection As New SqlConnection(connString)
        Dim command As New SqlCommand(sqlQuery, connection)
        Dim da As New SqlDataAdapter(command)
        Dim ds As New DataSet()
        da.Fill(ds)
        Return ds
    End Function
     
    As you can see I have used Products table of NORTHWIND database. This function returns DataSet. I have written a query and set connection to my Server. Then I have created a SqlCommand object by passing query and connection as parameters. Then I have created a SqlDataAdapter object, a DataSet object and fill DataSet object with SqlDataAdapter object.
     
  7. Open Service.cs file and import namespace
     
    C#
    using System.Data;
     
    VB.NET

    Imports System.Data
     
  8. Now write below function in Service.cs file
     
    C#
     
    [WebMethod]
    public DataSet GetProducts() {
        DataSet ds = ProductsClass.ProductsData();
        return ds;
    }
     
    VB.NET
     
    <WebMethod()> _
    Public Function GetProducts() As DataSet
        Dim ds As DataSet = ProductsClass.ProductsData()
        Return ds
    End Function
     
    This function in our Web Service code file returns DataSet. I have created a DataSet object and assigned the data of ProducsData() function of ProductsClass. We will call this method to get data in our consumer web site.
     
  9. See this Web Service in browser and copy the URL of Web Service. We need this URL for service reference to consume this Web Service.
 Now follow below steps to consume this Web Service and get data from this Web Service function.
  1. Open New Web Site
  2. Create an ASP.NET Empty Website either in Visual Basic or Visual C#
  3. Right click on the Website in Solution Explorer
  4. Select Add Service Reference
  5. Select Advanced option in Add Service Reference window
  6. Select Add Web Reference in Service Reference Settings
  7. Enter the copied URL in Add Web Reference window
  8. Change the Web reference name as DataBindWebService and click Add Reference
  9. Import namespace for the Web Service
    C#
     
    using DataBindWebService;
     
    VB.NET
     
    Imports DataBindWebService
     
  10. Drag and Drop a GridView in aspx page
     
     
    <asp:GridView ID="GridView1" runat="server">
     
    </asp:GridView>
     
  11. Write below code in Page_Load method of code behind file
     
    C#

    protected void Page_Load(object sender, EventArgs e) {
        Service service = new Service();
        GridView1.DataSource = service.GetProducts();
        GridView1.DataBind();
    }
     
    VB.NET

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim service As New Service
        GridView1.DataSource = service.GetProducts()
        GridView1.DataBind()
    End Sub
     
    Create a new instance of Web Service and call the GetProducts() method. Bind the data to GridView.
     
  12. View website in browser, you will see the result of data bound Web Service method.

Version history of ASP.NET

ASP.NET Version History---Features Detail
--------------------------------------------------------------------
4.5.1
4.5.1 and Visual Studio 2013
  1. One ASP.NET
  2. ASP.NET Scaffolding
  3. ASP.NET Identity
     
--------------------------------------------------------------------
4.5
4.5 and Visual Studio 2012
  1. Strongly Typed Data Controls
  2. Model Binding
  3. Unobtrusive Validation
  4. Bundling and Minification
  5. Async Support
  6. Support for asynchronous modules and handlers
  7. Friendly URL
  8. HTML5 Features enhancements
  9. Support for WebSocket protocol
  10. oAuth Support
-------------------------------------------------------------------- 
4.0
4.0 and Visual Studio 2010
  1. Introduced ClientIdMode property for Server Control
  2. Routing
  3. Introduced Meta tags MetaKeyword and MetaDescription
  4. Chart Control
-------------------------------------------------------------------- 
3.5
3.5 and Visual Studio 2008
  1. Integrated ASP.NET AJAX
  2. Support LINQ
  3. New Data controls LINQ DataSource, ListView and DataPager
  4. Dynamic Data
  5. Multi-targeting Framework Support
-------------------------------------------------------------------- 
2.0
2.0 and Visual Studio 2005
  1. New Data controls GridView, FormView and DetailsView
  2. DataSource controls SQLDataSource, Object DataSource, AccessDataSource, XMLDataSource and SiteMapDataSource
  3. Navigation controls
  4. Master pages
  5. Cross Page Postbacks
  6. Validation Groups
  7. Themes
  8. Skins
  9. Login controls
  10. Role Management
  11. Profiles
  12. Membership Service
  13. Localization and Globalization
-------------------------------------------------------------------- 
1.1
1.1 and Visual Studio .NET 2003
  1. ASP.NET Mobile controls
  2. Built-in support for ODBC and databases
  3. Internet Protocol version 6 (IPv6) support
-------------------------------------------------------------------- 
1.0
1.0 and Visual Studio .NET
  1. Support for Object-oriented Web application development
  2. Use of DLL class libraries

Introduction to Object Oriented Programming Concepts

Object Oriented Programming(OOP) Features

  • Object oriented programming (OOP) is a programming model where programs are organized around object and data rather than action and logic.
  • OOP allows decomposition of a problem into a number of entities called Object and then builds data and function around these objects.
  • The program is divided into a number of small units called Object. The data and function are build around these objects.
  • The data of the objects can be accessed only by the functions associated with that object.
  • The functions of one object can access the functions of other object.
OOP has the following important features:

Class

A class is the core of any modern Object Oriented Programming language such as C#.
In OOP languages, it is a must to create a class for representing data.
Class is a blueprint of an object that contains variables for storing data and functions to performing operations on these data.
Class will not occupy any memory space and hence it is only a logical representation of data.
To create a class, you simply use the keyword "class" followed by the class name:
class Employee
{

}

Object

Objects are the basic run-time entities in an object oriented system. They may represent a person, a place or any item that the program has to handle.
"Object is a Software bundle of related variable and methods. "
“Object is an instance of a class.”

Class will not occupy any memory space. Hence to work with the data represented by the class, you must create a variable for the class, which is called as an object.
When an object is created by using the keyword new, then memory will be allocated for the class in heap memory area, which is called as an instance and its starting address will be stored in the object in stack memory area.
When an object is created without the keyword new, then memory will not be allocated in heap, i.e., instance will not be created and object in the stack contains the value null.
When an object contains null, then it is not possible to access the members of the class using that object.
class Employee
{

}
Syntax to create an object of class Employee:

Employee objEmp = new Employee();
All the programming languages supporting object oriented programming will be supporting these three main concepts:
  1. Encapsulation
  2. Inheritance
  3. Polymorphism

Abstraction

Abstraction is "To represent the essential feature without representing the background details."
Abstraction lets you focus on what the object does instead of how it does it.
Abstraction provides you a generalized view of your classes or object by providing relevant information.
Abstraction is the process of hiding the working style of an object, and showing the information of an object in an understandable manner.

Real World Example of Abstraction

Suppose you have an object Mobile Phone.
Suppose you have 3 mobile phones as follows:
  • Nokia 1400 (Features:- Calling, SMS)
  • Nokia 2700 (Features:- Calling, SMS, FM Radio, MP3, Camera)
  • Black Berry (Features:-Calling, SMS, FM Radio, MP3, Camera, Video Recording, Reading E-mails)
Abstract information (Necessary and Common Information) for the object "Mobile Phone" is to make a call to any number and can send SMS." so that, for mobile phone object you will have an abstract class like the following:
    abstract class MobilePhone
    {
        public void Calling();
        public void SendSMS();
    }

    public class Nokia1400 : MobilePhone
    {

    }

    public class Nokia2700 : MobilePhone
    {
        public void FMRadio();
        public void MP3();
        public void Camera();
    }

    public class BlackBerry : MobilePhone
    {
        public void FMRadio();
        public void MP3();
        public void Camera();
        public void Recording();
        public void ReadAndSendEmails();
    }
Abstraction means putting all the variables and methods in a class which is necessary.
For example: Abstract class and abstract method.
Abstraction is the common thing.
Examples
  • If somebody in your college tells you to fill an application form, you will fill your details like name, address, data of birth, which semester, percentage you got, etc.
  • If some doctor gives you an application to fill the details, you will fill the details like name, address, date of birth, blood group, height and weight.
See in the above examples what is the common thing?
Age, name, address so you can create the class which consists of the common thing that is called abstract class.
That class is not complete and it can be inherited by another class.

Encapsulation

Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.
Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object.
Encapsulation is like your bag in which you can keep your pen, book, etc. It means this is the property of encapsulating members and functions.
    class Bag
    {
        book;
        pen;
        ReadBook();
    }
Encapsulation means hiding the internal details of an object, i.e., how an object does something.
Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is implemented.
Encapsulation is a technique used to protect the information in an object from the other object.
Hide the data for security such as making the variables as private, and expose the property to access the private data which would be public.
So, when you access the property, you can validate the data and set it.
Example
class Demo
{
   private int _mark;

   public int Mark
   {
     get { return _mark; }
     set { if (_mark > 0) _mark = value; else _mark = 0; }
   }
}

Real World Example of Encapsulation

Let's take an example of Mobile Phone and Mobile Phone Manufacturer.
Suppose you are a Mobile Phone Manufacturer and you designed and developed a Mobile Phone design(class), now by using machinery you are manufacturing a Mobile Phone(object) for selling, when you sell your Mobile Phone, the user only learns how to use the Mobile Phone but not how this Mobile Phone works.
This means that you are creating the class with function and by making object (capsule) of it, you are making availability of the functionality of your class by that object and without the interference in the original class.
Example 2
TV operation
It is encapsulated with cover and we can operate with remote and no need to open TV and change the channel.
Here everything is in private except remote so that anyone can access not to operate and change the things in TV.

  • ENCAPSULATION:- Encapsulation provides the ability to hide the internal details of an object from its users.The concept of encapsulation is also known as data hiding or information hiding. In c# , Encapsulation is implemented using the access modifier keywords.
  1. Public
  2. Private
  3. protected
  4. Internal
  5. Protected Internal

Inheritance

When a class acquire the property of another class, it is known as inheritance.
Inheritance is the process of object reusability.
For example: A child acquires the property of parents.
public class ParentClass
    {
        public ParentClass()
        {
            Console.WriteLine("Parent Constructor.");
        }

        public void print()
        {
            Console.WriteLine("I'm a Parent Class.");
        }
    }

    public class ChildClass : ParentClass
    {
        public ChildClass()
        {
            Console.WriteLine("Child Constructor.");
        }

        public static void Main()
        {
            ChildClass child = new ChildClass();

            child.print();
        }
    }

Output

Parent Constructor. 
Child Constructor. 
I'm a Parent Class. 

Polymorphism

Polymorphism means one name many forms.
One function behaves in different forms.
In other words, "Many forms of a single object is called Polymorphism."

Real World Example of Polymorphism

Example 1
A Teacher behaves with his student.
A Teacher behaves with his/her seniors.
Here teacher is an object but attitude is different in different situations.
Example 2
Person behaves like a SON in the house, at the same time that person behaves like an EMPLOYEE in office.
Example 3
Your mobile phone, one name but many forms:
  • As phone
  • As camera
  • As mp3 player
  • As radio

Polymorphism in .NET

Difference between abstraction and encapsulation is as given in the table below:
Abstraction Encapsulation
1. Abstraction solves the problem in the design level. 1. Encapsulation solves the problem in the implementation level.
2. Abstraction is used for hiding the unwanted data and giving relevant data. 2. Encapsulation means hiding the code and data into a single unit to protect the data from outside world.
3. Abstraction lets you focus on what the object does instead of how it does it. 3. Encapsulation means hiding the internal details or mechanics of how an object does something.
4. Abstraction- Outer layout, used in terms of design.
For example: Outer Look of a Mobile Phone, like it has a display screen and keypad buttons to dial a number.
4. Encapsulation - Inner layout, used in terms of implementation.
For example: Inner Implementation detail of a Mobile Phone, how keypad button and Display Screen are connect with each other using circuits.
The easier way to understand Abstraction and encapsulation is as follows:

Real World Example

Take an example of mobile phone:
You have a mobile phone, you can dial a number using keypad buttons. Even you don't know how these are working internally. This is called abstraction. You have the only information that is needed to dial a number. But not its internal working of mobile.
But how the mobile phone works internally and how keypad buttons are connected with internal circuit is called encapsulation.

2014/09/08

Understanding Transactions and Creating Transaction Enabled WCF Services.

When we talk about transactions in database operations, we need to perform some operation(database operations) in such a way that either all the operations are successful or all of them fail. This would result in the amount information being same once the transaction is successful or it fails.

Properties of Transaction

By definition a transaction must be Atomic, Consistent, Isolated and Durable. What does we mean by all these terms
  • Atomic: Atomic means that all the statements (SQL statement or operations) that are a part of the transaction should work as atomic operation i.e. either all are successful or all should fail.
  • Consistent: This means that in case the atomic transaction success, the database should be in a state that reflect changes. If the transaction fails then database should be exactly like it was when the transaction started.
  • Isolated: If more than one transactions are in process then each of these transactions should work independently and should not effect the other transactions.
  • Durable: Durability means that once the transaction is committed, the changes should be permanent i.e. these changes will get saved in database and should persist no matter what(like power failure or something).
Now having transactions from a simple class library's perspective ot from a simple .Net applications, it is just a matter of calling the operations within a transaction, checking whether all the operations are successful or not and deciding whether to commit or rollback the transaction. Refer this article to know about transactions in normal application:
But from a WCF service perspective, since the service itself may be running on a remote server and all the communication between the service and the client is in form of messages, the service itself need some configuration so that it can be made transaction enabled.
Now in rest of the article we will see how we can configure a WCF service to support transactions and how we can call a WCF operation within transactions.

Using the code

Understanding Two Phase Commit

The WCF transactions happen using two phase commit protocol. Two phase commit protocol is the protocol that is used to enable transactions in a distributed environment. This protocol mainly consist of two phases:
  • Prepare phase: In this phase the client application performs the operations of a WCF service. WCF service determines whether the requested operation will be successful or not and notify the client about the same.
  • Commit Phase: In the commit phase the client checks for the responses it got from the prepare phase and if all the responses are indicating that the operation can be carried out successfully the transaction is committed. If the response from any one of the operations indicates failure then the transaction will be rolled back. The actual operation on the service end will happen in the commit phase.
Now from the protocol, it is pretty clear that the WCF service will have to send the notification of whether the operation will succeed or fail to the client application. It would mean that the One way operations can never support transactions. The operations that support transactions have to follow the Request-Response Model(refer this for details on message exchange modes:

A note on binding

Since services communicate in form of messages the underlying message specifications play a very important role in supporting transactions. To have the possibility of transactions, the WS-AT(WS-AtomicTransaction) protocol need to be used. The binding that supports this is wsHttpBinding. So we will be using this binding to create our transaction enabled service.

Description of the Test Application

To illustrate the above process, let say I have two account holders, one person is trying to transfer some money to other person. From the database perspective this operation consist of two sub-operations i.e.
  • Debiting the first account by specified amount.
  • Secondly, crediting the second account with required amount.
Now from a technical perspective, if the first operation is successful but second one fails the result would be that the first persons account will be debited but second one will not be credited i.e. we loose the amount of information. The other way round will in fact increase the amount ion second account without even debiting the first amount.
So the bottom-line here is that we need either both of them to be successful to both of them should fail. Success of any one operation will result in inconsistent results and thus even if one operation fails we need to rollback what we did in the other operation. This is precisely where transaction are useful.
Let us say that the operations for credit and debit are exposed separately from a service. What we need to do is that, we need to transaction enable this service and then call these two methods within a transaction. The transaction will be committed only when both the operation indicate success. In case any one operation indicates failure or throws an exception, the transaction will not be committed.

Creating the Service

Let us create a simple service with a ServiceContract that exposes operations to debit an account, credit an account and get the account balance information for any account.
[ServiceContract]
public interface IService1
{
    [OperationContract]
    bool PerformCreditTransaction(string creditAccountID, double amount);

    [OperationContract]
    bool PerformDebitTransaction(string debitAccountID, double amount);

    [OperationContract]
    decimal GetAccountDetails(int id);
}
Now we want the operations PerformCreditTransaction and PerformDebitTransaction to work within a transaction. To do this we need to make some configuration in the service. The very first thing that is required with the OperationContract is to set the TransactionFlow property with the desired TransactionFlowOption. There are 3 possible values for TransactionFlowOption:
  • Mandatory: This specifies that this function can only be called within a transaction.
  • Allowed: This specifies that this operation can be called within a transaction but its not mandatory.
  • NotAllowed: This specifies that this operation can not be called within a transaction.
Now for both our operations, we want the operations to be called mandatory within a transaction so we will specify them with this option.
[ServiceContract]
public interface IService1
{
    [OperationContract, TransactionFlow(TransactionFlowOption.Mandatory)]
    bool PerformCreditTransaction(string creditAccountID, double amount);

    [OperationContract, TransactionFlow(TransactionFlowOption.Mandatory)]
    bool PerformDebitTransaction(string debitAccountID, double amount);

    [OperationContract]
    decimal GetAccountDetails(int id);
}
Now to illustrate the implementation part, We will work on a small application that contains a single table database. This table contains the account id and the amount present in the account.
The sample DB table looks like:

The UI will look like:

And now to perform these operations, we will write simple ADO.NET code in our service implementation. The important thing from the service implementation perspective is that the service implementation also needs to be decorated/adorned with OperationBehavior attribute with TransactionScopeRequired property set to true. So now let us look at the sample implementation of the service operations.
public class Service1 : IService1
{
    readonly string CONNECTION_STRING = ConfigurationManager.ConnectionStrings["SampleDbConnectionString1"].ConnectionString;

    [OperationBehavior(TransactionScopeRequired = true)]
    public bool PerformCreditTransaction(string creditAccountID, double amount)
    {
        bool creditResult = false;

        try
        {
            using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
            {
                con.Open();

                // And now do a credit
                using (SqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = string.Format(
                        "update Account set Amount = Amount + {0} where ID = {1}",
                        amount, creditAccountID);

                    // Let us emulate some failure here to see the that transaction will not
                    // get committed
                    // return false;

                    creditResult = cmd.ExecuteNonQuery() == 1;
                }
            }
        }
        catch
        {
            throw new FaultException("Something went wring during credit");
        }
        return creditResult;
    }

    [OperationBehavior(TransactionScopeRequired = true)]
    public bool PerformDebitTransaction(string debitAccountID, double amount)
    {
        bool debitResult = false;

        try
        {
            using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
            {
                con.Open();

                // Let us do a debit
                using (SqlCommand cmd = con.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = string.Format(
                        "update Account set Amount = Amount - {0} where ID = {1}",
                        amount, debitAccountID);

                    debitResult = cmd.ExecuteNonQuery() == 1;
                }
            }
        }
        catch
        {
            throw new FaultException("Something went wring during debit");
        }
        return debitResult;
    }

    public decimal GetAccountDetails(int id)
    {
        decimal? result = null;

        using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
        {
            using (SqlCommand cmd = con.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = string.Format("select Amount from Account where ID = {0}", id);

                try
                {
                    con.Open();
                    result = cmd.ExecuteScalar() as decimal?;
                }
                catch (Exception ex)
                {
                    throw new FaultException(ex.Message);
                }
            }
        }

        if (result.HasValue)
        {
            return result.Value;
        }
        else
        {
            throw new FaultException("Unable to retrieve the amount");
        }
    }
}
Note: The code is written to elaborate the transaction enabled services only, it is not as per the coding standards i.e it is vulnerable to SQL injection. It should not be taken as code that could go in production. It is just the sample code and has a lot of scope for improvement.
Now we have our ServiceContract ready and service implementation ready. Let us now use the appropriate binding i.e. wsHttpBinding to use this service. Also, in the service configuration we need to specify that this service is transaction enabled. This can be done by setting the transactionFlow property of the binding configuration of wsHttpBiding to true
Note: Please refer the web.config of the sample code to see how this is done.

Test Application

From our test application, we will simply call the functions within a transaction(using TransactionScope). We will check both the operations' return value, if both of the indicates success, we will commit the transaction(by calling Complete method on TransactionScope object). If any operation fails we will rollback the transaction by not calling Complete function and simply letting the TransactionScope object go out of scope).
private void PerformTransaction(string creditAccountID, string debitAccountID, double amount)
{
    // they will be used to decide whether to commit or rollback the transaction
    bool debitResult = false;
    bool creditResult = false;

    try
    {
        using (TransactionScope ts = new TransactionScope())
        {
            using (ServiceReference1.Service1Client client = new ServiceReference1.Service1Client())
            {
                debitResult = client.PerformDebitTransaction(debitAccountID, amount);
                creditResult = client.PerformCreditTransaction(creditAccountID, amount);
            }

            if (debitResult && creditResult)
            {
                // To commit the transaction 
                ts.Complete();
            }
        }
    }
    catch
    {
        // the transaction scope will take care of rolling back
    }
}
The code currently will work fine i.e. both the methods will return true and the transaction will get committed. To check the rollback action, we have a simple return false; statement commented in our service's PerformCreditTransaction operation, un-comment this statement to check that the transaction will not get committed.
Note: The code snippets shows the relevant code in the context. Please look at the sample code to get the full understanding.
So now we have a service that supports transactions. Before wrapping up let is look at the main operations we need in order to make a service transaction enabled.
  1. Decorate the OperationContract with required TransactionFlowOption.
  2. Decorate the operation implementation with OperationBehavior with TransactionScopeRequired as true.
  3. Use wsHttpBinding to utilize the underlying WS-AtomicTransaction protocol.
  4. Specify the transactionFlow property of the binding configuration of wsHttpBinding as true.

 What is AI? Artificial Intelligence (AI) is the ability of machines or computer systems to perform tasks that normally require human intell...