Google Map 3 with Multiple locations in Asp.Net C#


Google Map Version 3 API is especially designed to be faster and more applicable to mobile devices, as well as traditional desktop browser applications ….read more from google map api document.

Click here to download the article

If you find the Google Map 3 code library useful, please consider donating

(No more API registration key needed for Version 3.0)

In this article I am going to explain how we can show multiple locations binding from code behind dynamically (database or any data source).  Couple of moths ago in Asp.Net forum I have posted an article using Google Map Version 2.0
(http://forums.asp.net/p/1507845/3584193.aspx#3584193). Version two was kind of messy Java Script code but now in Version 3.0 Google made it very simple.

Create a ASPX page and copy paste the following markup code..

<html>
<head runat=”server”>
<meta name=”viewport” content=”initial-scale=1.0, user-scalable=no” />
<meta http-equiv=”content-type” content=”text/html; charset=UTF-8″ />
<title>Google Map 3.0</title>
<style type=”text/css”>
.formatText{color:Green;font-size:11px;font-family:Arial;font-weight:bold;}
</style>
<script type=”text/javascript” src=”http://maps.google.com/maps/api/js?sensor=false“></script>
<script type=”text/javascript”>
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(40.764015, -73.982797);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}

map = new google.maps.Map(document.getElementById(“map_canvas”), myOptions);

for (var i = 0; i < locationList.length; i++) {
var args = locationList[i].split(“,”);
var location = new google.maps.LatLng(args[0], args[1])
var marker = new google.maps.Marker({
position: location,
map: map
});
var j = i + 1;
marker.setTitle(message[i].replace(/(<([^>]+)>)/ig,””));
attachSecretMessage(marker, i);
}
}

function attachSecretMessage(marker, number) {
var infowindow = new google.maps.InfoWindow(
{ content: message[number],
size: new google.maps.Size(50, 50)
});
google.maps.event.addListener(marker, ‘click’, function() {
infowindow.open(map, marker);
});
}
</script>

</head>
<body style=”margin: 0px; padding: 0px;” onload=”initialize()”>
<form runat=”server”>
<div style=”padding-top: 10%;padding-left:20%”>
<div id=”map_canvas” style=”width: 50%; height: 50%”>
</div>
</div>
</form>
</body>
</html>

I have highlighted some of the lines from the above code

1)  The class formatText, simple css class for formating the info window text. You can replace your own css style here
.formatText{color:Green;font-size:11px;font-family:Arial;font-weight:bold;}

2) In the Java Script include statement I have mention sensor=false (because the sample app is targeting on web  page if you are using from Mobile application you should  set sensor=false. Read more about mobile app)

3) In the for loop I’ m using locationList.Length. Here locationList is Java Script array object which is getting generated from an Aspx code behind page and basically the locationList object has array of  Geo code information like Latitude and Longitude. In one my previous article I have explained how we can get the Geo-code location from an address using Yahoo API.

HTML out put

var locationList = new Array( ‘40.756012, -73.972614’ , ‘40.456012, -73.796087’ , ‘40.456012, -73.456807’ );

4) Splitting lattitude and longitude from the array object and assign it to Google function like below.

var args = locationList[i].split(“,”);

var location = new google.maps.LatLng(args[0], args[1])

5)   In marker we can able to set the title value and since I am using html tags and css class I’m replacing the html tags using the following syntax

marker.setTitle(message[i].replace(/(<([^>]+)>)/ig,””));

The rest of the mark up tags are same as mentioned in the Google doc.
So now we need to create the array from code behind. Copy paste the below code in to you code behind page load method
protected void Page_Load(object sender, EventArgs e)
 {
 List<String> oGeocodeList = new List<String>
 {
 " '40.756012, -73.972614' ",
 " '40.456012, -73.796087' ",
 " '40.456012, -73.456807' "
 };

 var geocodevalues = string.Join(",", oGeocodeList.ToArray());

 List<String> oMessageList = new List<String>
 {
 " '<span class=formatText >Google Map 3 Awesome !!!</span>' ",
 " '<span class=formatText>Made it very simple</span>' ",
 " '<span class=formatText>Google Rocks</span>' "
 };

 String message = string.Join(",", oMessageList.ToArray());

 ClientScript.RegisterArrayDeclaration("locationList", geocodevalues);

 ClientScript.RegisterArrayDeclaration("message", message);
 }

The above code List<String> oGeocodeList which creates a list of Geo-Code collection object. I have hard coded latitude and longitude (you can replace with your db procedure). Once you have created the list object we should convert in to Java Script array format like below

var geocodevalues = string.Join(“,”, oGeocodeList.ToArray()); and finally register the array

ClientScript.RegisterArrayDeclaration(“locationList”, geocodevalues); here locationList is the JS array object name.

Similarly I am creating the message array for the pop window (InfoWindow)

List oMessageList = new List
{
” ‘Google Map 3 Awesome !!!‘ “,
” ‘Made it very simple‘ “,
” ‘Google Rocks‘ ”
};

String message = string.Join(“,”, oMessageList.ToArray());   //convert list object to JS array format.

ClientScript.RegisterArrayDeclaration(“message“, message); //message = JS array object name.

Please refer the following links if you need to learn more about Map API 3.0

http://code.google.com/apis/maps/documentation/v3/introduction.html
http://code.google.com/apis/maps/documentation/v3/
http://code.google.com/apis/maps/documentation/v3/reference.html

Hope this help and If you have any comments, please feel free to write your feedback.

You can download the entire article from here or copy paste the URL

http://www.4shared.com/file/251039814/3e491cfc/GoogleMap3.html

If you find the Google Map 3 code library useful, please consider donating

Thanks
Deepu

Silverlight: Consume a web service in Silverlight


Silverlight application can talk to the server via web services like ASMX web services or WCF services or REST based services.  (for ex : file uploading to the server or sending emails etc.). In this article I am going to explain how to consume a web service in Silverlight. I am creating a simple contact form in Silverlight 3.0 (see the below image) which sends the contact information as email using ASMX web service. (You can download the entire article from here)

Open VS 2008 (SP 1.0) and create a new project called Contact Form (see the below image) which would be hosting the Silverlight application in a web application project.

Right click the web application project and add a new asmx file for web service (see the below image) and name it as EmailService.ASMX

Copy paste the below code inside the EmailService.asmx file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net.Mail;

namespace ContactForm.Web
{
 [WebService(Namespace = "http://tempuri.org/")]
 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 [System.ComponentModel.ToolboxItem(false)]

 public class EmailService : System.Web.Services.WebService
 {
 [WebMethod]
 public bool SendMail(string fromAddress, string toAddress, string subject, string body)
 {
 try
 {
 MailMessage msg = new MailMessage();
 msg.From = new MailAddress(fromAddress);
 msg.To.Add(new MailAddress(toAddress));
 msg.Subject = subject;
 msg.Body = body;
 msg.IsBodyHtml = true;

 SmtpClient smtp = new SmtpClient("127.0.0.1"); //replace with your smtp client
 smtp.Send(msg);
 return true;
 }
 catch(Exception exp)
 {
 //log exception here..
 return false;
 }
 }
 }
}

So the next step is creating the contact form interface with xaml markup.

In the xaml page Usercontrol deceleration you may need to include the input control namespace some thing like below and aslo add the reference from the library.

<UserControl x:Class=”ContactForm.MainPage”
xmlns:my=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input”

Copy paste the xaml in to the MainPage.xaml page.

<UserControl x:Class=”ContactForm.MainPage”
xmlns:my=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243; xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;
mc:Ignorable=”d” d:DesignWidth=”640″ d:DesignHeight=”480″>

<Grid x:Name=”LayoutRoot” Background=”White” Width=”500″>
<Grid x:Name=”contactGrid” Width=”500″>
<Grid.RowDefinitions>
<RowDefinition Height=”50″/>
<RowDefinition Height=”30″/>
<RowDefinition Height=”30″/>
<RowDefinition Height=”30″/>
<RowDefinition Height=”152″/>
<RowDefinition Height=”30″/>
</Grid.RowDefinitions>

<Grid.ColumnDefinitions>
<ColumnDefinition Width=”130″/>
<ColumnDefinition Width=”370″ />
</Grid.ColumnDefinitions>

<my:Label Grid.Column=”0″ FontFamily=”Arial” FontSize=”24″ HorizontalAlignment=”Left” Grid.ColumnSpan=”2″ Grid.Row=”0″ Content=”Contact Me”  />

<my:Label Grid.Column=”0″ HorizontalAlignment=”Right”   FontFamily=”Verdana” FontSize=”13″  Grid.Row=”1″ Content=”*Name : “/>
<TextBox Grid.Column=”1″ FontFamily=”Verdana” Width=”170″ Height=”25″ HorizontalAlignment=”Left” FontSize=”13″ Name=”txtName”  Grid.Row=”1″ Margin=”4,0,0,0″ />

<my:Label Grid.Column=”0″ HorizontalAlignment=”Right”   FontFamily=”Verdana” FontSize=”13″  Grid.Row=”2″ Content=”*Email : “/>
<TextBox Grid.Column=”1″ FontFamily=”Verdana” Width=”170″ Height=”25″ HorizontalAlignment=”Left” FontSize=”13″ Name=”txtEmail”  Grid.Row=”2″ Margin=”4,0,0,0″ />

<my:Label Grid.Column=”0″ HorizontalAlignment=”Right” FontFamily=”Verdana” FontSize=”13″  Grid.Row=”3″ Content=”Subject : “/>
<TextBox Grid.Column=”1″ FontFamily=”Verdana” Width=”170″ Height=”25″ HorizontalAlignment=”Left” FontSize=”13″ Name=”txtSubject”  Grid.Row=”3″ Margin=”4,0,0,0″ />

<my:Label Grid.Column=”0″ HorizontalAlignment=”Right” FontFamily=”Verdana” FontSize=”13″  Grid.Row=”4″ VerticalAlignment=”Top” Content=”*Message : “/>
<TextBox Grid.Column=”1″ FontFamily=”Verdana” Width=”350″ Height=”150″ HorizontalAlignment=”Left” VerticalAlignment=”Top” FontSize=”13″ Name=”txtMessage”  Grid.Row=”4″ Margin=”4,0,0,0″ />

<Button Grid.Column=”0″ Grid.ColumnSpan=”2″ HorizontalAlignment=”Center” Height=”25″ Grid.Row=”5″ Width=”75″ Content=”Send” Name=”btnSend” />

</Grid>
</Grid>
</UserControl>

So the next step is add reference to the web service in the silverlight app.Right click the Silverlight project and add a Service reference (see the below image)

Click the discover button in the image below and get the web service url (if you know the url you can copy paste directly).

In the codebehind page of the xaml file please paste the below code.


using System;
using System.Windows;
using System.Windows.Controls;
using ContactForm.EmailServiceReference;
using System.ServiceModel;
using System.Windows.Browser;

namespace ContactForm
{
 public partial class MainPage : UserControl
 {
 public MainPage()
 {
 InitializeComponent();

 btnSend.Click += new RoutedEventHandler(sendButton_Click);
 }

 private void sendButton_Click(object sender, RoutedEventArgs e)
 {
 if (txtName.Text.Length == 0 || txtEmail.Text.Length == 0 || txtMessage.Text.Length == 0)
 {
 MessageBox.Show("Required fields are missing");
 return;
 }
 string url = HtmlPage.Document.DocumentUri.ToString();

 url = url.Substring(0, url.LastIndexOf("/")) + "/EmailService.asmx";

 BasicHttpBinding bind = new BasicHttpBinding();

 EndpointAddress endpoint = new EndpointAddress(url);

 EmailServiceSoapClient emailService = new EmailServiceSoapClient(bind, endpoint);

 emailService.SendMailAsync(txtEmail.Text, "from@emailid.com", txtSubject.Text, txtMessage.Text);

 emailService.SendMailCompleted += new EventHandler<SendMailCompletedEventArgs>(emailService_Completed);
 }

 private void emailService_Completed(object sender, SendMailCompletedEventArgs e)
 {
 if (e.Result)
 {
 MessageBox.Show("You email has sent successfully");
 }
 else
 {
 MessageBox.Show("Sorry !!! unable to send email");
 }

 }
 }
}

Code Explanation

Once you have completed with add service reference you must include the following namespace in the MainPage.xaml.cs code behind

using ContactForm.EmailServiceReference;    (contact form web service namespace).

using System.ServiceModel; (system web service namespace).

using System.Windows.Browser; (Html Dom namespace).

In the page default constructor I am creating event handler for send button click.

btnSend.Click += new RoutedEventHandler(sendButton_Click);

BasicHttpBinding bind = new BasicHttpBinding();  // initializes http binding to configure endpoints that can communicate ASMX based web service.

EndpointAddress endpoint = new EndpointAddress(url); //provide a unique network address and you can replace with your web service url.

EmailServiceSoapClient emailService = new EmailServiceSoapClient(bind, endpoint);

emailService.SendMailAsync(txtEmail.Text, “from@email.com”, txtSubject.Text, txtMessage.Text); // sending email in Asynchronous method with the some simple parameter  to address, from address, subject and body of the email.

Once the web service method completed emailService_Completed method get fired

emailService.SendMailCompleted += new EventHandler<SendMailCompletedEventArgs>(emailService_Completed);

You can download the entire article from here or copy paste the URL

http://www.4shared.com/file/247655657/750739e9/ContactForm.html

Hope this help and If you have any comments, please feel free to write your feedback.

Thanks
Deepu

Asp.Net 3.5 Ajax Modal Popup Extender with User Control Event Bubbling


I had a requirement to implement login control in a pop up window using Ajax Modal Popup extender. In this article I am discussing how to implement Usercontrol event bubbling (ie subscribe the user control event  in the parent page)  and the AjaxModal popup extender.

You can download the entire article from here

For more information about Ajax Model Popup Extender please visit http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/ModalPopup/ModalPopup.aspx

If you find the Ajax Modal Popup code library useful, please consider donating



Scenario

Logged In users only can post the comment..
Login control is implemented in ASCX file.
Once the user logged in Successfully the user control event get fired in the Login Control ASCX page which is subscribed in the parent ASPX page.

Following are the screen shots for login control page and aspx page.

For more information about the user control event bubbling please visit the following links

http://asp.net-tutorials.com/user-controls/events/

http://codebetter.com/blogs/brendan.tompkins/archive/2004/10/06/Easily-Raise-Events-From-ASP.NET-ASCX-User-Controls.aspx

http://odetocode.com/code/94.aspx

Create a new ASCX  file called PopupLoginControl.ascx and copy paste the following markup tags.

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”ajaxtoolkit” %>

<asp:Button ID=”btnShowPopup” runat=”server” Style=”display: none” />

<ajaxtoolkit:ModalPopupExtender BackgroundCssClass=”modalBackground”
CancelControlID=”btnClose” runat=”server” PopupControlID=”Panel1″ ID=”ModalPopupExtender1″
TargetControlID=”btnShowPopup” />

<asp:Panel ID=”Panel1″ runat=”server” CssClass=”modalPopup” DefaultButton=”btnOk”>
<table width=”100%” border=”0″ cellpadding=”2″ cellspacing=”5″>
<tr>
<td style=”width:35%;padding-top:50px;”>
</td>
<td>
<asp:Label id=”labMsg” runat=”server” />
</td>
</tr>
<tr>
<td align=”right” valign=”middle”>
<strong>Email Id :</strong>
</td>
<td>
&nbsp;<asp:TextBox ID=”txtLogin” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td align=”right” valign=”middle”>
<strong>Password :</strong>
</td>
<td>
&nbsp;<asp:TextBox ID=”txtPassword” runat=”server” TextMode=”Password”></asp:TextBox>
</td>
</tr>
<tr>
<td>

</td>
<td>
<asp:Button ID=”btnOk” OnClick=”Login” runat=”server” Text=”Sign In” />
<asp:Button ID=”btnClose” runat=”server” Text=”Cancel” />

</td>
</tr>
</table>
</asp:Panel>

PopupLoginControl.ascx.Cs

 public event EventHandler LoginStatus;
 bool status;

 public Boolean IsLogin
 {
 get { return status; }
 }
 protected void Page_Load(object sender, EventArgs e)
 {

 }
 protected void Login(object sender, EventArgs e)
 {
 labMsg.Text = string.Empty;

 ModalPopupExtender1.Show(); //show pop up window

 if (LoginStatus != null)
 {
 if (txtLogin.Text.Equals("admin") && txtPassword.Text.Equals("admin"))
 {
 status = true;

 LoginStatus(this, EventArgs.Empty); //event get fired here.

 ModalPopupExtender1.Hide(); //hide pop up window once the user logged in successfully.
 }
 else
 {
 labMsg.Text = "<font color=red>Sorry user name and password could not find</font>";
 }
 }
 }
 public void EnableModelDialog(bool visibility)
 {
 if (visibility)
 {
 ModalPopupExtender1.Show();
 }
 else
 {
 ModalPopupExtender1.Hide();
 }
 }

LoginTest.aspx page(Markup)

<%@ Register Src=”PopupLoginControl.ascx” TagName=”PopupLoginControl” TagPrefix=”uc1″ %>

<style type=”text/css”>
.modalBackground
{
background-color: Gray;
filter: alpha(opacity=70);
opacity: 0.7;
}
.modalPopup
{
background-color: White;
height: 250px;
width:500px;
text-align:left;
}
</style>

<form id=”form1″ runat=”server”>

<asp:ScriptManager ID=”Scriptmanager1″ runat=”server” />

<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>

<ContentTemplate>

<asp:LinkButton ID=”lnkWriteMessage” runat=”server” OnClick=”ShowMessage”>Write Comments</asp:LinkButton>

<uc1:PopupLoginControl ID=”PopupLoginControl1″  OnLoginStatus=”PopupLoginCntl_Completed”
Visible=”false” runat=”server” />

<asp:Panel ID=”divComments” Visible=”false” runat=”server”>

<table width=”50%”>
<tr>
<td>
<textarea id=”txtComments” rows=”10″ cols=”60″></textarea>
</td>
</tr>
<tr>
<td>
<asp:Button id=”btnSave” runat=”server” Text=” Save ” onclick=”btnSave_Click” />
</td>
</tr>
</table>

</asp:Panel>

</ContentTemplate>

</asp:UpdatePanel>

</form>

LoginTest.aspx page(CSharp)

protected void ShowMessage(object sender, EventArgs e)
 {
 PopupLoginControl1.Visible = true;
 PopupLoginControl1.EnableModelDialog(true);
 }

//method get called when the usercontrol event get fired
 protected void PopupLoginCntl_Completed(object sender, EventArgs e)
 {
 if (PopupLoginControl1.IsLogin)
 {
 divComments.Visible = true;
 }
 else
 {
 divComments.Visible = false;
 }
 }

 protected void btnSave_Click(object sender, EventArgs e)
 {
//save your comments here.
 }

For more information about the user control event bubbling please visit the following links

http://asp.net-tutorials.com/user-controls/events/

http://codebetter.com/blogs/brendan.tompkins/archive/2004/10/06/Easily-Raise-Events-From-ASP.NET-ASCX-User-Controls.aspx

http://odetocode.com/code/94.aspx

Hope this help and If you have any comments, please feel free to write your feedback.

You can download the entire article from here or copy paste the URL

http://www.4shared.com/file/245044652/c1777187/AjaxModelExtender.html

If you find the Ajax Modal Popup code library useful, please consider donating


Thanks
Deepu

Yahoo Geocoding API Service in Asp.Net 3.5 C# using WebClient class (Asynchronously)


In this article I am going to explain how to consume yahoo Geocoding API service in Asp.Net C# using web client Asynchronous method.
If you are working with maps you may require latitude and longitude to show the address in map. Yahoo!s APIs is the awesome tool provides APIs for many of the services Maps, Music, Search, Search Marketing, Shopping, Travel etc…

Click here to download the entire article

Assume you have a list of locations in your database and need to pull Geo-coder (latitude and longitude) from yahoo API service  in Asynchronous manner.. (per day you can query 5000 request from a single ip address). Geocoding service is a free service you have to register in order to use it. http://developer.yahoo.com/maps/rest/V1/geocode.html

So lets create a simple class called Location with two properties LocationId,Address.

public class Location
{
public int LocationId { get; set; }
public string Address { get; set; }

public static List<Location> GetLocationList()
{
List<Location> oAddressList = new List<Location>
{
new Location{ LocationId = 1, Address = "1001 Emerald Heights Ct, Reston VA 20191"},
new Location{ LocationId = 2, Address = "1001 University Ave, West Des Moines, IA 50266"},
new Location{ LocationId = 3, Address = "701 First Ave Sunnyvale,CA"},
};
return oAddressList;
}
}

I have hard coded three different addresses you can change this with your database logic.  The next step is to create a new aspx page and make sure if you are using asynchronous call you have to add Async=”true” in the page header of the Aspx page.

Task List in the aspx page.

1) Add Async=”true”  in the page header.
2)
Get the locations list from the business object / database.
3) Initializing yahoo application id (http://developer.yahoo.com/maps/rest/V1/geocode.html).
4) Construct url for geocode service (make sure you are sending address in encode format using Server.UrlEncode method).
4) Consume Geo-code service using web client class with Asynchronous manner.
5) Send Address information along with a custom token, AddressId (so that I can update geocode information to database for the particular address).
5) Download result xml from yahoo api service.
6) Parse the xml content and get Latitude and longitude

In the Page_Load Method

protected void Page_Load(object sender, EventArgs e)
 {
string YAHOO_API_SIGNATURE = "YD-9G7bey8_JXxQP6rxl.fBFGgCdNjoDMACQA--";

 string YAHOO_API_URL = "http://local.yahooapis.com/MapsService/V1/geocode?appid=" + YAHOO_API_SIGNATURE + "&street=";

 string url = string.Empty;

 var oGeoCoderList = Location.GetLocationList();

 foreach (Location location in oGeoCoderList)
 {
 WebClient oWebClient = new WebClient();

 oWebClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCompleted);

 url = string.Concat(YAHOO_API_URL, Server.UrlEncode(location.Address));

 oWebClient.DownloadDataAsync(new Uri(url), location.LocationId);
 }
}

Code Explanations

Initializing yahoo application id

string YAHOO_API_SIGNATURE = “YD-9G7bey8_JXxQP6rxl.fBFGgCdNjoDMACQA–“;

Initializing yahoo web service API URL.

string YAHOO_API_URL = “http://local.yahooapis.com/MapsService/V1/geocode?appid=&#8221; + YAHOO_API_SIGNATURE + “&street=”;

Get location list from business object or database.

var oGeoCoderList = Location.GetLocationList();

Create a webclient object

WebClient oWebClient = new WebClient();

Create event handler (DownloadDataCompleted) this event get fired when an asynchronous data download operation complete.

oWebClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCompleted);

Append location address with yahoo api url.

url = string.Concat(YAHOO_API_URL, Server.UrlEncode(location.Address));

DownloadDataAsync method downloads resources as System byte array.

oWebClient.DownloadDataAsync(new Uri(url), location.LocationId);

Loop through the location list and send address information to yahoo service along with a custom token, AddressId (so that I can update laster to database for the particular address).

 void DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
 {
 try
 {
 if (e.Error == null) //make sure there is no error.
 {
 byte[] byteContent = e.Result;

 string result = System.Text.Encoding.ASCII.GetString(byteContent);

 if (!string.IsNullOrEmpty(result))
 {
 int addressId = (int)e.UserState;

 var xml = XElement.Parse(result);

 xml = StripXMLNameSpace(xml);

 if (xml != null)
 {
 XElement xelement = (XElement)xml;
 string latitude = (from geoCodeService in xelement.Descendants("Result").Descendants("Latitude")
 select geoCodeService.Value).Take(1).SingleOrDefault<String>();

 string longtitue = (from geoCodeService in xelement.Descendants("Result").Descendants("Longitude")
 select geoCodeService.Value).Take(1).SingleOrDefault<String>();

 UpdateLocation(addressId, latitude, longtitue);
 }
 }
 }
 else
 {
 //log your error information here.
 }
 }
 catch (Exception exp)
 {
 //log system exception here
 }
 }

 void UpdateLocation(int addressId, string latitude, string longtitue)
 {
 //implement your update logic here....
 }

 XElement StripXMLNameSpace(XElement root)
 {
 return new XElement(
 root.Name.LocalName,
 root.HasElements ?
 root.Elements().Select(el => StripXMLNameSpace(el)) :
 (object)root.Value
 );
 }

Once we retrieve the information from yahoo service the above method will convert the result system byte array to string using System.Text.Encoding.ASCII.GetString method and also get the user defined object which we already passed to the method and remove the xmlns:name space  from the XML result and getting the values of latitude and longitude from the nodes. In my upcoming articles  I would like to explain how to integrate Google (MAPS & Street View) and Virtual Earth (with multiple address location)

Hope this help and If you have any comments, please feel free to write your feedback.

You can download the entire article from here or copy paste this URL

http://www.4shared.com/file/241083617/7919b1a7/YahooApiGeoCoder.html

Thanks
Deepu

Create RSS 2.0 and Atom 1.0 in Asp.Net 3.5 C#


In this article I am going to explain how we can create web syndications like RSS 2.0 and Atom 1.0 in Asp.Net and C# with very minimal code. (You can download the entire article from here ).

RSS 2.0
Really Simple Syndication (RSS) is one of the syndication feed formats which can get the frequently updated content from the web site. (Refer:  http://en.wikipedia.org/wiki/RSS).
The specification of RSS format http://cyber.law.harvard.edu/rss/rss.html.  RSS is most widely used syndication format.

Atom 1.0
Atom is a syndication format which is more flexible than RSS.  Atom came into existence out of a need to improve RSS. (Refer: http://en.wikipedia.org/wiki/Atom_standardard)

In Asp.Net 3.5 frame work we can create subscription feeds with very minimal code using System.ServiceModel.Syndication namespace which contains all of the classes that make up the Syndication Object Model.   For example below is a sample Blog class I am defining a public method and some properties to retrieve the blog items (I have hardcoded two items you can replace this from your database logic).

The next step I am going to create another class called Syndication Helper which converts our web content to syndication format.

Code Explanation

Uri uri = new Uri(“https://deepumi.wordpress.com&#8221;);

Configure your site url ( blog or news).

SyndicationFeed syndicationFeed = new SyndicationFeed();
Syndicaiton Feed class represent a top level of feed object, (you can add your blog name / site name with description and the last blog/site updated time).

List<SyndicationItem> items = new List<SyndicationItem>();
Syndication Item class represent a individual feed atom/rss.item object like item url, item description, item id, last updated etc. Here I am creating a syndicaiton item collection object which mapping from MyBlogList() method.

List<Blog> oBlogList = Blog.GetMyBlogList();
foreach (Blog oBlog in oBlogList)
{
SyndicationItem oItem = new SyndicationItem(oBlog.Title,
SyndicationContent.CreateHtmlContent(oBlog.Description),
new Uri(oBlog.Url),
oBlog.BlogId.ToString(),
oBlog.LastUpdated);
items.Add(oItem);
}

Finally you are return the SyndicationFeed object to the aspx pages.
Now we need to render the atom and rss content in the aspx pages.

Create a new aspx page called rss.aspx and make sure there is no html markup in the page(just a blank page)

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

Code behind (RSS page)


Create a new aspx page called rss.aspx and make sure there is no html markup in the page(just a blank page)

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

Code behind (Atom page)


Hope this help and If you have any comments, please feel free to write your feedback.

You can download the entire article from here or copy paste this URL

http://www.4shared.com/file/240764190/b37e055d/Feeds.html

Thanks
Deepu

LINQ to XML CRUD Operations


CRUD (Create, Read, Update & Delete) four operations for adding, displaying, modifying and deleting data.  This articles explains how CRUD operation can be achieved using  LINQ to XML. (You can download the entire article from here).

For example you want to store  Members information in an XML file and you may need to implement  add /  edit / delete functionality through a  UI.

So I am going to create a XML file with four nodes like firstName,lastName,email and phone.

<?xml version="1.0" encoding="utf-8"?>
<Members>
 <member id="f02c78b4956f4b2f9ecfb7a5bfbcfbf6">
 <firstName>Deepu</firstName>
 <lastName>M.I</lastName>
 <email>me@gmail.com</email>
 <phone>123-456-7890</phone>
 </member>
</Members>

Screen shots for CRUD Operations (Create Screen)

Using the following method we can Create a new member information to the XML file.


XDocument doc = XDocument.Load(FilePath);  //load the xml file.
 IEnumerable<XElement> oMemberList = doc.Element("Members").Elements("member");
var oMember = new XElement("member",
 new XAttribute("id", Guid.NewGuid().ToString().Replace("-", "")),
 new XElement("firstName", txtFirstName.Value),
 new XElement("lastName", txtLastName.Value),
 new XElement("email", txtEmail.Value),
 new XElement("phone", txtPhone.Value)
 );
oMemberList.Last().AddAfterSelf(oMember);  //add node to the last element.
doc.Save(FilePath);

XDocument class will load the xml file and will find the last member node and save the information to the file.

The next screen will show all the members in the xml file in Grid format using ListView control.

XElement element = XElement.Load(FilePath);  //replace with xml file path
if (element != null)
{
var query = from member in element.Descendants("member")
select new
{
MemberId = (string)member.Attribute("id"),
FirstName = member.Element("firstName").Value,
LastName = member.Element("lastName").Value,
Email = member.Element("email").Value,
Phone = member.Element("phone").Value
};
if (query != null && query.Count() > 0)
{
lvMemberList.DataSource = query.ToList();
lvMemberList.DataBind();
}
}

Update method is similar to create method like load a xml file and find the corresponding member node by Id or email and finally it will update node values using SetElementValue method some thing like below.


XDocument doc = XDocument.Load(FilePath); //replace with xml file path
IEnumerable<XElement> oMemberList = doc.Element("Members").Elements("member"); //get the member node.
var oMember = (from member in oMemberList
 where
 member.Attribute("id").Value == 2
 select member).SingleOrDefault(); //replace memberId by querystring value.
 oMember.SetElementValue("firstName", firstName);
 oMember.SetElementValue("lastName", lastName);
 oMember.SetElementValue("email", email);
 oMember.SetElementValue("phone", phone);
 doc.Save(FilePath);

Finally the Delete will be deleteing a node element from the xml file.


XElement element = XElement.Load(FilePath);
 if (element != null)
 {
 var xml = (from member in element.Descendants("member")
 where
 member.Attribute("id").Value == 2
 select member).SingleOrDefault();

 if (xml != null)
 {
 xml.Remove();
 element.Save(FilePath);
 }
 }

Note : This post does not have the complete source code. please download the full working source code from the download link.

You can download the entire article from here copy paste this URL

http://www.4shared.com/file/236175264/b5df239/CRUD.html

Hope this help and If you have any comments, please feel free to write your feedback.

Thanks
Deepu

Compare xml files using C# LINQ


In this article you will learn how to compare two xml files using C# LINQ (Language Integrated Query one of the great features  in C# 3.0 release) .Imagine a scenario where you are consuming a third party web service for online book selling site. Every day you may need to update your site if any new book is launched and also you want to sync with your existing information. I am going to create a simple class called Book with three properties.  (You can download the  article source code from the bottom of the page.)

public class Book
{
 public Book()
 {

 }
 public int BookID { get; set; }
 public String Name { get; set; }
 public double Price { get; set; }
 public Book(int bookId, string name, double price)
 {
 this.BookID = bookId;
 this.Name = name;
 this.Price = price;
 }

}

The next step is to create custom comparer class which implements IEqualityComparer. The comparer class  returns true if both bookId’s  are equal.

public class BookComparer : IEqualityComparer<Book>
{
 public bool Equals(Book x, Book y)
 {
 return (x.BookID == y.BookID);
 }

 public int GetHashCode(Book book)
 {
 return book.BookID.GetHashCode();
 }
}

Sample XML files

Book_A.xml

<?xml version="1.0" encoding="utf-8" ?>
<Books>
 <Book bookId="100" name="Asp.Net" price = "230" />
 <Book bookId="101" name="C#" price = "200" />
 <Book bookId="102" name="Silverlight" price = "300" />
 <Book bookId="103" name="MFC Book" price = "300" />
</Books>

Book_B.xml

<?xml version="1.0" encoding="utf-8" ?>
<Books>
 <Book bookId="100" name="Asp.Net" price = "230" />
 <Book bookId="101" name="C#" price = "200" />
 <Book bookId="102" name="Silverlight" price = "300" />
 <Book bookId="104" name="WPF" price = "200" />
 <Book bookId="105" name="WCF" price = "200" />
</Books>

Result.XML

<?xml version="1.0" encoding="utf-8"?>
<Books>
 <Book bookId="100" name="Asp.Net" price="230" />
 <Book bookId="101" name="C#" price="200" />
 <Book bookId="102" name="Silverlight" price="300" />
 <Book bookId="103" name="MFC Book" price="300" />
 <Book bookId="104" name="WPF" price="200" />
 <Book bookId="105" name="WCF" price="200" />
</Books>

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
 {
 IEnumerable<Book> bookA = LoadXML("Books_A.xml");
 IEnumerable<Book> bookB = LoadXML("Books_B.xml");
 BookComparer oComparer = new BookComparer();
 var comparerList = bookA.Except(bookB, oComparer).ToList();
 List<Book> result = new List<Book>();
 result.AddRange(comparerList);
 result.AddRange(bookB);
 result = (from book in result
 orderby book.BookID ascending
 select book).ToList<Book>();

 XElement xElement = new XElement("Books",
 from book in result
 select new XElement("Book",
 new XAttribute("bookId", book.BookID.ToString()),
 new XAttribute("name", book.Name),
 new XAttribute("price", book.Price)
 )
 );
 xElement.Save(Server.MapPath("~/XML/result.xml"));
 }

 IEnumerable<Book> LoadBooksFromXML(string fileName)
 {
 XElement xml = XElement.Load(Server.MapPath("~/XML/" + fileName));
 var query = (from book in xml.Descendants("Book")
 orderby (int)book.Attribute("bookId") ascending
 select new Book(
 (int)book.Attribute("bookId"),
 (string)book.Attribute("name") != null ? (string)book.Attribute("name") : string.Empty,
 (double)book.Attribute("price"))
 );
 return query;
 }

Code Explanation

IEnumerable<Book> bookA = LoadXML(“Books_A.xml”);

LoadXML method load xml file and return a collection of Book class

BookComparer oComparer = new BookComparer(); //The BookComparer class instantiate a new object

var comparerList = bookA.Except(bookB, oComparer).ToList();

The above statement will compare the items in Books_A.xml  with Books_B.xml and return a collection of items which is not found in Book_B.xml

Based on the above XML files the return list would be some thing like below

<Book bookId=”103″ name=”MFC Book” price = “300” />

Finally we need to merge the items in to a new list and save as result.xml file.

Create a new List for hold the result list

List<Book> result = new List<Book>();
result.AddRange(comparerList);  //
result list
result.AddRange(bookB); //
book_B.xml collection.

//sort by book id ascending

result = (from book in result
orderby book.BookID ascending
select book).ToList<Book>();

//Save as new xml file.

XElement xElement = new XElement(“Books”,
from book in result
select new XElement(“Book”,
new XAttribute(“bookId”, book.BookID.ToString()),
new XAttribute(“name”, book.Name),
new XAttribute(“price”, book.Price)
)
);
xElement.Save(Server.MapPath(“~/XML/result.xml”));

You can download the entire article from here or copy paste this URL

http://www.4shared.com/file/232888750/82ac9ddf/XMLComparer.html

Hope this help and If you have any comments, please feel free to write your feedback.

Thanks
Deepu