Friday 29 July 2016

Example and Use of Delegate using user control

Introduction: In this Article we will discuss about how to create and raise the event for user control which is being used on the application. So as much as we know about the delegate which is normally known as function pointer in C# by using a delegate we have to raise an event to the user control which will show the content of the event on the main page or .aspx page. Here I am going to show you a simple example of delegate. Here I have one user control and one .aspx page. In which user control have a button only and .aspx page have a label and a dropdown list whenever we select any value from the drop down list and click on the button it will show the name of content at the main page. here we will call a method on main page using delegate.
Now we are going to make the project let us see how it is created follow the steps given below.
Step 1:
  1. Open the Visual Studio 2010.
  2. Open the web site application.
  3. Give any name.
Website Application
Step 2:  Now add a new folder to the site name as controls
  1. Add new item name as Web User Control to that folder.
  2. Click OK.
  3. It will look like as into the website shown below.
Add User Control
Step 3: Now we are going to drag and drop a button control on the Controls/WebUserControl.ascx.We can add the button control to the user control by writing the code given below to the source page of Controls/WebUserControl.ascx file which is given below.
Code:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"Inherits="Controls_WebUserControl" %><asp:Button ID="Button1" runat="server" Text="Click me!" BackColor="#9999FF"BorderColor="Fuchsia" BorderStyle="Groove" onclick="Button1_Click" />
Step 4: Further you have to write the code in the Controls/WebUserControl.ascx.cs file of the user control.
Code :using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class Controls_WebUserControl : System.Web.UI.UserControl{
   // Delegate declaration  public delegate void btn_Click(string str);
   // Event declaration  public event btn_Click btnHandler;
   // Page load  protected void Page_Load(object sender, EventArgs e)
  {
  }
  protected void Button1_Click(object sender, EventArgs e)
  {
     // Check if event is null     if (btnHandler != null)
      btnHandler(string.Empty);
     // Write some text to output      Response.Write("User Control's Button Click <BR/>");
  }
}
Code Description: In the above code we have written simple a delegate and an event handler and on click event of the button we have to check whether the event handler is empty or not if it have any argument then it will raise the event.
Step 5: Now we have to open the source file of default.aspx and write the code given below.
Code :
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%
@ Register Src="~/Controls/WebUserControl.ascx" TagName="WebUserControl"TagPrefix="BC" 
%>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"></asp:Content>
<
asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">    <h2>        Welcome to ASP.NET!
    </h2>   <p>   <asp:Label ID="lbl" Text=" Main Page Content : " runat
="server" 
BackColor="#0099FF"></asp:Label>        <asp:DropDownList ID="dropdownselect" runat="server" BackColor="#FFCC99"Height="59px" Width="105px">            <asp:ListItem>Amit</asp:ListItem>            <asp:ListItem>Alok</asp:ListItem>            <asp:ListItem>Rajesh</asp:ListItem>            <asp:ListItem>Manoj</asp:ListItem>            <asp:ListItem>Manish</asp:ListItem>        </asp:DropDownList>        <br />        <br />        <BC:WebUserControl ID="WebUserControl1" runat="server" />   </p></asp:Content>
Code Description: Here we have add only one label and a dropdown list to the default page. Further we are using the user control by adding the directive to the source file of default.aspx.
Step 6: In this step we will write the code for the default.aspx.cs page which is given below.
Code :
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class _Default : System.Web.UI.Page{
    protected void Page_Load(object sender, EventArgs e)
      { 
            WebUserControl1.btnHandler += newControls_WebUserControl.btn_Click(WebUserControl1_btnHandler);
      }
      void WebUserControl1_btnHandler(string str)
      {
           Response.Write("Main Page Event<BR/>Selected Value of drop down list is:    "  +                                        dropdownselect.SelectedItem.Text + "<BR/>");
      }   
}
Code Description: The above code will declare and define event of user control, when user Clicks on button which is inside user control. The given below event raised as I have called raised that event on button click.
Step 7: Now build the application by click on build option.
Before Run:
Before Run
Step 8: Further we have to run the application by pressing F5.
After Run: Select the name from the drop down list.
Select Item
Output : After selection Click the button user control it will raise an event which is shown in the output given below.
OutputE

Monday 27 June 2016

Throttling in WCF

Throttling

WCF throttling provides some properties that you can use to limit how many instances or sessions are created at the application level. Performance of the WCF service can be improved by creating proper instance.
AttributeDescription
maxConcurrentCallsLimits the total number of calls that can currently be in progress across all service instances. The default is 16.
maxConcurrentInstancesThe number of InstanceContext objects that execute at one time across a ServiceHost. The default is Int32.MaxValue.
maxConcurrentSessionsA positive integer that limits the number of sessions a ServiceHost object can accept. The default is 10.
Service Throttling can be configured either Adminstractive or Programatically

Administrative(configuration file)

Using <serviceThrottling> tag of the Service Behavior, you can configure the maxConcurrentCallsmaxConcurrentInstances ,maxConcurrentSessions property as shown below.
<system.serviceModel>
    <services >
      <service behaviorConfiguration="ServiceBehavior"  name="MyService">
        <endpoint address="" binding="wsHttpBinding" contract="IMyService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true "/>
          <serviceThrottling maxConcurrentCalls="500"
 maxConcurrentInstances ="100" 
maxConcurrentSessions ="200"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Programming Model

Use ServiceThrottlingBehavior object to set concurrent calls, session and instance property.
           ServiceHost host = new ServiceHost(typeof(MyService));
           ServiceThrottlingBehavior throttle
 = host.Description.Behaviors.Find();
            if (throttle == null)
            {
                throttle = new ServiceThrottlingBehavior();
                throttle.MaxConcurrentCalls = 500;
                throttle.MaxConcurrentSessions = 200;
                throttle.MaxConcurrentInstances = 100;
                host.Description.Behaviors.Add(throttle);
            }

            host.Open();
   

Sunday 26 June 2016

Extension Method in C#

To put it in a simple manner, Extension Methods have been introduced in .NET 3.5 framework to add methods to a class without altering the code of that class. Most of the times you don't have access to create your own methods in the third party dlls and you want to write your own method in that class, then the first question comes in your mind, how will I handle it?

The answer is simple: "Extension Methods".

Why Extension Method: Another question is, why do we need to use the extension methods, we can create our own methods in client application or in other class library and we can call those methods from the client application but the important point is, these methods would not be the part of that class (class of the third party dll). So adding the extension methods in the class, you are indirectly including another behavior in that class. I am talking about the class which is the part of the third party dll (Most Important).

So when you create your own extension methods for specific types those methods would be accessible for that type.

This can be easily understood by the following diagram:

ExMtd1.gif

(I am object of the class)

After some time, client application wants to add another behavior in that class; let's say 'talk' then extension methods can be used to add this extra behavior in that class without altering any code.

ExMtd2.gif

Implementation: The following is the structure of the third party class, which is not accessible to the developer. This class contains a method 'Walk'.
public class Class1{
    public String Walk()
    {
        return "I can Walk";    }}
Now it's time to create the Extension Method. Just use the following steps:

Step 1: Create the Static Class

Step 2: Create the Static Method and give any logical name to it. 

Step 3: In the Extension Method Parameter, just pass this along with the object type and 
the object name as given below:

ExMtd3.gif

The client application can access both the method "Walk" and the extension method "TalkExtMethod":
Class1 obj = new Class1 ();
Obj.TalkExtMethod ()  
obj.Walk ()


Benefits: There may be various benefits of using the Extension Methods in your code. Let's say you are using the method1 () of the class in the third party dll and the object instantiation has failed due to another reason; then you will get the object reference error while calling the method1 () if you did not handle the null reference check.
Class1 obj = GetClass1Object ();//If the obj is null, you will get the object reference errorobj.Method1();

Although the following code is safer than previous one but the problem is you will have to include this check every time when you call the Method1 and if the developer forgets to include this check in the code then the program throws an object reference error.
Class1 obj = GetClass1Object ();if (obj!= null)
{
    obj.Method1 ();
}

If we use the extension method to solve this problem we get outstanding results. Instead of checking the null reference every time in the code we handle it in the extension methods which is called by the client application.
public static string Method1ExtMethod(this Class1 objClass)
{
    //If the obj is not null, then call the Method1()
    if (objClass! = null)
    {
        return objClass.Method1 ();
    }
    return string.Empty;    
}
Class1 obj = GetClass1Object ();//Don't include any check whether the object is null or notobj.Method1ExtMethod()

Wednesday 27 April 2016

HTML Table Row Grouping with jQuery

It’s easy to group data in SQL statement, but if you have to display it using HTML table, It’s not drag and drop as in reporting environment. One way to group on server side and draw tr td accordingly. But If it is already created with tons of functionality attached, It’s risky to change. Don’t worry, you can do it easily with jQuery.
html table row grouping jquery

HTML:

Let’s take following HTML table as an example:
?
<table id="myTable" border="1" cellpadding="3" cellspacing="0">
<tr><th>Category</th><th>Product</th><th>Size</th><th>Price</th><th>Shipping</th></tr>
<tr><td>Category-1</td><td>Product-1</td><td>Big</td><td>102</td><td>Free</td></tr>
<tr><td>Category-1</td><td>Product-1</td><td>Big</td><td>132</td><td>Free</td></tr>
<tr><td>Category-1</td><td>Product-2</td><td>Big</td><td>130</td><td>Free</td></tr>
<tr><td>Category-1</td><td>Product-2</td><td>Small</td><td>100</td><td>Free</td></tr>
<tr><td>Category-2</td><td>Product-3</td><td>Big</td><td>130</td><td>Free</td></tr>
<tr><td>Category-2</td><td>Product-3</td><td>Big</td><td>100</td><td>Free</td></tr>
<tr><td>Category-2</td><td>Product-3</td><td>Small</td><td>100</td><td>10</td></tr>
<tr><td>Category-2</td><td>Product-4</td><td>Big</td><td>150</td><td>10</td></tr>
<tr><td>Category-3</td><td>Product-5</td><td>Big</td><td>150</td><td>10</td></tr>
<tr><td>Category-3</td><td>Product-5</td><td>Small</td><td>120</td><td>10</td></tr>
<tr><td>Category-3</td><td>Product-5</td><td>Big</td><td>120</td><td>Free</td></tr>
<tr><td>Category-4</td><td>Product-6</td><td>Big</td><td>120</td><td>10</td></tr>
<tr><td>Category-4</td><td>Product-6</td><td>Small</td><td>120</td><td>10</td></tr>
</table>

Script:

Before using the following method, Make sure the data is sorted. The logic is to check row by row if data is same in next row’s td, remove next row’s td and increase rowspan of current row’s td.
?
$(function() { 
//Created By: Brij Mohan
//Website: http://techbrij.com
function groupTable($rows, startIndex, total){
if (total === 0){
return;
}
var i , currentIndex = startIndex, count=1, lst=[];
var tds = $rows.find('td:eq('+ currentIndex +')');
var ctrl = $(tds[0]);
lst.push($rows[0]);
for (i=1;i<=tds.length;i++){
if (ctrl.text() ==  $(tds[i]).text()){
count++;
$(tds[i]).addClass('deleted');
lst.push($rows[i]);
}
else{
if (count>1){
ctrl.attr('rowspan',count);
groupTable($(lst),startIndex+1,total-1)
}
count=1;
lst = [];
ctrl=$(tds[i]);
lst.push($rows[i]);
}
}
}
groupTable($('#myTable tr:has(td)'),0,3);
$('#myTable .deleted').remove();
});
groupTable method has 3 arguments:
$rows: jQuery object of table rows to be grouped
startIndex: index of first column to be grouped
total: total number of columns to be grouped
In above code startIndex =0 and total = 3 it means table is grouped by first, second and third column. After grouping, you need to remove deleted class elements like this:
$(‘#myTable .deleted’).remove();
you can use code, but need to keep CREDIT COMMENT. The idea came to implement this just one hour ago. So the code can be optimized. Anyway, let me know if you have any issue.