Showing posts with label Web Service. Show all posts
Showing posts with label Web Service. Show all posts
0

Avoid Prevent Session TimeOut In Asp.Net To Keep Session Alive

Here i'm explaining How To Avoid Prevent Session TimeOut expiration In Asp.Net 2.0,3,5,4.0 to Keep Session Alive.

We can set timeout value in web.config file using Forms Authentication as mentioned below, Default value is 20 minutes.

This value gets reset or slide if there are calls between client and server and session expiration occurs if idle or no postbacks for specified time.
<authentication mode="Forms"/>
    <sessionState mode="InProc" cookieless="false" timeout="12">
    </sessionState>

This will cause session to expire if user is inactive for 12 minutes, there are scenarios where you would like to prevent timeout to keep session alive if user goes idle beyond set value in web.config.

Method 1:
We can Write a JavaScript to call a blank or empty page on the server at regular interval which should be little less then value specified in web.config.

I have created a KeepSessionAlive.aspx page and will call it every 10 minutes through JavaScript to slide the expiration.


Method 2:
We can use XMLHttpRequest to interact with server.



Method 3:
We can use timer control with update panel to send requests to server.
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
</asp:ScriptManager>
 
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="600000"/>
</ContentTemplate>
</asp:UpdatePanel>

These methods doesn't need any use interaction or the page to refresh, we can also create and Call WebService Using JQuery Or JavaScript for this.

0

Asp.Net Call WebService With Parameters From JavaScript JQuery

This example covers how to Call Asp.Net WebService PageMethods Or WebMethod With Parameters From JQuery Or JavaScript.

To Call WebService PageMethod through Ajax ,JavaScript or JQuery we need to uncomment or add following line before writing WebMethod

[System.Web.Script.Services.ScriptService]

Add jquery-1.7.2.min.js in application and reference it in Head section of page.

<head runat="server">
<script src="jquery-1.7.2.min.js" type="text/javascript"/>  
</head>

Add and create Web Service by Right click on solution explorer > Add New Item > WebService.asmx.
I have created a WebMethod which takes and return string parameter in it.

Call Asp.Net WebService From JQuery Or JavaScript


C# CODE
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public string Welcome(string name) 
    { 
        return "Welcome " + name;
    }
}

VB.NET CODE
 
 Public Function Welcome(name As String) As String
  Return "Welcome " & name
 End Function
End Class

Place one text input html control, one input button type on page, you can place asp.net button control either.
Enter Name: <input type="text" id="txtName" />
<asp:Button ID="btn" runat="server" Text="Invoke WebService" 
            OnClientClick="CallWebService(); return false;"/>
        
<asp:Label ID="lblMsg" runat="server" Text=""/>
 
<input type="button" id="btnCall" value="Call Service" 
       onclick="CallWebService(); return false;"/>

Add following Script in Head section of page to call PageMethod using JQuery.

To call WebService using JavaScript, we can write script as follows
Place ScriptManager on the page and add ServiceReference and path in it.

<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebService.asmx" />
</Services>
</asp:ScriptManager>

Write this Script in Head of page.

Build and run the code.

4

AutoCompleteExtender Example Ajax

In this post i m showing Ajax AutoComplete Extender Examples using ASP.NET C# and VB.NET with Database and WebService.

Autocomplete TextBox In GridView
In this example i am implementing the AutoComplete functionality to textbox in the EditItemTemaplate of GridView using AJAX autocomplete extender, for this we need to create a web service which calls the method to fetch data from database and display results as suggestions for textbox




AutoCompleteExtender TextBox CompletionList Width
Set Width of Completion List in Ajax AutoComplete Extender TextBox. The default behavior of completion list takes width equal to the width of textbox. we can change this behavior by applying some CSS style to set the width we want. default width is as shown below in the Image.


Autocomplete Textbox Progress Image
add animated Progress Image inside Ajax Auto complete extender textbox to represent loading of data.






Winforms AutoComplete TextBox In Windows Forms application
In this example i am explaining how to create a AutoComplete TextBox In windows forms application using C#.lp



hope this helps


.

27

Ajax Cascading DropDownList With Database Example in GridView

This example implements Ajax Cascading DropDownList With Database In GridView Using Asp.Net 2.0,3.5,4.0. There are several cases when you have two or three dropdowns in gridview and want second one (and third one) to be populated based on selection of first or second dropdownlist.

I've used Ajax cascading dropdownlist in EditItemTemaplete of GridView for updation of records in grid by fetching data from database to populate dropdowns,I've also implemented ajax auto complete extender textbox in it to edit name field

Make sure you have created ajax enabled website and installed ajax toolkit and ajax web extensions properly

Gridview displays Name, City, and Country on page load,



City and Country field turns into cascading dropdown list when user clicks on Edit link


Ajax cascading dropdown extender uses webservice to fetch data from database and populate dropdowns, city dropdown is populated based on country selected in country dropdown

Important points to remember

1. Put AjaxControlToolkit.dll in bin folder of your application.
2. Set EventValidation to false in page directive of your aspx page

<%@ Page Language="C#" EnableEventValidation="false"
AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>

Here is explanation why you need to turn it off ?
in order for the values to be submitted, EventValidation needs to be disabled for the page. EventValidation ensures that the values in each control match the values that were present when the page was rendered, but since these drop downs are populating on the client side, this is never true.

3. If you are getting Error method 500 or 12031 than read this to resolve this error

4. Webservice must have the webmethod with following signature and exact parameters
[WebMethod]
public CascadingDropDownNameValue[] GetColorsForModel(
string knownCategoryValues,
string category)

You can change the method name but return type must be CascadingDropDownNameValue[] with knownCategoryValues,category as parameters

First of all add a new webservice and name it CascadingDropDown.asmx
In code behind of this asmx file write following code
Add these namespaces
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using AjaxControlToolkit;
using System.Collections.Specialized;

/// <summary>
/// Summary description for CascadingDropDown
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class CascadingDropDown : System.Web.Services.WebService
{
//Create global Connection string
string strConnection = ConfigurationManager.ConnectionStrings
["dbConnectionString"].ConnectionString;

public CascadingDropDown () {

//Uncomment the following line if using designed components 
//InitializeComponent(); 
}
/// <summary>
/// WebMethod to populate country Dropdown
/// </summary>
/// <param name="knownCategoryValues"></param>
/// <param name="category"></param>
/// <returns>countrynames</returns>
[WebMethod]
public CascadingDropDownNameValue[] GetCountries
(string knownCategoryValues, string category)
{
//Create sql connection and sql command
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "Select * from Country";

//Create dataadapter and fill the dataset
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
con.Close();

//create list and add items in it 
//by looping through dataset table
List<CascadingDropDownNameValue> countryNames
= new List<CascadingDropDownNameValue>();
foreach (DataRow dRow in objDs.Tables[0].Rows)
{
string countryID = dRow["CountryID"].ToString();
string countryName = dRow["CountryName"].ToString();
countryNames.Add(new CascadingDropDownNameValue
(countryName, countryID));
}
return countryNames.ToArray();


}

[WebMethod]
public CascadingDropDownNameValue[] GetCities
(string knownCategoryValues, string category)
{
int countryID;
//this stringdictionary contains has table with key value
//pair of cooountry and countryID
StringDictionary countryValues =
AjaxControlToolkit.CascadingDropDown.
ParseKnownCategoryValuesString(knownCategoryValues);
countryID = Convert.ToInt32(countryValues["Country"]);

SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("@CountryID", countryID);
cmd.CommandText =
"Select * from City where CountryID = @CountryID";

SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
con.Close();
List<CascadingDropDownNameValue> cityNames =
new List<CascadingDropDownNameValue>();
foreach (DataRow dRow in objDs.Tables[0].Rows)
{
string cityID = dRow["CityID"].ToString();
string cityName = dRow["CityName"].ToString();
cityNames.Add(new CascadingDropDownNameValue
(cityName, cityID));
}
return cityNames.ToArray();
}

}


Now in html source of aspx page I've put two dropdowns in EditItemTemaplate of gridview
<EditItemTemplate>
<asp:DropDownList ID="ddlCountry" runat="server">
</asp:DropDownList><br />
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1"
runat="server"
Category="Country"
TargetControlID="ddlCountry"
PromptText="-Select Country-"
LoadingText="Loading Countries.."
ServicePath="CascadingDropDown.asmx"
ServiceMethod="GetCountries">
</ajaxToolkit:CascadingDropDown>
</EditItemTemplate>


Here TargetControlID is id of dropdown on which cascading dropdown is to be implemented ,Service path is path to webservice and ServiceMethod is method to fetch the data from databse and populate dropdown

You also need to add reference to webservive in script manager
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="CascadingDropDown.asmx" />
</Services>
</asp:ScriptManager>


The complete html source is like this
<%@ Page Language="C#" EnableEventValidation="false"
AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx" />
<asp:ServiceReference Path="CascadingDropDown.asmx" />
</Services>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
OnRowUpdating="GridView1_RowUpdating">

<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server"
Text='<%#Eval("ID") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblID" runat="server"
Text='<%#Bind("ID") %>'>
</asp:Label>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Name"
SortExpression="Name">
<ItemTemplate>
<asp:Label ID = "lblName" runat="server"
Text='<%#Eval("Name") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server"
Text='<%#Bind("Name") %>' >
</asp:TextBox>
<ajaxToolkit:AutoCompleteExtender
runat="server"
ID="autoComplete1"
TargetControlID="txtName"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="true"
CompletionSetCount="12" />
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Country"
SortExpression="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server"
Text='<%#Eval("Country") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCountry" runat="server">
</asp:DropDownList>
<ajaxToolkit:CascadingDropDown
ID="CascadingDropDown1"
runat="server"
Category="Country"
TargetControlID="ddlCountry"
PromptText="-Select Country-"
LoadingText="Loading Countries.."
ServicePath="CascadingDropDown.asmx"
ServiceMethod="GetCountries">
</ajaxToolkit:CascadingDropDown>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="City"
SortExpression="City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server"
Text='<%#Eval("City") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server"
OnSelectedIndexChanged="ddlCity_SelectedIndexChanged">
</asp:DropDownList><br />
<ajaxToolkit:CascadingDropDown
ID="CascadingDropDown2"
runat="server"
Category="City"
TargetControlID="ddlCity"
ParentControlID="ddlCountry"
PromptText="-Select City-"
LoadingText="Loading Cities.."
ServicePath="CascadingDropDown.asmx"
ServiceMethod="GetCities">
</ajaxToolkit:CascadingDropDown>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<div>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:dbConnectionString %>"
SelectCommand="SELECT [ID], [Name], [City],[Country]
FROM [Location]"
UpdateCommand="Update Location set [Name] = @Name,
[City] = @City,[Country] = @Country
where ID = @ID">
<UpdateParameters>
<asp:Parameter Name="Name" />
<asp:Parameter Name="ID" />
<asp:Parameter Name="Country"/>
<asp:Parameter Name="City"/>
</UpdateParameters>
</asp:SqlDataSource>

</div>
</form> 
</body>
</html>


Finally write this code in code behind of aspx page to update record
protected void GridView1_RowUpdating
(object sender, GridViewUpdateEventArgs e)
{
//Find dropdown to get selected Item text  
DropDownList ddlGridCountry = (DropDownList)
GridView1.Rows[e.RowIndex].FindControl("ddlCountry");
string strCountry =
ddlGridCountry.SelectedItem.Text.ToString();

DropDownList ddlGridCity = (DropDownList)
GridView1.Rows[e.RowIndex].FindControl("ddlCity");
string strCity =
ddlGridCity.SelectedItem.Text.ToString();

SqlDataSource1.UpdateParameters.Clear();
SqlDataSource1.UpdateParameters.Add
("Country", strCountry);
SqlDataSource1.UpdateParameters.Add("City", strCity);
}


Hope this helps

I wrote similar article in case you don't use ajax , than u can go through this

1. C#.NET Articles -Cascading DropDownList Populate dropdown based on selection of other dropdown in ASP.NET

2. Populating dropdown based on the selection of first drop down in DetailsView using FindControl and ItemTemplate

Download the sample code attached

16

Ajax AutoCompleteExtender in GridView

In this example i am implementing Ajax AutoCompleteExtender TextBox in EditItemTemaplate of GridView using AjaxControlToolkit In Asp.Net, for this we need to create a web service which calls the method to fetch data from database and display results as suggestions for textbox

We can also create AutoComplete TextBox In Winforms Windows Forms Application.

Add a new webservice to the project and name it AutoComplete.asmx or whatever you want, in the code behind of the web service we write methods to get records from database and a web method called GetCompletionList which takes text entered in textbox as parameter to search database , this method is automatically called when ever user types anything in the textbox, following is the code for web service.

C# CODE


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

    public AutoComplete () 
    {
             
    }

    [WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    {
        if (count == 0)
        {
            count = 10;
        }
        DataTable dt = GetRecords(prefixText);
        List items = new List(count);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string strName = dt.Rows[i][0].ToString();
            items.Add(strName);
        }
        return items.ToArray();
    }

    public DataTable GetRecords(string strName)
    {
        string strConn = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Parameters.AddWithValue("@Name", strName);
        cmd.CommandText = "Select Name from Test where Name like '%'+@Name+'%'";
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        con.Open();
        dAdapter.Fill(objDs);
        con.Close();
        return objDs.Tables[0];
   }
}


VB.NET
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Collections.Generic
Imports System.Data.SqlClient
Imports System.Data
Imports System.Configuration


 _
 _
 _
 _
Public Class AutoComplete
    Inherits System.Web.Services.WebService

     _
    Public Function GetCompletionList(ByVal prefixText As String, ByVal count As Integer) As String()
        If count = 0 Then
            count = 10
        End If
        Dim dt As DataTable = GetRecords(prefixText)
        Dim items As New List(Of String)(count)

        For i As Integer = 0 To dt.Rows.Count - 1
            Dim strName As String = dt.Rows(i)(0).ToString()
            items.Add(strName)
        Next
        Return items.ToArray()
    End Function

    Public Function GetRecords(ByVal strName As String) As DataTable
        Dim strConn As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString
        Dim con As New SqlConnection(strConn)
        Dim cmd As New SqlCommand()
        cmd.Connection = con
        cmd.CommandType = System.Data.CommandType.Text
        cmd.Parameters.AddWithValue("@Name", strName)
        cmd.CommandText = "Select Name from Test where Name like '%'+@Name+'%'"
        Dim objDs As New DataSet()
        Dim dAdapter As New SqlDataAdapter()
        dAdapter.SelectCommand = cmd
        con.Open()
        dAdapter.Fill(objDs)
        con.Close()
        Return objDs.Tables(0)

    End Function

End Class


In html source of aspx page add a ToolkitScriptManager and add ServiceReference and path to asmx file inside it, in gridview add autocomplete extender for the textbox which we want to show auto suggestion.

   1:  <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
   2:  <Services>
   3:       <asp:ServiceReference Path="AutoComplete.asmx"/>
   4:  </Services>
   5:  </asp:ToolkitScriptManager>
   6:   
   7:  <asp:UpdatePanel ID="UpdatePanel1" runat="server">
   8:  <ContentTemplate>
   9:   
  10:  <asp:GridView ID="GridView1" runat="server"
  11:                AutoGenerateColumns="False"
  12:                DataSourceID="SqlDataSource1">
  13:  <Columns>
  14:  <asp:CommandField ShowEditButton="True"/>
  15:  <asp:TemplateField HeaderText="ID" SortExpression="ID">
  16:  <ItemTemplate>
  17:  <asp:Label ID="lblID" runat="server" Text='<%#Eval("ID") %>'/>
  18:  </ItemTemplate>
  19:   
  20:  <EditItemTemplate>
  21:  <asp:Label ID="lblID" runat="server" Text='<%#Bind("ID") %>'/>
  22:  </EditItemTemplate>
  23:  </asp:TemplateField>
  24:   
  25:  <asp:TemplateField HeaderText="Name" SortExpression="Name">
  26:  <ItemTemplate>
  27:  <asp:Label ID = "lblName" runat="server" Text='<%#Eval("Name")%>'/>
  28:  </ItemTemplate>
  29:  <EditItemTemplate>
  30:  <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Name")%>'/>
  31:   
  32:  <asp:AutoCompleteExtender runat="server" 
  33:                            ID="autoComplete1" 
  34:                            TargetControlID="txtName"
  35:                            ServicePath="AutoComplete.asmx" 
  36:                            ServiceMethod="GetCompletionList"
  37:                            MinimumPrefixLength="1" 
  38:                            CompletionInterval="10"
  39:                            EnableCaching="true"
  40:                            CompletionSetCount="12" />
  41:  </EditItemTemplate>
  42:  </asp:TemplateField>
  43:   
  44:  </Columns>
  45:  </asp:GridView>
  46:  </ContentTemplate>
  47:  </asp:UpdatePanel>
  48:   
  49:  <asp:SqlDataSource ID="SqlDataSource1" runat="server"
  50:  ConnectionString="<%$ConnectionStrings:DatabaseConnectionString%>"
  51:  SelectCommand="SELECT [ID], [Name] FROM [Test]"
  52:  UpdateCommand="Update Test set [Name] = @Name where ID = @ID">
  53:  <UpdateParameters>
  54:  <asp:Parameter Name="Name" />
  55:  <asp:Parameter Name="ID" />
  56:  </UpdateParameters>
  57:  </asp:SqlDataSource>


AutoComplete Extender In GridView Asp.Net


Download Sample Code


Find More Articles