Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

September 2010 - Posts

Web server controls in ASP.Net - part 2

In this second post of presenting the basic web server controls in ASP.Net we will look into the Adrotator control. You can find the first post here.

I think that people who begin now with ASP.Net will find these posts useful.

We can use the Adrotator control and to serve up random banners in our web site.

I will use a hands-on an example with C# version.I will use an XML file that will serve as the source for my banners.

The AdRotator was included in ASP.Net 2.0 version.

I will be using VS 2010 Ultimate edition to create a simple asp.net application.

1) Launch Visual Studio 2010/2008/2005 (or express editions).

2) Create a new website and choose an approriate name.

3) From your toolbox just drag and drop an AdRotator Control in the Default.aspx page

5) Click on your project from the Solution explorer and create an Images folder

6) Place your random images in the folder above

7) Add a new item to your site. IName it “advs.xml”. Place it in the App_Data special folder that is already created in your project structure.

8) Copy and paste the following XML code inside the “advs.xml” file. 

<?xml version=”1.0″ encoding=”utf-8″ ?>
<Advertisements xmlns=”http://schemas.microsoft.com/AspNet/AdRotator-Schedule-File”>
</Advertisements>
<Ad>
<ImageUrl>~/images/ajax-logo.gif</ImageUrl>
<NavigateUrl>http://www.asp.net/ajax/</NavigateUrl>
<AlternateText>ASP.NET AJAX is a free framework for quickly creating efficient and interactive Web applications that work across all popular browsers</AlternateText>
<Keyword>asp.net ajax</Keyword>
<Impressions>100</Impressions>
</Ad>
<Ad>
<ImageUrl>~/images/asp-logo.png</ImageUrl>
<NavigateUrl>http://www.asp.net</NavigateUrl>
<AlternateText>ASP.NET is a free technology that allows anyone to create a modern web site</AlternateText>
<Keyword>Asp.Net</Keyword>
<Impressions>150</Impressions>
</Ad>
<Ad>
<ImageUrl>~/images/NET-logo.png</ImageUrl>
<NavigateUrl>http://www.microsoft.com/NET/</NavigateUrl>
<AlternateText>The .NET Framework is Microsoft’s comprehensive and consistent programming model for building applications </AlternateText>
<Keyword>.NET</Keyword>
<Impressions>250</Impressions>
</Ad>
</Advertisements>

Make sure you change the name of the images in the <ImageUrl> attribute to reflect the images you placed in the Images folder in your project.

9) Now select the AdRotaror control and from the properties window in VS select the property called AdvertisementFile .Click on the ellipsis button and navigate until you find the “advs.xml” file.

10) Run your application and observe all the banners specified in the .xml file appearing randomly according to their weight (Impressions attribute).

If you want to enable some sort of filtering in your ads, you can do so.

If you place a DropDownlist control in your default.aspx page and add as items these names

  • asp.net ajax
  • Asp.Net
  • .NET

Enable AutoPostBack property for this control.By clicking on this control in the Default.aspx.cs,

You will be presented with the event handling routine for the standard event(SelectedIndexChanged).

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
AdRotator1.KeywordFilter = DropDownList1.SelectedItem.Value;
}


We set the property Keywordfilter of the AdRotator control to the value of the selected item from the list, thus selecting only the banners that match the keyword.

Run your application and choose different items from the dropdownlist . In my example there are 3 banners with 3 different keywords so only one banner will be shown every time you choose a different item.

I would like to show you how you can retrieve the ads if we have a Sql Server database as our source file.

1) First we need to create the database . Select the App_Data special folder and add a new item, a Sql Server Database. Call it banners.mdf.We need to create a table and we will call it ads

The definition for this table, for fields and data types could be


1st row

ImageUrl = ~/images/asp-logo.png
NavigateUrl=http://www.asp.net
AlternateText=ASP.NET is a free technology that allows anyone to create a modern web site
Keyword=Asp.Net
Impressions=150
2nd row

ImageUrl = ~/images/ajax-logo.gif
NavigateUrl=http://www.asp.net/ajax
AlternateText=ASP.NET AJAX is a free framework for quickly creating efficient and interactive Web applications that work across all popular browsers
Keyword=asp.net ajax
Impressions=100

3rd row

ImageUrl = ~/images/NET-logo.png
NavigateUrl=http://www.microsoft.com/NET
AlternateText=The .NET Framework is Microsoft’s comprehensive and consistent programming model for building applications
Keyword=.Net
Impressions=250

 

Now create a new .aspx page and make it the Start page.Name it as you want.

Place a new AdRotator control in the newly created page.

Now we must have a datasource control that points to the database we created and tie this datasource control with the rotator control.

Click on the little arrow in the rotator control and choose New Data Source, choose database from the window and then from the Configure DataSource window, select the banner database and click Next.

Then select the ads table and select all the fields from the table. Test the query and click Finish.

Run your application and see the ads to apper now from the database.

You can email me if you want the source code or leave a comment.

Hope it helps!!!!

Web server controls in ASP.Net - part 1

I am going to write a new series of blog posts regarding the most common web server controls we use in ASP.Net applications.Lots of people that start now in ASP.Net want to know more about these standard controls.

In this post I will look into the  calendar control. I will present its basic functionality and also look into the more advanced functionality it has.


I will be using VS 2010 Ultimate edition and C# to create a simple asp.net application.

1) Launch Visual Studio 2010/2008/2005.

2) Create a new website and name it with a meaningful name, e.g CalendarSite

3) Drag and drop a Calendar control from the toolbox into the default.aspx page.Leave the default name

4) Let’s examine some of the most used properties.

SelectedDate: By setting this property to a value, you have this value-date selected in the calendar control. Set the value to a date and run your application

VisibleDate: Whenever we want to use a different month or year, when the control initially loads, we can set the VisibleDate property to a date

If you want to select any particular day just click on the hyperlink on the bottom of each day.

5) But what if we wanted to select all of the days of a particular week or all the days of a particulat month.

Then we need to look into another useful property of the Calendar control, the SelectionMode. For selecting all the days of the week, you can set its value to DayWeek.

For selecting all the days in a month, you can set its value to DayWeekMonth.

Run your application and you will see more selectors (arrows) in the calendar control. By clicking on them you will be able to select a whole week or month.

Some other very important properties are:

DayNameFormat
, which allow us to change the number of letters the header day text contains
FirstDayOfWeek, which allow us to set the first day of the week to Monday if we want to


We have so many options to style the control by setting the values of properties like BorderColor,BordeWidth,BorderStyle,BackColor to the values we want.

We can also set the values of various font properties. We can always use the smart tag(little arrow on the top right hand corner) to use one of the many predefined formatting styles for our calendar control.

Now that I have covered some of the basic stuff, I would like to mention

Calendar click events
Control Calendar cell’s rendering


6) Every time the user selects a date in you calendar control, you capture this selection by the SelectionChanged event.

Add a literal control to the default.aspx page. Name it SelectedDatesLiteral

Just double click on a day in the calendar control. In the event handling routine, type the following

 foreach (DateTime selectedDate in Calendar1.SelectedDates)
{
SelectedDatesLiteral.Text = string.Format(“You selected: {0:d}<br/>{1}”, selectedDate, SelectedDatesLiteral.Text);
}

Here, I just loop through the selected dates and append their values to a literal control.Run your application and see for yourself.

If we want to add content in a day in the calendar, we must use  the DayRender event. This event is invoked once for every day in the calendar. The table cell and the date are passed to the event handler and can be used to render custom content or look up data in a database etc. We will pull event data from an xml file.Add an xml file to your project and call it events.xml. Place this file in the App_Data special folder. The contents of this file could be something like this.

<?xml version=”1.0″ encoding=”utf-8″ ?>
<Events>
<Event Month=”1″ Day=”1″>Happy New Year.</Event>
<Event Month=”2″ Day=”29″>Happy leap day.</Event>
<Event Month=”12″ Day=”25″><![CDATA[Merry Christmas.]]></Event>
<Event Month=”12″ Day=”7″><![CDATA[Bob's Birthday!]]></Event>
<Event Month=”12″ Day=”28″><![CDATA[16th anniverary]]></Event>
</Events>

 Add a XMLDataSource control in to your default.aspx page and configure it so it reads the contents of your xml file.

Then in the DayRender Event type the following

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
string xpath = string.Format(“//Event[@Month={0} and @Day={1}]/text()”, e.Day.Date.Month, e.Day.Date.Day);
XmlDocument doc = XmlDataSource1.GetXmlDocument();

StringBuilder content = new StringBuilder(e.Day.DayNumberText);
foreach (XmlNode node in doc.SelectNodes(xpath))
{
content.Append(“<br/>”);
content.Append(node.Value);
}

e.Cell.Text = content.ToString();
}

Make sure you have added these namespaces in the Default.aspx.cs file

I am using an XPath to filter out only the nodes in our xml document that have content.

Then I am opening the xml document and then I am building a string with values that will be displayed in the calendar cell for the current day.

Then I loop through all the items that were returned back from the XML document and append those values together in order to create a string of all of events that happend in this specific day.

Run your application and see the content that is passed from the xml file to the specific dates, e.g Christmas day.

If you need the full code, just email me.

Hope it helps!!!

Using Linq to Objects within an ASP.Net application

I am thinking to continue the LINQ series of posts but I want to give a clear example on Linq to Objects.

In all my classes people seem to have the following answer to this question, "What kind of data can we query with LINQ?"

Most people say "Well, we can query an SQL server database" . I am not very pleased when people forget the other flavors.

LINQ to Objects allow us to write “queries” over collections of objects.This is the first and most basic flavor of LINQ. LINQ to Objects enables you to perform
complex query operations against any enumerable object. By that I mean any object that implements the IEnumerable interface.

I will use Visual Studio 2010 Ultimate edition.You can use VS 2010/VS2008 Professional edition.

VS 2010/VS2008 Epxress editions will be fine for this example. I am using C# for this one.

 

1) Fire VS and create a new asp.net website with a name of your choice. Choose local filesystem as the location of your website files.

2)  Add a GridView web server control to the Default.aspx page.

3) Add a Class file in your website ( Add - > New item ) . I am going to have data related to football so i named it Football.cs

4) Inside the public class Football type

        public string FootballTeamName { getset; }
        public string Manager { getset; }
        public string TeamCaptain { getset; }
        public int ChampionshipsWon { getset; }

 

5) Now that we have a class to work with, we should create a simple generic List of the Football objects and then bind that list to the Gridview control.

6) This is the code for the generic list of the Football objects. We place this code in the Default.aspx page.

public List<Football> GetFootballData()
{
return new List<Football> {
new Football { FootballTeamName="Liverpool", Manager="Roy Hodgson"
TeamCaptain="Steven Gerrard",ChampionshipsWon=18  },
new Football { FootballTeamName="ManUtd", Manager="Alex Ferguson"
TeamCaptain="Rio Ferdinand", ChampionshipsWon=18},
new Football { FootballTeamName="Chelsea", Manager="Carlos Ancelotti"
TeamCaptain="Frank Lampard",ChampionshipsWon=4 },
new Football { FootballTeamName="Everton", Manager="David Moyes"
TeamCaptain="Phil Neville",ChampionshipsWon=9 }

};

}

7) Now we add the code in the Page_Load() event handling routine. We just type

 var football = GetFootballData();
 this.GridView1.DataSource = football;
 this.GridView1.DataBind();

8) Run your application and see the results in the web browser.

9) Imagine we want to filter our data. Let's write the query first in a non-LINQ way.

Comment out the code in the Page_Load event handling routine.We want to query the data where the Manager is "Roy Hodgson".

In the Page_Load event handling routine type

 var football = GetFootballData();
var query = new List<Football>();
foreach (var f in football)
{
if (f.Manager == "Roy Hodgson" ) query.Add(f);
}
this.GridView1.DataSource = query;
    this.GridView1.DataBind();

10) Run your application and see the in the browser the record that satisfies the criteria.

11) If we want to have more complex queries (grouping or sorting ) then the code becomes a bit hard to follow and maintain.

12) Now we will write a number of queries the "LINQ" way. We do not have to worry anymore on exactly how a query is going to be executed.

We just need to define what the query should return. The compiler must come up with a way and determine how the query will be executed.

13) Comment out the code inside the Page_Load event handling routine and type this code

        var football = GetFootballData();
        var query = from f in football
                    select f;
        this.GridView1.DataSource = query;
        this.GridView1.DataBind();
  

14) Run your application and see the results. We use the GetFootballData() method to obtain the generic list collection.Then we use the simplest LINQ query to select all the Football objects from the generic collection.

We do have new language keywords like select and from.

15) Now let's say that we want only the Manager and FootballTeamName values. Comment out the code inside the Page_Load event handling routine and type this code

           var football = GetFootballData();
           var query = from f in football
                       select new { f.FootballTeamName, f.Manager };
           this.GridView1.DataSource = query;
           this.GridView1.DataBind();

 

Run your application and see the results.What we did here is called Projection and contains the Manager and FootballTeamName values for all the objects.

16) If we want to have some ordering(get the values back according to the object Manager descending) of the data we just re-write the code above

        var football = GetFootballData();
        var query = from f in football
                    orderby f.Manager descending
                    select new { f.FootballTeamName, f.Manager };
        this.GridView1.DataSource = query;
        this.GridView1.DataBind();

 Run your application and see the results.

17) We do have query filters in LINQ. We can use the where clause.If we want to find how many teams won more than 10 championships we should type ( after commenting out all our code in the Page_Load )

 

        var football = GetFootballData();
        var query = from f in football
                    where f.ChampionshipsWon > 10
                    select f;

        this.GridView1.DataSource = query;
        this.GridView1.DataBind();

Run your application and see the results.

18) If we want to get only the Manager name and the team captain name for the last 2 records we should type (after commenting out all our code in the Page_Load)

        var football = GetFootballData();
        var query = (from f in football

        select new { f.Manager, f.TeamCaptain }).Reverse().Take(2);

        this.GridView1.DataSource = query;
        this.GridView1.DataBind();

Run your application and see the results. We use the Reverse() method that inverts the order of the elements in a sequence.

We also use the Take() method to return a specified number of elements from the start of a sequence.

This post can be very useful to people that begin to learn LINQ.Email me if you want the source code.

Hope it helps!!!

Linq to XML & ASP.Net - part 6

This is the sixth post in a new series of posts regarding LINQ to XML and ASP.Net.Please do read the first post here. You can find the second post here .

You can find the third post here . You can read the fourth post here . You can find the fifth post here .

In this post I would like to show on how to create a xml document on the fly and save it on a file in our local disk.

I will use Visual Studio 2010 Ultimate edition and C# as the development language. Visual Studio 2010/2008 express editions will suffice.  


1) Fire VS and create a web site. Choose an appropriate name for your site.

2) In the code behind file Default.aspx.cs, add the namespace

using System.Xml.Linq;

All the classes we need to manipulate XML documents are inside this namespace.

In this sixth example we want to find the the information of the second element.

3) In the Page_Load  event handling routine of the default.aspx.cs file, type the following


XDocument xDoc = new XDocument(
            new XDeclaration("1.0""UTF-8"null),
            new XElement"Students",
                new XElement("Student",
                    new XComment("We only have 3 elements"),
                    new XElement("StudentId""5"),
                    new XElement("Name""Lewis"),
                    new XElement("Sex""Male")
                    )));

            xDoc.Save("C:\\test\\student.xml");
            Response.Write("Saved");
 
We use the XDocument class to represent an xml document. Then we create a new XML declaration (XDeclaration) and after that we do create XML elements (XElement) with the appropriate content.
Finally we use the Save method of the XDocument object, to save the newly created file in the local filesystem.
Email me if you need the source code. Hope its helps !!!!
Linq to XML & ASP.Net - part 5

This is the fifth post in a new series of posts regarding LINQ to XML and ASP.Net.Please do read the first post here. You can find the second post here .

You can find the third post here . You can read the fourth post here .

The xml file we are going to use in all these posts is the students.xml file. You can find the contents of this xml file in the first post.

I will use Visual Studio 2010 Ultimate edition and C# as the development language. Visual Studio 2010/2008 express editions will suffice.  

In this fourth post I will look at how to "How to find elements in a specific position within an xml file using LINQ to XML".

In this post we want to find e.g the second element, the last two elements, the first two elements.

1) Fire VS and create a web site. Choose an appropriate name for your site.

2) Add the existing students.xml file in your website.

3) In the code behind file Default.aspx.cs, add the namespace

using System.Xml.Linq;

All the classes we need to manipulate XML documents are inside this namespace.

In this first example we want to find the the information of the second element

In the Page_Load  event handling routine of the default.aspx.cs file, type the following

       XElement xelement = XElement.Load(@"C:\Users\fofo\Documents\
Visual Studio 2010\WebSites\forblog\xml\students.xml");


         var student = xelement.Descendants("Student").ElementAt(1);
         Response.Write(student);
 
4) We use the ElementAt method to return an element at a specified index at a sequence. The output of this LINQ to XML query will be
2 Mary Female ASP.Net Physics 

Ormond street Edinburgh FIFE 95701 U.K


So we get back all the information for the second student in the xml document.
5) Let's try another example. What if we wanted to list the first 2 elements and all their data?Comment out these lines of code
       
var student = xelement.Descendants("Student").ElementAt(1);
         Response.Write(student);
and type
var students = xelement.Descendants("Student").Take(2);
        foreach (var student in students)
            Response.Write(student);
 
Take operator gets the first x number of elements in a sequence.Run your application and see in the browser the following results.  
1 nikos Male Office 2010 Maths 

Kosti Palama Athens Attica 13231 GREECE
 

2 Mary Female ASP.Net Physics

Ormond street Edinburgh FIFE 95701 U.K
 
6) What if we wanted to retrieve the 2nd and 3rd element?Comment out these lines of code 
 
var students = xelement.Descendants("Student").Take(2);
        foreach (var student in students)
            Response.Write(student);
 
and type
 var students = xelement.Descendants("Student").Skip(1).Take(2);

        foreach (var student in students)
            Response.Write(student);
Skip operator gets all the elements after skipping x number of elements.
Run your application and see in the browser the following results.  
 
2 Mary Female ASP.Net Physics 
Ormond street Edinburgh FIFE 95701 U.K
 
3 Giacomo Male Silverlight Chemistry
Messsina road 12 Livorno Toscany 23701 Italy
 
7) What if we wanted to get the last two elements in the xml file?Comment out these lines of code 
 
var students = xelement.Descendants("Student").Skip(1).Take(2);

        foreach (var student in students)
            Response.Write(student);
and type
  var students = xelement.Descendants("Student").Reverse().Take(2);

        foreach (var student in students)
            Response.Write(student);
Reverse operator performs a reversal transformation on the elements.
Run your application and see in the browser the following results.   
4 Gaia Female English WPF 
Mopipetro 32 Milano Bergamo 43501 Italy
 
3 Giacomo Male Silverlight Chemistry
 
Messsina road 12 Livorno Toscany 23701 Italy

Email me if you need the source code. Hope its helps !!!!
Linq to XML & ASP.Net - part 4

This is the fourth post in a new series of posts regarding LINQ to XML and ASP.Net.Please do read the first post here. You can find the second post here .

You can find the third post here .

The xml file we are going to use in all these posts is the students.xml file. You can find the contents of this xml file in the first post.

I will use Visual Studio 2010 Ultimate edition and C# as the development language. Visual Studio 2010/2008 express editions will suffice.  

In this fourth post I will look at how to "How to sort elements with an xml file  using LINQ to XML".

In this post we want to sort the elements in the students.xml document according to City in a descending order.

1) Fire VS and create a web site. Choose an appropriate name for your site.

2) Add the existing students.xml  file in your website.

3) In the code behind file Default.aspx.cs, add the namespace

using System.Xml.Linq;

All the classes we need to manipulate XML documents are inside this namespace.

In the Page_Load  event handling routine of the default.aspx.cs file, type the following

      XElement xelement = XElement.Load(@"C:\Users\fofo\Documents\
Visual Studio 2010\WebSites\forblog\xml\students.xml");


        var cities = from thecity in xelement.Elements("Student")
        let city = (string)thecity.Element("Address").Element("City")
        orderby city descending
        select city;

            Response.Write("Sort all cities descending: ");
            Response.Write("<br/>");
            foreach (string mycity in cities)
            {   
                Response.Write(mycity);
                Response.Write("<br/>");
           
            }
 
4) In our LINQ to XML query we see  how easy is to sort using the order by clause.
        let city = (string)thecity.Element("Address").Element("City")
        orderby city descending
5) Run your application and see in the browser the following results.  
Sort all cities ascending: 
Milano
Livorno
Edinburgh
Athens

Email me if you need the source code. Hope its helps !!!!
Linq to XML & ASP.Net - part 3

This is the third post in a new series of posts regarding LINQ to XML and ASP.Net.Please do read the first post here. You can find the second article here .

The xml file we are going to use in all these posts is the students.xml file. You can find the contents of this xml file in the first post.

I will use Visual Studio 2010 Ultimate edition and C# as the development language. Visual Studio 2010/2008 express editions will suffice.  

In this third post I will look at how to "Read an element with a specific attribute in an XML document using LINQ to XML".

In this post we want to find the name of the seminars from the students.xml document that have tha attribute "E-Learning"

1) Fire VS and create a web site. Choose an appropriate name for your site.

2) Add the existing students.xml file in your website.

3) In the code behind file Default.aspx.cs, add the namespace

using System.Xml.Linq;

All the classes we need to manipulate XML documents are inside this namespace.

In the Page_Load  event handling routine of the default.aspx.cs file, type the following

        XElement xelement = XElement.Load(@"C:\Users\fofo\Documents\
Visual Studio 2010\WebSites\forblog\xml\students.xml");
    

  var seminars = from seminar in xelement.Elements("Student")
  where (string)seminar.Element("Seminar").Attribute("Type") == "E-Learning" 
  select seminar;

            Response.Write("Students with seminars of type E-Learning: ");
            Response.Write("<br/>");
            foreach (XElement xEle in seminars)
            {   
                Response.Write(xEle.Element("Seminar").Value);
                Response.Write("<br/>");
 
4) In our LINQ to XML query we see that we access a specific attribute with this line of code. It is pretty straight-forward.
 where (string)seminar.Element("Seminar").Attribute("Type") == "E-Learning" 
5) Run your application and see in the browser the following results. 
Students with seminars of type E-Learning:  
Office 2010
ASP.Net
Silverlight
English


Email me if you need the source code. Hope its helps !!!!
Linq to XML & ASP.Net - part 2

This is the second post in a new series of posts regarding LINQ to XML and ASP.Net.Please do read the first article here.

The xml file we are going to use in all these posts is the students.xml file. You can find the contents of this xml file in the link above.

I will use Visual Studio 2010 Ultimate edition and C# as the development language. Visual Studio 2010/2008 express editions will suffice.  

In this second post I will look at how to "Read an element inside another element in an XML document using LINQ to XML".


1) Fire VS and create a web site. Choose an appropriate name for your site.

2) Add the existing students.xml file in your website.

3) In the code behind file Default.aspx.cs, add the namespace

using System.Xml.Linq;

All the classes we need to manipulate XML documents are inside this namespace.

In the Page_Load  event handling routine of the default.aspx.cs file, type the following

         XElement xelement = XElement.Load(@"C:\Users\fofo\
Documents\Visual Studio 2010\WebSites\forblog\xml\students.xml");
    

var addresses = from address in xelement.Elements("Student")
       where (string)address.Element("Address").Element("City") == "Athens" &&
       (string)address.Element("Sex").Value == "Male"
       select address;
            
Response.Write("Address details of students living in Athens: ");
            Response.Write("<br/>");
            
foreach (XElement xEle in addresses)
            {   
        Response.Write(xEle.Element("Address").Element("Street").Value);
        Response.Write("<br/>");
        Response.Write(xEle.Element("Address").Element("State").Value);
        Response.Write("<br/>");
        Response.Write(xEle.Element("Address").Element("Zip").Value);
        Response.Write("<br/>");
        Response.Write(xEle.Element("Address").Element("Country").Value);
        Response.Write("<br/>");
            }
 
4)It is very easy to see what i am doing here. If you look more carefully at our students.xml we see that the <Address> element has nested elements within. We need to access the data inside the nested elements.
         <Address>
            <Street>Kosti Palama</Street>
            <City>Athens</City>
            <State>Attica</State>
            <Zip>13231</Zip>
            <Country>GREECE</Country>
        </Address>

We see that these elements <Street>, <City>, <State>, <Zip>, <Country> are inside the <Address> element.
We just find the element within the element with this line of code
address.Element("Address").Element("City")
I think we can see in the Linq query the power of LINQ. We do query the xml file the same way we would query another data source. So no need to learn different APIs for different data sources.
5) Run your application and see in the browser the following results.
Address details of students living in Athens: 
Kosti Palama
Attica
13231
GREECE

Email me if you need the source code. Hope its helps !!!!
Linq to XML & ASP.Net - part 1

I am going to write a new series of articles regarding LINQ to XML and how to use it in ASP.Net web sites.

I am not going into details what LINQ is or what LINQ to XML is. LINQ is a technology that is an established 3 years old technology.If you google these terms you will find thousands of references.

So I strongly suggest you to do so before reading any further. I am providing some basic links.

LINQ to XML uses LINQ syntax to generate, read, and sort XML data. LINQ to XML uses its own set of objects, such as XDocument, XElement, and
XAttribute to represent parts of an XML document.

I will use Visual Studio 2010 Ultimate edition and C# as the development language. Visual Studio 2010/2008 express editions will suffice. 

In this very first post I will look at how to "Read from an XML document using LINQ to XML"

But before we proceed we must have an xml document to query. Please note that we are going to use the following xml document in all our examples. I have named it students.xml.

<?xml version="1.0" encoding="utf-8" ?>

<Students>
    <Student>
        <StudentId>1</StudentId>
        <Name>nikos</Name>
        <Sex>Male</Sex>
      <Seminar Type="Blended-Learning">Maths</Seminar>
        <Seminar Type="E-Learning">Office 2010</Seminar>
        <Address>
            <Street>Kosti Palama</Street>
            <City>Athens</City>
            <State>Attica</State>
            <Zip>13231</Zip>
            <Country>GREECE</Country>
        </Address>
    </Student>
  <Student>
    <StudentId>2</StudentId>
        <Name>Mary</Name>
        <Sex>Female</Sex>
    <Seminar Type="Blended-Learning">Physics</Seminar>
      <Seminar Type="E-Learning">ASP.Net</Seminar>
        <Address>
            <Street>Ormond street</Street>
            <City>Edinburgh</City>
            <State>FIFE</State>
            <Zip>95701</Zip>
            <Country>U.K</Country>
        </Address>
    </Student>


  <Student>
    <StudentId>3</StudentId>
        <Name>Giacomo</Name>
        <Sex>Male</Sex>
    <Seminar Type="E-Learning">
      Silverlight</Seminar>
      <Seminar Type="Blended-Learning">Chemistry</Seminar>
        <Address>
            <Street>Messsina road 12</Street>
            <City>Livorno</City>
            <State>Toscany</State>
            <Zip>23701</Zip>
            <Country>Italy</Country>
        </Address>
    </Student>


  <Student>
      <StudentId>4</StudentId>
        <Name>Gaia</Name>
        <Sex>Female</Sex>
        <Seminar Type="E-Learning">English</Seminar>
        <Seminar Type="Blended-Learning">WPF</Seminar>
        <Address>
            <Street>Mopipetro 32</Street>
            <City>Milano</City>
            <State>Bergamo</State>
            <Zip>43501</Zip>
            <Country>Italy</Country>
        </Address>
    
    </Student>

</Students>

 

1) Fire VS and create a web site. Choose an appropriate name for your site.

2) Add an new XML file to your site. Name it students.xml and just paste in it the xml code above.

3) In the code behind file Default.aspx.cs, add the namespace

using System.Xml.Linq;

All the classes we need to manipulate XML documents are inside this namespace.

In the Page_Load  event handling routine of the default.aspx.cs file, type the following

         XElement xelement = XElement.Load(@"C:\Users\fofo\
Documents\Visual Studio 2010\WebSites\forblog\xml\students.xml");

        var students = xelement.Elements();
        // Read the entire XML
        foreach (var student in students)
        {
            Response.Write(student.Element("Name").Value);
            Response.Write("-");

            Response.Write(student.Element("StudentId").Value);
            Response.Write("<br/>");

 

We use the XElement.Load method to create a new XElement from a file specified in the path. Then we store in a variable the collection of the child elements.

Then we just iterate through the elements. It is quite clear that we are only interested in the Name and StudentId values of all students in the XML doc.

4)  Run your application and see in the browser the following results.

nikos-1
Mary-2
Giacomo-3
Gaia-4

I will continue with more posts on LINQ to XML.Hope it helps!!!


How to create an Ajax enabled Web Service in ASP.Net

In this post I will try to show you with a detailed example how to create an Ajax enabled Web Service and consume it from client scripts running in a different Web site. It will be a simple example but the principles apply to the most complicated ones.

I will use Visual Studio 2010 Ultimate edition. You can use Visual Studio 2008 as well. VS 2010/2008 express editions will suffice for this example.

I will use VB.net as the development language.

1) Fire VS and use the Web Service template to create a web service application and save it in the local IIS and not in the local filesystem.

Create in the local IIS a new Web Application called CalculateWebService.

2) Delete the Service.vb file and the Service.asmx file.

3) Add in your web service project a new web service (Add->New item) and call it Calculate.asmx

4) In oder to allow this Web Service to be called from script, using ASP.NET AJAX we must add this line of code in the Calculate.vb file


<System.Web.Script.Services.ScriptService()> 

 5) Add a namespace just after the Imports statements. I have called it Calculus. You can name it as you want.Place all the code for the web service inside the Namespace.

Namespace Calculus

'Code goes here

End Namespace

6) Update the Calculus.asmx file to reflect the changes. It should look like that

<%@ WebService Language="VB" CodeBehind="~/App_Code/Calculate.vb" 
Class="Calculus.Calculate" %>
 

7) Comment out the HelloWorld() function and add another one that adds 2 integers. Do not comment out the

<WebMethod()>

So our new little function should look something  like this.

  Public Function Add(ByVal a As IntegerByVal b As IntegerAs String

            Dim myresult As String
          
            Dim res As Integer

            res = a + b
            myresult = res.ToString()

            Return myresult


        End Function

8) Test your web service by viewing it in the browser. If evertything is working fine we should create the application that will consume this web service.Copy the web service URL in a notepad.You will need it shortly.

In my case is http://localhost/CalculateWebservice/Calculate.asmx

9) Close your web service project and create a new web site in your local IIS. Create a new web application and name it ConsumeCalculus.

Have a look at the picture below - click on the image to enlarge


 10 ) Inside the <form> tags we can have markup that looks like this

    
        First Number:<input type="text" id="txtnuma"/><br />
        Second Number:<input type="text" id="txtnumb" /><br />
        <button id="CalculusButton">ADD</button><br />
        <span id="additionres"></span>   

 11) In order to be able to call the web service we should add a ScriptManager control and make it aware of that service. The code should be inside the form element.

  So your code should look something like that.Paste the code in the notepad in the Path attribute.

    <asp:ScriptManager>
    
    <Services>
<asp:ServiceReference 
Path="http://localhost/CalculateWebservice/Calculate.asmx"  />
    
  </Services>
    
    </asp:ScriptManager>
    First Number:<input type="text" id="txtnuma"/><br />
    Second Number:<input type="text" id="txtnumb" /><br />
        <button id="CalculusButton">ADD</button><br />
        <span id="additionres"></span>
 

 12) We should call the web service from our button. The javascript method we want to call when this button is clicked is

   "OnCalculusClick()"

 13) So the complete markup for the button is

<asp:Button Text="Submit" ID="btnadd" runat="server" 
OnClick="OnCalculusClick();return false;" />

 14) Inside the <head> section of our page we have to write the Javascript code. Our complete code looks like this

<script type="text/javascript">
     
     function OnCalculusClick() 
        
    {
        Calculus.Calculate.Add($get("txtnuma").value, $get("txtnumb").value,
             OnCalculusComplete);
    }

    function OnCalculusComplete(result) 
    
    {
        var myres = $get("additionres");
        myres.innerHTML = result;
    }
    </script>

I will explain what we did in the code above. we did create our first Javascript function OnCalculusClick() .

We must call the web service and must know the name of the web method, so we add this bit of code

Calculus.Calculate.Add($get("txtnuma").value, $get("txtnumb").value,
             OnCalculusComplete);

 

The name of the namespace, the name of the web service class and the name of our web method comprise the qualified name, thus Calculus.Calculate.Add

 

Then we get the values from the textboxes using $get which is short for document.getElementByID . We do have another parameter(OnCalculusComplete method) and it is required by our client. This method will be called asynchronously. This is called a callback method.

Then we add a new function OnCalculusComplete. This is going to receive a parameter which is the result of the web method. So the result will be the string that our web service returns.

Then I just get the value that the web service returns and assign it to my <span> element that has an ID of "additionres".

15) Run your application, fill in the textboxes with integers and hit the button. Then you will be able to see the result that comes straight from the web service.

Email me if you need the code.

Hope it helps!!!

 

Posted: Sep 21 2010, 12:47 AM by nikolaosk | with 1 comment(s) |
Filed under: , ,
More Posts « Previous page - Next page »