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

WYSIWYG Rich Editor Controls for ASP.NET



·  RadEditor (Telerik). AJAX-enabled.
·  WebHtmlEditor (Infragistics). Part of the NetAdvantage for ASP.NET suite (I think).
·  Cute Editor (CuteSoft)
·  FreeTextBox (FreeTextBox.com). Free for basic edition. Source code available (for a price).
·  Peter's Textboxes (Peter Blum). Suite of enhanced text box controls.
·  UltimateEditor (Karamasoft)
·  AspLib Component library (Astron Digital). Includes a WYSIWYG editor, among other things.
·  ASPxHtmlEditor Suite (DevExpress)
·  EditLive! (Ephox)
·  eWebEditor (eWebEditor)
·  eWebEditPro (Ektron)
·  InnovaStudio WYSIWYG Editor (InnovaStudio)
·  FCKeditor (FredCK.com)
·  Html TextBox (ActiveUp). Part of the ActiveUp.WebControls suite.
·  pinEdit (Pintexx)
·  RichTextBox (aspControls)
·  RichTextEditor (Syncfusion)
·  RTE ASP.NET Control. Released under an MS-PL license on CodePlex. Includes source.
·  SmartText (Z-SoftNet)
·  soEditor (SiteObjects).
·  SPAW Editor v.2 (Solmetra)
·  TinyMCE (Moxiecode). JavaScript based; open source under LGPL.
·  Ueditor (Yardi). Free; source and restribution for a price.
·  WebHtmlEdit Control (JitBit Software)