Tuesday, 29 January 2013

Allow only Numeric values in ASP Text box control using JavaScript

Write the following code in .aspx head tag

<script language="Javascript">
       <!--
       function isNumberKey(evt)
       {
          var charCode = (evt.which) ? evt.which : event.keyCode
          if (charCode != 46 && charCode > 31
            && (charCode < 48 || charCode > 57))
             return false;

          return true;
       }
       //-->
</script>

Call this event on required textboxes

<asp:TextBox ID="Txt_Others" runat="server" onkeypress="return isNumberKey(event)"
                    CssClass="TextBox" required="" Text="0"></asp:TextBox>

Thursday, 17 January 2013

Delagates in C#

Definition:

A delegate is a type safe “Function Pointer” which holds references to static or instance methods. Delegates are used to call methods dynamically at runtime (do not scratch your head; you will understand this by examples).

Trival Delegate Example:

public delegate void MyDelegate(string text);
protected void Page_Load(object sender, EventArgs e)
{
    MyDelegate d = new MyDelegate(MyMethod);
    //d += new MyDelegate(MyMethod1);
    d("hello");
}
private void MyMethod(string text)
{
    Response.Write(text);
}
 
Reference 

Differences between Stored Procedures and Functions

  • Procedure can return zero or n values whereas function can return one value which is mandatory.
  • Procedures can have input/output parameters for it whereas functions can have only input parameters.
  • Procedure allows select as well as DML statement in it whereas function allows only select statement in it.
  • Functions can be called from procedure whereas procedures cannot be called from function.
  • Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.
  • We can go for transaction management in procedure whereas we can't go in function.
  • Procedures can not be utilized in a select statement whereas function can be embedded in a select statement.

Handling Application_Error in ASP.NET using app's global.asax

Write the following code in global.asax file 

protected void Application_Error(Object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    if (ex is ThreadAbortException)
        return;
    Logger.Error(LoggerType.Global, ex, "Exception");
    Response.Redirect("unexpectederror.htm");
}
 
Click here for Reference Page

How to Read, Merge two DataSets from two Xml files & write it to a new Xml file

    XmlTextReader readerOne = new XmlTextReader("C:\\generated.xml");
    XmlTextReader readerTwo = new XmlTextReader("C:\\your-file.xml");

    DataSet dsOne = new DataSet();
    dsOne.ReadXml(readerOne);

    DataSet dsTwo = new DataSet();
    dsTwo.ReadXml(readerTwo);

    dsOne.Merge(dsTwo);
    dsOne.WriteXml("C:\\CompleteResource.xml");
    Console.WriteLine("Merge completed");
 
Reference link: 
http://stackoverflow.com/questions/11394624/inject-one-xml-file-in-the-other-merge-two-xml-files-in-visual-studio-2010 

Friday, 11 January 2013

How to create a countdown timer using C# and ASP.NET AJAX

Please check the below sample:
 
 
In .aspx page 

<div id="timelabel"></div>
 <script type="text/javascript">

var leave =<%=seconds %>;


CounterTimer();
var interv=setInterval(CounterTimer,1000);


function CounterTimer()
{
var day = Math.floor(leave / ( 60 * 60 * 24))
var hour = Math.floor(leave / 3600) - (day * 24)
var minute = Math.floor(leave / 60) - (day * 24 *60) - (hour * 60)
var second = Math.floor(leave) - (day * 24 *60*60) - (hour * 60 * 60) - (minute*60)


hour=hour<10 ? "0" + hour : hour;
minute=minute<10 ? "0" + minute : minute;
second=second<10 ? "0" + second : second;


var remain=day + " days   "+hour + ":"+minute+":"+second;
leave=leave-1;


document.getElementById("timelabel").innerText=remain;


}






 
In .aspx page.cs
 
    public double seconds;
    protected void Page_Load(object sender, EventArgs e)
    {
        seconds = (GetEndTime() - GetStartTime()).TotalSeconds;


    }
    private DateTime GetStartTime()
    {
        return DateTime.Now;
    }
    private DateTime GetEndTime()
    {
        return new DateTime(2008, 7, 23, 8, 10, 0);
    }

Change GridView row color based on condition in C# (GridView.RowDataBound Event)

 protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        string value = "";
        string value2 = "";
        double cval;
        double sval;
        double color;
        double round;
        double reversal;
     
        value = e.Row.Cells[4].Text.ToString().Trim();
        value2 = e.Row.Cells[3].Text.ToString().Trim();

        if (value != "&nbsp;" && value != "" )
        {
            if(value == "0" && value2 != "0" )
            {
                e.Row.Cells[1].Style.Add("background-color", "GREEN");
                e.Row.Cells[2].Style.Add("background-color", "GREEN");
            }

            else if( value != "0" && value2 == "0")
            {
                e.Row.Cells[1].Style.Add("background-color", "PURPLE");
                e.Row.Cells[2].Style.Add("background-color", "PURPLE");
            }

            else
            {
            cval = Convert.ToDouble(value);
            sval = Convert.ToDouble(value2);

            color = cval / sval * 100;
            round = Math.Round(color);
            reversal = cval - sval;
             

            if (round <= 25)
            {
                e.Row.Cells[1].Style.Add("background-color", "GREEN");
                e.Row.Cells[2].Style.Add("background-color", "GREEN");
            }

            else if (round > 25 && round <= 50)
            {
                e.Row.Cells[1].Style.Add("background-color", "BLUE");
                e.Row.Cells[2].Style.Add("background-color", "BLUE");
            }
            else if (round > 50 && round < 75)
            {
                e.Row.Cells[1].Style.Add("background-color", "ORANGE");
                e.Row.Cells[2].Style.Add("background-color", "ORANGE");
            }

            else if (round >= 75)
            {
                e.Row.Cells[1].Style.Add("background-color", "RED");
                e.Row.Cells[2].Style.Add("background-color", "RED");
            }
        }
        }    
    }

Monday, 7 January 2013

WCF Interview Questions



1. What is the difference between WCF and ASMX Web Services?
Simple and basic difference is that ASMX or ASP.NET web service is designed to send and receive messages using SOAP over HTTP only. While WCF can exchange messages using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP, MSMQ, NamedPipes etc).
Another tutorial WCF Vs ASMX has detailed discussion on it. 

2. What are WCF Service Endpoints? Explain.
For Windows Communication Foundation services to be consumed, it’s necessary that it must be exposed; Clients need information about service to communicate with it. This is where service endpoints play their role.
A WCF service endpoint has three basic elements i.e. Address, Binding and Contract.
  • Address: It defines "WHERE". Address is the URL that identifies the location of the service.
  • Binding: It defines "HOW". Binding defines how the service can be accessed.
  • Contract: It defines "WHAT". Contract identifies what is exposed by the service.
3. What are the possible ways of hosting a WCF service? Explain.
For a Windows Communication Foundation service to host, we need at least a managed process, a ServiceHost instance and an Endpoint configured. Possible approaches for hosting a service are:
  1. Hosting in a Managed Application/ Self Hosting
    1. Console Application
    2. Windows Application
    3. Windows Service
  2. Hosting on Web Server
    1. IIS 6.0 (ASP.NET Application supports only HTTP)
    2. Windows Process Activation Service (WAS) i.e. IIS 7.0 supports HTTP, TCP, NamedPipes, MSMQ.
4. How we can achieve Operation Overloading while exposing WCF Services?
By default, WSDL doesn’t support operation overloading. Overloading behavior can be achieved by using "Name" property of OperationContract attribute.
[ServiceContract]
interface IMyCalculator
{
   [OperationContract(Name = "SumInt")]
   int Sum(int arg1,int arg2);

   [OperationContract(Name = "SumDouble")]
   double Sum(double arg1,double arg2);
}
When the proxy will be generated for these operations, it will have 2 methods with different names i.e. SumInt and SumDouble. 

5. What Message Exchange Patterns (MEPs) supported by WCF? Explain each of them briefly.
1. Request/Response 2. One Way 3. Duplex
Request/Response
It’s the default pattern. In this pattern, a response message will always be generated to consumer when the operation is called, even with the void return type. In this scenario, response will have empty SOAP body.
One Way
In some cases, we are interested to send a message to service in order to execute certain business functionality but not interested in receiving anything back. OneWay MEP will work in such scenarios. If we want queued message delivery, OneWay is the only available option.
Duplex
The Duplex MEP is basically a two-way message channel. In some cases, we want to send a message to service to initiate some longer-running processing and require a notification back from service in order to confirm that the requested process has been completed. 

6. What is DataContractSerializer and How its different from XmlSerializer?
Serialization is the process of converting an object instance to a portable and transferable format. So, whenever we are talking about web services, serialization is very important.
Windows Communication Foundation has DataContractSerializer that is new in .NET 3.0 and uses opt-in approach as compared to XmlSerializer that uses opt-out. Opt-in means specify whatever we want to serialize while Opt-out means you don’t have to specify each and every property to serialize, specify only those you don’t want to serialize. DataContractSerializer is about 10% faster than XmlSerializer but it has almost no control over how the object will be serialized. If we wanted to have more control over how object should be serialized that XmlSerializer is a better choice. 

7. How we can use MessageContract partially with DataContract for a service operation in WCF?
MessageContract must be used all or none. If we are using MessageContract into an operation signature, then we must use MessageContract as the only parameter type and as the return type of the operation.

8. Which standard binding could be used for a service that was designed to replace an existing ASMX web service?
The basicHttpBinding standard binding is designed to expose a service as if it is an ASMX/ASP.NET web service. This will enable us to support existing clients as applications are upgrade to WCF. 

9. Please explain briefly different Instance Modes in WCF?
WCF will bind an incoming message request to a particular service instance, so the available modes are:
  • Per Call: instance created for each call, most efficient in term of memory but need to maintain session.
  • Per Session: Instance created for a complete session of a user. Session is maintained.
  • Single: Only one instance created for all clients/users and shared among all.Least efficient in terms of memory.
10. Please explain different modes of security in WCF? Or Explain the difference between Transport and Message Level Security.
In Windows Communication Foundation, we can configure to use security at different levels
a. Transport Level security means providing security at the transport layer itself. When dealing with security at Transport level, we are concerned about integrity, privacy and authentication of message as it travels along the physical wire. It depends on the binding being used that how WCF makes it secure because most of the bindings have built-in security.
            <netTcpBinding>
            <binding name="netTcpTransportBinding">
               <security mode="Transport">
                          <Transport clientCredentialType="Windows" />
               </security>
            </binding>
            </netTcpBinding>
b. Message Level Security For Tranport level security, we actually ensure the transport that is being used should be secured but in message level security, we actually secure the message. We encrypt the message before transporting it.
             <wsHttpBinding>
             <binding name="wsHttpMessageBinding">
               <security mode="Message">
                           <Message clientCredentialType="UserName" />
               </security>
              </binding>
             </wsHttpBinding>
It totally depends upon the requirements but we can use a mixed security mode also as follows:
             <basicHttpBinding>
             <binding name="basicHttp">
               <security mode="TransportWithMessageCredential">
                          <Transport />
                               <Message clientCredentialType="UserName" />
               </security>
             </binding>
             </basicHttpBinding>



Friday, 4 January 2013

Dynamically Adding TextBox Control to ASPNET Table

This demo shows how to generate a Table with TextBoxes dynamically based from the number of Columns and Rows entered from the TextBox control and print the values of the dynamically added TextBox on the page. See the screen shot below:



To start, let’s declare the following global variables below:

private int numOfRows = 0;
private int numOfColumns = 0;

Here’s the code block for the generating the Tables with TextBoxes.

private void GenerateTable(int colsCount, int rowsCount)
{
        //Creat the Table and Add it to the Page
        Table table = new Table();
        table.ID = "Table1";
        Page.Form.Controls.Add(table);

        // Now iterate through the table and add your controls
        for (int i = 0; i < rowsCount; i++){
            TableRow row = new TableRow();
            for (int j = 0; j < colsCount; j++){
                TableCell cell = new TableCell();
                TextBox tb = new TextBox();

                // Set a unique ID for each TextBox added
                tb.ID = "TextBoxRow_" + i + "Col_" + j;
                // Add the control to the TableCell
                cell.Controls.Add(tb);
                // Add the TableCell to the TableRow
                row.Cells.Add(cell);
            }

            // Add the TableRow to the Table
            table.Rows.Add(row);
        }
}


As you can see from above code, we just simply create a blank table and add it to the form and then fill the table with columns and  rows of TextBoxes based from the values of rowsCount and colsCount.
Now let’s call the method above on Page_Load event to recreate the Table when it post backs.

protected void Page_Load(object sender, EventArgs e)
{
         // the two paramters are declared globally
         GenerateTable(numOfColumns, numOfRows);
}

Now let’s call the method above on Button Click event (Generate Table) and pass the necessary parameters needed, see below code block.

protected void Button1_Click(object sender, EventArgs e)
{
        //Check if the inputs are numbers
        if (int.TryParse(TextBox1.Text.Trim(), out numOfColumns) && int.TryParse(TextBox2.Text.Trim(), out numOfRows))
        {
            //Generate the Table based from the inputs
            GenerateTable(numOfColumns, numOfRows);

            //Store the current Rows and Columns In ViewState as a reference value when it post backs
            ViewState["cols"] = numOfColumns;
            ViewState["rows"] = numOfRows;
        }
        else
        {
            Response.Write("Values are not numeric!");
        }
}

Since we are done creating our Table with TextBoxes dynamically then we can grab the values entered from the dynamic TextBox using Request.Form method. Here’s the code block below.

protected void Button2_Click(object sender, EventArgs e)
{
    //Check if ViewState values are null
    if (ViewState["cols"] != null && ViewState["rows"] != null)
    {
        //Find the Table in the page
        Table table = (Table)Page.FindControl("Table1");
        if (table != null)
        {
            //Re create the Table with the current rows and columns
            GenerateTable(int.Parse(ViewState["cols"].ToString()), int.Parse(ViewState["rows"].ToString()));

            // Now we can loop through the rows and columns of the Table and get the values from the TextBoxes
            for (int i = 0; i < int.Parse(ViewState["rows"].ToString()) ; i++)
            {
                for (int j = 0; j < int.Parse(ViewState["cols"].ToString()); j++)
                {
                    //Print the values entered
                    if (Request.Form["TextBoxRow_" + i + "Col_" + j] != string.Empty)
                    {
                        Response.Write(Request.Form["TextBoxRow_" + i + "Col_" + j] + "<BR/>");
                    }
                }
            }
        }
    }
}



That’s it! I hope someone find this pot useful!