Sunday, February 6, 2011

Session Variables

Requests between servers and browsers are handled via HTTP - Hypertext Transfer Protocol.

HTTP is a stateless protocol. This means that each request is serviced as it comes; after the request is processed, all of the data is discarded. No state is maintained across requests even from the same client. In a nutshell, data from one page is generally unavailable on the next page etc.

When we create a Desktop Application, often we use variables to hold data that persists for the life of the program execution. There are several ways to achieve the same result on the ASP.NET platform. One way is to use Session Variables.

A Session Variable can be read from anywhere in your website. You can use them to store information for the lifetime of a single users visit. Session variables do not need to be declared, they can be written on the fly.

Session("SessionName") = value

That's not to say that we have stopped using variables, not at all. But in the ASP.NET environment we can no longer rely on them to store application wide data.

Checking the Session Exists

Sessions Time-out if the user is idle for a period of time. This period of time is variable from server to server but generally it is a matter of only a few minutes. Because of this, we should always check if the session exists before we attempt to reference one.

If Session.Item("CustomerID") IsNot Nothing Then
            Response.Write(Session("CustomerID"))
Else
            Response.Write("Session CustomerID does not exist")
End If

Response, Request & Query Strings

Requests between servers and browsers are handled via HTTP - Hypertext Transfer Protocol.

HTTP is a stateless protocol. This means that each request is serviced as it comes; after the request is processed, all of the data is discarded. No state is maintained across requests even from the same client. In a nutshell, data from one page is generally unavailable on the next page etc.

Response is a property of the HttpResponse object. This represents the outgoing data from the current Web form object. We can use the Redirect method to navigate to a new Web form. 

response.redirect("nextpage.aspx")

Request is a property of the HttpRequest object. This represents incoming data to the current Web form. The information stored in the Request object collections originates from the client

We can read the properties of the HttpRequest object to learn more about the client and the page currently being viewed.

lblURL.Text = Request.Url.ToString 

Use Query Strings to send data to the next page

A Query String is composed of field-value pairs and is appended to a URL.

response.redirect("pagename.aspx?FieldName=Value")

The above URL contains a querystring containing a single name/value pair.

Here is another example:

response.redirect("pagename.aspx?FieldName1=Value1&FieldName2=Value2")

Query Strings are useful for passing non sensitive data between 2 pages. The querystring begins with the question mark (?) character. Each name value pair is delineated by an ampersand (&) character.

When using the concatenation character to build a querystring, you need to really pay attention to the ampersand as you are using it in 2 contexts:

1) as the delineator in the querystring
2) as the concatenation operator in the string as it is being built

For instance:


In the above querystring, there are 3 name/value pairs. Each value for each name, is supplied by a string variable. The string is built using the concatenation operator - the ampersand, however, each subsequent name/value pair is also separated by the ampersand character. Concentrate & you will be fine (see what I did there?). LOL.

Read Query Strings on the next page

We can use the request object to read the values of the fields within the Query String.

Dim X as String = Request.QueryString("FieldName")


or as per the above example:


Dim strFirstName as String = Request.QueryString("Firstname")
Dim strLastName as String = Request.QueryString("Lastname")
Dim strPostCode as String = Request.QueryString("PostCode")



The following series of screenshots show values from textboxes being concatenated into a querystring & then displayed on the following page:

1.

 2.

 3.

 4.

 5.

Get a copy of the project here :))

global.asax

What is the Global.asax file?
Adding a global.asax file to your application allows your application to respond to application & session level events

Application level events
There are a number of application level events available in the global.asax file.

The Application_Start event is fired the first time when an application starts.
Application_Start

The Application_End event is last event of its kind that is fired when the application ends or times out. It typically contains application cleanup logic.
Application_End

Session level events
There are two session level events available in the global.asax file.

The Session_Start event is fired whenever a new session of the application starts.
Session_Start

The Session_End event is fired whenever a session with the application ends.
Session_End


Further reading:
MSDN: Global.asax file http://msdn.microsoft.com/en-us/library/1xaas8a2%28VS.71%29.aspx
Understanding the Global.asax file http://aspalliance.com/1114
StackOverflow: What are the Pros and Cons of using Global.asax? http://stackoverflow.com/questions/135661/what-are-the-pros-and-cons-of-using-global-asax

Cookies

What is a cookie?
Cookies are small text files that are added to a users browser by a web application to store session/user specific data. A web application is able to read the contents of a cookie(s) on each subsequent visit a user makes to a website.

Security considerations
Cookies are unsuitable for storing secure information such as passwords.

Adding a cookie
A cookie may contain a number of name/value pairs when it is added to the browser. The expiry date of a cookie defines how long the cookie should remain in the browser for.

Response.Cookies("userInfo")("userName") = "straximo"
Response.Cookies("userInfo")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(1)
Use the Response (outgoing) object to add a cookie.

Modifying a cookie
A cookie may be modified simply by overwriting it.

Response.Cookies("userInfo")("userName") = "straximo4"
Response.Cookies("userInfo")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(1)
Use the Response (outgoing) object to modify a cookie.

Removing a cookie
A cookie is removed by setting the expiry date to a time in the past.

Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(-1)
Use the Response (outgoing) object to remove a cookie.

Reading a cookie
After checking that a cookie exists, a cookie value may be read & used just like any other value.

If Not Request.Cookies("userInfo") Is Nothing Then
  Label1.Text = Request.Cookies("userName")("userName")
  Label2.Text = Request.Cookies("userName")("lastVisit")
End If

Use the Request (outgoing) object to read a cookie.

Multiple Constructors

What are multiple constructors?
A constructor is also a method and so it may also be overloaded.

eg. Constructor with an empty parameter list
Public Class User
Public Sub New()
   ' Code...
End Sub

End Class

eg. Constructor containing 2 parameters in the parameter list
Public Class User
Public Sub New(UserName As String, Password As String)
   ' Code...
End Sub

End Class

eg. Constructor containing 3 parameters in the parameter list
Public Class User
Public Sub New(UserName As String, Password As String, MembershipType As Membership)
   ' Code...
End Sub

End Class

Method Overloading

What is Method Overloading?
Method Overloading is a means to having multiple methods with the same name, but which have differing parameter lists. Also called 'Polymorphism' - one name, many forms.

eg. getUserName function with empty parameter list
Public Function getUserName() As String
   ' Code...
Return Value
End Function

eg. getUserName function with a single string parameter called UserID
Public Function getUserName(UserID as Integer) As String
   ' Code...
Return Value
End Function

eg. getUserName function with a string parameter called UserID & a Date parameter called MembershipDate
Public Function getUserName(UserID As Integer, MembershipDate As Date) As String
   ' Code...
Return Value
End Function

Further reading:
Create Overloaded Methods in VB.NET http://www.devx.com/dotnet/Article/9303
Method Overloading http://en.wikipedia.org/wiki/Method_overloading
What is a page Postback?
When a Page Loads, it is either loading for the first time or it is loading again based on some kind of user interaction with that page. In the case of the latter, we call this a Postback.


How to avoid problems with Postback
You may have code in your load event that should only run the first time a page loads. 

Each page contains a boolean property called IsPostback. This property can be checked at runtime to determine whether the page is loading for the first time or posting back to itself.


Use an If statement to determine the state of the Postback property.

Further reading:


MSDN: Page.IsPostback property http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx

Debugging: Setting Breakpoints

What is a Breakpoint?
A breakpoint is a specified point in the program where program execution pauses. During this pause, the values of variables, parameters and other objects may be examined.

How do I set a Breakpoint?
Place your cursor in the margin of the code editor and double-click. You will now see a red bullet in the margin, this represents the breakpoint. Double-click to remove.


Run your project. When program execution reaches the breakpoint, the program will enter break mode. You will notice that the current  breakpoint is highlighted with a yellow background.



While in break mode, use your mouse to hover over the names of variables, parameters and other objects to see the value they currently store.





If you have multiple break points, click the play button to reach each subsequent breakpoint.

Further reading:
MSDN: Debugging basics. Breakpoints http://msdn.microsoft.com/en-us/library/4607yxb0.aspx
Wikipedia: Breakpoints http://en.wikipedia.org/wiki/Breakpoint

Page Tracing

What is page tracing?
Tracing allows you to view diagnostic information about a single request for an ASP.NET page.


You can enable page tracing by entering Trace="True" in the page directive at the top of the source view.

Why use page tracing?
Page tracing is a handy way to see values such as session variables at run-time.

Further reading:
How to: Enable Tracing for an ASP.NET Page http://msdn.microsoft.com/en-us/library/94c55d08.aspx
MSDN: Reading ASP.NET trace information http://msdn.microsoft.com/en-us/library/kthye016%28VS.80%29.aspx

Wednesday, February 2, 2011

Console.Read Method

From "Console.Read Method (System)" ( http://bit.ly/g9pebT )

The Read method blocks its return while you type input characters; it terminates when you press the Enter key.

Pauses, slowing things down. System.Threading.Thread.Sleep

Accepts an argument specifying the length of the pause in milliseconds.
1 second = 1000 milliseconds

System.Threading.Thread.Sleep(5000)

The difference between classes & modules

From "Classes vs. Modules" ( http://bit.ly/eEMVtk )

"The main difference between classes and modules is that classes can be instantiated as objects while standard modules cannot. Because there is only one copy of a standard module's data, when one part of your program changes a public variable in a standard module, any other part of the program gets the same value if it then reads that variable. In contrast, object data exists separately for each instantiated object. Another difference is that unlike standard modules, classes can implement interfaces..."