Wednesday, November 24, 2010

Calling server side code from client side

Today, I am going to explain you how to call a server side function/code from client side (JavaScript).

Ajax provide us the facility to use server side code from client side without postback.

You can call server side code by using webservice(.asmx) or using page methods in same aspx page.
The page methods are rendered as inline javascript.

If you are using asp.net 2.0 then you require
ASP.NET AJAX extensions for ASP.NET 2.0

you website need to be ajax enabled for using this functionality.

I just explaining this functionality by a simple Example

add a javascript file naming script.js in you website

and write below methos in your javascript file

function CallMe(src,dest)
 {   
     var ctrl = document.getElementById(src);
     // call server side method
     PageMethods.GetGroupName(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());
 }



now move on to your aspx page
add  a reference of your javascript file in body tag of page


and paste below code 


<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
    <div>
        <asp:Label ID="lbl_Group_Code" runat="server" Text="Group Code"></asp:Label>
        <asp:TextBox ID="txt_Group_Code" runat="server"></asp:TextBox><br />
        <asp:TextBox ID="txt_Group_Name" runat="server" ReadOnly="True"></asp:TextBox><br />
    </div>
    </form>





also remember to check following property of script manager in script manager tag
 EnablePageMethods="true" 
this property enables your code to use server side webmethods


now come to your aspx.cs page


write a public static method here as follows


   public static string GetGroupName(string GRP_CODE)
        {
            if (GRP_CODE == null || GRP_CODE.Length == 0)
                return String.Empty;
            OracleConnection conn = null;
            try
            {
                string connection = ConfigurationManager.ConnectionStrings["csTextile"].ConnectionString;
                conn = new OracleConnection(connection);
                string Oracle = "Select GRP_NAME from FA_GRP_MST where GRP_CODE = :GRP_CODE";
                OracleCommand cmd = new OracleCommand(Oracle, conn);
                cmd.Parameters.Add(":GRP_CODE", OracleType.VarChar).Value = GRP_CODE;
                conn.Open();
                string GRP_Name = Convert.ToString(cmd.ExecuteScalar());
                return GRP_Name;
            }
            catch (OracleException ex)
            {
                return "error";
            }
            finally
            {
                conn.Close();
            }
        }





Method should be public static


I use Oracle as database in my website so I use OracleConnection and Command etc...
replace Oracle with sql in your app.


now add following line before your method


   [System.Web.Services.WebMethod]


like this


   [System.Web.Services.WebMethod]
        public static string GetGroupName(string GRP_CODE)
        {
            if (GRP_CODE == null || GRP_CODE.Length == 0)
                return String.Empty;
            OracleConnection conn = null;
            try
            {
                string connection = ConfigurationManager.ConnectionStrings["csTextile"].ConnectionString;
                conn = new OracleConnection(connection);
                string Oracle = "Select GRP_NAME from FA_GRP_MST where GRP_CODE = :GRP_CODE";
                OracleCommand cmd = new OracleCommand(Oracle, conn);
                cmd.Parameters.Add(":GRP_CODE", OracleType.VarChar).Value = GRP_CODE;
                conn.Open();
                string GRP_Name = Convert.ToString(cmd.ExecuteScalar());
                return GRP_Name;
            }
            catch (OracleException ex)
            {
                return "error";
            }
            finally
            {
                conn.Close();
            }
        }




now add the following code in page load event


if (!Page.IsPostBack)
            {
                txt_Group_Code.Attributes.Add("onblur", "javascript:CallMe('" + txt_Group_Code.ClientID + "', '" + txt_Group_Name.ClientID + "')");
                txt_Group_Code.Attributes.Add("onchange", "javascript:CallMe('" + txt_Group_Code.ClientID + "', '" + txt_Group_Name.ClientID + "')");
            }

now test your code

write if any problem occurs

have a happy coding

Monday, August 30, 2010

Auto Complete Extender

Hello Friends,

Now I am going to describe how to use auto complete extender control of ajax control toolkit.

For this I assume that you know the basics of webservice and how to create them.

Step 1. Add Ajax Control Toolkit reference in your website. For this See This Post
Step 2. If the ScriptManager tag is not present is your form then it should be specified inside the Form tag.<asp:ScriptManager Id="sm1" runat="server" />

Step 3. create a webservice in your solution
add this line
[System.Web.Script.Services.ScriptService]

 to your webservice just above the class defination and below the mentioned two lines
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]


Create a Method in webservice which meets your requirments like this one


[WebMethod]
public string[] GetInfo(string prefixText)
{
 int count = 10;
 string sql = "Select * from test Where Name like @prefixText";
 SqlDataAdapter da = new SqlDataAdapter(sql,”Your Connection String Comes Here”));
 da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value = prefixText+ "%";
 DataTable dt = new DataTable();
 da.Fill(dt);
 string[] items = new string[dt.Rows.Count];
 int i = 0;
 foreach (DataRow dr in dt.Rows)
 {
  items.SetValue(dr["Name"].ToString(),i);
  i++;
 }
 return items;
}






Step4: Now insert  auto complete extender to your page like this


<cc1:AutoCompleteExtender TargetControlID="txtName" CompletionInterval="1000"
ID="AutoCompleteExtender1" UseContextKey="false" MinimumPrefixLength="1" ServiceMethod="GetInfo"
ServicePath="../AutoComplete.asmx" runat="server">
</cc1:AutoCompleteExtender>


where service path is the path to your webservice and service method is the method name created  for auto complete
and target control id is the id of the text box where you want auto complete.
also set AutoCompleteType property of text box to disabled.


Now all set 
run your solution and enjoy.......



Saturday, January 23, 2010

how to use Always Visible control in asp.net

Now I am going to describe how to use Modal Popup Extender in ASP.NET website
Follow the below mentioned steps
Step 1. Add Ajax Control Toolkit reference in your website. For this See This Post
Step 2. If the ScriptManager tag is not present is your form then it should be specified inside the Form tag.<asp:ScriptManager Id="sm1" runat="server" />
Step 3. now insert Always Visible Control like
// Paste this code below the page directive and above all othe tags
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="
cc1" %>
// drap
Always Visible Control in you page and set  targetcontrolid, etc.. for example
<cc1:AlwaysVisibleControlExtender ID="Button1_AlwaysVisibleControlExtender"
    runat="server" Enabled="True" TargetControlID="Button1" VerticalSide="Top" HorizontalSide="Right">
</cc1:AlwaysVisibleControlExtender>

where TargetControlId :
ID of control for this extender to always make visible
and VerticleSlide and HorizontalSlide are the properties to set the position of the control


Properties of Modal Popup Extender and their meaning
  • TargetControlID - ID of control for this extender to always make visible
  • HorizontalOffset - Distance to the HorizontalSide edge of the browser in pixels from the same side of the target control. The default is 0 pixels.
  • HorizontalSide - Horizontal edge of the browser (either Left, Center, or Right) used to anchor the target control. The default is Left.
  • VerticalOffset - Distance to the VerticalSide edge of the browser in pixels from the same side of the target control. The default is 0 pixels.
  • VerticalSide - Vertical edge of the browser (either Top, Middle, or Bottom) used to anchor the target control. The default is Top.
  • ScrollEffectDuration - Length in seconds of the scrolling effect to last when the target control is repositioned. The default is .1 second.
  • UseAnimation - Whether or not to animate the element into position. The default is false.


Friday, January 22, 2010

Creating a RSS Feed for your website

Now I am going to explain how to Create RSS Feed for your website


Step 1. Open/ create new Website/ Project.
Step 2. Open/ Create aspx webpage.
Step 3. add the outputcache directve in the page by pasting the following code below the page directive in the html source view
<%@ OutputCache Duration="120" VaryByParam="Group" %>
Step 4. go to code (.cs) file of the page and add the following namesspaces
//---- To establish connection with database and fetching data which is to be publish in the RSS ----
using System.Data.SqlClient;

//--to create instance of encoding used in creating xmltextwriter
using System.Text;

//-- to create xmltextwriter
using System.Xml;

Step 5. Paste the following code in the page load event.
// Clear any previous output from the buffer
        Response.Clear();
        Response.ContentType = "text/xml";
        XmlTextWriter xtwRSSFeed = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
        xtwRSSFeed.WriteStartDocument();

        // The mandatory rss tag
        xtwRSSFeed.WriteStartElement("rss");
        xtwRSSFeed.WriteAttributeString("version", "2.0");

        // The channel tag contains RSS feed details
        xtwRSSFeed.WriteStartElement("channel");
        xtwRSSFeed.WriteElementString("title", "Title of the RSS");
        xtwRSSFeed.WriteElementString("link", "Link of the RSS");
        xtwRSSFeed.WriteElementString("description", "Description of the RSS.");
        xtwRSSFeed.WriteElementString("copyright", "Your Copyright Detail.");

        // Objects needed for connecting to the SQL database
        SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ToString());
        SqlCommand cmd = new SqlCommand("YourProcedureNameToGetDataFromDatabase", Con);
       
        cmd.CommandType = CommandType.StoredProcedure;
       
        if (Con.State == ConnectionState.Closed)
        {
            Con.Open();
        }

        SqlDataReader SqlDR = cmd.ExecuteReader();

        // Loop through the content of the database and add them to the RSS feed

        while (SqlDR.Read())
        {
            xtwRSSFeed.WriteStartElement("item");
            xtwRSSFeed.WriteElementString("title", SqlDR["Title"].ToString());
            xtwRSSFeed.WriteElementString("description", SqlDR["Description"].ToString());
            xtwRSSFeed.WriteElementString("link", "http://www.feedpedia.com/View.aspx?View=" + SqlDR["ID"]);
            xtwRSSFeed.WriteElementString("pubDate", SqlDR["Date"].ToString());
            xtwRSSFeed.WriteEndElement();
        }

        SqlDR.Close();
        Con.Close();

        // Close all tags

        xtwRSSFeed.WriteEndElement();
        xtwRSSFeed.WriteEndElement();
        xtwRSSFeed.WriteEndDocument();
        xtwRSSFeed.Flush();
        xtwRSSFeed.Close();
        Response.End();

Note. Dont forget to change the connection string in the web.config file

Using RSS Feed in Your Website


I am going to explain the process of using RSS Feeds in the following steps


Step 1. First Create a new website oropen existing website in which you want to use/ read RSS Feed

Step 2. Then, Create/ open .aspx page where you want to show the data using RSS Feed.

Step 3. Then, drag the XMLData source component from Toolbox under  Data tab-> to the page.
Step 4. Configure the Datasource of XMLDataSource 
            Provide the Url of Feed in DataFile Field and following line 'rss/channel/item' in XPath Field or you can provide these two field from properties of XMLDataSource too.
Step 5. Drag DataList to your page and choose Datasource to XMLDataSource1 (Id of XMLDataSource).
Step 5. Paste the following code in the in the html source view between Item Template of DataList

                <asp:LinkButton ID="lbtnLink" runat="server" PostBackUrl='<%#XPath("link")%>' Text='<%#XPath("title")%>'></asp:LinkButton>
                <hr color="#0099ff" />
                <br />
                <%#XPath("description")%>
                <hr color="#ccaa33" />
                <br />
                <%#XPath("pubDate")%><br />  


 Now All set and run the page to view the output.




Here is the html source view of the above written steps


        <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="http://timesofindia.indiatimes.com/rssfeedsdefault.cms"
            XPath="rss/channel/item"></asp:XmlDataSource>       
        <br />
        <asp:DataList ID="DataList1" runat="server" BackColor="Green" BorderColor="#DEDFDE" CellPadding="3"
            BorderWidth="1px" DataSourceID="XmlDataSource1"
            ForeColor="Black" GridLines="Vertical">

            <ItemTemplate>
                <asp:LinkButton ID="lbtnLink" runat="server" PostBackUrl='<%#XPath("link")%>' Text='<%#XPath("title")%>'></asp:LinkButton>
                <hr color="#0099ff" />
                <br />
                <%#XPath("description")%>
                <hr color="#ccaa33" />
                <br />
                <%#XPath("pubDate")%><br />
            </ItemTemplate>
        </asp:DataList>   

Saturday, January 9, 2010

How to use Hover Menu in asp.net

HoverMenu is an ASP.NET AJAX extender that can be attached to any ASP.NET Server Controls, and will associate that control with a popup panel to display additional content. When the user moves the mouse cursor over the main control, the popup gets displayed at the specified position and a CSS style can also be applied to the main control to highlight the selection or mouse over action.


Now I am going to describe how to use Hover Menu Extender in ASP.NET website
Follow the below mentioned steps
Step 1. Add Ajax Control Toolkit reference in your website. For this See This Post
Step 2. If the ScriptManager tag is not present is your form then it should be specified inside the Form tag.<asp:ScriptManager Id="sm1" runat="server" />


Step 3. In head tag provide link to the css file like <link href="HoverTest.css" rel="stylesheet" type="text/css" />

Step 4. now insert Madal Popup extender like
// Paste this code below the page directive and above all othe tags
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
// drap Hover Menu extender in you page and set popupcontrolid etc.. for example

-------------------------------------------------------------


<form id="form1" runat="server">

<asp:ScriptManager ID="SM1" runat="server" />

<asp:Repeater ID="rptTestHover" runat="server">

<ItemTemplate>
<asp:Panel ID="pnlMenu" runat="server" Width="200px" BackColor="Beige" BorderWidth="1px">
<asp:HyperLink ID="lnk_HyperLink1" runat="server" NavigateUrl="#"
Text='<%#DataBinder.Eval(Container.DataItem, "MenuText")%>' />
</asp:Panel>
<asp:Panel ID="pnlShowHover" runat="server">

<%#DataBinder.Eval(Container.DataItem, "MenuInfo")%>
</asp:Panel>
<ajaxToolkit:HoverMenuExtender ID="hmeShow" runat="server" TargetControlID="pnlMenu"

PopupControlID="pnlShowHover" PopupPosition="Right" PopDelay="10" />
</ItemTemplate>
</asp:Repeater>
</form>

------------- Hover menu extender control -------------------

   <ajaxToolkit:HoverMenuExtender ID="hmeShow" runat="server" TargetControlID="pnlMenu"

PopupControlID="pnlShowHover" PopupPosition="Right" PopDelay="10" />
----------------------------------------------------------------------------------


where 'pnlShowHover' is the Id of Panel which you want to show when Mover Hover over 'pnlMenu'


Properties of Hover Menu Extender and their meaning


TargetControlID - The control that the extender is targeting. When the mouse cursor is over this control, the hover menu popup will be displayed.
PopupControlID - The ID of the control to display when mouse is over the target control. In this case, it's just a simple panel with two links:



HoverCssClass - The CSS class to apply to the target when the hover menu popup is visible.
PopupPostion - Where the popup should be positioned relative to the target control. Can be Left (Default), Right, Top, Bottom, Center.
OffsetX/OffsetY - The number of pixels to offset the Popup from it's default position, as specified by PopupPosition. So if you want it to popup to the left of the target and have a 5px space between the popup and the target, the value should be "-5".
HoverDelay - The time, in milliseconds, before the popup displays after hovering over the target control. Default is 0.
PopDelay - The time, in milliseconds, for the popup to remain visible after the mouse moves away from the target control. Default is 100.
Animations - Generic animations for the HoverMenu extender. See the Using Animations walkthrough and Animation Reference for more details.
OnShow - The OnShow animation will be played each time the hover menu is displayed. The hover menu will be positioned correctly but hidden. The animation can use <HideAction Visible="true" /> to display the hover menu along with any other visual effects.
OnHide - The OnHide animation will be played each time the hover menu is hidden.

Hope this post helps you in using Modal PopupExtender in your website.

Thursday, January 7, 2010

how to use modal popup extender control in asp.net

Now I am going to describe how to use Modal Popup Extender in ASP.NET website
Follow the below mentioned steps
Step 1. Add Ajax Control Toolkit reference in your website. For this See This Post
Step 2. If the ScriptManager tag is not present is your form then it should be specified inside the Form tag.<asp:ScriptManager Id="sm1" runat="server" />
Step 3. In head tag provide link to the css file like <link href="ModalTest.css" rel="stylesheet" type="text/css" />


ModalTest.css File is as follows



body, div, p, h1, h2, h3, h4, ul, li, table
    {
              margin:0;
              padding:0;
              border:none;
    }
    /*Modal Popup*/
    .modalBackground
    {
              background-color:Olive;
              filter:alpha(opacity=70);
              opacity:0.7;
    }
    .modalPopup
    {
              background-color:#ffffdd;
              border-width:3px;
              border-style:solid;
              border-color:Gray;
              padding:3px;
              width:250px;
    }

Step 4. now insert Madal Popup extender like
// Paste this code below the page directive and above all othe tags
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
// drap modal popup extender in you page and set popupcontrolid, targetcontrolid, cancelcontrolid and backgroundcssclass etc.. for example

<ajaxtoolkit:modalpopupextender
        id="mpeTest"
        runat="server"
        backgroundcssclass="modalBackground"
        cancelcontrolid="CancelButton"
        dropshadow="true"
        okcontrolid="OkButton"
        popupcontrolid="Panel1"   
        targetcontrolid="lbtnTest">
    </ajaxtoolkit:modalpopupextender>

where Panel1 is the Id of Panel which you want to show when Link Button lbtnTest clicked


Properties of Modal Popup Extender and their meaning



TargetControlID - The ID of the element that activates the modal popup
PopupControlID -
The ID of the element to display as a modal popup
BackgroundCssClass -
The CSS class to apply to the background when the modal popup is displayed
DropShadow -
Set to True to automatically add a drop-shadow to the modal popup
OkControlID -
The ID of the element that dismisses the modal popup
OnOkScript -
Script to run when the modal popup is dismissed with the  OkControlID
CancelControlID -
The ID of the element that cancels the modal popup
OnCancelScript -
Script to run when the modal popup is dismissed with the CancelControlID
PopupDragHandleControlID -
The ID of the embedded element that contains the popup header/title which will be used as a drag handle
X -
The X coordinate of the top/left corner of the modal popup (the popup will be centered horizontally if not specified)
Y -
The Y coordinate of the top/left corner of the modal popup (the popup will be centered vertically if not specified)
RepositionMode -
The setting that determines if the popup needs to be repositioned when the window is resized or scrolled


Hope this post helps you in using Modal PopupExtender in your website.

Using Ajax Control Toolkit in asp.net 2.0

I am going to explain about how to use ajax control toolkit in asp.net 2.0

Follow the below mentioned steps to use ajax control toolkit

Step 1.  Download Control toolkit from here

Step 2. Create a ajax enabled website

Step 3. add reference of the AjaxControlToolkit.dll file in your website

Step 4. click on toolbox tab from the left panel, then right click and click on add tab and provide name to your tab say Ajax Toolkit. the right click on your new tab then click on choose items. A new window opens  click on Browse at the .Net Framework Component tab. search for AjaxControlToolkit.dll file in your computer.

Step 5. now it is all set to use ajax control toolkit in your website. Just drag and drop the controls you want to  use in your website and do the programming.

Hope this post will help you in using ajax control toolkit.
your suggestion and comments are invited....

Wednesday, January 6, 2010

opening browser window from win application in asp.net

Recently I encounter a situation where I have to open a browser window from desktop/ window application.
I tried a lot and found the solutions.

namespace I used for that

using System.Diagnostics;

I call following function to meet my requirment


public void OpenBrowser(string SiteUrl)
    {
        Process proc = new Process();
        proc.StartInfo.UseShellExecute = true;
        proc.StartInfo.FileName = SiteUrl;
        proc.Start();
    }


this function requests SiteUrl as input parameter where SiteUrl is the web address of the page I want to open in browser window.

Hope this code helps you in your coding

enjoy coding.......................