DotNet Friends

October 2, 2009

URL rewriting in asp.net

what is URL rewriting ?

URL rewriting is the process of intercepting an incoming Web request and redirecting the request to a different resource. When performing URL rewriting, typically the URL being requested is checked and, based on its value, the request is redirected to a different URL.

http://msdn.microsoft.com/en-us/library/ms972974.aspx 

why URL rewriting?

1) Make User Friendly and Secure URL

Example :  In your application, you create a page which display category information and it’s relevant category. At that time we normally passing a value via query string,

http://Site.com/category.aspx?categoryid=1. Any user play with URL, you can also do the URL Encryption. but sometime case is complex at that time it is not possible.

2) Make SEO Friendly URL

3) Usability & Maintainability

Use Of Browser file?

ASP.NET uses .browser files to determine the capabilities of the browser, and how to render markup to that browser.

Browser files are used to reduce the load of the page made by the view state by storing it in a server side session variable.

In particular Rewriting Module: Handling Post back with URL Rewriting.

what is ControlAdapter?

for more detail please check :

http://msdn.microsoft.com/en-us/library/system.web.ui.adapters.controladapter.aspx

Create demo project for URL Rewriting:

Step 1:

Create Web application with (Asp.net 2.0 with c#)

Step 2:

Put two button in the form (default.aspx)

Put Below code for Button1_Click Event :

Response.Redirect("Default.aspx?id=1");

Put Below code for Button2 _Click Event:

Response.Redirect("/urlrewriting/FirstSection/Default.html");

Step 3: Run Application

once you press Button2 it give Error page.

Step 4:

Create Class FormRewriterControlAdapter.cs

   1: using System;

   2: using System.Data;

   3: using System.Configuration;

   4: using System.Web;

   5: using System.Web.Security;

   6: using System.Web.UI;

   7: using System.Web.UI.WebControls;

   8: using System.Web.UI.WebControls.WebParts;

   9: using System.Web.UI.HtmlControls;

  10:  

  11: public class FormRewriterControlAdapter : System.Web.UI.Adapters.ControlAdapter

  12: {

  13:     protected override void Render(HtmlTextWriter writer)

  14:     {

  15:         base.Render(new RewriteFormHtmlTextWriter(writer));

  16:     }

  17: }

  18:  

  19: public class RewriteFormHtmlTextWriter : HtmlTextWriter

  20: {

  21:     public RewriteFormHtmlTextWriter(HtmlTextWriter writer)

  22:         : base(writer)

  23:     {

  24:         this.InnerWriter = writer.InnerWriter;

  25:     }

  26:  

  27:     public RewriteFormHtmlTextWriter(System.IO.TextWriter writer)

  28:         : base(writer)

  29:     {

  30:         base.InnerWriter = writer;

  31:     }

  32:  

  33:     public override void WriteAttribute(string name, string value, bool fEncode)

  34:     {

  35:         if (name == "action")

  36:         {

  37:             HttpContext Context = HttpContext.Current;

  38:             if (Context.Items["ActionAlreadyWritten"] == null)

  39:             {

  40:                 value = Context.Request.RawUrl;

  41:                 Context.Items["ActionAlreadyWritten"] = true;

  42:             }

  43:         }

  44:         base.WriteAttribute(name, value, fEncode);

  45:     }

  46: } 

 

Create Class MyHttpHandler.cs

   1: using System;

   2: using System.Data;

   3: using System.Configuration;

   4: using System.Web;

   5: using System.Web.Security;

   6: using System.Web.UI;

   7: using System.Web.UI.WebControls;

   8: using System.Web.UI.WebControls.WebParts;

   9: using System.Web.UI.HtmlControls;

  10:  

  11: public class MyHttpHandler : IHttpModule

  12:  

  13: {

  14:     public MyHttpHandler()

  15:     {

  16:         //

  17:         // TODO: Add constructor logic here

  18:         //

  19:     }

  20:  

  21:     #region IHttpModule Members

  22:  

  23:     public void Dispose()

  24:     {

  25:        

  26:     }

  27:  

  28:     public void Init(HttpApplication app)

  29:     {

  30:         app.BeginRequest += new EventHandler(Application_BeginRequest);

  31:     }

  32:  

  33:     private void Application_BeginRequest(object sender, EventArgs e)

  34:     {

  35:         System.Web.HttpApplication app = (System.Web.HttpApplication)sender;

  36:         string requestedUrl = app.Request.Path.ToLower();

  37:         string realUrl = GetRealUrl(requestedUrl);

  38:         if (!String.IsNullOrEmpty(realUrl))

  39:             app.Context.RewritePath(realUrl, false);

  40:     }

  41:  

  42:     private string GetRealUrl(string requestedUrl)

  43:     {

  44:         // Implement your own logic here

  45:         MyURL obj = new MyURL();

  46:         return obj.GetRealPath(requestedUrl);

  47:     } 

  48:     #endregion

  49: }

 

create Class MyURL.cs

   1:  

   2: using System;

   3: using System.Data;

   4: using System.Configuration;

   5: using System.Web;

   6: using System.Web.Security;

   7: using System.Web.UI;

   8: using System.Web.UI.WebControls;

   9: using System.Web.UI.WebControls.WebParts;

  10: using System.Web.UI.HtmlControls;

  11: using System.Collections.Generic;

  12:  

  13: /// <summary>

  14: /// Summary description for MyURL

  15: /// </summary>

  16: public class MyURL

  17: {

  18:     public MyURL()

  19:     {

  20:         //

  21:         // TODO: Add constructor logic here

  22:         //

  23:     }

  24:  

  25:     public string GetRealPath(string requestedUrl)

  26:     {

  27:         string path = "";

  28:         Dictionary<string, string> paths = GetPathsFromDatabase();

  29:         if (paths.ContainsKey(requestedUrl))

  30:             paths.TryGetValue(requestedUrl, out path);

  31:         return path;

  32:     }

  33:  

  34:     private static Dictionary<string, string> GetPathsFromDatabase()

  35:     {

  36:         Dictionary<string, string> paths = new Dictionary<string, string>();

  37:         paths.Add("/urlrewriting/FirstSection/Default.html".ToLower(), "/urlrewriting/Default.aspx?SectionID=1");

  38:         paths.Add("/urlrewriting/SecondSection/Default.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=2");

  39:         paths.Add("/urlrewriting/FirstSection/Page1.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=1&Item=1");

  40:         paths.Add("/urlrewriting/FirstSection/Page2.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=1&Item=2");

  41:         paths.Add("/urlrewriting/SecondSection/Page1.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=2&Item=1");

  42:         paths.Add("/urlrewriting/SecondSection/SubSection/AnotherOne/Page5.aspx".ToLower(), "/urlrewriting/Default.aspx?SectionID=2&Item=5");

  43:         paths.Add("/urlrewriting/Default.aspx".ToLower(), "/urlrewriting/Default.aspx");

  44:         return paths;

  45:     } 

  46: }

Register Http Handler in to Web.Config

   1: <system.web>

   2:         <httpModules>

   3:             <add name="MyHttpHandler" type="MyHttpHandler"/>

.Browser File

Add New .browser file from Add New Item.

   1: <browsers>

   2:     <browser id="NewBrowser" parentID="Mozilla">

   3:         <identification>

   4:             <userAgent match="Unique User Agent Regular Expression" />

   5:         </identification>

   6:  

   7:         <capture>

   8:             <userAgent match="NewBrowser (?'version'\d+\.\d+)" />

   9:         </capture>

  10:  

  11:         <capabilities>

  12:             <capability name="browser" value="My New Browser" />

  13:             <capability name="version" value="${version}" />

  14:         </capabilities>

  15:     </browser>

  16:  

  17:     <browser refID="Mozilla">

  18:         <capabilities>

  19:             <capability name="xml" value="true" />

  20:         </capabilities>

  21:     </browser>

  22: <!--FormRewrite Control Adapter-->

  23:     <browser refID="Default">

  24:         <controlAdapters>

  25:             <adapter controlType="System.Web.UI.HtmlControls.HtmlForm"

  26:                 adapterType="FormRewriterControlAdapter" />

  27:         </controlAdapters>

  28:     </browser>

  29: </browsers>

step 5: Run Application

Now Press Button 2:

http://localhost:2696/urlrewriting/FirstSection/Default.html and it is run.

 

Now made some change in to system. Remove browser file and click button2, after that made postback at that time above URL is change to original URL.

Reference Site :

For Detail Example :

http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

 

Hope this help you.

Thnx

 

August 28, 2009

PDF Viewer in asp.net

Filed under: Asp.Net 2.0, C#.net, dotnet — Tags: , — patriwala @ 1:49 pm

Here I am explaining how to create PDF Viewer in asp.net.

iPaper in asp.net

Steps:

1) create Class Library Project Here I am give name OnlinePdfViewer. Here I am using c#.net. Write below code in to file.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OnlinePdfViewer
{
    public class DisplayPdf : WebControl
    {
        private string _filepath;
        public string FilePath
        {
            get
            {
                return _filepath;
            }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    _filepath = string.Empty;
                }
                else
                {
                    int tild = -1;
                    //check ~ symbol including in pdf path then remove
                    tild = value.IndexOf('~');
                    if (tild != -1)
                    {
                        _filepath = value.Substring((tild + 2)).Trim();
                    }
                    else
                    {
                        _filepath = value;
                    }
                }
            }
        }   

        protected override void RenderContents(HtmlTextWriter writer)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<iframe src=" + Convert.ToString(FilePath) + " ");
                //fix height and width
                sb.Append("width=800px height=500px");
                sb.Append("<View PDF: <a href=" + Convert.ToString(FilePath) + "</a></p> ");
                sb.Append("</iframe>");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                writer.Write(Convert.ToString(sb));
                writer.RenderEndTag();
            }
            catch
            {
                //If any problem in the PDF at that time display below information
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                writer.Write("PDF Control...");
                writer.RenderEndTag();
            }
        }
    }
}      

2) Run the project it generate dll –> OnlinePdfViewer.dll.

3) Create New Web Application give name – DemoPDFViewer.I have create application in asp.net with c#.

    Here I have create demo application In application User can upload PDF and View uploaded PDF in PDF viewer.

3.1) Add the Reference of OnlinePdfViewer.dll into Site.

3.2) Make PDF folder into Site.

3.3) Upload PDF Functionality

ASPX Code :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="OnlinePdfViewer" Namespace="OnlinePdfViewer" TagPrefix="PdfViewer" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>PDF View Online</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <center>
            <table>
                <tr>
                    <td colspan="2" align="center" style="font-family: Verdana; font-size: larger">
                        Online PDF Viewer
                    </td>
                </tr>
                <tr>
                    <td>
                        Upload PDF File
                    </td>
                    <td>
                        <asp:FileUpload ID="fup" runat="server" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="lblMsg" runat="server" ViewStateMode="Disabled" Font-Bold="true" ForeColor="Red"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <asp:Button ID="btnView" Text="View PDF" runat="server" Visible="false" OnClick="btnView_Click" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2" id="pnlPDFViewer" visible="false" runat="server">
                        <asp:HyperLink ID="HyperLink1" runat="server">Open PDF into New Page</asp:HyperLink>
                        <br />
                        <PdfViewer:DisplayPdf ID="displaypdf1" runat="server" BorderStyle="Inset" BorderWidth="2px"
                            Style="height: 500px;" Width="800px" />
                    </td>
                </tr>
            </table>
        </center>
    </div>
    </form>
</body>
</html>

CS Code:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

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

    }

    public string Uploadedfilename { get { return Convert.ToString(ViewState["filename"]); } set { ViewState["filename"] = value; } }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (fup.HasFile)
        {
            string strFilePath = Server.MapPath("PDF") + "\\";
            Uploadedfilename = Convert.ToString(Guid.NewGuid()) + ".pdf";
            strFilePath = strFilePath + Uploadedfilename;
            fup.SaveAs(strFilePath);
            lblMsg.ForeColor = Color.Blue;
            lblMsg.Text = "PDF File Upload Successfully";
            btnView.Visible = true;
        }
        else
        {
            lblMsg.Text = "Please Upload PDF File";
        }
    }
    protected void btnView_Click(object sender, EventArgs e)
    {
        pnlPDFViewer.Visible = true;
        displaypdf1.FilePath = @"~/pdf/" + Uploadedfilename;
        HyperLink1.NavigateUrl = @"~/pdf/" + Uploadedfilename;
    }
}

4) compile code and run application.

 

thnx

December 3, 2008

Convert Generic List In To DataTable

Create simple asp.net application with C#. Add new class (GenericToDataTable).

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

public class GenericToDataTable
{
/// <summary>
/// Default Constructor
/// </summary>
private GenericToDataTable()
{ }
/// <summary>
///
/// </summary>
/// <typeparam name=”T”>Custome Class </typeparam>
/// <param name=”lst”>List Of The Custome Class</param>
/// <returns> Return the class datatbl </returns>
public static DataTable ConvertTo<T>(IList<T> lst)
{
//create DataTable Structure
DataTable tbl = CreateTable<T>();
Type entType = typeof(T);

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
//get the list item and add into the list
foreach (T item in lst)
{
DataRow row = tbl.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
tbl.Rows.Add(row);
}

return tbl;
}

/// <summary>
///
/// </summary>
/// <typeparam name=”T”>Custome Class</typeparam>
/// <returns></returns>
public static DataTable CreateTable<T>()
{
//T –> ClassName
Type entType = typeof(T);
//set the datatable name as class name
DataTable tbl = new DataTable(entType.Name);
//get the property list
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
foreach (PropertyDescriptor prop in properties)
{
//add property as column
tbl.Columns.Add(prop.Name, prop.PropertyType);
}
return tbl;
}
}

after add above class compile the code.

after compilation add new class into project (Class Name: clsUser).

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for clsUser
/// </summary>
public class clsUser
{
//create property userid
private int _UserId;
public int UserID
{
get { return _UserId; }
set { _UserId = value; }
}
//create property username
private string _UserName;
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
/// <summary>
/// Default Constructor
/// </summary>
public clsUser()
{ }

public clsUser(int userid,string username)
{
this.UserID = userid;
this.UserName = username;
}
}

After adding this class into project go to Default.aspx page in this page type below code on Page Load event.

//create generic list of class clsUser
System.Collections.Generic.List<clsUser> obj = new
System.Collections.Generic.List<clsUser>();
//add data into list
for (int i = 0; i < 10; i++)
{
obj.Add(new clsUser(i,”a”+i.ToString()));
}
//convert list to datatable
DataTable dt= GenericToDataTable.ConvertTo<clsUser>(obj);

now check the DataTable(dt).

thnx

September 20, 2008

find not working in visual studio

Filed under: dotnet — Tags: — patriwala @ 6:12 pm

Find option is not working in the visual studio environment. solved this issue follow the below steps.

steps :

1) open the visual studio in safe mode using command devenv/safemode

go to command prompt and type your visual studio path. in my pc is

” C:\Program Files\Microsoft Visual Studio 8\Common7\IDE “

run above code and check.

it work then the problem either the cause should be third-party applications, services or Visual Studio Add-ins.

if find is not working yet then follow the 2nd step.

2) open the command prompt and type your visual studio path. in my pc is

” C:\Program Files\Microsoft Visual Studio 8\Common7\IDE “

type below code : devenv /resetsettings

this command is Restores Visual Studio default settings.

now check in the Visual Studio.

Thnx

September 14, 2008

September 10, 2008

Encrypt Sections Of Web.Config File in ASP.NET 2.0

1) why the need of Encryption in Web.Config File?

We know that Web.Config file hold sensitive information like (Database server name , user name,password ect). In any database related application the database is more important.Β  if you do not protect database related information from malicious user or hacker sometime it create a danger situation for anyone.

below are the sections which hold the sensitive data.

1) appSettings

2) connectionStrings

3) SessionState

In dotnet Framework 2.0 introduced a protected configuration feature that allows you to encrypt sensitive data. you can configure file data using command line tool.which is describe below in detail.

There are two protected configuration providers are included.

1) RSAProtectedConfigurationProvider (default)

2) DataProtectionConfigurationProvider (Data Protection application programming interface)

  • Encrypt the connectionStrings section in Web.config

Steps :

1) create web application using (asp.net with c#).

2) Add the web.config file in your created application. add connection string in the web.config file.

   1: <connectionStrings>
   2:     <add name="mycon" connectionString="Data Source=.\sqlexpress;Initial Catalog=tempdb;uid=sa;pwd:sa007"/>
   3:   </connectionStrings>

or

   1: <connectionStrings>
   2:    <add name="mycon" connectionString="Data Source=.\sqlexpress;Initial Catalog=tempdb;Integrated Security=True"/>
   3:  </connectionStrings>

3) now here is the two possibility either you use the VS.net 2005 or Configure application as virtual Directory.

case 1 (configured application as virtual directory)

aspnet_regiis -pe “connectionStrings” -app “/Your Application Name” -prov “DataProtectionConfigurationProvider”

case 2 VS.net 2005

aspnet_regiis.exe -pef “connectionStrings” YOUR Application Path –prov “DataProtectionConfigurationProvider”

Description : aspnet_regiis.exe (%windir%\Microsoft.Net\Framework\ Dotnet Version)
Options :
1) -pe : switch specifies the configuration section to encrypt.
2) -pef : physical path for your configuration file
3) -app your web application's virtual path.
4) -prov provider name
4) run above code result will be.
Β  image
5) check the web.config file.
   1:    <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
   2:      <EncryptedData>
   3:        <CipherData>
   4:          <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAjADWCXozG0u/o7BY2jzY0gQAAAACAAAAAAADZgAAqAAAABAAAADW4TyTJUuqAbIF+Hj1hlQ6AAAAAASAAACgAAAAEAAAALatNmZNNiKQeIdh/ns863VAAQAA5e6qwI4+JVZB/bL5xmHOLyewcO9pp2sc8vtcDT4ZNwK+oHDq//zsfL+cf6FDlgv++bJcXETNPl8TQ4fEqYaP8pHrim3QkFCf59B3q3tAKR9bvXvNJaUmCixcKQopPPwDH5lvmsXawT6gxNpSDqMz+4vBGN63U1oXCRn2dUpC9DxesEhgh4X5uZuCBSxjvsQM2G97mIwbFUPh8LwTSRoeiPdVz8oycnZQiO7AKpNmshpnOvjTIMQYArQyFR1IQA8DTE7qWf95Ciqapa+Kq7NInVNc/5cuYaP0+0jJBPYUw/mWpRYKD1KAUdRPpdQO6QSbVC/lK/m2Vb7OPL78M/gT07TIKTKleIjaN90wgDVaETW06o5hcSNbTZb6OudrZAw+0/uFZbxxKFQZpK5WAKl68IJzfO0YSi67EDeGPyPXCQcUAAAA26tsHR9708+5EFpzAjeFgAnHBNQ=</CipherValue>
   5:        </CipherData>
   6:      </EncryptedData>
   7:    </connectionStrings>
6) in the your page (default.aspx) put below code
Response.Write("Connection String Is " +ConfigurationManager.ConnectionStrings["mycon"].ConnectionString);
7) Run Application Check Result
image

i hope that above code is worked. now if you want to change connection string then what to do?
steps :
1)

case 1 (configured application as virtual directory)

   aspnet_regiis -pd "connectionStrings" -app "Your Application Name"

case 2 VS.net 2005

   aspnet_regiis -pdf "connectionStrings" Your Application Path
2) Result of Executed code
image
3) check the web.config file.

thnx

Transfer Session Variable From ASP To ASP.Net 2.0

you can transfer you asp session to asp.net session. here i give small demo for that.

steps:

1) create asp page (mypage.asp)

   1:
   2: <%@LANGUAGE="Vbscript" CODEPAGE="1252"%>
   3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4: <html xmlns="http://www.w3.org/1999/xhtml">
   5: <head>
   6: <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   7: <title>Untitled Document</title>
   8: </head>
   9: <form name='form1' action='login.asp' method='post'>
  10: User Name : <input type='text' name='username'>
  11: <br>
  12: <input type='submit' value="Login">
  13: </form>
  14: <body>
  15: </body>
  16: </html>

2) create second asp page (login.asp)

   1: <%
   1:
   2: If Request.Form("username") = "" then
   3:     Response.Write("Login Failed.<br><br>")
   4: else
   5:      Response.Write("Transfer Session in To Hidden Field")
   6:     ' create asp session user here
   7:      Session("user") =Request.Form("username")
   8:      ' in the form action go to the aspx page called default.aspx
   9:      Response.Write("<form name='form1' id='form1' action='Default.aspx' method='post' >")
  10:
  11:      For each Item in Session.Contents
  12:         Response.Write("<input type=hidden name=" & Item)
  13:         Response.Write( " value=" & Session.Contents(item) & " >")
  14:      next
  15:      Response.Write("</FORM>")
  16:
  17:      Response.Write("<script>form1.submit();</script>")
  18: End If

%>

3) create aspx page with (asp.net with c#)

   1: <%@ Page Language="C#" %>
   2:
   3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4:
   5: <script runat="server">
   1:
   2:     protected void Button1_Click(object sender, EventArgs e)
   3:     {
   4:         //redirect to asp page
   5:         Response.Redirect("myasp.asp");
   6:     }
   7:     protected void Page_Load(object sender, EventArgs e)
   8:     {
   9:         //get the Request 
  10:         for (int i = 0; i < Request.Form.Count; i++)
  11:         {
  12:             //transfer value
  13:             Session[Request.Form.GetKey(i)] = Request.Form[i].ToString();
  14:         }
  15:         //check the session
  16:         if (Session["user"] != null)
  17:         {
  18:             Response.Write("Hi " + Session["user"].ToString());
  19:         }
  20:     }

</script>

   6:
   7: <html xmlns="http://www.w3.org/1999/xhtml" >
   8: <head runat="server">
   9:     <title>ASPX Page</title>
  10: </head>
  11: <body>
  12:     <form id="form1" runat="server">
  13:     <div>
  14:         <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
  15:     </form>
  16: </body>
  17: </html>

4) now start the application start page is (mypage.asp).

click on the login button it will go to login.asp page.

in the login.asp page session is create Session(“user”) =Request.Form(“username”)

if login is success then page is go to the default.asp.

on the default.aspx page load event

//get the Request

for (int i = 0; i < Request.Form.Count; i++)

{

//transfer value

Session[Request.Form.GetKey(i)] = Request.Form[i].ToString();

}

thnx

September 6, 2008

Embedding Resources in ASP.Net 2.0

Filed under: Asp.Net 2.0, C#.net, dotnet — Tags: — patriwala @ 5:40 am
  • embed resources

let’s start with the very basicΒ if iΒ tell youΒ create the customize control (inherit the Textbox and create new Textbox MyTextBox) .

in other wordΒ youΒ  can create customize textbox with three condition

1) Upper Case : when user selected Upper Case all enter input converted into Upper Character.

2) Lower Case : when user selected Lower Case all enter input converted into Lower Character.

3) None :Β  nothing to do.

now what can you do?

i am explain from my level.

1. i writen java script in the customizeΒ class.

2. i create java script and put that java script into my webapplication. i only written related function name in customize class.

above method is good but i face some problem which i explaining

1) in class i have written javascript which code is very long and unmanged from my site and the main thing is when small change occure i findΒ into that much of code and replace and build that application.

2) in external javascript you added that javascript into the web application (this method is reallyΒ good but some time if we not added that javascript then we are in trouble).

in both of the case java script is readable i have to find that thing one java script easy to manage and second thing not readable.

now i m check that thing in to the embed resourceΒ application.

  • Benifit Of embed resources :

1)Β manage allΒ your dependencies into one single assembly likeΒ you identify the some stuff which are need in the application every time (like your company logo image,your company profile information).

2) especially javascript is not readable.

Steps :

1) create ClassLibrary Project In Visual Studio (Open –> File –> Project –> Class Library in C# Tag). give project Name : MyResource

2) Add Reference (go to Solution ExploreΒ –> Right Click On Reference –> select Add Reference).

2.1) select System.Web

3) change the Class Name MyTextBox

4) Inherite the TextBox Class in MyTextBox Class.

   1: public class MyTextBox : System.Web.UI.WebControls.TextBox

5) create Textbox which has different mode like when user select

1) upper then what ever they typed convered into upper

2) Lower then what ever they typed converted into lower

3) None nothing

now the main thing if you want toΒ implement this then you want a create Java Script for this.

now add Java Script in to project.give a name MyJs.Js.

6) now Right Click On Added JavaScript and Select Property. change the Build Action –> Embedded Resource.

7) Add the Below Code in to MyTextBox Class.

   1: //enum for selection
   2:         public enum TextType
   3:         {
   4:             UpperCase,
   5:             LowerCase,
   6:             None
   7:         }
   8:
   9:         //property TextStyle
  10:         private TextType _TextStyle;
  11:         public TextType TextStyle
  12:         {
  13:             get { return _TextStyle; }
  14:             set { _TextStyle = value; }
  15:         }
  16:
  17:         public MyTextBox()
  18:         {
  19:
  20:         }
  21:
  22:         /// <summary>
  23:         /// 
  24:         /// </summary>
  25:         /// <param name="writer"></param>
  26:         protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
  27:         {
  28:             //add the attribute to in
  29:             if (this.TextStyle == TextType.LowerCase)
  30:             {
  31:                 writer.AddAttribute("onkeyup", "lower(this.id);");
  32:             }
  33:             else if (this.TextStyle == TextType.UpperCase)
  34:             {
  35:                 writer.AddAttribute("onkeyup", "upper(this.id);");
  36:             }
  37:             base.AddAttributesToRender(writer);
  38:         }
  39:
  40:         protected override void OnPreRender(EventArgs e)
  41:         {
  42:             //Register Java Script
  43:             Page.ClientScript.RegisterClientScriptInclude("MyTextBox", Page.ClientScript.GetWebResourceUrl(this.GetType(), "MyResource.MyJS.js"));
  44:             base.OnPreRender(e);
  45:         }

8 ) now in the AssemblyInfo File Add the WebResource.

   1: //Add Name Space using System.Web.UI;
   2: //your NameSpace 
   3: [assembly: WebResource("MyResource.MyJS.js", "text/javascript", PerformSubstitution = true)]

9) Now Build Project then Create WebApplication (asp.net using C#) or Add New web Site In Existing Project. here i added new web site in Existing project.

10) Add MyTextBox Dll Reference in to Newly Created WebSite.

11) Add MyTextBox In to WebPage. Set the property

12) Run Web Site And Check.

how to retriving resource (ImageFile,html file) from the embeding resource ?

steps :

1) Add Image In to your exiting Class Library Project (Image Name :MyImage.Jpg).

2) now Right Click On Added JavaScript and Select Property. change the Build Action –> Embedded Resource.

3) now in the AssemblyInfo File Add the WebResource.

   1: [assembly: WebResource("MyResource.MyImage.jpg", "img/jpg")]

4) Build the Project. and go to the WebSite Project.

5) in the web site project put the image control.

6) now in the page load event get the myimage from the dll file.

   1: //the first argument type --> give the your class name
   2:       //second is resource name
   3:       Image1.ImageUrl =
   4:            Page.ClientScript.GetWebResourceUrl(typeof(MyResource.MyTextBox), "MyResource.MyImage.jpg");

7) check code.

Now the interesting thing check the page source.

Thnx

September 3, 2008

URL Mapping In ASP.Net 2.0

  • URL Mapping :

          URL Mapping is a new feature introduced in ASP.NET 2.0. you can change your URL more understanding purpose Example you can generally write http://localhost/UrlMapping/Detail.aspx?Id=1 In this URL we passing a query string value when any user see this url it like some improper. you can improve this using the URL Mapping http://localhost/UrlMapping/one.aspx in our application there is no aspx page like one.aspx. we just mapped that page.

Steps :

1) Create Web Application Using (Asp.net 2.0 with C#).

2) put below control in to Page (default.aspx)

   1: <table align="center">
   2:              <tr>
   3:                  <td style="font-size: 16px; color: blue" bgcolor="#ffffff" bordercolor="#ff9900"
   4:                      nowrap="noWrap">
   5:                      Get Detail Information
   6:                  </td>
   7:              </tr>
   8:              <tr>
   9:                  <td style="width: 147px">
  10:                      <asp:Button ID="btnd1" runat="server" Font-Bold="True" Text="Detail 1" OnClick="btnd1_Click" />
  11:                  </td>
  12:              </tr>
  13:              <tr>
  14:                  <td style="width: 147px">
  15:                      <asp:Button ID="btnd2" runat="server" Font-Bold="True" Text="Detail 2" OnClick="btnd2_Click" />
  16:                  </td>
  17:              </tr>
  18:              <tr>
  19:                  <td style="width: 147px">
  20:                      <asp:Button ID="btnd3" runat="server" Font-Bold="True" Text="Detail 3" OnClick="btnd3_Click" />
  21:                  </td>
  22:              </tr>
  23:              <tr>
  24:                  <td style="width: 147px">
  25:                      <asp:Button ID="btnd4" runat="server" Font-Bold="True" Text="Detail 4" OnClick="btnd4_Click" />
  26:                  </td>
  27:              </tr>
  28:          </table>

3) put below code in to CS (default.cs).

   1: protected void btnd1_Click(object sender, EventArgs e)
   2:     {
   3:         Response.Redirect("~/one.aspx");
   4:     }
   5:     protected void btnd2_Click(object sender, EventArgs e)
   6:     {
   7:         Response.Redirect("~/two.aspx");
   8:     }
   9:     protected void btnd3_Click(object sender, EventArgs e)
  10:     {
  11:         Response.Redirect("~/three.aspx");
  12:     }
  13:     protected void btnd4_Click(object sender, EventArgs e)
  14:     {
  15:         Response.Redirect("~/four.aspx");
  16:     }

4) add new page detail.aspx.

5) now the main thing where you map this url because there is no page like one.aspx,two.aspx,three.aspx,four.aspx. 

6) now in the web config file you put below code in between <system.web> and </system.web>

 

   1: <urlMappings enabled="true" >
   2:     <!--url which you want mappedURL = transfered url location -->
   3:     <add mappedUrl="~/Detail.aspx?id=1" url="~/one.aspx"/>
   4:     <add mappedUrl="~/Detail.aspx?id=2" url="~/two.aspx"/>
   5:     <add mappedUrl="~/Detail.aspx?id=3" url="~/three.aspx"/>
   6:     <add mappedUrl="~/Detail.aspx?id=4" url="~/four.aspx"/>
   7:   </urlMappings>

 

Thanks.

September 1, 2008

How To Generate Captcha Image In Asp.net 2.0

  • why Captcha Image Required ?

          Restrict User to Auto Registration or Login in the site. General Senario for that if you have a company who create new login or registration for the users. in this situation you never be going registration or login one by one. you create simple file in that file you put that information and one program which execute this process. as a company you want to restict this kind of activity at that time you want some code which is dyanamically generate and user enter that code and done the login or registration process at that time you can use this Captcha Image.

 

Steps :

1) create simple Asp.net 2.0 Application.

2) Add New Page (GenerateImage.aspx) — Generate Random Image and display in to page

put below code in to the web page.

2.1) create property (Height – Image Height,Width – Image Width,text – Display Text)

2.2) create Random No

private Random ObjRandom = new Random();

here below all code for (GenerateImage.aspx.cs)

   1: private int _height = 75;
   2:    public int height
   3:    {
   4:        get { return _height; }
   5:        set { _height = value; }
   6:    }
   7:  
   8:    private string _text = "generateimage";
   9:    public string text
  10:    {
  11:        get { return _text; }
  12:        set { _text = value; }
  13:    }
  14:  
  15:    private int _width = 275;
  16:    public int width
  17:    {
  18:        get { return _width; }
  19:        set { _width = value; }
  20:    }
  21:    /// <summary>
  22:    /// Get Character from Random Number
  23:    /// </summary>
  24:    /// <param name="genNo"></param>
  25:    /// <returns></returns>
  26:    public string getChar(int genNo)
  27:    {
  28:        switch (genNo)
  29:        { 
  30:            case 0:
  31:                return "a";
  32:            case 1:
  33:                return "b";
  34:            case 2:
  35:                return "c";
  36:            case 3:
  37:                return "d";
  38:            case 4:
  39:                return "e";
  40:            case 5:
  41:                return "f";
  42:            case 6:
  43:                return "g";
  44:            case 7:
  45:                return "h";
  46:            case 8:
  47:                return "i";
  48:            case 9:
  49:                return "j";
  50:        }
  51:        return string.Empty;
  52:    }
  53:  
  54:    //generating random numbers.
  55:    private Random ObjRandom = new Random();
  56:  
  57:    protected void Page_Load(object sender, EventArgs e)
  58:    {
  59:        //generate random text
  60:        Random r = new Random();
  61:        string str =r.Next().ToString().Substring(0,4);
  62:        char[] ch = str.ToCharArray();
  63:        text = string.Empty;
  64:        foreach (char var in ch)
  65:        {
  66:            //get appropriate char
  67:            text += getChar(Convert.ToInt32(var.ToString()));
  68:        }
  69:        //generate random image
  70:        GenerateImage();
  71:    }
  72:    /// <summary>
  73:    /// Generate Image
  74:    /// </summary>
  75:    private void GenerateImage()
  76:    {
  77:        //using System.Drawing; and using System.Drawing.Imaging;
  78:        //Create a new 32-bit bitmap image.
  79:        //specify height width
  80:        //if you want to change pass that value in to query string
  81:        Bitmap ObjBitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);
  82:        //Create a graphics object 
  83:        Graphics ObjGraphic = Graphics.FromImage(ObjBitmap);
  84:        ObjGraphic.SmoothingMode = SmoothingMode.HighQuality;
  85:  
  86:        Rectangle ObjRect = new Rectangle(0, 0, this.width, this.height);
  87:  
  88:        // Fill in the background color
  89:        //using System.Drawing.Drawing2D;
  90:        //you specify different fillup style
  91:        HatchBrush ObjHatchBrush = new HatchBrush(HatchStyle.BackwardDiagonal, Color.Transparent, Color.Transparent);
  92:        ObjGraphic.FillRectangle(ObjHatchBrush, ObjRect);
  93:        // Text Font Size
  94:        SizeF ObjectFontSize;
  95:        float fontSize = ObjRect.Height + 3;
  96:        Font ObjFont;
  97:        // Adjust the font size until the text fits within the image.
  98:        do
  99:        {
 100:            fontSize--;
 101:            ObjFont = new Font(FontFamily.GenericSerif, fontSize, FontStyle.Bold);
 102:            ObjectFontSize = ObjGraphic.MeasureString(this.text, ObjFont);
 103:        } while (ObjectFontSize.Width > ObjRect.Width);
 104:  
 105:        // Set up the text format.
 106:        StringFormat ObjectStringFormat = new StringFormat();
 107:        ObjectStringFormat.Alignment = StringAlignment.Center;
 108:        ObjectStringFormat.LineAlignment = StringAlignment.Center;
 109:  
 110:        // Create a path using the text and warp it randomly.
 111:        GraphicsPath ObjGraphicPath = new GraphicsPath();
 112:        ObjGraphicPath.AddString(this.text, ObjFont.FontFamily, (int)ObjFont.Style, ObjFont.Size, ObjRect, ObjectStringFormat);
 113:        float size = 6F;
 114:        PointF[] points =
 115:            {
 116:                new PointF(this.ObjRandom.Next(ObjRect.Width) / size, this.ObjRandom.Next(ObjRect.Height) / size),
 117:                new PointF(ObjRect.Width - this.ObjRandom.Next(ObjRect.Width) / size, this.ObjRandom.Next(ObjRect.Height) / size),
 118:                new PointF(this.ObjRandom.Next(ObjRect.Width) / size, ObjRect.Height - this.ObjRandom.Next(ObjRect.Height) / size),
 119:                new PointF(ObjRect.Width - this.ObjRandom.Next(ObjRect.Width) / size, ObjRect.Height - this.ObjRandom.Next(ObjRect.Height) / size)
 120:            };
 121:        Matrix ObjMatrix = new Matrix();
 122:        ObjMatrix.Translate(0F, 0F);
 123:        ObjGraphicPath.Warp(points, ObjRect, ObjMatrix, WarpMode.Perspective, 0F);
 124:  
 125:        //Draw Text
 126:        ObjHatchBrush = new HatchBrush(HatchStyle.Wave, Color.Gray, Color.DarkGray);
 127:        ObjGraphic.FillPath(ObjHatchBrush, ObjGraphicPath);
 128:  
 129:        //Add more noise in the image
 130:        int m = Math.Max(ObjRect.Width, ObjRect.Height);
 131:        for (int i = 0; i < (int)(ObjRect.Width * ObjRect.Height / 30F); i++)
 132:        {
 133:            int x = this.ObjRandom.Next(ObjRect.Width);
 134:            int y = this.ObjRandom.Next(ObjRect.Height);
 135:            int w = this.ObjRandom.Next(m / 52);
 136:            int h = this.ObjRandom.Next(m / 52);
 137:            ObjGraphic.FillEllipse(ObjHatchBrush, x, y, w, h);
 138:        }
 139:        ObjFont.Dispose();
 140:        ObjHatchBrush.Dispose();
 141:        ObjGraphic.Dispose();
 142:        this.Response.ContentType = "image/jpeg";
 143:        Session.Add("ImageString",this.text);
 144:        ObjBitmap.Save(this.Response.OutputStream, ImageFormat.Jpeg);
 145:    }

 3) Now In Default.aspx

<table>

<tr>

<td>

Enter User Name :</td>

<td>

<asp:TextBox ID=”txtUserName” runat=”server”></asp:TextBox>

<asp:RequiredFieldValidator ID=”RequiredFieldValidator3″ runat=”server” ControlToValidate=”txtUserName”

ErrorMessage=”RequiredFieldValidator”>*</asp:RequiredFieldValidator></td>

</tr>

<tr>

<td>

Enter Email Address :</td>

<td>

<asp:TextBox ID=”txtEmailAddress” runat=”server”></asp:TextBox>

<asp:RequiredFieldValidator ID=”RequiredFieldValidator2″ runat=”server” ControlToValidate=”txtEmailAddress”

ErrorMessage=”RequiredFieldValidator”>*</asp:RequiredFieldValidator></td>

</tr>

<tr>

<td>

Description :</td>

<td>

<asp:TextBox ID=”txtDescrition” TextMode=”MultiLine” runat=”server”></asp:TextBox>

</td>

</tr>

<tr>

<td>

Type Below Code :

</td>

<td>

<asp:TextBox ID=”txtImage” runat=”server”></asp:TextBox>

<asp:RequiredFieldValidator ID=”RequiredFieldValidator1″ runat=”server” ControlToValidate=”txtImage”

ErrorMessage=”RequiredFieldValidator”>*</asp:RequiredFieldValidator></td>

</tr>

<tr>

<td align=”center” colspan=”2″>

<!– Get Image From the GenerateImage Page –>

<img id=”img” src=”GenerateImage.aspx” />

</td>

</tr>

<tr>

<td colspan=”2″ align=”center”>

<asp:Button ID=”btnSubmit” Text=”Submit” runat=”server” OnClick=”btnSubmit_Click” />

<asp:Button ID=”btnCancel” Text=”Cancel” runat=”server” OnClick=”btnCancel_Click” ValidationGroup=”Cancel” />

</td>

</tr>

</table>

4) Now In Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)

{

}

protected void btnSubmit_Click(object sender, EventArgs e)

{

string str = Session["ImageString"].ToString();

if (str == txtImage.Text)

{

Response.Write(“you enter right”);

}

else

{

Response.Write(“you enter false”);

}

}

protected void btnCancel_Click(object sender, EventArgs e)

{

Response.Redirect(“default.aspx”);

}

 

Thnx.

Older Posts »

Blog at WordPress.com.