Saturday, November 12, 2011

Using AJAX AutoCompleteExtender with Web Services

Hi All,


Today I will demonstrate you on how to populate a text box with suggested values when user types a character in text box using a AJAX Auto Complete Extender. This demonstrate uses web service to get data from the database.
Suppose I have a database called "Demo" and have a table called "tblFlightInformation" to store Flight Schedule details.

Following is the database table script;

USE [Demo]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tblFlightInformation](
[FlightId] [int] NOT NULL,
[FlightDestination] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[FlightLeaveTime] [datetime] NULL,
[FlightReturnTime] [datetime] NULL,
 CONSTRAINT [PK_tblFlightInformation] PRIMARY KEY CLUSTERED
(
[FlightId] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF



Lets populate the table with sample data;

INSERT INTO dbo.tblFlightInformation (FlightId, FlightDestination, FlightLeaveTime, FlightReturnTime)
VALUES (1, 'India', '2011-11-12 19:30:00', '2011-11-12 23:00:00')

INSERT INTO dbo.tblFlightInformation (FlightId, FlightDestination, FlightLeaveTime, FlightReturnTime)
VALUES (2, 'Italy', '2011-11-13 06:00:00', '2011-11-13 12:45:00')

INSERT INTO dbo.tblFlightInformation (FlightId, FlightDestination, FlightLeaveTime, FlightReturnTime)
VALUES (3, 'Singapore', '2011-11-13 04:10:00', '2011-11-14 01:15:00')

INSERT INTO dbo.tblFlightInformation (FlightId, FlightDestination, FlightLeaveTime, FlightReturnTime)
VALUES (4, 'America', '2011-12-01 09:20:00', '2011-12-06 08:50:00')

INSERT INTO dbo.tblFlightInformation (FlightId, FlightDestination, FlightLeaveTime, FlightReturnTime)
VALUES (5, 'Saudi Arabia', '2011-12-10 23:10:00', '2011-12-13 19:10:00')



Lets create an asp.net web site and add a web service (WebServiceFlightInformation.asmx) and a web method called "LoadDestinationInformation".

[WebMethod]
public List<string> LoadDestinationInformation(string prefixText)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["FlightInformation"].ConnectionString;

using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select FlightDestination from tblFlightInformation where " +
"FlightDestination like @FlightDestination + '%'";
cmd.Parameters.AddWithValue("@FlightDestination", prefixText);
cmd.Connection = conn;
conn.Open();

List<string> FlighDestination = new List<string>();

using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
FlighDestination.Add(sdr["FlightDestination"].ToString());
}
}

conn.Close();
return FlighDestination;
}
}


After that lets create the user interface by adding a aspx page to our web site. Following is the mark up for the aspx page.

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Ajax AutoCompleteExtender without Webservice</title>
</head>
<body>
<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="ScriptManager1" runat="server" EnablePageMethods = "true"/>
<div>
<asp:TextBox ID="txtCountry" runat="server" AutoPostBack="True"></asp:TextBox>
<ajax:AutoCompleteExtender ID="AutoCompleteExtender1"
runat="server"
TargetControlID="txtCountry"
MinimumPrefixLength="1"
EnableCaching="true"
CompletionSetCount="1"
CompletionInterval="1000"
ServiceMethod="LoadDestinationInformation"
ServicePath="WebServiceFlightInformation.asmx">
</ajax:AutoCompleteExtender>
</div>
</form>
</body>
</html>


That's all and have a look into the below image, that's how it works.....



Happy Coding.

Thursday, November 10, 2011

Lets work around with XPath

XPath is nothing more than a language which gives you the capability of finding information in an XML document.
So what is XPath is all about : 
  • XPath is a syntax for defining parts of an XML document
  • XPath uses path expressions to navigate in XML documents
  • XPath contains a library of standard functions
  • XPath is a major element in XSLT
  • XPath is a W3C recommendation
Lets start with a sample demo;
I have created an xml file which contains information about flights schedule and I call it as "flightSchedule.xml" for the moment. 


Following is my xml file:
<!--?xml version="1.0" encoding="utf-8" ?-->
<flightschedule>
  <flight>
    <flightid>flight-001</flightid>
    <flightdestination>India</flightdestination>
    <flighttime>10.45.00AM</flighttime>
    <flightreturntime>15.20.00PM</flightreturntime>
</flight>
  <flight>
    <flightid>flight-002</flightid>
    <flightdestination>Singapore</flightdestination>
    <flighttime>06.00.00AM</flighttime>
    <flightreturntime>12.45.00PM</flightreturntime>
 </flight>
  <flight>
    <flightid>flight-546</flightid>
    <flightdestination>West Indies</flightdestination>
    <flighttime>01.00.00AM</flighttime>
    <flightreturntime>23.00.00PM</flightreturntime>
  </flight>
  <flight>
    <flightid>flight-879</flightid>
    <flightdestination>Australia</flightdestination>
    <flighttime>08.10.00AM</flighttime>
    <flightreturntime>13.30.00PM</flightreturntime>
  </flight>
  <flight>
    <flightid>flight-324</flightid>
    <flightdestination>Japan</flightdestination>
    <flighttime>04.40.00AM</flighttime>
    <flightreturntime>16.00.00PM</flightreturntime>
     </flight>
</flightschedule>


Now lets see how can we access or load this xml file in my .aspx page.
  • We can use "XMLHttpRequest" to load the xml file like the following                                                                                  var xhttp = new XMLHttpRequest();
So, in my example i will show you how to select values from the xml file using XPath. Imaging I want to select all the flight ids. So I can set is as "/flightSchedule/flight/flightId", and I can select the values using var nodes = xml.selectNodes(path);


And here is the output
flight-001
flight-002
flight-546
flight-879
flight-324


Following is the code for the sample demo;
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="xPath.aspx.cs" Inherits="xPath.xPath" %>


<!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">
<body>
<script type="text/javascript">
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp = new XMLHttpRequest();
}
else
{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", dname, false);
xhttp.send("");
return xhttp.responseXML;
}
xml = loadXMLDoc("flightSchedule.xml");
path = "/flightSchedule/flight/flightId";
// code for IE
if (window.ActiveXObject)
{
var nodes = xml.selectNodes(path);


for (i = 0; i < nodes.length; i++)
{
document.write(nodes[i].childNodes[0].nodeValue);
document.write("<br />");
}
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
var nodes = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
var result = nodes.iterateNext();


while (result)
{
document.write(result.childNodes[0].nodeValue);
document.write("<br />");
result = nodes.iterateNext();
}
}
</script>
</body>
</html>


Happy Coding 




Monday, November 7, 2011

File Upload Control inside update panel - ASP/AJAX

Today when I was developing my asp.net application at my office, I came across with some difficulties when dealing with the File Upload Control that I had in asp.net. I have placed a button and a file upload control with some other controls inside an update panel. The issue was whenever I clicked on the upload button, the property "HasFile" of the file upload control gave me "false". hmm, what went wrong?? was it because of the file upload does not post back data when it reside inside a update panel...???  

This issue made me read some articles and do some research on this and it was due to missing some attributes on POST method. huh???

So what can we do to avoid this.

Add the following code in your page_Load() method:


VB
Page.Form.Attributes.Add("enctype", "multipart/form-data")

C#

Page.Form.Attributes.Add("enctype", "multipart/form-data");



That's all and my file upload control started working fine !!!

Happy Coding.