Pages

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;
    }
}

Thursday, November 18, 2010

Web Services - Method Overloading

This is not as same as we have in the Class. It will be build successfully but when we use or consume, it will generate error message - "Use the MessageName property of the WebMethod custom attribute to specify unique message names for the methods". when WSDL (Web Service Description Language) is generated, it will not be able to make the difference between methods because WSDL does not deal on the base of parameters.
To overcome this just do the following: Also add the following line above the class

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
[WebMethod(MessageName = "Print1", Description = "Print 1", EnableSession = true)]
    public int A(int a, int b)
    {         return 1;     }
    [WebMethod(MessageName = "Print2", Description = "Print 2", EnableSession = true)]
    public int A(int x)
    {         return 2;     }
Reason
By passing the 'MessageName Property’ it changes the method name in the WSDL as shown below:
<wsdl:operation name="A">
            <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">Print 1</wsdl:documentation>
            <wsdl:input name="Print1" message="tns:Print1SoapIn" />
            <wsdl:output name="Print1" message="tns:Print1SoapOut" />
</wsdl:operation>
<wsdl:operation name="A">
            <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">Print 2</wsdl:documentation>
            <wsdl:input name="Print2" message="tns:Print2SoapIn" />
            <wsdl:output name="Print2" message="tns:Print2SoapOut" />
</wsdl:operation>

About Multicast Delegates

Multicast Delegate
Delegate that holds the reference of more than one method.
Multicast delegates must contain only methods that return void, otherwise run-time exception will be thrown.
Example
delegate void DelegateMulticast(int x);
Class ClassX
{
    static void A(int x)
    {
        Console.WriteLine("Hello A");
    }
    static void B(int x)
    {
        Console.WriteLine("Hello B");
    }
    public static void Main()
    {
        DelegateMulticast func = new DelegateMulticast(A);
        func += new DelegateMulticast(B);
        func(1);             // Both A and B are called
        func -= new DelegateMulticast(A);
        func(2);             // Only B is called
    }
}
Description
As you see that there are 2 methods named A & B with one parameter and void as return type.
Create delegate object
DelegateMulticast func = new DelegateMulticast(A);
Then the Delegate are added and removed using the += operator and -= operator resp.

Wednesday, October 27, 2010

Site Down For Maintenance - app_offline.htm

Sometimes we require to display the Site Under Construction message to the visitor while we are fixing bugs, upgrading features etc. For this just place the app_offline.htm on the root directory of the application.When ASP.Net sees that it will shut down the application and stop processing any new incoming request for that application. ASP.Net will send the content of this file "app_offline.htm" for all the incoming request. This file must have at least 512 bytes of content within it. If you do not have that content just place some content and comment them.

Tuesday, October 19, 2010

Display country with flags in the dropdown using javascript

Sometime it is required to display images with the text in the dropdown.
Here is the code to display the images in the dropdown.
Create a folder "flags" and place the flag images there.

<%@ Page Language="C#" AutoEventWireup="true"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Display images in dropdown</title>
    <script type="text/javascript">
    function SetFlag()
    var ddlCountry=document.getElementById('ddlCountry');              
    var iso = ddlCountry.options[ddlCountry.selectedIndex].value; 
  if (iso.length > 0)
  {
    document.getElementById('imgFlag').src =  "flags/" + iso + ".png";
    ddlCountry.options[ddlCountry.selectedIndex].style.backgroundImage = "url(flags/" + iso + ".png" +")";
    ddlCountry.options[ddlCountry.selectedIndex].style.backgroundRepeat="no-repeat";
    ddlCountry.options[ddlCountry.selectedIndex].style.backgroundPosition="right";    
  }
  else
    document.getElementById('imgFlag').src =  "flags/pixel.gif";
}
function getDropdownListTextWithImage()
{
   var ddlCountry=document.getElementById('ddlCountry');       
    for(var j = 0, limit1 = ddlCountry.options.length; j < limit1;  j++)
    {
        ddlCountry.options[j].style.backgroundImage = "url(flags/" + ddlCountry.options[j].value + ".png" +")";
        ddlCountry.options[j].style.backgroundRepeat="no-repeat";
        ddlCountry.options[j].style.backgroundPosition="right";       
    }
}
    </script>
</head>
<body onload="SetFlag();getDropdownListTextWithImage();">
    <form id="form1" runat="server">
    <div style="background-repeat:no-repeat;background-position:top right">
     <asp:DropDownList runat="server" ID="ddlCountry" onchange="SetFlag();" onkeydown="SetFlag();" onkeyup="SetFlag();" TabIndex="4" EnableViewState="false" ValidationGroup="AddComment"
     >
     <asp:ListItem value="">[Not specified]</asp:ListItem>
    <asp:ListItem value="al" >Albania </asp:ListItem>
    <asp:ListItem value="dz">Algeria</asp:ListItem>
    <asp:ListItem value="ar">Argentina</asp:ListItem>
    <asp:ListItem value="am">Armenia</asp:ListItem>
    <asp:ListItem value="au">Australia</asp:ListItem>
    <asp:ListItem value="at">Austria</asp:ListItem>    
     </asp:DropDownList>&nbsp;
  <asp:Image runat="server" ID="imgFlag" AlternateText="Country flag" Width="16" Height="11" EnableViewState="false" />
    </div>
    </form>
</body>
</html>

Display Rupee Symbol Website

To display the Rupee symbol on the website, just place this line in the <head> section and it will convert all the 'Rs' / 'Rs.' for you.

<script src="http://cdn.webrupee.com/js" type="text/javascript"></script>

Tuesday, October 12, 2010

Difference between ref & out

The out and the ref  parameters are very useful when your method needs to return more than one values.
The out Parameter
1. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.
2. Variables passed as an out arguments need not be initialized prior to being passed.
class Example
{
    static void Method(out int i)
    {
        i = 90;
    }
    static void Main()
    {
        int k;
        Method(out k);
        // k is now 90
    }
}
3. The calling method is required to assign a value before the method returns.
class Example
{
    static void Method(out int i)
    {
        i = 90;
    }
    static void Main()
    {
        int k;
        Method(out k);  // k is now 90       
    }
}
The ref parameter
1. ref requires that the variable be initialized before being passed.
class Example
{
    static void Method(ref int i)
    {
        i += 30;
    }
    static void Main()
    {
        int k=3;
        Method(ref k);  // k is now 33       
    }
}

Note:
Methods cannot be overloaded if one method takes a ref argument and the other takes an out argument. These two methods, for example, are identical in terms of compilation, so this code will not compile:
class Example
{
    // compiler error CS0663: "cannot define overloaded
    // methods that differ only on ref and out"
    public void Method(out int i) {  }
    public void Method(ref int i) {  }
}
Overloading can be done, however, if one method takes a ref or out argument and the other uses neither, like this:
class Example
{
    public void Method(int i) {  }
    public void Method(out int i) {  }
}

Tuesday, September 14, 2010

SQL - Date range query


Sometimes we need to get info from the db with the range provided in the stored procedure based on the date and the the date that we send to stored procedure is of the format "dd-mm-yyyy"
Here is the solution to the problem

exec GetCandidateResume @FromDate=N'07-09-2010',@ToDate=N'30-09-2010'

CREATE PROCEDURE [GetCandidateResume] 
(     
    @FromDate    VARCHAR(20),
    @ToDate        VARCHAR(20)
)     
AS 
SELECT
    CandidateId,
    CandidateName
FROM tbl_CandidateInfo
WHERE
    (CONVERT(DATETIME,CONVERT(VARCHAR(12),CandidateAppliedDate,105),105) >=CONVERT(DATETIME, @FromDate, 105))
    AND
    (CONVERT(DATETIME,CONVERT(VARCHAR(12),CandidateAppliedDate,105),105) <=CONVERT(DATETIME, @ToDate, 105))


Hoping that this will help.
:)

Thursday, September 9, 2010

How to add Microsoft Chart control in ASP.Net

This article will show you how to add Microsoft Chart on your web page.

First Download and install this.

When the RenderType property is set to ImageTag, the Chart control saves the rendered chart images as files in memory or on disk (For more information, see Chart Image Rendering). You can specify how the Chart control manages the image files. To do this, use the ImageStorageMode property.
In the ImageStorageMode property, you choose to use the chart HTTP handler to manage image files or to manage them manually.

By default, the ImageStorageMode property is set to UseHttpHandler. This causes the Chart control to use the ChartHttpHandler that is registered in the Web.config file to manage the rendered chart images.

Now create a page and drag and drop the chart control.
Eg:
<asp:Chart ID="Chart1" runat="server" Height="280px" IsMapEnabled="False" IsSoftShadows="False"
        Palette="Excel" Width="380px" ImageLocation="../writereaddata/Chart_#SEQ(25,5)" ImageStorageMode="UseImageLocation">
</asp:Chart>

Now you need to do some settings in the Web.Config file

When you drag a Chart control from the Toolbox onto the design surface of the ASP.NET page, the ChartHttpHandler is automatically registered in the Web.config file as "ChartImageHandler". You can configure ChartImageHandler's behavior in the <appSettings> element. The applicable code section is provided below with the automatically generated settings:

<appSettings>
<add key="ChartImageHandler" value="storage=file;timeout=20;" />
</appSettings>

To manage rendered chart images manually, set the ImageStorageMode property to UseImageLocation, and then set the ImageLocation property to an absolute or relative path.

You can insert three different keywords into the ImageLocation property.


Keyword Description
#UIDGenerate a unique identifier for each rendered chart image. For example: "~/Temp/ChartPicture#UID".
Using this keyword ensures that the server replies each page request with the correct rendered image. You must manually remove old files. Otherwise the number of files will grow indefinitely.


#SEQ(maxFiles,minutes)Generates a file sequence number, up to the number defined by maxFiles, then start the sequence again and replace the first file in the sequence. For example: "Picture_#SEQ(300,5)" generates the following file names (assuming ImageTypePng): Picture_000001.jpg, Picture_000002.jpg, ... set to
The minutes parameter specifies the timeout for each file in the sequence. However, it does not guarantee the validity of a filename for the specified period. If a file is recycled before its timeout period is exceeded, the file a warning message is inserted into the Application Event Log. You should set the maxFile parameter to a reasonably large number to avoid image files being overridden inappropriately.
#NOGUIDPARAM

Removes the GUID string from the image file's URL. For example: "Picture_#SEQ(300,5)#NOGUIDPARAM".
By default, the Chart control adds a GUID string to the image URL.

Tuesday, August 31, 2010

Error : ASP.net The given path's format is not supported

This error occurs when you try to save the file in the desired folder using the ASP.net file upload control.

HttpPostedFile myFile = fileUpload.PostedFile;

myFile.SaveAs(Server.MapPath("\\news\\") + myFile.FileName);

The above line will generate the error. As it will try to save the file in the path :
C:\home\sites\xyz\news\C:\Upload\filetoupload.txt

which is invalid format because of c:\ being used twice and hence you getting the
invalid format error.

When working with file names and paths it's recommended to use System.IO.Path-class 

So use
myFile.SaveAs(Server.MapPath("\\news\\") + System.IO.Path.GetFileName(myFile.FileName));

Hoping that this will help.
:)