Wednesday, October 29, 2008

How To Call .net Webservice using Javascript

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld(string strName) {
        return "Hello" +strName;
    }
   
}
<!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>
    <title>Untitled Page</title>

    <script type="text/javascript"> function sendDataAsXML_SOAP() {
   var req_params = "", url = "", number = 0, type = "";
   /* Configure Parameters */
   url = "http://localhost/TestWebservice/Service.asmx";
   user = document.getElementById("Text1").value;
  
   req_params = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><HelloWorld >";
   req_params = req_params + "<strName>" + user + "</strName>";
   req_params = req_params + "</HelloWorld></soap:Body></soap:Envelope>";
   alert(req_params);
   /* Send XML/SOAP Request To Web Service Using Browser's Javascript DOM */
   try {
      ajax_request = new XMLHttpRequest();
      }
   catch (trymicrosoft) {
      try {
         ajax_request = new ActiveXObject("Msxml2.XMLHTTP");
         }
      catch (othermicrosoft) {
         try {
            ajax_request = new ActiveXObject("Microsoft.XMLHTTP");
            }
         catch (failed) {
            ajax_request = false;
            }
         }
      }
   ajax_request.open("POST", url, true);
   ajax_request.setRequestHeader("Content-Type", "text/xml;charset=utf-8");
   ajax_request.onreadystatechange = receiveXML_SOAPData;
   ajax_request.send(req_params);
   }

function receiveXML_SOAPData() {
   if (ajax_request.readyState == 4) {
      if (ajax_request.status == 200) {
         /* Parse The Response Data */
         //result.innerText = ajax_request.responseText;
         alert(ajax_request.responseText);
        
         }
      }
   }

    </script>

</head>
<body>
    <form action="#">
        <input type="text" id="Text1" />
        <input type="button" onclick="sendDataAsXML_SOAP();" value="Call WebService" />
    </form>
</body>
</html>

Calling page methods from javascript using ASP.NET AJAX

We can call page methods (static methods declared in scope of asp.net page) using MS Ajax framework for ASP.NET. That is how can we do it : 1) Drop ScriptManager control on page 2) Set EnablePageMethods property of ScriptManager control to true 3) Add static public method in page-behind code (or its parent class) and mark it with [System.Web.Services.WebMethod] attribute: 4) add following javascript code to it
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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>Untitled Page</title>

   <script type="text/javascript">
   function CallMethod()
   {
       GetTime();
   }

   function GetTime()
 
   {
 
       PageMethods.GetTime(GetTimeCallback,ErrorHandler,TimeOutHandler);
                  
 
   }
   function TimeOutHandler(result)
   {
        alert("Timeout :" + result);
   }
   /// <summary>
   /// Callback function invoked on failure of the page method 
   /// </summary>
 
   function ErrorHandler(result)
   {
       var msg=result.get_exceptionType() + "\r\n";
       msg += result.get_message() + "\r\n";
       msg += result.get_stackTrace();
       alert(msg);
   }
  GetTimeCallback = function (result) {
   /// <summary>
   /// Is called when server sent result back
   /// </summary>
   /// <param name="result">
   /// Result of calling server method, 
   /// string - server time 
   /// </param>
   if(result) {
        $get("resultDiv").innerHTML = result;
   }
}
   </script>

</head>
<body>
   <form id="form1" runat="server">
       <asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release"
           LoadScriptsBeforeUI="true">
       </asp:ScriptManager>
       <div id="resultDiv">
       </div>
       <input value="GetTime" type="button" onclick="GetTime();" />
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {

   }
   [System.Web.Services.WebMethod]
   public static string GetTime()
   {
       return DateTime.Now.ToString();
   }

}

Monday, October 27, 2008

How To Load xml string into DataSet

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!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>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="server">
           </asp:GridView>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string xmldata = "<DocumentElement>" +
             "<OutLier>" +
             "<Name>1</Name>" +
             "<DOB>19800101</DOB>" +
             "<State>GG</State>" +
             " <ID>12345</ID> " +
             " <SIG>Y</SIG> " +
             "</OutLier>" +
              "<OutLier>" +
             "<Name>2</Name>" +
             "<DOB>19800101</DOB>" +
             "<State>GG</State>" +
              " <ID>1325</ID> " +
             " <SIG>Y</SIG> " +
             "</OutLier>" +
             "</DocumentElement>";

        try
        {
            DataSet ds = new DataSet();
            System.IO.StringReader sr = new System.IO.StringReader(xmldata);
            ds.ReadXml(sr);
            GridView1.DataSource = ds;
            GridView1.DataBind();

        }
        catch (ArgumentNullException ex)
        {
            ex.Message.ToString();
        }

    }
}

Saturday, October 25, 2008

How to convert from XmlTextWriter to String?

public string CreateXML(string strAuth,string strTran,string strDL,string strCode,string strMsgCode,string strMessage)
    {
        string xmlString;
        StringWriter sw = new StringWriter();
        XmlTextWriter writer = new XmlTextWriter(sw);
        // start writing!
        writer.WriteStartDocument();
        writer.WriteStartElement("Result");
        writer.WriteElementString("Authentication", strAuth);
        writer.WriteElementString("Transaction", strTran);
        writer.WriteElementString("DL", strDL);
        writer.WriteElementString("Code", strCode);
        writer.WriteElementString("MsgCode", strMsgCode);
        writer.WriteElementString("Msg", strMessage);
        writer.WriteEndElement();
        //Write XML, and then flush the writer...

        writer.Flush();
        //Return text from string writer...

        xmlString = sw.ToString();
        //close the Objects
        writer.Close();
        sw.Close();
        return xmlString;



    }

Wednesday, October 22, 2008

Error: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.Asp Net SqlConnection

when we deal with huge amount of data, generally it may occur TIMEOUT problem... in those situations Take care of 3 things ( problem will be almost solved ) 1. put the connection timeout property in Connection string string connstring=" Data Source=localhost;User ID=sa; pwd=secret; Initial catalog=nothwind;connect timeout=900;"; 2. set the command timeout for the SqlCommand Object com.CommandTimeout=0; // this will makes Command to execute unlimited seconds 3. Now .... last but not the least... in the form unload function destroy the connection object conn.Dispose();

Friday, October 17, 2008

Using an XML file for your ASP.NET settings

A very common requirement for web applications is that they be configurable in an easy way. A lot of times it doesn't make sense to use a database to store some simple settings for your web site, especially if the application doesn't require one in the first place. There are a ton of ways to accomplish this task, but it seems to me that XML is perfectly suited for this problem. I don't mean to presume that it is better than other solutions but in case it fits the bill for your project, here is once way it can be used. check out this link

Wednesday, October 15, 2008

Two approaches to redirection in ASP.NET

Directing a user to another page or resource is a common aspect of a web application. The user may initiate the transfer to another page any number of ways, including clicking a button or link or selecting a value in a drop-down list.

ASP.NET provides a few ways to move to different pages. Here's a look at these options, along with commentary on when you should use which approach.

http://www.builderau.com.au/program/asp/soa/Two-approaches-to-redirection-in-ASP-NET/0,339028371,339292658,00.htm?feed=rss

Monday, October 13, 2008

read, write and save values in app.config file

public void ChangeConfigValue()
        {
            string filename = System.AppDomain.CurrentDomain.BaseDirectory + @"web.config";
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(filename);
            XmlNodeList nodeList = xmldoc.DocumentElement.ChildNodes;

            foreach (XmlElement element in nodeList)
            {
                if (element.Name.ToLower() == "appsettings")
                {
                    XmlNodeList node = element.ChildNodes;
                    if (node.Count > 0)
                    {
                        foreach (XmlElement el in node)
                        {
                            if (el.Attributes["key"].InnerText == "ConnectionString")
                            {                           
                                el.Attributes["value"].InnerText = "321";//write the value
                                string s= el.Attributes["value"].InnerText;//read the value
                                break;
                            }
                        }
                    }
                    break;
                }
            }
            xmldoc.Save(filename);
        }

Wednesday, October 1, 2008

Adding tooltips to GridView headers

check out this post http://www.rosshawkins.net/archive/2007/04/15/adding-tooltips-to-gridview-headers.html.aspx

ASP.NET Gridview and Conditioanl Image

Depending upon a value in the data source, we can conditionally display images in GridView columns. For example, the following TemplateField declaration conditionally displays approved.gif or unapproved.gif based on IsApproved flag in the DataSet that the GridView is bound to:
<asp:TemplateField HeaderText="Yes">
                       <ItemTemplate>
                         <asp:Image ID="ApprovalImage" Height="20px" Width="20px" runat="server" ImageUrl='<%# "~/Images/" + ((Eval("U_Yeah").ToString()== "Y") ? "apply.png" : "del.jpg") %>' />
                       </ItemTemplate>
 </asp:TemplateField>