March 25, 2011

WebService Code Example

Below WebService Example gets the Stock Price based on the CompanyCode Entered by the user

1.) Add an asmx page into solution by choosing the webservice Template
2.) Write the code in StockQuotewebService.cs file in APP_CODE Folder


StockQuotewebService.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;


/// <summary>
/// Summary description for StockQuotewebService
/// </summary>
[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 StockQuotewebService : System.Web.Services.WebService {


    public StockQuotewebService () {


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


    public class SecurityInfo
    {
        public String CompnanyCode;
        public String CompnanyName;
        public double StockPrice;


        public SecurityInfo()
        {
            CompnanyCode = "";
            CompnanyName = "";
            StockPrice = 0.0;
        }


    }


    //Private Method for the webService
    public SecurityInfo GetInformation(String Code)
    {
        Random rObj = new Random();
        SecurityInfo obj = new SecurityInfo();
        obj.CompnanyCode = Code;
        obj.StockPrice = rObj.Next(1200);
        obj.CompnanyName = Code + "  " + "PVT LIMITED";


        return obj;




    }


    //Exposed Method from the web service
    [WebMethod]
    public SecurityInfo GetComapnyPrice(string code)
    {


       SecurityInfo result= GetInformation(code);
       return result;
    }




}


StockQuotewebService.asmx

<%@ WebService Language="C#" CodeBehind="~/App_Code/StockQuotewebService.cs" Class="StockQuotewebService" %>

After Executing this webservice you ll see the below Interface to test the Service



                
click on Invoke will show you the below result

                    
3.) Right click on root folder in Solution Explorer add App_WebReference choose the above created
     webservice and give reference name in my case it is 'localhost' ,click on  'Add Reference'
4.) Add an .aspx page to consume the above web service

Below is the code to Consume Above Web Service


UseStockPricewebService.aspx

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


<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Company code:<asp:TextBox ID="txtCode" runat="server"></asp:TextBox><br />
        <asp:Button ID="btnGetQuote" runat="server" Text="GETSTOCKQUOTE" 
            onclick="btnGetQuote_Click" /><br />
        
        Code<asp:Label ID="lblCode" runat="server" Text=""></asp:Label><br />
        Name<asp:Label ID="lblName" runat="server" Text=""></asp:Label><br />
        Price<asp:Label ID="lblPrice" runat="server" Text=""></asp:Label><br />
    </div>
    </form>
</body>
</html>



UseStockPricewebService.aspx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using localhost;
public partial class UseStockPricewebService : System.Web.UI.Page
{
    StockQuotewebService wsObj = new StockQuotewebService();
    protected void Page_Load(object sender, EventArgs e)
    {




    }
    protected void btnGetQuote_Click(object sender, EventArgs e)
    {
        StockQuotewebService .SecurityInfo obj = wsObj.GetComapnyPrice(txtCode.Text);
        lblCode.Text ="   : "+ obj.CompnanyCode;
        lblName.Text = "   : " + obj.CompnanyName;
        lblPrice.Text = "   : " + obj.StockPrice.ToString();


    }
}




Below is the o/p when you run the above seStockPricewebService.aspx 

Click on GETSTOCKQUOTE Button 'll see the below o/p


March 20, 2011

Bind XML Document in Grid View

Below is the sample code to show data from the XML document in tabular format

BindXMlDoc.aspx

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


<!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>

BindXMlDoc.aspx.cs


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 BindXMlDoc : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataSet ds=GetXMLData();
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
    }


    private DataSet GetXMLData()
    {
        // Set the path of the XML file and XML schema.
        string strPath = Server.MapPath(Request.ApplicationPath);
        // Declare a data set.
        DataSet dsUsers = new DataSet();
      
        // Read the XML into the data set.
        dsUsers.ReadXml(strPath + "\\XMLFile5.xml");
        return dsUsers;
    }
}


XMLFile5.xml


<?xml version="1.0" encoding="utf-8" ?>
<StudentList>


  <student>
    <name>Test1</name>
    <Id>1</Id>
    
  </student>


  <student>
    <name>Test2</name>
    <Id>2</Id>
    
    
  </student>
  
  
</StudentList>


Below is the o/p

XML Parsing in ASP.NET

Below is the sample code to parse the XML Document

XMLFile5.xml

<?xml version="1.0" encoding="utf-8" ?>
<StudentList>


  <student>
    <name>Test1</name>
    <Id>1</Id>
  </student>


  <student>
    <name>Test2</name>
    <Id>2</Id>
  </student>


</StudentList>




ExXmlParser.aspx.cs


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;
using System.Xml;


public partial class ExXmlParser : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing


        xdoc.Load(System.Web.HttpContext.Current.Server.MapPath("~/XMLFile5.xml"));//loading XML in xml doc


        XmlNodeList name = xdoc.GetElementsByTagName("student");


        foreach (XmlNode xNode in name)//traversing XML 
        {
            foreach (XmlElement xelement in xNode)
            {


                Response.Write(xelement.FirstChild.Value + "   ");
                
            }
            Response.Write("<br/>");
        }
    }
}


Below is the o/p 

Save Data in CSV file from DataSet


Below is the method to save the data from Dataset to file named OrderData.csv


  public void WriteOrderData(DataSet ds)
    {
        try
        {
            string path = "~/Error/" + "OrderData" + ".csv";
           // if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
           // {
                File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
            //}
            using (StreamWriter sw = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                
                DataTable dt = ds.Tables[0];
                int iColCount = dt.Columns.Count;
                for (int i = 0; i < iColCount; i++)
                {
                    sw.Write(dt.Columns[i]);
                    if (i < iColCount - 1)
                    {
                        sw.Write(",");
                    }
                }
                sw.Write(sw.NewLine);
                // Write Table Rows.
                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < iColCount; i++)
                    {
                        if (!Convert.IsDBNull(dr[i]))
                        {
                            sw.Write(dr[i].ToString());
                        }
                        if (i < iColCount - 1)
                        {
                            sw.Write(",");
                        }
                    }
                    sw.Write(sw.NewLine);
                } sw.Close();




            }
            ////save dialog box




            String filePath = System.Web.HttpContext.Current.Server.MapPath("Error/OrderData.csv");
             System.IO.FileInfo targetFile = new FileInfo(filePath);
            if (targetFile.Exists)
            {


                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + targetFile.Name);
                HttpContext.Current.Response.AddHeader("Content-Length", targetFile.Length.ToString());
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.WriteFile(targetFile.FullName);


            }




            
        }
        catch (Exception ex)
        {
            WriteError(ex.Message);
        }


    }

March 19, 2011

Logging in EventLog

To log the Error in EventLog following is the code sample

EventLog1.cs

using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using System.Text;
using System.Collections.Generic;
using System.Threading;
using System.IO;
using System.Globalization;


/// <summary>
/// Summary description for EventLog
/// </summary>
public class EventLog1
{

    public  void LogException(string ErrorDescription,String FunctionName)
    {


        // Log Category in the event logs


        string Log = "TestLog";


        // Check to see if the log for TestLog Category exists on the machine


        // If not, create it


        if ((!(EventLog.SourceExists(Log))))
        {


            EventLog.CreateEventSource(Log, Log);


        }


        // Now insert your exception information into the TestLog event log


        EventLog logEntry = new EventLog();


        logEntry.Source = Log;


        logEntry.WriteEntry(ErrorDescription + "in" + FunctionName, EventLogEntryType.Error);


    }
}


TestLog.aspx.cs
Use this from the code



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 TestLog: System.Web.UI.Page
{
//Create object of the above class to use it

 EventLog1 evtlog = new EventLog1();

  protected void TestMethod(object sender, EventArgs e)
    {
       try
       {
           //code which can cause the error
       }
       catch (Exception ex)
       {
          evtlog.LogException(ex.Message, "TestMethod");
          
        }
    }
}

March 12, 2011

Install sqlserver 2008 on Windows 7


To Install sqlServer2008 on Windows 7 you need SqlServer2008 Service Pack1 to resolve compatibility issues
1.) Download it from the below link
Install "Microsoft SQL Server 2008 Express with Tools" (SQLEXPRWT_x64_ENU.exe)
1. If you run "SQLEXPRWT_x86_ENU.exe", you'll come across a pop up of 
 incompatibly, You have to click on Run Programs on that pop up
2. If you run "SQLEXPRWT_x86_ENU.exe", you'll come across a "SQL Server Installation Center" window.
3. You normally click at the "Installation" tab on the left pane, and click "New SQL Server stand-alone installation or add features to an existing installation".
4. A "SQL Server 2008 Setup" installation window appears, and have the following steps included:
- Setup Support Rules
- Installation Type
- Product Key (depending on the type of installation type you selected)
- and so on...
5. Once you get to the "Installation Type" step of the installation, instead of adding a new feature to the existing SQL Instance (that I initially setup as SQLExpress), try the install new instance, or something to that effect. There are only two options in this portion, so it won't be difficult to select.
6.Once you get to the "add service account type" Choose the NTAuthority User from the  drop down list options
7. Once you get to the "Authentication Type" you can choose windows authentication  and click on Add Current user button then Click on Next 
8. Click next until you reach the "Feature Selection" step of the installation. There, select All
(If you ll only select management studio not the Database engine , Your installation will be done successfully but you ll not be able to connect to server as there will be no services installed and restarted)
9. Install on 

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.


I got the above error at the beginning of   sqlserver2008 installation on my windows7 server

Below  is the trick  what i did to fix it

I Created  folder in C: drive and named it 'temp'
and it solved the problem

March 5, 2011

Cookies example in ASP.NET

Below is the sample code to save n fetch cookie in ASP.NET

Excookie .aspx.cs

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 Excookie : System.Web.UI.Page
{
    private void Page_Load(object sender, System.EventArgs e)
    {
       
       //  Check if browser accepts cookies.
        if (Request.Browser.Cookies)
        {
            //  If the cookie(UpdatedDate) does not exist...
            if (Request.Cookies["UpdatedDate"] == null)
            {
                //  Create cookie object.
                HttpCookie cookUpdateDate = new HttpCookie("UpdatedDate",
                DateTime.Now.ToString());
                // Set the expiration .
                cookUpdateDate.Expires = DateTime.Now.AddDays(1);
                // Add to cookies collection.
                Response.Cookies.Add(cookUpdateDate);


                // Display message.
                Response.Write("This is when you last updated.");
            }
            else
            {
                // Fetch the cookie.
                HttpCookie cookUpdateDate = Request.Cookies["UpdatedDate"];
             
                // Display a message.


                Response.Write("Last Updated Time: " +
                  cookUpdateDate.Value);


                // Update the cookie value on the client.
                Response.Cookies["UpdatedDate"].Value =
                  DateTime.Now.ToString();


                //Update the cookie Expiration on the client.
                Response.Cookies["UpdatedDate"].Expires =
                  DateTime.Now.AddDays(1);
            }
        }
        else
        {
            Response.Write("Cookies has been disabled in the browser .");
        }
    }
}


Below is the saved cookie file on my machine

Custom Validator for Checkbox server control

Custom Validator for Checkbox

ExCustomValidator.aspx

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


<html>
<head>
</head>
<body>
    <form id="Form1" runat="server">
        <p>
            Check checkbox For Accepting the terms n conditons 
        </p>
        <p>
            <asp:CheckBox id="CheckBox1" runat="server" 
             Text=" Accept Terms and conditions"></asp:CheckBox>
            &nbsp; 
            <asp:CustomValidator id="CustomValidator1" 
             runat="server" ErrorMessage="Please Accept Trems and Conditions" 
             OnServerValidate="CustomValidator1_ServerValidate">
            </asp:CustomValidator>
        </p>
        <p>
            <asp:Button id="Button1" onclick="Button1_Click" 
             runat="server" Text="Submit"></asp:Button>
        </p>
        <p>
            <asp:Label id="Label1" runat="server"></asp:Label>
        </p>
       
    </form>
</body>
</html>

ExCustomValidator.aspx.cs


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 ExCusomValidator : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


    }


    public void CustomValidator1_ServerValidate(Object source,
     ServerValidateEventArgs args)
    {


        args.IsValid = (CheckBox1.Checked == true);
    }


    public void Button1_Click(Object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Label1.Text = "Thank you for Accepting";
        }
        else
        {
            Label1.Text = "";
        }
    }
}

Custom Validator for CheckBoxList Server Control

ASP.NET has no Required Field Validator available for Checkbox List or Checkbox .
Below is the Example to use Custom Validator for checkboxlist which validates that atleast one checkbox should be selected from the list.


ExCustomValidator1.aspx


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


<script language="javascript" type="text/javascript"> 


function CheckAgeGroup(sender, args)
{
     
    var options = document.getElementById('chKAge').getElementsByTagName('input');
    var ischecked=false;
    args.IsValid =false;
    for(i=0;i<options.length;i++)
    {
        var opt = options[i];
        if(opt.type=="checkbox")
        {
            if(opt.checked)
            {
                ischecked= true;
                args.IsValid = true;                
            }
        } 
    }
}


</script>


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBoxList ID="chKAge" CellPadding="2" cellspacing="0"  RepeatColumns="2" runat="server"> 
            <asp:ListItem Value="1">2-9</asp:ListItem>
            <asp:ListItem Value="2">10-18</asp:ListItem>
            <asp:ListItem Value="3">19-30</asp:ListItem>
            <asp:ListItem Value="4">30-60</asp:ListItem>
                                        </asp:CheckBoxList>                                     
  <asp:CustomValidator  ClientValidationFunction="CheckAgeGroup" ValidationGroup="Group1" ID="ValidateAge" runat="server" ErrorMessage="Please Select Age Group" > </asp:CustomValidator>  
  <asp:Button ID="btnSubmit" Text ="submit" runat ="server" ValidationGroup =  "Group1" />
    
    </div>
    </form>
</body>
</html>