Pages

Tuesday, January 4, 2011

Dopostback on Key Press using javascript

<script type="text/javascript">
document.onkeyup = KeyCheck;
function KeyCheck(e) {
    var KeyID = (window.event) ? event.keyCode : e.keyCode; 
//alert("KeyId="+KeyID);
switch (KeyID) {
        case 118:
            __doPostBack('__Page', 'F7');
            break;
        case 119:
            __doPostBack('__Page', 'F8');
            break;
        case 120:
            __doPostBack('__Page', 'F9');
            break;
        case 121:
            __doPostBack('__Page', 'F10');
            break;
    }
}
</script>
Code Behind write:
protected void Page_Load(object sender, EventArgs e)
    {
        Page.ClientScript.GetPostBackEventReference(this, "");
        string eventArgs = Request["__EVENTARGUMENT"]; if (!string.IsNullOrEmpty(eventArgs))
        {
            switch (eventArgs)
            {
                case "F7":
                    a("F7");
                    break;
                case "F8":
                    a("F8");
                    break;
                case "F9":
                    a("F9");
                    break;
                case "F10":
                    a("F10");
                    break;
            }
        }
    }
   public void a(string str)
    {
         Response.Write("You pressed : " + str);
    }

Monday, January 3, 2011

Delete duplicate rows from the table

Create table ##Test (a int not null, b int not null, c int not null, id int not null identity) on [Primary]
GO
INSERT INTO ##Test (A,B,C) VALUES (1,1,1)
INSERT INTO ##Test (A,B,C) VALUES (1,1,1)
INSERT INTO ##Test (A,B,C) VALUES (1,1,1)

INSERT INTO ##Test (A,B,C) VALUES (1,2,3)
INSERT INTO ##Test (A,B,C) VALUES (1,2,3)
INSERT INTO ##Test (A,B,C) VALUES (1,2,3)

INSERT INTO ##Test (A,B,C) VALUES (4,5,6)
GO
Select * from ##Test
GO
Delete from ##Test where id <
(Select Max(id) from ##Test t where ##Test.a = t.a and
##Test.b = t.b and
##Test.c = t.c)
GO
Select * from ##Test
drop table ##Test
GO

Wednesday, December 22, 2010

Printer friendly using Javascript

<script language="javascript" type="text/javascript">
        function PrintThisPage() {
            var sOption = "toolbar=no,location=no,directories=yes,menubar=no,";
            sOption += "scrollbars=yes,width=750,height=600,left=100,top=25";
            var sWinHTML = document.getElementById('printcontent').innerHTML;
            var winprint = window.open("", "", sOption);
            winprint.document.open();
            winprint.document.write('<html><LINK href=\'Includes/Css/style.css\' rel=Stylesheet><body>');
            winprint.document.write('<br/><a href=\'javascript:window.print();\'>Print</a>');
            winprint.document.write(sWinHTML);
            winprint.document.write('<br/><a href=\'javascript:window.print();\'>Print</a>');
            winprint.document.write('</body></html>');
            winprint.document.close();
            var oAvail = winprint.document.getElementById('divAvail')
            if (oAvail != null) {
                oAvail.style.overflow = "visible";
            }
            winprint.focus();
        }
</script>
<div id="printcontent" style="width: 100%">This content will be opened in a new window </div>
<asp:ImageButton ID="btnPrint" runat="server" ImageUrl="~/Includes/Images/printerIcon.gif"
                    AlternateText="Print" CausesValidation="false" OnClientClick="javascript:PrintThisPage();" />

Tuesday, December 21, 2010

Displaying records from the database in gridview based on the page and not fetching all the records from the database.

Here is the way for accessing the records from the database and displaying it in the gridview.
You can use custom paging for navigating withing the pages of the gridview.


EXEC  usp_GetRecords 2,5  -- this will fetch only 5 records starting from 6 to 10

CREATE PROCEDURE usp_GetRecords
(
 @iPageNumber INT,  -- this is the page number sent during pagination
 @iNumberOfRecords INT -- this is the number of records displayed per page
)
AS
DECLARE @iStartNumber INT
DECLARE @iEndNumber INT
SET @iEndNumber = (@iPageNumber * @iNumberOfRecords)
SET @iStartNumber = (@iEndNumber - @iNumberOfRecords) + 1;

WITH cte_t1(rownumber,id,a,b)
AS
(
 SELECT ROW_NUMBER() OVER(ORDER BY id) AS rownumber,id,a,b FROM t1
)
SELECT * FROM cte_t1
WHERE rownumber BETWEEN @iStartNumber AND @iEndNumber

Tuesday, December 7, 2010

Calling Server side function using javascript

Every server-side method that is called from the client-side, must be declared as “static”, and also has to be decorated with the [System.Web.Services.WebMethod] tag.

Default.aspx
<script type='text/javascript'>
       function DisplayMessage() {
            PageMethods.Message("Amit",OnGetMessageSuccess, OnGetMessageFailure);
        }
        function OnGetMessageSuccess(result, userContext, methodName) {
            alert(result);
        }
        function OnGetMessageFailure(error, userContext, methodName) {
            alert(error.get_message());
        }

function CallMe(src, dest) {
            var ctrl = document.getElementById(src);
            // call server side method
            PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);
        }
        // set the destination textbox value with the ContactName
        function CallSuccess(res, destCtrl) {
            var dest = document.getElementById(destCtrl);
            dest.value = res;
        }
        // alert message on some failure
        function CallFailed(res, destCtrl) {
            alert(res.get_message());
        }
    </script>
<body>
    <form id='form1' runat='server'>
    <asp:ScriptManager ID='ScriptManager1' runat='server'  EnablePageMethods='true' />
<div>
            <input type='submit' value='Get Message' onclick='DisplayMessage();return false;' 

/>
<asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1"></asp:Label>
        <asp:TextBox
            ID="txtId1" runat="server"></asp:TextBox>
        <br />
            <asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None"
                ReadOnly="True"></asp:TextBox><br />

</div>
</form>
</body>
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");
                    }
    }
[System.Web.Services.WebMethod]
    public static string Message(string str)
    {
        return str;
    }

[System.Web.Services.WebMethod]
    public static string GetContactName(string custid)
    {
        if (custid == null || custid.Length == 0)
            return String.Empty;
        SqlConnection conn = null;
        try
        {
            string connection = ConfigurationSettings.AppSettings["ConnectionString"];
            conn = new SqlConnection(connection);
            string sql = "Select sEmpFName from EMP_EmpPersonal where iEmployeeId = @CustID";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("CustID", custid);
            conn.Open();
            string contNm = Convert.ToString(cmd.ExecuteScalar());
            if (contNm.Length > 0)
                return contNm;
            else
                return "No record found.";
        }
        catch (SqlException ex)
        {
            return "error";
        }
        finally
        {
            conn.Close();
        }
    }

Monday, November 29, 2010

Calling Web service using javascript overloaded web method

Here is the code for calling the webservice using javascript with overloaded web methods
Default.aspx
<script type="text/javascript">
       function CallWebService() {
           WS.a(ReuqestCompleteCallback, RequestFailedCallback);
           WS.b('Amit',ReuqestCompleteCallback, RequestFailedCallback);
       }
       function ReuqestCompleteCallback(result)
       {
           // Display the result.
           var divResult = document.getElementById("divMessage");
           divResult.innerHTML = result;
       }
       function RequestFailedCallback(error) {
           var stackTrace = error.get_stackTrace();
           var message = error.get_message();
           var statusCode = error.get_statusCode();
           var exceptionType = error.get_exceptionType();
           var timedout = error.get_timedOut();
 
           // Display the error.  
           var divResult = document.getElementById("Results");
           divResult.innerHTML = "Stack Trace: " + stackTrace + "  " +  "Service Error: " + message + "  " +  "Status Code: " + statusCode + "  " +  "Exception Type: " + exceptionType + "  " +  "Timedout: " + timedout;
          }
    </script>
<form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WS.asmx" />
        </Services>
        </asp:ScriptManager>
    </div>
    <div>
            <input type="button" value="Call Web Service" onclick="CallWebService();" />
        </div>
        <div id="divMessage">
        </div>
    </form>
WebService == WS.asmx
1. You can't use method overloading in web service since wsdl 1.1 does not supports it. That is the reason why you  are using alias name for the overloaded methods
2. When you use alias name then the webmethod is exposed as alias name instead of original name in the wsdl. So you need call your webmethod using alias name from your client. Your client have no idea about the original method name when alias is used. 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WS : System.Web.Services.WebService
{
    public WS()
    {
  }
  [WebMethod(Description = "HelloWorld Returns 'Hello World'", MessageName = "a")]
    public string HelloWorld()
    {
        return "Hello World";
    }
    [WebMethod(Description = "HelloWorld Returns Given Name", MessageName = "b")]
    public string HelloWorld(string Name)
    {
        return Name;
    }
}