28 February 2012

Click event when Enter button is Pressed in asp.net

Click event when Enter button is Pressed in asp.net

Javascript
function clickButton(e, buttonid){
      var evt = e ? e : window.event;
      var bt = document.getElementById(buttonid);
      if (bt){
          if (evt.keyCode == 13){
                bt.click();
                return false;
          }
      }
}




//code behind TextBox1.Attributes.Add("onkeypress", "return clickButton(event,'" + Button1.ClientID + "')");
 

The code behind generates the following code:

<    asp:Button id="Button1"
           Text="Submit"
           OnClick="SubmitBtn_Click" 
           runat="server" onkeypress="return clickButton(event,'Button1')"/   >




This causes web control Button1 to be clicked when the enter key is hit inside TextBox1.


12 January 2012

Naming Conventions in Dotnet – C# and VB.Net


Naming Conventions in Dotnet – C# and VB.Net



Use the following three conventions for capitalizing identifiers.

Pascal Case
The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. You can use Pascal case for identifiers of three or more characters. For example:

BackColor

Use this for Class, Interface, Enum, function name and Static Field

Camel Case
The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized. For example:

backColor

Use this for Parameter name,
Uppercase
All letters in the identifier are capitalized. Use this convention only for identifiers that consist of two or fewer letters. For example:

System.IO
System.Web.IO

You might also have to capitalize identifiers to maintain compatibility with existing, unmanaged symbol schemes, where all uppercase characters are often used for enumerations and constant values. In general, these symbols should not be visible outside of the assembly that uses them

10 January 2012

Export Datatable to Excel in C# Windows application


// Export Datatable to Excel in C# Windows application

using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace ExportExcel
{
    public partial class ExportDatatabletoExcel : Form
    {
        public ExportDatatabletoExcel()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
         
            DataTable dt = new DataTable();

            //Add Datacolumn
            DataColumn workCol = dt.Columns.Add("FirstName", typeof(String));

            dt.Columns.Add("LastName", typeof(String));
            dt.Columns.Add("Blog", typeof(String));
            dt.Columns.Add("City", typeof(String));
            dt.Columns.Add("Country", typeof(String));

            //Add in the datarow
            DataRow newRow = dt.NewRow();

            newRow["firstname"] = "Arun";
            newRow["lastname"] = "Prakash";
            newRow["Blog"] = "http://royalarun.blogspot.com/";
            newRow["city"] = "Coimbatore";
            newRow["country"] = "India";

            dt.Rows.Add(newRow);

            //open file
            StreamWriter wr = new StreamWriter(@"D:\\Book1.xls");

            try
            {

                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
                }

                wr.WriteLine();

                //write rows to excel file
                for (int i = 0; i < (dt.Rows.Count); i++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (dt.Rows[i][j] != null)
                        {
                            wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
                        }
                        else
                        {
                            wr.Write("\t");
                        }
                    }
                    //go to next line
                    wr.WriteLine();
                }
                //close file
                wr.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

9 January 2012

TRY...CATCH in Sql Server


TRY...CATCH in Sql Server

Errors in Transact-SQL code can be processed by using a TRY…CATCH construct similar to the exception-handling features of the Microsoft Visual C++ and Microsoft Visual C# languages. A TRY…CATCH construct consists of two parts: a TRY block and a CATCH block. When an error condition is detected in a Transact-SQL statement that is inside a TRY block, control is passed to a CATCH block where the error can be processed.

After the CATCH block handles the exception, control is then transferred to the first Transact-SQL statement that follows the END CATCH statement. If the END CATCH statement is the last statement in a stored procedure or trigger, control is returned to the code that invoked the stored procedure or trigger.


BEGIN TRY
    SELECT *
        FROM sys.messages
        WHERE message_id = 21;
END TRY
GO
-- The previous GO breaks the script into two batches,
-- generating syntax errors. The script runs if this GO
-- is removed.
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber;
END CATCH;
GO

8 January 2012

WAITFOR in Sql Server 2008


WAITFOR in Sql Server 2008

Blocks the execution of a batch, stored procedure, or transaction until a specified time or time interval is reached, or a specified statement modifies or returns at least one row.


A. Using WAITFOR TIME

The following example executes the stored procedure sp_update_job at 10:20 P.M. (22:20).

USE msdb;
EXECUTE sp_add_job @job_name = 'TestJob';
BEGIN
    WAITFOR TIME '22:20';
    EXECUTE sp_update_job @job_name = 'TestJob',
        @new_name = 'UpdatedJob';
END;
GO
B. Using WAITFOR DELAY

The following example executes the stored procedure after a two-hour delay.

BEGIN
    WAITFOR DELAY '02:00';
    EXECUTE sp_helpdb;
END;
GO

http://msdn.microsoft.com/en-us/library/ms187331(v=SQL.100).aspx

30 December 2011

Calculate Time Difference Between DateTime Objects


Calculate Time Difference Between DateTime Objects

To get time difference you need to use TimeSpan object, with code like this:
TimeSpan ts = DateTime1 - DateTime2;
For example, if you want to calculate time difference between server time and UTC time:
[ C# ]
protected void Page_Load(object sender, EventArgs e)
{
    // Declare and get DateTime values
    DateTime StartDate = System.DateTime.Now;
    DateTime EndDate = System.DateTime.UtcNow;
 
    // Find time difference between two dates
    TimeSpan TimeDifference = StartDate - EndDate;
 
    // Write difference in hours and minutes
    Response.Write("Time difference between server time and Coordinated Universal Time (UTC) is " + 
        TimeDifference.Hours.ToString() + " hours ");
    if (TimeDifference.Minutes != 0)
        Response.Write(" and " + TimeDifference.Minutes.ToString() + " minutes.");
 
}

29 December 2011

Web Farm in Asp.net


Web Farm in Asp.net
After developing our asp.net web application we host it on IIS Server.  Now one standalone server is sufficient to process ASP.NET Request and response for a small web sites but when the site comes for big organization where there an millions of daily user hits then we need to host the sites on multiple Server. This is called web farms. Where single site hosted on multiple IIS Server and they are  running behind the Load Balancer.
Fig : General Web Farm Architecture
This is the most common scenarios for any web based production environment. Where Client will hit an Virtual IP ( vIP) . Which is the IP address of Load Balancer. When Load balancer received the request based on the server load it will redirect the request to particular Server.

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...