Monday, June 27, 2011

Create rounded corners with CSS 3 using Border-radius


The CSS3 border-radius property allows web developers to easily utilise rounder corners in their design elements, without the need for corner images or the use of multiple div tags, and is perhaps one of the most talked about aspects of CSS3.


Since first being announced in 2005 the boder-radius property has come to enjoy widespread browser support (although with some discrepancies) and, with relative ease of use, web developers have been quick to make the most of this emerging technology.
Here’s a basic example:
This box should have a rounded corners for Firefox, Safari/Chrome, Opera and IE9.
The code for this example is, in theory, quite simple:
#example1 {
border-radius: 15px;
}
However, for the moment, you’ll also need to use the -moz- prefix to support Firefox (see the browser support section of this article for further details):
#example1 {
-moz-border-radius: 15px;
border-radius: 15px;
}

How it Works

Rounder corners can be created independently using the four individual border-*-radius properties (border-bottom-left-radius, border-top-left-radius, etc.) or for all four corners simultaneously using the border-radius shorthand property.
We will firstly deal with the syntax for the individual border-*-radius properties before looking at how the border-radius shorthand property works.

border-bottom-left-radius, border-bottom-right-radius, border-top-left-radius, border-top-right-radius

The border-*-radius properties can each accept either one or two values, expressed as a length or a percentage (percentages refer to the corresponding dimensions of the border box).
The Syntax:
border-*-*-radius: <length> | <%> ] [ <length> | <%> ]?
Examples:
border-top-left-radius: 10px 5px;
border-bottom-right-radius: 10% 5%;
border-top-right-radius: 10px;
Where two values are supplied these are used to define, in order, the horizontal and vertical radii of a quarter ellipse, which in turn determines the curvature of the corner of the outer border edge.
Where only one value is supplied, this is used to define both the horizontal and vertical radii equally.
The following diagram gives a few examples of how corners might appear given differing radii:
border-radius-diagram-1
If either value is zero, the corner will be square, not round.

border-radius

The border-radius shorthand property can be used to define all four corners simultaneously. The property accepts either one or two sets of values, each consisting of one to four lengths or percentages.
The Syntax:
<length> | <percentage> ]{1,4} [ / [ <length> | <percentage> ]{1,4} ]?
Examples:
border-radius: 5px 10px 5px 10px / 10px 5px 10px 5px;
border-radius: 5px;
border-radius: 5px 10px / 10px;
The first set of (1-4) values define the horizontal radii for all four corners. An optional second set of values, preceded by a ‘/’, define the vertical radii for all four corners. If only one set of values are supplied, these are used to determine both the vertical and horizontal equally.
For each set of values the following applies:
If all four values are supplied, these represent the top-left, top-right, bottom-right and bottom-left radii respectively. If bottom-left is omitted it is the same as top-right, if bottom-right is omitted it is the same as top-left, and if only one value is supplied it is used to set all four radii equally.

Browser Support

At present Opera (version 10.5 onward), Safari (version 5 onward) and Chrome (version 5 onward) all support the individual border-*-radius properties and the border-radius shorthand property as natively defined in the current W3C Specification (although there are still outstanding bugs on issues such as border style transitions, using percentages for lengths, etc.).
Mozilla Firefox (version 1.0 onward) supports border-radius with the -moz- prefix, although there are some discrepancies between the Mozilla implementation and the current W3C specification (see below).
Update:Recent Firefox nightly versions support border-radius without the -moz- prefix.
Safari and Chrome (and other webkit based browsers) have supported border-radius with the -webkit- prefix since version 3 (no longer needed from version 5 onward), although again with some discrepancies from the current specification (see this article for further details of how older versions of Webkit handle border-radius).
Even Microsoft have promised, and demonstrated in their recent preview release, support for border-radius from Internet Explorer 9 onward (without prefix).

The -moz- prefix

Mozilla’s Firefox browser has supported the border-radius property, with the -moz- prefix, since version 1.0. However, it is only since version 3.5 that the browser has allowed elliptical corners, i.e. accepting two values per corner to determine the horizontal and verical radii independently. Prior to version 3.5, the browser only accepted one value per corner, resulting in corners with equal horizontal and vertical radii.
The syntax, from Firefox 3.5 onwards, for the main part follows the current W3C specification, as described throughout this article, prefixed by -moz-. The only major difference is in the naming of the individual border-*-radius properties, with the -moz- prefixed properties following a slightly different naming convention as follows:
W3C SpecificationMozilla Implementation
border-radius-moz-border-radius
border-top-left-radius-moz-border-radius-topleft
border-top-right-radius-moz-border-radius-topright
border-bottom-right-radius-moz-border-radius-bottomright
border-bottom-left-radius-moz-border-radius-bottomleft
The Mozilla implementation also behaves slightly differently from the specification when percentages are supplied. You can read more on the Mozilla Developer Center here.

Cross Browser Examples

Here’s a few basic examples that should work in current versions of Firefox, Safari/Chrome, Opera and even IE9:
A
B
C
D
E
F

#Example_A {
height: 65px;
width:160px;
-moz-border-radius-bottomright: 50px;
border-bottom-right-radius: 50px;
}
#Example_B {
height: 65px;
width:160px;
-moz-border-radius-bottomright: 50px 25px;
border-bottom-right-radius: 50px 25px;
}
#Example_C {
height: 65px;
width:160px;
-moz-border-radius-bottomright: 25px 50px;
border-bottom-right-radius: 25px 50px;
}
#Example_D {
height: 5em;
width: 12em;
-moz-border-radius: 1em 4em 1em 4em;
border-radius: 1em 4em 1em 4em;
}
#Example_E {
height: 65px;
width:160px;
-moz-border-radius: 25px 10px / 10px 25px;
border-radius: 25px 10px / 10px 25px;
}
#Example_F {
height: 70px;
width: 70px;
-moz-border-radius: 35px;
border-radius: 35px;
}

Tuesday, June 21, 2011

Search Engine Friendly URL’s Using Routing in ASP.Net 3.5

What is Routing?
Routing is a technique which enables us to use a descriptive, search engine and human friendly URL’s for ASP.Net application to access a resource. In this technique, the URL will not map to a resource physically. For example, in a normal asp.net application, the URL "http://localhost/Articles/Default.aspx" will actually corresponds to a physical file called Default.aspx under the folder “Articles”.



Below are some of the examples of valid URLs using Routing,

http://localhost/ArticleSite/Articles/list/csharp
http://localhost/ArticleSite/Articles/list/java
http://localhost/ArticleSite/Articles/edit/csharp
http://localhost/Shopping/electronics/show/homeappliances
http://localhost/Shopping/electronics/show/mobiles

Advantages of Routing
Most often, we work on data driven websites where data is categorized and stored. For example, if we are building a shopping website we may have products in various categories like home appliances, mobiles, Apparels, Jewels, Perfumes, etc. To build a list page to display the products in a category, we will normally develop an asp.net page that accepts the category ID as query string to populate the product list. For example,
http://localhost/Shopping/productlist.aspx?CatID=C91E9918-BEC3-4DAA-A54B-0EC7E874245E

As you can see, the above URL is not readable and descriptive to understand the purpose it is going to serve. When we use routing in these scenarios we can make the URL more descriptive, readable, predictable and most importantly search engine friendly. Something similar to,

http://localhost/Shopping/electronics/show/mobiles

The above URL speaks itself i.e. it is intended to display a list of mobile phones in electronics category.

Initially, the ASP.Net routing engine is packed with the new ASP.Net MVC framework. Later, Microsoft shipped this feature (System.Web.Routing namespace) with .Netframework 3.5 SP1 to work with normal asp.net application.
Moving forward, we will implement a simple routing mechanism in ASP.Net 3.5. In order to provide routing in asp.net application, we need to first define routes and routing handler.

What is a Route?
 A route is a format or pattern of URL we define for application. The route can have placeholders and constant values. The place holders will be replaced with the values that we supply in the URL during processing.
For example,
{controller}/{action}/{Category}  -- /products/list/cars or /product/list/phones
Articles/{action}/{Category} --    /Articles/list/jQuery, /Articles/edit/jQuery

As you can see above, the placeholders are normally placed in { } and constants (Articles) are defined between the allowed delimiter /. The Routing engine will read place holder values, populate it into a name/value pairs and make it available for processing throughout the request.

Read this msdn article to know more about defining routes and adding constraints.
A Route is processed and resolved to a virtual path by a route handler. Once we defined our routes, we need to define our route hander to handle the request that follows the route pattern.

What is a RouteHandler?
A RouteHandler is an object that returns the instance of the actual ASP.NET page or HTTP Handler to complete the processing for the URL requested. A RouteHandler class should inherit the System.Web.Routing.IRouteHandler interface and implement GetHttpHandler() method.

To summarize, in order to work with routing, one should define Routes and RouteHandler to handle incoming request. A route should be registered with a Route handler in Application_Start event of the application object i.e. in global.asax file and it should be added to RouteTable object. Once registered, the incoming request is intercepted by the routing module; it matches the request URL with the registered routes and forwards them to the registered RouteHandler to complete the processing. The routing module is registered in HttpModules section of the web.config.

To understand the routing in ASP.Net, we will build a very simple asp.net application that displays list of employees in different departments.

Steps
1. Create a new Asp.Net website and include a new SqlExpress database in App_Data Folder.
2. Create 2 new tables called Employees and Department with some relevant columns.

Something like below image,

            In this example, we will create a simple route that has the department id of the employees in the URL instead of passing it as query string. Refer below pattern,
"Employees/{Dept}/{action}.aspx"

The valid URL’s for the above routes may be,
Employees/Sales/list.aspx
Employees/HR/list.aspx
Employees/IT/edit.aspx
Employees/Sales/delete.aspx

As I said earlier, we need to first create and register route to a route handler in Global.asax file. In order to register RouteHandler, we need to create the route handler to handle the request that has the url in the following route pattern
"Employees/{Dept}/{action}.aspx"

To do this, right click your solution in solution explorer and include a class file. I have named it as EmployeeRouteHandler. Import the routing namespace System.Web.Routing. Now, inherit the class from IRouteHandler interface and implement GetHttpHanlder() method, which should  return the actual page or a handler to handle the request. Refer the code below,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Routing;
using System.Web.Compilation;
/// <summary>
/// Summary description for EmployeeRouteHandler
/// </summary>
public class EmployeeRouteHandler: IRouteHandler
{
       public EmployeeRouteHandler()
       {
              //
              // TODO: Add constructor logic here
              //
       }

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        string DeptName = requestContext.RouteData.Values["Dept"] as string;
        HttpContext context = HttpContext.Current;
        context.Items.Add("Dept", DeptName);
        string action = requestContext.RouteData.Values["action"] as string;
        if(action.ToLower() == "list")
            return BuildManager.CreateInstanceFromVirtualPath("~/Default.aspx", typeof(Page)) as Page;
        else
            return BuildManager.CreateInstanceFromVirtualPath("~/Default.aspx", typeof(Page)) as Page;
    }


}


In the above code, we have extracted the place holder value(Department id and action in our case) from the RouteData object. Refer the below line,
string DeptName = requestContext.RouteData.Values["Dept"] as string;
string action = requestContext.RouteData.Values["action"] as string;

Note
The Routing engine will process the incoming URL and will populate the values that are matching the placeholders and will make it available throughout the request.

The actual Page object or the target page can be got by calling the CreateInstanceFromVirtualPath() method in BuildManager object.

Next, we need to populate the RouteTable with all the possible Routes and RouteHandler object to process the incoming request to the application. To do this, we need to first add a Global.asax file into our solution. Right click the solution, and select “Add New Item”. In the dialog, select “Global Application Class” and click OK.
Now, register all the Routes with their corresponding RouteHandler and populate it into the RouteTable object in Application_Start event. It is only "Employees/{Dept}/{action}.aspx" in our case.

Refer the code below,
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Routing" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
    }

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.Add("EmpOperation",new Route
        (
           "Employees/{Dept}/{action}.aspx",
                new EmployeeRouteHandler()
        )
       
        );
    }

Remember to import the System.Web.Routing namespace in order to access routing. Read this msdn article to know more about defining routes and adding constraints.

To list the employees in a department, drag a GridView control and SqlDataSource control into our Default.aspx page. Configure the Select Parameter collection to accept the DeptID as value to fetch the employees only in that department.
Refer the code below,

ASPX
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="EmpID" HeaderText="EmpID" InsertVisible="False"
                ReadOnly="True" SortExpression="EmpID" />
            <asp:BoundField DataField="EmpName" HeaderText="EmpName"
                SortExpression="EmpName" />
            <asp:BoundField DataField="Dept1" HeaderText="Dept" SortExpression="Dept1" />
            <asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
            <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
            <asp:BoundField DataField="Country" HeaderText="Country"
                SortExpression="Country" />
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="SELECT * FROM [Employees] Emp INNER JOIN Department d ON
        Emp.Dept=d.DeptID WHERE (Emp.[Dept] = @Dept)"
        onselecting="SqlDataSource1_Selecting">
        <SelectParameters>    
            <asp:QueryStringParameter DefaultValue="IT" Name="Dept" QueryStringField="Dept"
                Type="String" />            
        </SelectParameters>
    </asp:SqlDataSource>

CodeBehind
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        HttpContext context = HttpContext.Current;
        if(context.Items["Dept"] != null)
        e.Command.Parameters["@Dept"].Value = context.Items["Dept"].ToString();
    }
}
Execute the application and you can see it in action.
You can try the URLs.
http://localhost:16792/RoutingDemo/Employees/Sales/list.aspx
http://localhost:16792/RoutingDemo/Employees/IT/list.aspx
http://localhost:16792/RoutingDemo/Employees/HR/list.aspx


Wednesday, June 15, 2011

URL Rewriting using urlrewrite.NET


URL Rewriting with URLRewriter.Net Simplest Way


The Android Developer's Cookbook
Want to get started building applications for Android? Already building Android applications and want to get better at it? This book brings together all the expert guidance–and code–you’ll need!URL Rewriting with URLRewriter.Net 

URL Rewriting has lots of benefits, listing its main benefits
  • SEO Friendly URL
  • Secured URL
  • No need to change bookmark with change in site structure.

Before URL Rewriting my URL looks like
http://localhost:2661/URLRewrite2/DynamicPage.aspx?MyTitleId=1

After URL Rewriting URL is changed to 

http://localhost:2661/URLRewrite2/Article/Asp-Net-website-paths-1.aspx


Lets Understand URL Rewriting with Simple Example

A Website displaying articles list in a gridview on clicking the article link, it will display dynamically generated article content.

Before URL Rewriting when you mouse-over 1st Article Link, "Asp.net Website Path" it uses query string to display the article content.


Dynamic page display Querysting, before URL Rewriting.



After URL Rewriting we will achieve how SEO Friendly URL is used to display article content.


Now, lets understand how we can achieve it.

For URL Rewriting we are using URLRewriter.Net which is available free. Download URLRewriter.Net

Step-by-Step Explanation

Step 1: Download Binary Files for URLRewriter.Net

Step 2: Add Reference to Binary Files, Right click project "Add Reference" and add binary files.


Step 3: Update Web.Config File to make URLRewriter.Net works.
<configuration>

<configSections>
<section name="rewriter"
requirePermission="false"
type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
</configSections>

<system.web>

<httpModules>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
</httpModules>

</system.web>

<system.webServer>

<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
</modules>

<validation validateIntegratedModeConfiguration="false" />

</system.webServer>

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

</configuration>


Step 4: Adding Function to Generate SEO Friendly URL from given Title

public static string GenerateURL(object Title, object strId)
{
string strTitle = Title.ToString();

#region Generate SEO Friendly URL based on Title
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');

strTitle = strTitle.ToLower();
char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray();
strTitle = strTitle.Replace("c#", "C-Sharp");
strTitle = strTitle.Replace("vb.net", "VB-Net");
strTitle = strTitle.Replace("asp.net", "Asp-Net");

//Replace . with - hyphen
strTitle = strTitle.Replace(".", "-");

//Replace Special-Characters
for (int i = 0; i < chars.Length; i++)
{
string strChar = chars.GetValue(i).ToString();
if (strTitle.Contains(strChar))
{
   strTitle = strTitle.Replace(strChar, string.Empty);
}
}

//Replace all spaces with one "-" hyphen
strTitle = strTitle.Replace(" ", "-");

//Replace multiple "-" hyphen with single "-" hyphen.
strTitle = strTitle.Replace("--", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("-----", "-");
strTitle = strTitle.Replace("----", "-");
strTitle = strTitle.Replace("---", "-");
strTitle = strTitle.Replace("--", "-");

//Run the code again...
//Trim Start and End Spaces.
strTitle = strTitle.Trim();

//Trim "-" Hyphen
strTitle = strTitle.Trim('-');
#endregion

//Append ID at the end of SEO Friendly URL
strTitle = "~/Article/" + strTitle + "-" + strId + ".aspx";

return strTitle;
}


Step 5: Changing DataBinder.Eval Function in .Aspx Page to reflect changes in URL of Grid.
Note: Learn more about DataBinder.Eval Function


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Width="788px">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<Columns>
   <asp:TemplateField HeaderText="Title">
       <ItemTemplate>
           <asp:HyperLink ID="hlTitle" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Title")%>' NavigateUrl='<%#GenerateURL(DataBinder.Eval(Container.DataItem,"Title"),DataBinder.Eval(Container.DataItem,"Id"))%>'></asp:HyperLink>           
       </ItemTemplate>
   </asp:TemplateField>
   <asp:TemplateField HeaderText="Description">
       <ItemTemplate>
           <asp:Label ID="lblDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Description")%>'></asp:Label>
       </ItemTemplate>
   </asp:TemplateField>
</Columns>
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>


Now, Lets Check the stuff so far developed.

Assigning SEO Friendly URL in to grid.


On clicking URL inside grid it will point to Dynamically Generated Page with SEO Friendly URL, rather than QueryString.


Things to consider while URL Rewriting.

Problem 1: Page Postback, will turns User Friendly URL into Original URL.
Problem 2: CSS, Image Files pointing to URL Rewriting Page won't work, as they might be pointing with absolute path.

Problem 1: Page Postback for Page displaying URL Rewritten URL
Page Postback of Page displaying User friendly URL will turns into original state when same page postback occurs. In our example, I am adding one button and trying to make Page Postback. You will notice that Page Postback will turns the User Friendly URL into original URL containing QueryString.


For Resolving Page PostBack problem for Page displaying URL Rewritten URL

This article is inspired from Scott's URL Rewritten article. Adding two files as mentioned by scott. If you are developing code in VB download files from Scott's article, else for C# download files with Sourcecode at the end of this article.



Now, lets test the Page Postback by clicking on Button, you will notice this time, URL remains the same.




Problem 2: Image Display Problem
Now, lets display image on for this page and lets observe what problem we may run into. I have added following line to display image, but it won't works.
<img src="Images/article.gif" />


Resolve Problem, by refrencing file from root.
<img src="../Images/article.gif" />

ASP.NET appSettings Cache


You want to improve the performance of the appSettings in ASP.NET using site-wide caching. Retrieving application settings in ASP.NET is needlessly slow. Here we see how you can cache your appSettings values in the C# programming language, and why it is faster.

Static caches

Here is an optimization that not only makes the code 30 times faster, but also allows better code separation and clarity. We will use ASP.NET global variables. Here are the settings in Web.config.
Web.config appSettings keys [XML]

<?xml version="1.0"?>
<configuration>
    <appSettings>
 <add key="SiteTitle" value="The New York Times - Breaking News..."/>
 <add key="SitePrefix" value=NYT/>
 <add key="SiteHeader" value="Breaking News, World News & Mutimedia"/>
 <add key="BaseUrl" value=http://nytimes.com//>
    </appSettings>

Encapsulate settings

Using properties is ideal for these appSettings. My first appSettings article demonstrates this, but the properties are slow because they cause repeated NameValueCollection lookups. We can make a new class in App_Code, and fill it as follows.
SiteGlobal class that caches appSettings [C#]

using System;
using System.Web;
using System.Web.Configuration;

public static class SiteGlobal
{
    /// <summary>
    /// Full site title tag at root.
    /// </summary>
    static public string RootTitle { get; set; }

    /// <summary>
    /// Header prefix on root page.
    /// </summary>
    static public string RootPrefix { get; set; }

    /// <summary>
    /// Header main part on root page.
    /// </summary>
    static public string RootHeader { get; set; }

    /// <summary>
    /// Main site Url with http://.
    /// </summary>
    static public string BaseUrl { get; set; }

    static SiteGlobal()
    {
 // Cache all these values in static properties.
 RootTitle = WebConfigurationManager.AppSettings["SiteTitle"];
 RootPrefix = WebConfigurationManager.AppSettings["SitePrefix"];
 RootHeader = WebConfigurationManager.AppSettings["SiteHeader"];
 BaseUrl = WebConfigurationManager.AppSettings["BaseUrl"];
    }
}
Using static classes. Static classes are useful for holding static methods and enforce code correctness. There is a static constructor that sets the properties. When the ASP.NET AppDomain for this site is initialized the properties will be accessed and cached. It has static public properties. Properties can be static just like variables and methods. These properties can be accessed without a class instance.

Access cached values

Now we can simply call into the SiteGlobal class and use the properties there for access to the appSettings. Using the cached values is 30 times faster, and will reduce memory pressure.
Example Page_Load event handler [C#]

protected void Page_Load(object sender, EventArgs e)
{
    Title1.Text = SiteGlobal.RootTitle;
    Prefix1.InnerHtml = SiteGlobal.RootPrefix;
    Header1.InnerHtml = SiteGlobal.RootHeader;
}

Summary

We saw how you can cache appSettings in ASP.NET with a static class and static properties. This provides clearer code and also improves performance. This will cut milliseconds off of your page load times and, when averaged over thousands of visitors, will reduce your power costs.

ASP.NET MapPath Resolves Virtual, Physical Paths


You need to use MapPath to resolve virtual paths and physical paths. You run the ASP.NET development server on your local machine, but the paths on it are not the same as they are on your server. Here we use MapPath to find physical paths and file locations, using the C# programming language.

Understand MapPath

First, in ASP.NET the ~ tilde indicates the root of a virtual path. We need the tilde because otherwise ASP.NET can't figure out if a path is absolute or relative. Let's look at some virtual paths and what they might map to.
Virtual paths

~/App_Data/Sample.xml
~/
~/Map.txt

Physical paths

C:\Website\Files\Sample.xml
C:\Website\Default.aspx
C:\Website\Map.txt

Use MapPath method

You can call MapPath in any C# file in your ASP.NET website. You may want to include the System.Web namespace first, but this is not required. Make sure you are looking at a C# file in your ASP.NET project and then add some code that looks similar to parts of the following.
Example code that uses MapPath [C#]

using System;
using System.Web;

/// <summary>
/// This is an example code-behind file you can put in App_Code.
/// It shows examples of using MapPath in code-behind easily.
/// </summary>
public class Example
{
    public Example()
    {
 // This will locate the Example.xml file in the App_Data folder.
 // ... (App_Data is a good place to put data files.)
 string a = HttpContext.Current.Server.MapPath("~/App_Data/Example.xml");

 // This will locate the Example.txt file in the root directory.
 // ... This can be used in a file in any directory in the application.
 string b = HttpContext.Current.Request.MapPath("~/Example.txt");
    }
}
Using Server.MapPath. Here we note that the Server.MapPath does the same thing as the Request.MapPath method. In this example, the two versions will do the same thing. There may be some differences in different usage scenarios, but in those cases a more detailed guide would be helpful. The two methods are interchangeable in most ASP.NET projects.

XML files

Here we note that you can use the MapPath method to access many different paths on the server. There is an entire article here about XElement examples. XElement is an XML object that can open a file, much like StreamReader.
XElement Example

Virtual hosts security

Here we note that if you are using a virtual shared host, there may be problems in your code related to file permissions and security checks. The problem may not be MapPath at all. MapPath is very simple and unless you have a typo in the argument, it won't cause you any problems.

Performance

Here we mention that MapPath performance is over 1000 times slower than a simple string append. Therefore, it could be worthwhile to cache the paths, in a technique similar to that in my article about appSettings caches.
appSettings Cache

Summary

Here we looked at the MapPath method in the C# programming language. MapPath is a method that resolves virtual paths to machine paths. It has great utility for XML and some other data files. It can work as a bridge between website-specific virtual paths, and a physical path that most .NET I/O methods will require.

Sunday, June 12, 2011

Best Free available wysiwyg html editor

As a developer, i suggest two editor is giving complete copetance to give features those are given at licensed or paid editor controls. :-)


1. CKEditor
2. TinyMCE