Tuesday, June 16, 2009

Point to root directory Image Display Problem and Solution in Asp.net

Master Page is creating problem when a page inside folder is trying to refer master page. The reason of problem is Master Page is using absolute image url, which changes when you try to refer same inside folder.

A simple solution to problem is to define relative path for images inside master page.

So if you have coded like following in your MasterPage File

<img src="Images/Logo.gif"/>

Than Replace it with, 


<img src="<%= Page.ResolveUrl("~")%>Images/Logo.gif"/>

Dynamically Generate Meta Tags for ASP.NET Pages

create an XML file that contains the data for the meta tags. Right click the website and choose Add > New Item > XML File. Name the file TagData.xml and add the following XML:

<tags pageName="/WebForm1.aspx">
<tag name="keyword" value="This is a keyword"></tag>
<tag name="description" value="This is a description"></tag>
<tag name="author" value="malcolm sheridan"></tag>
</tags>
<tags pageName="/ChildFolder/WebForm1.aspx">
<tag name="keyword" value="This is a keyword for the child pages"></tag>
<tag name="description" value="This is a description for the child pages"></tag>
<tag name="author" value="malcolm sheridan for this page too"></tag>
</tags>


In the XML above I have created a parent node called metaTags. Inside I have created a tags node which contains a pageName attribute. That value is how we will match the current requested page to the XML data. Each tags node contains a tag node that corresponds to the meta data we want sent to the browser. In this example I want to set meta tags for the all the pages to have keyword, description and author meta tags, but the values rendered to the browser will differ depending on what page the user is on. In a real world scenario this information would be stored inside a database, but I decided to keep this data inside an XML file to keep it simple and focus on how to do this.

Having outlined what meta tags we want sent to the browser, we now have to write the code that will read the XML file and dynamically add the meta tags at runtime. Seeing as though we’re using Master Pages this is the ideal spot to add it. Add the following code to read the XML file:

C#

XDocument doc = XDocument.Load(Server.MapPath("~/TagData.xml"));
var metaTags = doc.Descendants("tag")
              .Where(o => o.Parent.Attribute("pageName").Value == Request.Url.AbsolutePath)
               .Select(o => new
               {
                    Value = o.Attribute("value").Value,
                    Name = o.Attribute("name").Value
               });

VB.NET

Dim doc As XDocument = XDocument.Load(Server.MapPath("~/TagData.xml"))
Dim metaTags = doc.Descendants("tag").Where(Function(o) o.Parent.Attribute("pageName").Value = Request.Url.AbsolutePath).Select(Function(o) New With {Key .Value = o.Attribute("value").Value, Key .Name = o.Attribute("name").Value})

For flexibility and ease of use I have decided to use the power of LINQ to XML to read the XML data. To start with the XML document is load into an XDocument object. From there I have created a LINQ query to return all the tag nodes where the parent node has an attribute called pageName and the value is equal to the current page.   Then the object returned is an anonymous type that has a Value and Name property. The values of those properties are the value and name attribute values.

Now that we have the data in memory, the next step is to create the meta tag and add it to the page dynamically. To do this you use the HtmlMeta class. This allows you programmatic access to the HTML meta tags. Add the following code below to your project:

C#

foreach (var item in metaTags)
{              
     HtmlMeta meta = new HtmlMeta();
     meta.Name = item.Name;
     meta.Content = item.Value;
     Page.Header.Controls.Add(meta);
}

VB.NET

For Each item In metaTags
       Dim meta As New HtmlMeta()
       meta.Name = item.Name
       meta.Content = item.Value
       Page.Header.Controls.Add(meta)
Next item

The foreach loop enumerates through each item returned from the LINQ query. It assigns the Name and Content value to the HtmlMeta object. Finally the object is added to the page by calling Page.Header.Controls.Add(meta). Run the project and once the default page has loaded

Sunday, April 26, 2009

Finding All Controls on Page in Asp.net

To find all controls on Page, including child controls. i.e. Loop through all control list.

Example: I have a page with Controls on Page, Pannel Controls (Which contains Few more child controls). Now I want to find list of all controls on Page including child control.

private void ListControlCollections()
    {
        ArrayList controlList = new ArrayList();
        AddControls(Page.Controls,controlList);

        foreach (string str in controlList)
        {
            Response.Write(str + "
");
        }
        Response.Write("Total Controls:" + controlList.Count);
    }

    private void AddControls(ControlCollection page,ArrayList controlList)
    {
        foreach (Control c in page)
        {
            if (c.ID != null)
            {
                controlList.Add(c.ID);
            }
           
            if(c.HasControls())
            {
                AddControls(c.Controls, controlList);
            }
        }
    }

Saturday, April 25, 2009

Multiple Querystring for Url Rewriting Asp.net

How to Handle Multiple Querystring for Url Rewriting in Asp.net

Please go through my earlier article on Url Rewriting.
@Update to my earlier article on Simplest Way to write Url Rewriting

If you have gone through my earlier article

<rewriter>
<rewrite url="~/Article/(.+)-(.+)-(.+).aspx" to="~/DynamicPage.aspx?MyTitleId=$2&CategoryId=$3">
</rewriter>


In Web.Config file you can handle special character by replacing it with its code.
Example in our case we have replace & with &

After making changes to web.config file you need to pass third argument as category Id, and that its. Your code is ready to handle multiple querystring argument.