Tuesday, December 20, 2011

Bind DataBase Data to TreeView


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
using System.Data.SqlClient;

public partial class Treeview : System.Web.UI.Page
{
    SqlConnection cn = new SqlConnection("server=.;database=Prasad;uid=sa;pwd=sa123");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            filldata();
        }
    }

    private void filldata()
    {
        try
        {
            cn.Open();
            {
                SqlCommand SqlCmd = new SqlCommand("Select id,NodeName from tblTreeViewParent", cn);
                SqlDataReader Sdr = SqlCmd.ExecuteReader();
                SqlCmd.Dispose();
                string[,] ParentNode = new string[100, 2];
                int count = 0;

                while (Sdr.Read())
                {
                    ParentNode[count, 0] = Sdr.GetValue(Sdr.GetOrdinal("id")).ToString();
                    ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("NodeName")).ToString();
                }
                Sdr.Close();
                for (int loop = 0; loop < count; loop++)
                {
                    TreeNode root = new TreeNode();
                    root.Text = ParentNode[loop, 1];
                    //root.Target = "_blank";
                    //root.NavigateUrl = "Tree1.aspx";

                    SqlCommand Module_SqlCmd = new SqlCommand("Select id , ChieldName from tblTreeviewChild where Pid =" + ParentNode[loop, 0], cn);
                    SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader();
                    while (Module_Sdr.Read())
                    {
                        //siva To Add children module to the root node
                        TreeNode child = new TreeNode();
                        child.Value = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("id")).ToString();
                        child.Text = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("ChieldName")).ToString();
                        //child.Target = "_blank";
                        //child.NavigateUrl = "Tree2.aspx";
                        root.ChildNodes.Add(child);
                    }
                    Module_Sdr.Close();
                    TreeView1.Nodes.Add(root);
                    TreeView1.ExpandAll();

                }

            }

        }
        catch
        {
        }
        finally
        {
            cn.Close();
        }
    }
}

Monday, December 19, 2011

How to call a Web Service from client-side JavaScript using ASP.Net AJAX

http://www.semenoff.dk/en/Code-Corner/ASP.Net.AJAX/WebService-From-JavaScript.aspx

How to call a Web Service from client-side JavaScript using ASP.Net AJAX

Published 18.08.2007. Last updated 09.09.2007

Introduction

ASP.Net AJAX framework provides us with an easy and elegant way to consume Web Services from client-side JavaScript code. In fact it is even easier to write a simple AJAX enabled Web Service and connect to it from client-side JavaScript then it is to write an article like this one.
In this article I have tried to collect some of my experiences which I hope can be useful for you to get started with using ASP.Net AJAX technology in general and ASP.Net AJAX enabled Web Services in particular.

Background

For some time ago I was looking for a possibility to dynamically update some parts of my page without refreshing the rest of it. In fact I only needed to update some small text fields on my page. Apart from this text my page had a lot of graphics on it and it was a bit irritating for users to watch the whole page flashing while those text fields were updated. So I had to avoid refreshing the graphics on the page while updating my text data. ASP.Net AJAX technology has shown to be perfect choice for this purpose.
It is possible to use different AJAX techniques to achieve this kind of behaviour, for example: partial page updates, page methods and Web Service calls. In this article I will try to cover the Web Service approach.

Installing ASP.Net AJAX

Whell, first of all to get started you will have to install the ASP.Net AJAX framework. You can do the first step by visiting AJAX: The Official Microsoft ASP.NET 2.0 Site. There you can find links and pretty good instructions on how to install and get started with ASP.Net AJAX. I was using ASP.Net AJAX version 1.0 while writing this article.

Creating AJAX enabled Web Service

Lets us assume that you managed to install the ASP.Net AJAX framework. So we can start with creating new AJAX ebabled Web Application:
Add new AJAX enabled Web Application
What we need now is the AJAX enabled Web Service. Let us add new Web Service called MySampleService to the project:
Add new Web Service to the project
In order to AJAX enable it we will have to add the following attribute to the Web Service declaration part:

[System.Web.Script.Services.ScriptService()].

When this is done our Web Service is ready to respond to client-side JavaScript calls.
One more thing has to be done here: we need the Web Method that we will call from client-side JavaScript. Let us define it like this:
[WebMethod]
public string GetServerResponse(string callerName)
{
 if(callerName== string.Empty)
  throw new Exception("Web Service Exception: invalid argument");

 return string.Format("Service responded to {0} at {1}", callerName, DateTime.Now.ToString());
}
 

Configuring ASP.Net Application

ASP.Net applications web.config file also has to be modified in order to enable Web Service calls from client-side JavaScript code.
This modification is though made for you by Microsoft Visual Studio 2005 if you are using ASP.Net AJAX template. Here is the example of what can be inserted into httpHandles section of your web.config file:
<configuration>
 ...
 <system.web>
  ...
  <httpHandlers>
   <remove verb="*" path="*.asmx"/>
   <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, 
     System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   ...
  </httpHandlers>
  ...
 </system.web>
 ...
<configuration>

Making client-side JavaScript code

Let us take a look at the default.aspx file that was automatically created in our project (if it was not - then you will have to add one manually). First we have to make sure that we have one and only one instance of Script Manager object on your page:
<body>
 <form id="form1" runat="server">
  <asp:ScriptManager ID="ScriptManager1" runat="server">
  </asp: ScriptManager>
  <div>
  </div>
 </form>
</body>
Then we have to add Services collection to our ScriptManager object, add ServiceReference to the Services collection and specify Path to the desired service.
The result might look like this:
<body>
 <form id="form1" runat="server">
  <asp:ScriptManager ID="ScriptManager1" runat="server">>
   <Services>
    <asp:ServiceReference Path="~/WebServices/MySampleService.asmx" />
   </Services>
  </asp:ScriptManager>
  <div>
  </div>
 </form>
</body>
 
or like this if you prefer to do it directly in your code-behind file :

ScriptManager1.Services.Add(new ServiceReference("~/WebServices/MyWebService.asmx"));

Now we need some client-side functions, button to trigger Web Service request and a text box to provide the input for the Web Service:
  • SendRequest - this function will send asyncroneus request to the Web Service
  • OnComplete - this function will receive result from the Web Service
  • OnError - this function will be triggered if an error occures while executing Web Service
  • OnTimeOut - this function will be triggered if Web Service will not respond
  • MyTextBox - text box with the input for the Web Service
  • RequestButton - the button that triggers SendRequest function
The result might look like this:
<head id="Head1" runat="server">
 <title>Web Service call from client-side JavaScript</title>

 <script language="javascript" type="text/javascript">
  function SendRequest() {
   MySampleService.GetServerResponse(form1.MyTextBox.value, OnComplete, OnError, OnTimeOut);
  }

  function OnComplete(arg)
  {
   alert(arg);
  }

  function OnTimeOut(arg)
  {
   alert("timeOut has occured");
  }

  function OnError(arg)
  {
   alert("error has occured: " + arg._message);
  }
 </script>

</head>
<body>
 <form id="form1" runat="server">
  <asp:ScriptManager ID="ScriptManager1" runat="server">
   <Services>
    <asp:ServiceReference Path="~/WebServices/MySampleService.asmx" />
   </Services>
  </asp:ScriptManager>
  <div>
   <input type="text" value="" id="MyTextBox" />
   <input type="button" value="Send Request to the Web Service" id="RequestButton" 
    onclick="return SendRequest()" />
  </div>
 </form>
</body>  
  
This is basically it. You have a functioning client-side JavaScript code that calls server-side Web Service and treats returned response:
Web Service Response to client-side JavaScript call
If we supply empty input value to the GetServerResponse method of MySampleService then as expected it will throw an exception. This exception will be caught by the OnError function in the client-side JavaScript:
Web Service Exception

Conclusion

The described client-to-server communication model where client-side JavaScript code invokes Web Service methods provides us with a lot of flexibility to extend the web site functionality. At the same time the traffic is minimal: we send only the input data required by the Web Method and we receive only the return value from the method being invoked.

Wednesday, November 23, 2011

AdRotator Example in ASP.net



Figure1.
Add a new XML File.
Figure2.
Put this code .XML File.
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
       <Ad>
            <ImageUrl>~/Banners/468X60_add.gif</ImageUrl>
            <NavigateUrl>http://www.Mindcracker.com/Registration/Register.aspx</NavigateUrl>
            <AlternateText>Advertisement</AlternateText>
            <Impressions>100</Impressions>
            <Keyword>Header</Keyword>
            <Category>Script</Category>
      </Ad>
      <Ad>
            <ImageUrl>~/Banners/468X60_Consultant.gif</ImageUrl>
            <NavigateUrl>http://www.mindcracker.com/Consultants/</NavigateUrl>
            <AlternateText>Advertisement</AlternateText>
            <Impressions>100</Impressions>
            <Keyword>Header</Keyword>
            <Category>Script</Category>
      </Ad>
      <Ad>
            <ImageUrl>~/Banners/468X60_Employer.gif</ImageUrl>
            <NavigateUrl>http://www.Mindcracker.com/Registration/Register.aspx</NavigateUrl>
            <AlternateText>Advertisement</AlternateText>
            <Impressions>100</Impressions>
            <Keyword>Header</Keyword>
            <Category>Script</Category>
      </Ad>
      <Ad>
            <ImageUrl>~/Banners/468X60_Jobseeker.gif</ImageUrl>
            <NavigateUrl>http://www.mindcracker.com/Jobs/</NavigateUrl>
            <AlternateText>Advertisement</AlternateText>
            <Impressions>100</Impressions>
            <Keyword>Header</Keyword>
            <Category>Script</Category>
      </Ad>
      <Ad>
            <ImageUrl>~/Banners/468X60_Recruiter.gif</ImageUrl>
            <NavigateUrl>http://www.Mindcracker.com/Registration/Register.aspx</NavigateUrl>
            <AlternateText>Advertisement</AlternateText>
            <Impressions>100</Impressions>
            <Keyword>Header</Keyword>
            <Category>Script</Category>
      </Ad>
</Advertisements>

XML file elements:
·          ImageUrl – The image that will be displayed. This can be a relative link or a fully qualified internet URL.
·          NavigateUr – The link that will be followed if the user clicks the banner.
·          AlternateText – The text that will be displayed instead of the picture if it cannot be displayed. This text will also be used as a tooltip in some newer browsers.
·          Impressions – A number that sets how often an advertisement will appear.
·          Keyword – A Keyword that identifies a group of advertisement.
The actual AdRotator class provides a limited set of properties. You specify both the appropriate advertisement file in the AdvertisementFile property and the type of window that the link shouls follow in the Target property. You can also set the KeywordFilter property so that the banner will be chosen from entries that have a specific keyword.
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile="~/Advertise.xml" Target="_blank" />
There are two ways to do bind XML file on a page. First is drag and drop a XML Data Source and  configure it. Like this:
<asp:XmlDataSource ID="XmlDataSourceAd" runat="server"
                DataFile="~/Advertise.xml">
</asp:XmlDataSource>

<asp:AdRotator ID="AdRotatorHeader" runat="server" KeywordFilter="Header"
                OnAdCreated="AdRotatorHeader_AdCreated" Target="_blank"DataSourceID="XmlDataSourceAd"/>
            <asp:Label ID="LabelHeaderScript" runat="server" Visible="False"></asp:Label>

protected void AdRotatorHeader_AdCreated(object sender, AdCreatedEventArgs e)
    {
        try
        {
            if (e.AdProperties["Category"].ToString() == "Script")
            {              
                LabelHeaderScript.Text = e.AdProperties["ImageUrl"].ToString();
                LabelHeaderScript.Visible = false;
                AdRotatorHeader.Visible = true;
            }
        }
        catch (Exception ex)
        {
            string str = ex.Message;
            AdRotatorHeader.Visible = false;
        }
    }
And socond thing is you can call XML file direct using AdvertisementFile property, like this:
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile="~/Advertise.xml" Target="_blank" />
Output should be like this.
After refreshing page then you will see second image.

Tuesday, November 22, 2011

Image Enlarge Using CSS


CSS Code


.PZ3-l { float:left; margin-right:10px; }
.PZ3-r { float:right; margin-left:10px; direction:rtl; }
  html>/**/body .PZ3-r { position:relative; }

.PZ3zoom {
}

.PZ3zoom a,.PZ3zoom a:visited { display:block;
  padding:0; overflow:hidden; text-decoration:none;
  height:100%; width:100%; }
  html>/**/body .PZ3-r a { right:0; }

.PZ3zoom a:hover { position:absolute;
  z-index:999; padding:0; background:none;
  cursor:default; height:auto; width:auto;
  overflow:visible; border:2px solid #800000;
  margin:-1px 0 0 -1px; }
  html>body .PZ3zoom a:hover { margin:-1px -1px 0 -1px; }

.PZ3zoom a img { border:0; height:100%; width:100%; }
.PZ3zoom a:hover img { height:auto; width:auto;
  border:0; }

a:hover .PZ3cap,
a:hover .PZ3cap { padding:3px 5px; }
.PZ3inr { display:block; padding:2px 5px; }

.noCap a:hover .PZ3cap { display:none; }
.noBdr,.noBdr a:hover { border:0; }
.Lnk a:hover { cursor:pointer; }

HTML Code


<div class="PZ3zoom PZ3-l Bdr Cap Lnk" style="width:155px; height:115px;">
  <a href="#"><asp:Image ID="Image1" ImageUrl="~/images/image-1.jpg" runat="server" /></a></div>

Tuesday, November 15, 2011

Indexes

Index:
An Index can be created on a single column or a combination of columns in a database table. A table index is a database structure that arranges the values of one or more columns in a database table in specific order. 
Syntax:
CREATE INDEX idxModel
ON Product (Model)

Reference for SQLServer Tutorial Site

Thursday, November 10, 2011

Convert Numbers to Words in C#

http://midnightprogrammer.net/post/Convert-Numbers-to-Words-in-C.aspx


Convert Numbers to Words in C#






Use the below code to convert numbers to words and currency to word programatically (Check the code below). Instead you can create a DLL and use it or whatever the way you likeWink24. May 2009 22:18
Download the full Code from the below Link:
Usage: 

Create Class File in App_Code Folder and Paste Below code:

using System;
using System.Collections.Generic;
using System.Text;


namespace Num2Wrd
{


    public class NumberToEnglish
    {


        public String changeNumericToWords(double numb)
        {
            String num = numb.ToString();
            return changeToWords(num, false);
        }


        public String changeCurrencyToWords(String numb)
        {
            return changeToWords(numb, true);
        }


        public String changeNumericToWords(String numb)
        {
            return changeToWords(numb, false);
        }


        public String changeCurrencyToWords(double numb)
        {
            return changeToWords(numb.ToString(), true);
        }


        private String changeToWords(String numb, bool isCurrency)
        {
            String val = "", wholeNo = numb, points = "", andStr = "", pointStr = "";
            String endStr = (isCurrency) ? ("Only") : ("");
            try
            {
                int decimalPlace = numb.IndexOf(".");
                if (decimalPlace > 0)
                {
                    wholeNo = numb.Substring(0, decimalPlace);
                    points = numb.Substring(decimalPlace + 1);
                    if (Convert.ToInt32(points) > 0)
                    {
                        andStr = (isCurrency) ? ("and") : ("point");// just to separate whole numbers from points/Rupees
                        endStr = (isCurrency) ? ("Rupees " + endStr) : ("");
                        pointStr = translateRupees(points);
                    }
                }
                val = String.Format("{0} {1}{2} {3}", translateWholeNumber(wholeNo).Trim(), andStr, pointStr, endStr);
            }
            catch
            {
                ;
            }
            return val;
        }


        private String translateWholeNumber(String number)
        {
            string word = "";
            try
            {
                bool beginsZero = false;//tests for 0XX
                bool isDone = false;//test if already translated
                double dblAmt = (Convert.ToDouble(number));
                //if ((dblAmt > 0) && number.StartsWith("0"))


                if (dblAmt > 0)
                {//test for zero or digit zero in a nuemric
                    beginsZero = number.StartsWith("0");
                    int numDigits = number.Length;
                    int pos = 0;//store digit grouping
                    String place = "";//digit grouping name:hundres,thousand,etc...
                    switch (numDigits)
                    {
                        case 1://ones' range
                            word = ones(number);
                            isDone = true;
                            break;
                        case 2://tens' range
                            word = tens(number);
                            isDone = true;
                            break;
                        case 3://hundreds' range
                            pos = (numDigits % 3) + 1;
                            place = " Hundred ";
                            break;
                        case 4://thousands' range
                        case 5:
                        case 6:
                            pos = (numDigits % 4) + 1;
                            place = " Thousand ";
                            break;
                        case 7://millions' range
                        case 8:
                        case 9:
                            pos = (numDigits % 7) + 1;
                            place = " Million ";
                            break;
                        case 10://Billions's range
                            pos = (numDigits % 10) + 1;
                            place = " Billion ";
                            break;
                        //add extra case options for anything above Billion...
                        default:
                            isDone = true;
                            break;
                    }
                    if (!isDone)
                    {//if transalation is not done, continue...(Recursion comes in now!!)
                        word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos));
                        //check for trailing zeros
                        if (beginsZero) word = " and " + word.Trim();
                    }
                    //ignore digit grouping names
                    if (word.Trim().Equals(place.Trim())) word = "";
                }
            }
                catch
                {
                    ;
                }
            return word.Trim();
        }


        private String tens(String digit)
        {
            int digt = Convert.ToInt32(digit);
            String name = null;
            switch (digt)
            {
                case 10:
                    name = "Ten";
                    break;
                case 11:
                    name = "Eleven";
                    break;
                case 12:
                    name = "Twelve";
                    break;
                case 13:
                    name = "Thirteen";
                    break;
                case 14:
                    name = "Fourteen";
                    break;
                case 15:
                    name = "Fifteen";
                    break;
                case 16:
                    name = "Sixteen";
                    break;
                case 17:
                    name = "Seventeen";
                    break;
                case 18:
                    name = "Eighteen";
                    break;
                case 19:
                    name = "Nineteen";
                    break;
                case 20:
                    name = "Twenty";
                    break;
                case 30:
                    name = "Thirty";
                    break;
                case 40:
                    name = "Fourty";
                    break;
                case 50:
                    name = "Fifty";
                    break;
                case 60:
                    name = "Sixty";
                    break;
                case 70:
                    name = "Seventy";
                    break;
                case 80:
                    name = "Eighty";
                    break;
                case 90:
                    name = "Ninety";
                    break;
                default:
                    if (digt > 0)
                    {
                        name = tens(digit.Substring(0, 1) + "0") + " " + ones(digit.Substring(1));
                    }
                    break;
            }
            return name;
        }


        private String ones(String digit)
        {
            int digt = Convert.ToInt32(digit);
            String name = "";
            switch (digt)
            {
                case 1:
                    name = "One";
                    break;
                case 2:
                    name = "Two";
                    break;
                case 3:
                    name = "Three";
                    break;
                case 4:
                    name = "Four";
                    break;
                case 5:
                    name = "Five";
                    break;
                case 6:
                    name = "Six";
                    break;
                case 7:
                    name = "Seven";
                    break;
                case 8:
                    name = "Eight";
                    break;
                case 9:
                    name = "Nine";
                    break;
            }
            return name;
        }


        private String translateRupees(String Rupees)
        {
            String cts = "", digit = "", engOne = "";
            for (int i = 0; i < Rupees.Length; i++)
            {
                digit = Rupees[i].ToString();
                if (digit.Equals("0"))
                {
                    engOne = "Zero";
                }
                else
                {
                    engOne = ones(digit);
                }
                cts += " " + engOne;
            }
            return cts;
        }
    }
}