Archive

Archive for the ‘Asp.Net 2.0’ Category

URL rewriting in asp.net

October 2, 2009 Leave a comment

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

 

Crystal report with multiple sub report navigation problem in asp.net

September 16, 2009 Leave a comment

Here I am explain the crystal report problem during the development.

I want to create Main report which having three sub reports. I create that report and call that report using asp.net but I have phase navigation problem.

Problem :

When Clicking the “Next” navigation button while on page 1 of Report Page 2 is appear, when clicking the “Next” navigation button while on page 2 , page 2 is repeated.

Solution :

Initially we write a Crystal report viewer code in to Page_Load event we move that code to Page_Init event and the Report navigation work.

Hope this help you.

thnx

PDF Viewer in asp.net

August 28, 2009 12 comments

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

Calling Web service from Flex – Part 1

June 23, 2009 5 comments

Here I am Explain how to use Web Services in Flex Application.

Steps:

1) First we create web service in Asp.net with C#. create new Web method in Web service is GetName.

[WebMethod]
    public string GetName(string UserName)
    {        
        return "WelCome  " + UserName;
    }

My web service name is WebServices.

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }
    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
    [WebMethod]
    public string GetName(string UserName) {        
        return "WelCome  " + UserName;
    }
}

2) Open Flex Application.

3) Put below control in to application.

    3.1)  WebService (ID =MyWebService)

    3.2) Label for display Information

    3.3) TextArea (ID=txtUserName) – get value and pass value in to WebService

    3.4) Button (ID=btnSubmit) – Call Web service

    3.5) TextArea (ID=txtResult) – Display result from Web service

Application Page Info.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<!--Web Service Information 
wsdl  URL of Web Service
fault  if any error loading web service
operation  method name in Webservices
request  pass the parameter to Webservices
*here I get the TextBox Value 
-->
<mx:WebService id="MyWebService" wsdl="http://localhost:3549/ChangeWebConfigFile/WebService.asmx?WSDL"
    fault="mx.controls.Alert.show(event.fault.faultString)" >
    <mx:operation name="GetName">
        <mx:request>        
        <UserName>{txtUserName.text}</UserName>
        </mx:request>
    </mx:operation>
</mx:WebService>
<mx:VBox>

    <mx:Label text="Enter User Name">        
    </mx:Label>
    <mx:TextArea id="txtUserName" text="test">        
    </mx:TextArea>
    
    <mx:Button id="btnSubmit" label="Submit.." click="checkUserName();">        
    </mx:Button>
    <mx:TextArea id="txtResult"/>    
</mx:VBox>
<mx:Script>
    <![CDATA[
      private function checkUserName():void
    {
        MyWebService.GetName.send();
        txtResult.text= MyWebService.GetName.lastResult;            
    }                 
    ]]>
</mx:Script>
</mx:Application>

4) Run Flex Application.

 

image

 

 

thnx

Convert Generic List In To DataTable

December 3, 2008 19 comments

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

CS0030: Cannot convert type

September 14, 2008 Leave a comment

Actual Error Was : CS0030 Cannot convert type ‘ASP.changepassword_aspx’ to ‘System.Web.UI.WebControls.ChangePassword’.

I have created web application using asp.net 2.0 with c#. Application Run In VS Studio Perfect but when publish this application in to local host some of the link can not run and it give this error. below is the description of that.

error

Steps :

1) open the Error Page (here is ChangePassword.aspx)

case 1 : change the PageName means Rename ChangePassword.aspx to ChPassword.aspx

case 2: change the class name in code behind and Inherit attribute of the page. here the class name is ChangePassword and Inherit attribute of page is ChangePassword. you can change both of this.

Thanx

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

September 10, 2008 1 comment

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

September 10, 2008 3 comments

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

Embedding Resources in ASP.Net 2.0

September 6, 2008 3 comments
  • 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

URL Mapping In ASP.Net 2.0

September 3, 2008 3 comments
  • 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.

Follow

Get every new post delivered to your Inbox.

Join 244 other followers