August 10, 2011

Gold Price Web Service

This Web Service returns current gold price , last updated on time  and change in price.
Operation GetCurrentGoldPrice returns ArrayOfStrings with Price,Date,ChangeInPrice


WebService URL
http://184.168.209.81/GoldWebService/GetGoldPrice.asmx

wsdl Document
http://184.168.209.81/GoldWebService/GetGoldPrice.asmx?WSDL

code for screen scraping with Html Agility Pack

Html Agility Pack  is a .NET code library that allows you to parse "out of the web" HTML files.
If you want to scrap some data from HTMl file over the we this is the easiest solution .
The only problem is you are dependent on third party , IF they change the structure , then you have to again work around with the changes.

Below is the sample code I am writing to for this
1.) To use Html Agility Pack download it from the below path

2.) Add the reference of HTMLAgilityPack.dll from the above downloaded folder in your bin folder of the ASP.NET solution.


3.) See the below code to read the data using this in you Class




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.IO;
using System.Net;
using HtmlAgilityPack;
public partial class GetGoldPrice : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
           FindDIVFromHTMLOnWeb();


    }
    private void FindDIVFromHTMLOnWeb()
    {
        HtmlWeb web = new HtmlWeb();
        HtmlDocument doc = web.Load("http://www.testdomain.com");
        HtmlNode dataNode = doc.DocumentNode.SelectSingleNode("//div[@id='[id of the div to be fetched]']");
        string data = dataNode.InnerText;
        Response.Write(data);




    }
}

August 2, 2011

Code for Data Caching In ASP.NET with SqlCacheDependency

Below is the code sample for Data Caching


ExDatacaching.aspx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Web.Caching;


public partial class ExDatacaching : System.Web.UI.Page
{


    SqlConnection connObj = new SqlConnection();
    DataSet ds = new DataSet();
    SqlDataAdapter objAdapter;
    CacheItemRemovedCallback onRemove;
    protected void Page_Load(object sender, EventArgs e)
    {
        onRemove = new CacheItemRemovedCallback(this.RemovedCallback);
        if (Cache["Student"] == null)
        {
            connObj.ConnectionString = ConfigurationManager.ConnectionStrings["dotNetTrainingConnectionString"].ToString();
            connObj.Open();


            SqlCommand objCommand = new SqlCommand("Select * from student", connObj);
         
           objAdapter = new SqlDataAdapter(objCommand);  
            objAdapter.Fill(ds);
            SqlCacheDependency dep = new SqlCacheDependency(objCommand);  
            connObj.Close();


            Cache.Insert("Student", ds, dep, Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1),
               CacheItemPriority.Default, onRemove);




            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
            lblStatus.Text = "Fresh From DB";
        }
        else
        {
            GridView1.DataSource = Cache["Student"];
            GridView1.DataBind();


        }


    }


    void RemovedCallback(string key, Object value,
       CacheItemRemovedReason reason)
    {
        Cache["Status"] = "Cache item: " + key + " value: " +
           value.ToString() + " was " + reason.ToString();
    }


    protected void btnRemove_Click1(object sender, EventArgs e)
    {
        Cache.Remove("Student");
    }


    public void ExDatacaching_PreRender(object sender, EventArgs e)
    {
        // Display status.
        if (Cache["Status"] != null)
            lblStatus.Text = Cache["Status"].ToString();


    }
}

ExDatacaching.aspx

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


<!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" onprerender ="ExDatacaching_PreRender">
    <div>
         <asp:Button ID="btnRemove" runat="server" Text ="Remove" OnClick="btnRemove_Click1" />
       <asp:Label ID="lblStatus" runat="server" Text ="" />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>

Above SqlCacheDependency works only when SQLSERVER is allowed to Notify about the changes made and Application is ready to receive the notifications

For this
First write below code in global.asax file


 void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup


        System.Data.SqlClient.SqlDependency.Start(ConfigurationManager.ConnectionStrings["dotNetTrainingConnectionString"].ToString());


    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown


        System.Data.SqlClient.SqlDependency.Stop (ConfigurationManager.ConnectionStrings["dotNetTrainingConnectionString"].ToString());


    }


Plus make sure Database is also configured to notify for the changes 
to do that 
execute below command on sqlserver



SELECT NAME, IS_BROKER_ENABLED
FROM   SYS.DATABASES


If it is not enabled (IS_BROKER_ENABLED=0)execute below command to enable notification 


ALTER DATABASE <database>  SET ENABLE_BROKER


August 1, 2011

OFAC SDN WEB SERVICE

This web services is created for Money Transfer Businesses in US to meet the requirements of the US Treasury Department s Office of Foreign Asset Control (OFAC).OFAC restricts transactions with specific countries, organizations and individuals. The Office of Foreign Assets Control (OFAC) of the US Department of the Treasury administers and enforces economic and trade sanctions based on US foreign policy and national security goals against targeted foreign countries, terrorists, international narcotics traffickers, and those engaged in activities related to the proliferation of weapons of mass destruction. OFAC acts under Presidential wartime and national emergency powers, as well as authority granted by specific legislation, to impose controls on transactions and freeze foreign assets under US jurisdiction. This WebService checks in SDNLIST Provided by OFAC ,for the Blocked Person (Both FirstName and Last Name) in Method (CheckBlockedNames)or the Corporation (Only Last Name) in Method (CheckBlockedEntities)


 In Method( CheckBlockedNamesWithTolerance) Web Service returns the 
List of Matching Individuals and Corporation within the tolerance given by the web service client by calculating the LEVENSHTEIN distance

WEBSERVICE END POINT : 


http://184.168.209.81/SDNWebService/CheckSDNBlockedPerson.asmx


wsdl document link


http://184.168.209.81/SDNWebService/CheckSDNBlockedPerson.asmx?WSDL



Below is the Test client written to Use all 3 methods of the above web service


1.) Add the web Reference of the web Service  URL 




Default.aspx.cs 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebReference;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
       CheckSDNBlockedPerson OBJ = new CheckSDNBlockedPerson();
     
        //Use Methoid to know if the Individual is in blocked list provided by OFAC Dept
       bool result = OBJ.CheckBlockedNames("Khantibhal", "Patel");


        if (result ==true )
        {
            Response.Write("Khantibhai patel is black listed person <br/>");
        }
        else
        {
            Response.Write("Khantibhai patel is not black listed person <br/>");


        }




        //Use Methoid to know if the Corporation is in blocked list provided by OFAC Dept
        bool result1 = OBJ.CheckBlockedEntities("POPULAR FRONT FOR THE LIBERATION OF PALESTINE");


        if (result1 == true)
        {
            Response.Write("POPULAR FRONT FOR THE LIBERATION OF PALESTINE is balck listed Entity <br/>");
        }
        else
        {
            Response.Write("POPULAR FRONT FOR THE LIBERATION OF PALESTINE is not balck listed Entity <br/>");


        }




        //Use Methoid to get the matching blacklisted names with the tolerance specified


        BLOCKLISTTolerance [] OBJLIST= OBJ.CheckBlockedNamesWithTolerance("KHANTIbHAI", "PATe", 6);
       foreach (BLOCKLISTTolerance I in OBJLIST)
       {


           Response.Write(I.FirstName);
           Response.Write("  ");
           Response.Write(I.LastName );
           Response.Write("  ");
           Response.Write(I.Tolerance);
           Response.Write("<BR/>");




       }




    }
}


Below will be the o/p