jump to navigation

How to change the master page depending on the client’s browser October 6, 2010

Posted by fofo in Visual Studio 2005, Visual Studio 2008, Visual Studio 2010.
Tags: ,
1 comment so far

In one of my seminars on ASP.Net, I was asked a question from a student regarding master pages and the various browser appications.

He basically asked if it was possible to have a different master page depending on the client’s browser.

My initial answer was to find the browser’s version programmatically and according to this value to have a particular master page dynamically assigned during the PreInit stage of the Page lifecycle.

But there is a simpler way.At first we need to create a website using Visual Studio 2008/2010.

Then copy the original Site.master page to the root directory of the website and rename it to AnotherSite.master.

Then we need to copy and paste in the root direcotory the Site.css and rename it to NewSite.css.

So we have now two master pages and two .css files.

Edit the AnotherSite.master and change the css reference

from

 <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
to
 <link href="~/Styles/NewSite.css" rel="stylesheet" type="text/css" />

Now we do need to make some changes to the Newsite.css file.  You can change the background color, for example

body   
{
background:#efefef;

The page layout

.page
{
    width: 1200px;

Now we can go add a new web form to our page. We will call it “Anotherpage.aspx”.

Select as a master page the AnotherSite.master.

Then go to the “Source” of the newly created page and edit the Page directive according to the following line.

<%@ Page Title="" Language="C#"
mozilla:MasterPageFile="~/AnotherSite.master" 
ie:MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="MyNewPage.aspx.cs" Inherits="MyNewPage" %>

Run your application with IE and Firefox and notice the respective masterpages being applied to the web page.

Hope it helps!!!

Advertisements

How to use cookies in ASP.Net applications October 6, 2010

Posted by fofo in asp.net, VB 2005, VB 2008, Visual Studio 2005, Visual Studio 2008, Visual Studio 2010.
Tags:
6 comments

In this post we are going to see a step by step example on how to read,write,delete cookies in asp.net websites.

Cookies are small pieces of text that you can associate with a website which are transfered down to the user’s computer when the user visits the website.

You can use any of the versions of Visual studio (VS 2005,VS2008,VS2010 express editions work fine).

I will use VS 2010 Ultimate edition and VB.net as the .Net language of choice.

Before we begin it is very important to note some of the limitations of cookies. They store relatively small amount of information about 4kbytes.

Browsers limit the number of cookies associated with a website ( 20 cookies for a certain website ). There is also a limit on how many cookies a browser can handle regarding all websites and that is about 300.

All the data in cookies is stored as text so bear that in mind that you should not store sensitive information in a cookie. You should use the information in the cookie to identify a user, a user’s last visit e.t.c

1) Create an Asp.net web site and name it as you want.

2) Let’s add a cookie in the cookies collection. In the Page_Load event handling routine of the default.aspx page type

Response.Cookies("LastVisit").Value = DateTime.Now.ToString()
Response.Cookies("LastVisit").Expires = DateTime.Now.AddDays(10)

3)  We add a new cookie now that it will be stored in the user’s computer and we set it to expire after 10 days.So if someone visits our website today and then it visits it after 12 days, the browser will delete the cookie

from the users hard disk.Comment out the two line of code in the Page_Load event handling routine.We can use an alternative way to create a cookie and write information on it.

Dim mycookie As HttpCookie = New HttpCookie("LastVisit")
mycookie.Value = DateTime.Now.ToString()
mycookie.Expires = DateTime.Now.AddDays(10)
Response.Cookies.Add(mycookie)

4)  You can store multiple values in the same cookie with the help of subkeys. Comment out the 4 lines of code above. Type the following lines of code in the Page_Load routine

Response.Cookies("mydata")("LastVisit") = DateTime.Now.ToString()
Response.Cookies("mydata")("username") = "fofo"
Response.Cookies("mydata").Expires = DateTime.Now.AddDays(10)

5) Comment out the line above. We will write the same statement as above with a different syntax.Type the following lines of code in the Page_Load routine

 Dim mycookie As HttpCookie = New HttpCookie("mydata")
mycookie.Values("LastVisit") = DateTime.Now.ToString()
mycookie.Values("username") = "fofo"
mycookie.Expires = DateTime.Now.AddDays(10)
Response.Cookies.Add(mycookie)

6) Another thing we can do with the cookies is to specify the scope of the cookie. For example we might want to have a cookie stored on the user’s computer only

if the user visits a specific folder-page e.g Marketing. So if someone visits http://www.mysite.com the cookie is not visible, but if he visits http://www.mysite.com/marketing and all pages within that folder the cookie is visible.

In order to achieve that we use the Path property to restrict the cookie to a particular path to a website.Comment out the lines above and type the following

Dim mycookie As HttpCookie = New HttpCookie("mydata")

        mycookie.Values("LastVisit") = DateTime.Now.ToString()
        mycookie.Values("username") = "fofo"
        mycookie.Expires = DateTime.Now.AddDays(10)
        mycookie.Path = "/Marketing"
        Response.Cookies.Add(mycookie)

7) Another property we can use is the Domain property. So in the previous example we can comment out the

mycookie.Path = “/Marketing”

and type

mycookie.Domain = "help.mysite.com"

This cookie will only be sent back to the server is the page is associated with the domain “help.mysite.com”

8) In order to read cookies sent through the user’s browser back to the server we do the following.

First you need to add a label web server control to your default.aspx page. Then in the Page_Load event handling routine type

If Not Request.Cookies("LastVisit") Is Nothing Then 

Label1.Text = Server.HtmlEncode(Request.Cookies("LastVisit").Value)
End If

9) Run you application and you will see that you successfully set a cookie and read it back from the user’s computer.

10) If you want to modify the cookie’s value and expiration date you can type something like

Response.Cookies("LastVisit").Value = DateTime.Now.ToString()
Response.Cookies("LastVisit").Expires = DateTime.Now.AddDays(30)

The code above will reset the value of “LastVisit” to the actual current time and set a new expiration date for the cookie

11) If you want to delete a cookie from the user’s computer you can type the following

 Response.Cookies("LastVisit").Expires = DateTime.Now.AddDays(-1)

Then the browser will delete the cookie from the user’s  computer.

If you need the source code just email me.

Hope it helps!!!

Caching an ASP.Net page October 6, 2010

Posted by fofo in asp.net, VB 2005, VB 2008, VB 9.0, Visual Basic 10.0, Visual Studio 2005, Visual Studio 2008, Visual Studio 2010, VS 2010.
Tags:
1 comment so far

The issue of “caching” keeps coming up in my asp.net seminars so I though it would be a good idea to write a post. I know it is a well documented feature and widely used but I really believe most people will be able to use this rather simple example and understand the concepts behind caching.

You can use any of the versions of Visual studio (VS 2005,VS2008,VS2010 express editions work fine).

I will use VS 2010 Ultimate edition and VB.net as the .Net language of choice.

1) Create an Asp.net web site and name it as you want.

2) In the default.aspx page add a new paragraph or header with content of your choice.In my case i have added something like this

<h2>Caching is really useful!!!!</h2>

3) Let’s think simple at first. We do want to cache the entire page (default.aspx)

Just below the Page directive ( top of the page ) you add the following bit of code:

<%@ OutputCache Duration="20" VaryByParam="none" %>

We do cache the page for 20 seconds. That is determined by the Duration Attribute.

4) Save your work and run your application. The first time we see the output of the asp.net page, this is served directly from the asp.net engine.

If you hit refresh for a period for less than 20 seconds the page is served from the Cache.

5) Let’s see a more complex scenario involving query strings and how we can make a decision on whether to cache the page or not based on the value of the query string. Add a new label control to the .aspx page

 <asp:Label ID="mylabel" runat="server"></asp:Label>

In the Page_Load event handler routine add the code

If (Not Request("id") Is Nothing) Then 
mylabel.Text = " The query string value is " + Request("id").ToString()

End If

6) Change the OutputCache directive to

 <%@ OutputCache Duration="20" VaryByParam="id" %>

7) Run your application and type in the url address bar http://localhost:6141/caching/Default.aspx?id=5. See the results. If you hit refresh right away the page is refreshed from the cache and it is not reloaded.

If you type this http://localhost:6141/caching/Default.aspx?id=6 ( within the 20 seconds period ) it senses that the id has changed now and it re-renders the page. It also sets a new caching period of 20 seconds.

8) What is really interesting to bear in mind ( and not many people know ) is that you can have different caching settings depending on the client’s browser.The first step is to change the OutputCache directive to this

<%@ OutputCache Duration="20" VaryByParam="id" VaryByCustom="browser" %>

9) Basically we say “Continue to cache the page as long as the clients use the same browser”. So if you have 3 people in a row that have IE8 hitting your page, will all get the same cached version of the page.

If someone hits our page with Firefox or Chrome, they will a brand new rendered page. At this time it will be created a 20 seconds cache window period specific for each browser.This functionality is built into the caching module, and will insert separate cached versions of the page for each browser name and major version.

10) Now if we need to apply the caching techniques we just learnt in all pages of our asp.net application we will have to make a few modifications in the web.config file.We will add something that is called “Cache Profiles”

Just below the <system.web> add this snippet

 <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="basic" 
               duration="20" 
               varyByParam="id" 
               varyByCustom="browser"
               />

        </outputCacheProfiles>

      </outputCacheSettings>

    </caching>

So we have created a new profile that is called “basic”. Now let’s apply this cache profile to one or more pages in our website.

So we switch back to our default.aspx page and in the OutputCache directive, type

 <%@ OutputCache CacheProfile="basic" %>

Run your application again and you will see that we do have the same caching effects.

Obviously you can create different cache profiles and apply them to various pages.

I will have more posts on caching shortly.

Hope it helps!!!

Cross-Page postbacks in ASP.Net October 5, 2010

Posted by fofo in asp.net, C#, Visual Studio 2005, Visual Studio 2008, Visual Studio 2010.
Tags:
add a comment

In this post I would like to talk about cross-page postbacks in ASP.Net.

When you have a .aspx page with a button on it and you click that button the page will be posted back to the original page.

What we want to do now is to click that button and post back to an alternate page rather than the original one.

I am going to use Visual Studio 2010 Ultimate edition. You can use VS 2008/2005. All the express editions will suffice for our example.

I am going to use C# as the development language.

Let’s move on to our hands-on example.

1) Create an ASP.Net web site with an appropriate name in your file system.

2) In this first example we will see the typical scenario on how you postback back to the original page.

You should add some web server controls in the default.aspx page. Add 4 textboxes for ( Name,Age,Address,City ) and 4 labels and a button.

Basically, the markup should look like this

     Name:
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <br />
    Age:  <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
    <br />
    Address:
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <br />
    <br />
    City:
    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    <br />
    <br />
    <asp:Button ID="Button1" runat="server" Text="Submit" 
          onclick="Button1_Click" />

<br />

     <asp:Label ID="labName" runat="server" Text="Label"></asp:Label>
    <br />
     <asp:Label ID="lblAge" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Label ID="labAddress" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Label ID="labCity" runat="server" Text="Label"></asp:Label>
    <br />

3)  In the Page_Load event handling routine of the default.aspx page type.

 if (IsPostBack)
    {
      
      labName.Text = TextBox1.Text;
      lblAge.Text = TextBox4.Text;
      labAddress.Text = TextBox2.Text;
      labCity.Text = TextBox3.Text;
    }

4) Run you application and see all the data that we inputed in the textboxes appearing in the label controls.This is a typical postback within the same page.

5) Add another page in your site and name it SecondPage.aspx. Cut the label controls from the default.aspx and paste them in the SecondPage.aspx so we have,

    <asp:Label ID="labName" runat="server" Text="Label"></asp:Label>
    <br />
     <asp:Label ID="lblAge" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Label ID="labAddress" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Label ID="labCity" runat="server" Text="Label"></asp:Label>

6) Now we want to post back from the Default.aspx page to the SecondPage.aspx.

We go to the default.aspx page and we set the PostBackUrl property of the button to the SecondPage.aspx.

          <asp:Button ID="Button1" runat="server" Text="submit" 
          onclick="Button1_Click" PostBackUrl="~/SecondPage.aspx" />

7)  We go to the Page_Load event handling routine of the SecondPage.aspx and we type

labName.Text = TextBox1.Text;
lblAge.Text = TextBox4.Text;
labAddress.Text = TextBox2.Text;
labCity.Text = TextBox3.Text;

Straight away we see that we have error indicators that inform us that TextBox1,TextBox2,TextBox3,TextBox4 are dot declared.

We have to modify our code and try to reference the textbox controls from the SecondPage.aspx .

So the new code in the Page_Load event is like this

if (this.PreviousPage.IsCrossPagePostBack)

{

TextBox text1 = this.PreviousPage.FindControl(“TextBox1”) as TextBox;
TextBox text2 = this.PreviousPage.FindControl(“TextBox2”) as TextBox;
TextBox text3 = this.PreviousPage.FindControl(“TextBox3”) as TextBox;
TextBox text4 = this.PreviousPage.FindControl(“TextBox4”) as TextBox;
labName.Text = text1.Text;
lblAge.Text = text4.Text;
labAddress.Text = text2.Text;
labCity.Text = text3.Text;
}

8) We do use FindControl() method to locate a reference to the controls on the source page (Default.aspx).We store those references in new object variables.

Then we assign in the label controls the Text values we get from the referenced controls. We use the IsCrossPagePostBack property to determine if a postback occurred from the source page.

9) Run your application, fill in the  and see for yourself that textbox control values are posted back to the SecondPage.aspx

Email me if you want the source code.

Hope it helps!!!

Populate web server controls in ASP.Net applications from a web service October 5, 2010

Posted by fofo in asp.net, C#, Visual Studio 2005, Visual Studio 2008, Visual Studio 2010.
Tags:
add a comment

In this post I would like to present you with a very simple example on how to create a simple web service that access data from a database.

Then we will create a consuming application that will consume the web service. I will use VS 2010 Ultimate edition and C# as the development language.

I know that web services are explained in many places over the web but I will have a go.

They are small units of code that handle specific tasks (they convert kilometers to miles ) and are based on XML communication protocols.

They are great because they are independent of operating systems,languages,systems and devices.

Before you read on, I assume that you understand terms like SOAPWSDL and XML .

1) Use VS 2010/2008/2005. Express editions will suffice. I am going to use the Pubs database. You can download the installation scripts of the Pubs database from here.

I am going to retrieve all the data from the Authors table.

2) Create a new project and choose asp.net web service application. You have this option from the available templates when you click File->New Project.

3) Add these namespaces at the top of the Service.cs

using System.Data;
using System.Web.Configuration;
using System.Data.SqlClient;
 

Also note that our web service class inherits from WebService base class and not from the Page class

public class Service : System.Web.Services.WebService

4) In the web.config file in the <connectionStrings> add

  <connectionStrings>
    <add name="pubs" connectionString="Data Source=.;
Initial Catalog=pubs;Integrated Security=True"
        providerName="System.Data.SqlClient" />
  </connectionStrings>

5) Delete the Helloworld method. Under the [WebMethod]

 public DataSet GetAuthors()
    {
        SqlConnection conn = new SqlConnection
(WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString);
        SqlDataAdapter myAdapter;
        DataSet productDataSet;
        string commandString = "Select * from Authors";
        myAdapter = new SqlDataAdapter(commandString, conn);
        productDataSet = new DataSet();
        myAdapter.Fill(productDataSet);
        return productDataSet;
 
 
    }

I just get the connection string from the web.config using the WebConfigurationManager class and create a new connection object. I store my SQL Query in a string and then use the connection object and the string that stores the SQL query as paramaters when creating an Adapter object.Then I create a dataset and fill this dataset using theadapter object.

6) Build and run your application. You will see the service running and Invoke the GetAuthors method. Make sure it works.

7) Add a new item to your project, a web form.Leave the default name.

8) Add a Gridview web server control in the default.aspx page. Now we need to add a reference to the web service.Add Web Reference-> Select Web services in this solution and type in the web reference the name, AuthService

9) In the Page_Load event handling routine, type

 AuthorService.Service auth = new AuthorService.Service();
 GridView1.DataSource = auth.GetAuthors();
 GridView1.DataBind();

We just create an object of the AuthorService.Service class (auth) and then it is very easy(we call the GetAuthors() method) to bind the results to the GridView.

10) Run your application and see the author data populating the GridView control.

Email me if you want the source code.

Hope it helps!!!!