Facebook Twitter Delicious Stumble Upon
0 comments

Url rewriting using global.asax

To rewrite the url only using asax file like www.domain.com/items.aspx?ID=1
to 
www.domain.com/fackurl.aspx?ID=1 Add the below content in the Global.asax file

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext myContext = HttpContext.Current;
    Regex rewrite_regex = new Regex(@"(.+)\/((.+)\.aspx)", RegexOptions.IgnoreCase);
    try
    {
        //see if we need to rewrite the URL
        Match match_rewrite = rewrite_regex.Match(myContext.Request.Path.ToString());
        if (match_rewrite.Groups[2].Captures[0].ToString() == "Default.aspx")
        {
            if (Request.QueryString["ID"] != null)
                myContext.RewritePath("~/Mail/Index.aspx?ID=" + Request.QueryString["ID"].ToString(), true);
        }
    }
    catch (Exception ex) { }
}

Tags: url rewriting in asp.net sample code, url rewriting using global.asax asp net, url rewriting with global.asax, url rewriting using global.asax asp net
0 comments

URL Rewriting in ASP.NET 2.0

In order to rewrite the url called www.domain.com/myfolder/items.aspx?Item_ID=1 to
www.domain.com/items/1 or www.domain.com/items/1.html or www.domain.com/items/1.aspx follow the steps


1. Create an xml file under root directory named as Rule.xml and write this code


<?xml version="1.0" encoding="utf-8" ?>
<urlrewrites>
  <rule>
    <url>item/(.*)</url>
    <rewrite>myfolder/items.aspx?Item_ID=$1</rewrite>
  </rule>
  <rule>
    <url>item/(.*)\.html</url>
    <rewrite>myfolder/items.aspx?Item_ID=$1</rewrite>
  </rule>
  <rule>
    <url>item/(.*)\.aspx</url>
    <rewrite>myfolder/items.aspx?Item_ID=$1</rewrite>
  </rule>
  <rule>
    <url>Products/Cart/(.*)\.aspx</url>
    <rewrite>Cart.aspx?ID=$1</rewrite>
  </rule>
</urlrewrites>


2. Add the below content in the Global.asax file


void Application_BeginRequest(Object sender, EventArgs e)
{
    string sPath = Context.Request.Path;//To overcome Postback issues, stored the real URL.
    Context.Items["VirtualURL"] = sPath;
    Regex oReg;
    System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
    xmlDoc.Load(Server.MapPath("~/Rule.xml"));
    foreach (System.Xml.XmlNode oNode in xmlDoc.DocumentElement.SelectNodes("rule"))
    {
        oReg = new Regex(oNode.SelectSingleNode("url/text()").Value);
        Match oMatch = oReg.Match(sPath); if (oMatch.Success)
        {
            sPath = oReg.Replace(sPath, oNode.SelectSingleNode("rewrite/text()").Value); break;
        }
    }
    Context.RewritePath(sPath);
}

3. Create a class file named as Form.cs and paste this code


using System;
using System.Web.UI;
using System.Web;

public class FormRewriterControlAdapter : System.Web.UI.Adapters.ControlAdapter
{
    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        base.Render(new RewriteFormHtmlTextWriter(writer));
    }
}

public class RewriteFormHtmlTextWriter : HtmlTextWriter
{

    public RewriteFormHtmlTextWriter(HtmlTextWriter writer)
        : base(writer)
    {
        this.InnerWriter = writer.InnerWriter;
    }

    public RewriteFormHtmlTextWriter(System.IO.TextWriter writer)
        : base(writer)
    {
        base.InnerWriter = writer;
    }

    public override void WriteAttribute(string name, string value, bool fEncode)
    {
        // If the attribute we are writing is the "action" attribute, and we are not on a sub-control, 
        // then replace the value to write with the raw URL of the request - which ensures that we'll 
        // preserve the PathInfo value on postback scenarios 
        if ((name == "action"))
        {
            HttpContext Context = default(HttpContext);
            Context = HttpContext.Current;
            if (Context.Items["ActionAlreadyWritten"] == null)
            {
                // Because we are using the UrlRewriting.net HttpModule, we will use the 
                // Request.RawUrl property within ASP.NET to retrieve the origional URL 
                // before it was re-written. You'll want to change the line of code below 
                // if you use a different URL rewriting implementation. 
                value = Context.Request.RawUrl;
                // Indicate that we've already rewritten the 
's action attribute to prevent 
                // us from rewriting a sub-control under the control 
                Context.Items["ActionAlreadyWritten"] = true;
            }
        }
        base.WriteAttribute(name, value, fEncode);
    }
}


4. Write this line of code in every page which you want mask the url

protected override void Render(HtmlTextWriter writer)
{
    if (HttpContext.Current.Items["VirtualURL"] != null)
    {
        string sVirURL = HttpContext.Current.Items["VirtualURL"].ToString();
        RewriteFormHtmlTextWriter oWriter = new RewriteFormHtmlTextWriter(writer);//, sVirURL);
        base.Render(oWriter);
    }
}

5. To use this <a href="item/1">Mouse</a>




6. In items.aspx use like this


if (!IsPostBack)
   if (Request.QueryString["Item_ID"] != null)
 string id = Request.QueryString["Item_ID"].ToString();



Tags: URL Rewriting in ASP.NET 2.0,URL Rewriting with ASP.NET 2.0,url rewriting in asp.net,url rewriting, asp.net url rewriting example, url rewriting sample project,url rewriting in asp.net sample code
0 comments

How to pragmatically retrieve smtp server details from web.config file


Saving the smtp details in web.config file like this:


<system.net>

<mailSettings>

<smtp from="username@gmail.com">

<network host="smtp.gmail.com" port="587" userName="username@gmail.com" password="password" defaultCredentials="true"/>

</smtp>

</mailSettings>

</system.net>


and retrieving the smtp detail in cs file follow like this:  


SmtpSection MailSettings = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

if (settings != null)
{
    string From = MailSettings.From;
    int Port = MailSettings.Network.Port;
    string Host = MailSettings.Network.Host;
    string Password = MailSettings.Network.Password;
    string UserName = MailSettings.Network.UserName;
}



Tags: Smtp server details from web.config file, gmail smtp settings in web.config file







0 comments

Downloading Images from external url


string imgFullPath = "https://www.google.co.in/images/srpr/logo3w.png";

//get the full path 

string FileName = Path.GetFileNameWithoutExtension(imgFullPath) + Path.GetExtension(imgFullPath);

//if you want you can download image in your desired extension 


WebClient wc = new WebClient();

wc.DownloadFile(imgFullPath, Server.MapPath("~/images/temp/") + FileName);

//download the file in images location


FileStream fs = new FileStream(Server.MapPath("~/images/temp/" + FileName), FileMode.Open, FileAccess.Read, FileShare.Read);

//get the image in file stream


System.Drawing.Image nwImage = System.Drawing.Image.FromStream(fs);

//Now using this nwImage you can resize the image 


nwImage.Save(Server.MapPath("~/images/") + "your_own_image_name.extension");

File.Delete(Server.MapPath("~/images/temp/" + FileName));

//if no needed the original image delete the file using this



Tages: Downloading images from external url, resizing root folder images, downloading images from path,
0 comments

Allow only numbers in textbox using javascript

Use the following code:

function AllowNumsOnly(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
 else
        return true;
}

<asp:TextBox ID="txt_Qty" runat="server" onkeypress="return AllowNumsOnly(event);"></asp:TextBox>

Tag: Allow only numbers in textbox using javascript,allow numbers only onkeypress