Jan 18 2007

Server Variables

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 10:03

I always find a difficulty in remembering all the server variables and how they can help me, here is a list of all the server variables I ran in a testing application. You will see the server variables with a sample data coming from the testing application:

ALL_HTTP HTTP_CONNECTION:Keep-Alive HTTP_ACCEPT:*/* HTTP_ACCEPT_ENCODING:gzip, deflate HTTP_ACCEPT_LANGUAGE:en-gb HTTP_HOST:localhost HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)
ALL_RAW Connection: Keep-Alive Accept: */* Accept-Encoding: gzip, deflate Accept-Language: en-gb Host: localhost User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)
APPL_MD_PATH /LM/w3svc/1/root/Testing
APPL_PHYSICAL_PATH C:\Projects\Testing\
AUTH_TYPE  
AUTH_USER  
AUTH_PASSWORD  
LOGON_USER  
REMOTE_USER  
CERT_COOKIE  
CERT_FLAGS  
CERT_ISSUER  
CERT_KEYSIZE  
CERT_SECRETKEYSIZE  
CERT_SERIALNUMBER  
CERT_SERVER_ISSUER  
CERT_SERVER_SUBJECT  
CERT_SUBJECT  
CONTENT_LENGTH 0
CONTENT_TYPE  
GATEWAY_INTERFACE CGI/1.1
HTTPS off
HTTPS_KEYSIZE  
HTTPS_SECRETKEYSIZE  
HTTPS_SERVER_ISSUER  
HTTPS_SERVER_SUBJECT  
INSTANCE_ID 1
INSTANCE_META_PATH /LM/W3SVC/1
LOCAL_ADDR 127.0.0.1
PATH_INFO /Testing/WebForm1.aspx
PATH_TRANSLATED C:\Projects\Testing\WebForm1.aspx
QUERY_STRING  
REMOTE_ADDR 127.0.0.1
REMOTE_HOST 127.0.0.1
REMOTE_PORT 2368
REQUEST_METHOD GET
SCRIPT_NAME /Testing/WebForm1.aspx
SERVER_NAME localhost
SERVER_PORT 80
SERVER_PORT_SECURE 0
SERVER_PROTOCOL HTTP/1.1
SERVER_SOFTWARE Microsoft-IIS/5.1
URL /Testing/WebForm1.aspx
HTTP_CONNECTION Keep-Alive
HTTP_ACCEPT */*
HTTP_ACCEPT_ENCODING gzip, deflate
HTTP_ACCEPT_LANGUAGE en-gb
HTTP_HOST localhost
HTTP_USER_AGENT Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)

 

Hope this helps,

Regards

Tags: ,

Dec 8 2006

Concurrency in ADO.NET

Category: ASP.NET 1.xBil@l @ 14:27

During my reading to the Microsoft ADO.NET Core Reference by David Sceppa I am getting to learn so many things, among which ways to handle concurrency Options:

1- Include only the Primary Key Columns
This way, when User A and User B both read the same record at the same time, when it comes for updating the record, the last who updates wins, since no way to update a primary key!

2- Include All Columns in the WHERE clause
This way, first one to update the record wins! The second who had the same version of the record at the same time will fail to update.

3- Include Primary Key and Timestamp Columns
This way, only the first one wins the update, but in this case few checkings will be done in the WHERE clause, only the primary key(s) and a timestamp column.

4- Include the Primary Key Columns and Modified Columns
This is not recommended, because you as a developer should provide a different stored procedure for each updatable column.

Hope this helps!

Regards

Tags:

Nov 25 2006

HttpSessionState and ASP.NET Exception

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 14:32

A nice trick I read in the ASP.NET 2.0 Core Reference is that, when an exception occurs at the end of the request, that is the GetLastError of the Server object returns an exception, the Session data is lost, however, in your handler of the Exception, if you call Server.ClearError, the Session is restored!

That is a great tip Dino, Thanks!

Regards

Tags: ,

Oct 20 2006

Store C# Collection in XML

Category: ASP.NET 1.xBil@l @ 15:25

While developing a multi-threaded Web Application, I had the need to store my collections generated in multiple thread somewhere.

I tried the CACHE in .NET, however, threads do block the whole CACHE and notonly an item in the CACHE, so as usual, the solution is with XML.

Now, the key is how to come up with a simple and easy way to store any collection into XML without the need to have a seperate method for each collection I have in the application, the answer is typically Reflection.

I will show you a method that is capable of storing any collection implementing IList into XML:

 public class Helper
 {
  public static void StoreCollectionInXML(IList list)
  {
   // Validate list
   if (list == null)
    throw new Exception("Collection cannot be null");

   if (list.Count == 0)
    throw new Exception("Collection cannot be empty");

   // Create XmlTextWriter
   string filePath = HttpRuntime.AppDomainAppPath + "
\\XML\\" + list.GetType().Name + ".xml";
   XmlTextWriter writer = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
   
   // Set the Writer formatting
   writer.Formatting = Formatting.Indented;

   // Convert collection
   Helper.CollectionToXML(list, writer);

   // Close the writer
   writer.Flush();
   writer.Close();
  }
  
  private static void CollectionToXML(IList list, XmlTextWriter writer)
  {
   // Validate list
   if (list == null)
    throw new Exception("Collection cannot be null");

   if (list.Count == 0)
    throw new Exception("Collection cannot be empty");

   // Validate writer
   if (writer == null)
    throw new RAException("XmlTextWriter cannot be null");

   //Write the root element
   writer.WriteStartElement(list.GetType().Name);

   foreach(object obj in list)
   {
    // Start an element
    writer.WriteStartElement(list[0].GetType().Name);

    // Get all properties
    PropertyDescriptorCollection pInfo = Helper.GetProperties(obj);
    if (pInfo != null)
    {
     foreach(PropertyDescriptor p in pInfo)
     {
      // Add Property
      writer.WriteElementString(p.DisplayName, p.GetValue(obj).ToString());
     }
    }
    // Close the element
    writer.WriteEndElement();
   }

   // Close root element
   writer.WriteEndElement();
  }

  private static PropertyDescriptorCollection GetProperties(object obj)
  {
   // Get the type of the object
   Type t = obj.GetType();

   // Get the properties
   PropertyDescriptorCollection props;
   props = TypeDescriptor.GetProperties(t);

   if (props != null)
    return props;
   
   return null;
  }
 }

The main method is: StoreCollectionInXML

This method, simply validates the List we want to store in XML, and then creates an instance of the XmlTextWriter.

Then it calls the CollectionToXML method, this method, writes the Root and the sub elements into the XML file. This method, gets the Type of the objects stored in the collection, then for each Type it calls the method GetProperties. That method will return all the properties of that Type.

Once I have all the properties, I can use the property name and value to generated a new XML element and its value.

I hope you liked this post!

Regards

Tags:

Oct 5 2006

Filter Collection of Objects

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 06:04

I have been developing an API for an application of mine at work. The API returns a set of objects in the form of Collections. I needed a way to filter the collection based on some values I provide.

I have passed by this blog post:

http://codebetter.com/blogs/brendan.tompkins/archive/2004/09/02/24116.aspx

Brendan creates something known as CollectionView, that supports both Windows and Web collections.

I took that code, and did some modifications on it:

  1. I removed the IBindingList interface
  2. I removed all methods from the IList and ICollection implementation that might allow change of data in teh input Collection.
  3. I removed the sorting feature

I made the collection a normal collection that takes as input a collection, and then allows the developer to filter data inside.

In addition, I made the CollectionView capable of filtering not only on the direct properties of the classes inside the IList, but also multilevel properties as follows:

Currently, you can filter on simple data-types properties:

public string/int/double (etc ...) PropertyName
{
   get {}
   set {}
}

My CollectionView allows you to do filtering even on:

public Person MyPerson
{
    get {}
    set {}
}

Where Person is a class, so you can filter a collection of objects, where each object might have a property of type another object, i.e. you can filter a collection based on a property in the multilevel properties of the objects in the Collection.

An example illustrates how to use the new ApplyFilter method:

Suppose, a class Person has a property of type Address, where Address is another class that has a property called City as follows:

 

 public class Person
 {
  //members
  private string firstName=null;
  private string lastName=null;
  private Address address = null;
  
  //Public constructor
  public Person(string FirstName,string LastName, Address address)
  {
   this.firstName =FirstName;
   this.lastName=LastName;
   this.address = address;
  }

  #region Properties for member access
  public string FirstName
  {
   get
   {
    return firstName;
   }
   set
   {
    firstName=value;
   }
  }

  public string LastName
  {
   get
   {
    return lastName;
   }
   set
   {
    lastName=value;
   }
  }

  public Address Address
  {
   get
   {
    return this.address;
   }
   set
   {
    this.address=value;
   }
  }

  #endregion
 }
}


 public class Address
 {
  private string city;

  public string City
  {
   get
   {
    return this.city;
   }
   set
   {
    this.city = value;
   }
  }

  public Address(string City)
  {
   this.city = City;
  }
 }

Now you create a collection of Person class as follows:

PersonCollection pCol = new PersonCollection();
Person p1 = new Person("Bilal", "Haidar", new Address("Beirut"));
Person p2 = new Person("Lara", "Keyrouz", new Address("Beirut"));
Person p3 = new Person("Wessam", "Zeidan", new Address("Zahle"));
Person p4 = new Person("Ziad", "Hanna", new Address("Beirut"));
Person p5 = new Person("Alaa", "Said", new Address("Saida"));

Now, you want to get all persons in Beirut, which is a property called City inside object Address, where Address is a property inside Person class, so you can see the hierarchy:

Person
   --------> Address
                       --------> City

What you do is use the new ApplyFilter method as follows:

CollectionView cv = new CollectionView(pCol);
cv.ApplyFilter("Address","City", new Object[] {"Beirut"},FilterOperand.Equals);

The first parameter in the ApplyFilter is the Property, the second is the SubProperty, then an array of objects to provide the data in where to search, then an operand of equals.

You can even search for direct and simple properties as follows:

CollectionView cv = new CollectionView(pCol);
cv.ApplyFilter("FirstName",null, new Object[] {"Bilal"},FilterOperand.Equals);

I have also added a new Filter Option called "InRange", this way, you can search for a set of values as follows:

CollectionView cv = new CollectionView(pCol);
cv.ApplyFilter("FirstName",null, new Object[] {"Bilal", "Wessam"},FilterOperand.InRange);

This way, it will bring you person records whose FirstName are in a set of values (Bilal and Wessam).

The additions are:

  1. Support for multilevel property filter
  2. A new Filter Operan called InRange has been added
  3. Data to be filtered according to has been changed to an array of Objects

You can download the CollectionView.cs file and use it in your applications.

I will be enhancing it with sort option, maybe more Filter Operands too!!

Hope you liked this post!!

Regards

 

Tags: ,

May 23 2006

Session_End and HttpRuntime

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 06:53

I had a need few days ago to delete some files in the Session_End. As you know, Session_End will be fired, even if the client's session ends, because the Session is based on the Server and therefore, after the Session times-out the Session_End on the server will be executed.

However, I needed to use some properties from the HttpContext and it happened that thre is not always an Active Context when the Session_End fires, especially when the browser is closed from the client side before the session expires.

So to overcome this, you can use HttpRuntime, and I mainly used HttpRuntime.AppDomainAppPath to get the physical path of my application to locate the files I need to delete.

Hope this trick helps you out!

Regards

Tags: ,

May 18 2006

Looping Through Page Controls

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 11:41

A very common question on the ASP.NET forums, is how to loop through the page controls, and find dynamically my control!

Here is the solution, its R E C U R S I O N !!

A very simple example, that loops through the page controls, and once it finds a Panel, it prints out, I am a Panel

 

    public void ShowPanels(Control p_Control)
    {
        try
        {
            // If control found is of type Panel
            if (p_Control.GetType().FullName.Equals("System.Web.UI.WebControls.Panel"))
            {
                                Response.Write ("I am a Panel!");
            }

            // Looping through all controls
            foreach (Control _control in p_Control.Controls)
            {
               ShowPanels(_control);
            }
        }
        catch (Exception ex)
        {
            throw new ApplicationException(ex.ToString());
        }
    }


Hope this helps,

Regards

Tags: ,

May 12 2006

String Enumeration in C#

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 12:12

I have always had the need to use String Enumerations. What do I mean by that?

Suppose we have this Enum Type:

    public enum StringNames
    {
        Bilal,
        Wessam,
        Elsa,
        Samer,
        Tarek,
        Farah,
        Firas,
        Mohammad
    }

In my code, I would like to have something as:

string _Name = "Bilal";
switch (_Name)
{    
        case StringNames.Bilal:
                break;    
        case StringNames.Wessam:           
                break;     
        case StringNames.Elsa:           
                break;      
        .......
}

Well the above doesn't work as it is. How to make it work?

There is a method called Enum.Parse, there are two overloads, we will be using the one with the IgnoreCase boolean option as follows:

StringNames _StringNames = (StringNames)Enum.Parse(typeof(StringNames), _Name, true);

This will convert the string value "Bilal" contained in _Names, into a EnumType value, so now after executing the above statement, you have:


 _StringNames = StringNames.Bilal

So, StringNames.Bilal is an EnumValue equals the EnumValue _StringNames, so rewriting the above switch statement would be something as:

    string _Name = "Bilal";
    StringNames _StringNames = (StringNames)Enum.Parse(typeof(StringNames),_Name,true);

    switch (_StringNames)
    {
        case StringNames.Bilal:
            break;
        case StringNames.Wessam:
            break;
        case StringNames.Elsa:
            break;
        .......
    }

I want to thank my colleague Raed for uncovering for me the real return type of the Enum.Parse method.

Hope helps you out!

Regards

Tags: ,

Apr 29 2006

Define an Event Handler for a HyperLink Server Control

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 09:37

Hello, a common question on the ASP.NET Forum is:

How to define an Event Handler for a HyperLink?

The solution as follows:

protected System.Web.UI.WebControls.HyperLink HyperLink1;
    
private void Page_Load(object sender, System.EventArgs e)
{
    HyperLink1.Attributes.Add("onClick",
Page.GetPostBackEventReference(this.HyperLink1,"HyperLinkPostBack$"+this.HyperLink1.ID)); if ( (IsPostBack) && (Request.Form["__EVENTTARGET"] != null) && (Request.Form["__EVENTARGUMENT"].ToString().StartsWith("HyperLinkPostBack")) ) { string[] args = Request.Form["__EVENTARGUMENT"].ToString().Split('$'); if ( (string.Compare(args[0], "HyperLinkPostBack", false, System.Globalization.CultureInfo.InvariantCulture) == 0)
&& (args.Length > 1) ) { HyperLinkHandler(args[1].ToString()); } } } public void HyperLinkHandler(string ID) { Response.Write("You clicked HyperLink with ID : "+ ID); }

                
 

                
 
 Or You could use this way, using IPostBackEventHandler:

                
private void Page_Load(object sender, System.EventArgs e)
{
    HyperLink1.Attributes.Add("onClick", Page.GetPostBackEventReference(this, "HyperLinkPostBack" + "$" + this.HyperLink1.ID));
}

public void RaisePostBackEvent(string eventArgument)
{
    if (!string.IsNullOrEmpty(eventArgument))
        {
            string[] args = eventArgument.Split('$');
                if ((string.Compare(args[0], "HyperLinkPostBack", false, System.Globalization.CultureInfo.InvariantCulture) == 0) 
&& (args.Length > 1)) { HyperLinkHandler(args[1].ToString()); } } } public void HyperLinkHandler(string ID) { Response.Write("You clicked HyperLink with ID : " + ID); }

                
 

Hope that helps,

Regards

Tags: ,

Apr 28 2006

Modal Dialog Window Caching Problem

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 09:35

Hello:

Suppose you open a Modal Dialog window inside your ASP.NET page. In that dialog window, you have a GridView, DataGrid, or whatever control. Do some changes on that control, you will see that the data has changed right?

Ok, then close the dialog window, then open it again from the ASP.NET Page, you will see the old data and not the data you changed last time, right?

Ok, this is because the data has been cached by the Modal Dialog. It seems that this is how Modal Dialog Windows are built to cache.

To overcome this, you would need to add the following in the top of the ASP.NET page that is being opened with the Modal Dialog:

<%@ OutputCache Location="None" VaryByParam="None" %>

Hope that helps,

Regards

Tags: ,