DotNet Friends

October 11, 2008

Get Primary key – Foreign key relations table in sql server 2005

Why it is required?

The main purpose of this is finding related constraint table from database.

Check below Query.

–get table list with constraint(primary and foreign key)

select * from information_schema.constraint_column_usage

–get table list with foreign key constraint

select * from information_schema.referential_constraints

–get the relation

select

tblAll.table_name as PrimaryTableName,

tblAll.column_name as PrimaryTableColumn,

tblFK.table_name as ForeignKeyTable,

tblFK.column_name as ForeignKeyColumn

from information_schema.constraint_column_usage tblAll

inner join information_schema.referential_constraints tblAllFK on tblAllFK.unique_constraint_name = tblAll.constraint_name

inner join information_schema.constraint_column_usage tblFK on tblAllFK.constraint_name=tblFK.constraint_name

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

The media set has 2 media families but only 1 are provided

Filed under: Database, SqlServer — Tags: — patriwala @ 7:28 am

I got this error when restore database from .bak file.

why this error happen?

when you backup the database at that time you have not delete the existing path means you start a back up behalf of the previous one means your backup is divided in to more parts.

steps :
1)  you select all the related .bak file.

example here mydatabase name is test1. first i backup that at that time mybackup name is test1_17.bak. second backup i take at 18 and backup file name is test1_18.bak. now when you selecte restore database at that time you selected both this file.

rightclick on database –> task –> Restore –> Database

open one dialog box — now select fromdevice and add related files (test1_17.bak and test1_18.bak).

* when you take a backup at that time you remove the previous file.

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.

August 27, 2008

Upload CSV File And Read Using ASP.net

steps :

1) Create Simple Web Application Using (ASP.Net with C#).

2) Create Class CSVReader (CSVReader.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: using System.IO;
  11: using System.Text;
  12: using System.Collections;
  13:  
  14: public class CSVReader
  15: {
  16:     //
  17:     private Stream objStream;
  18:     private StreamReader objReader;
  19:  
  20:     //add name space System.IO.Stream
  21:     public CSVReader(Stream filestream) : this(filestream, null) { }
  22:  
  23:     public CSVReader(Stream filestream, Encoding enc)
  24:     {
  25:         this.objStream = filestream;
  26:         //check the Pass Stream whether it is readable or not
  27:         if (!filestream.CanRead)
  28:         {
  29:             return;
  30:         }
  31:         objReader = (enc != null) ? new StreamReader(filestream, enc) : new StreamReader(filestream);
  32:     }
  33:     //parse the Line
  34:     public string[] GetCSVLine()
  35:     {
  36:         string data = objReader.ReadLine();
  37:         if (data == null) return null;
  38:         if (data.Length == 0) return new string[0];
  39:         //System.Collection.Generic
  40:         ArrayList result = new ArrayList();
  41:         //parsing CSV Data
  42:         ParseCSVData(result, data);
  43:         return (string[])result.ToArray(typeof(string));
  44:     }
  45:  
  46:     private void ParseCSVData(ArrayList result, string data)
  47:     {
  48:         int position = -1;
  49:         while (position < data.Length)
  50:             result.Add(ParseCSVField(ref data, ref position));
  51:     }
  52:  
  53:     private string ParseCSVField(ref string data, ref int StartSeperatorPos)
  54:     {
  55:         if (StartSeperatorPos == data.Length - 1)
  56:         {
  57:             StartSeperatorPos++;
  58:             return "";
  59:         }
  60:  
  61:         int fromPos = StartSeperatorPos + 1;
  62:         if (data[fromPos] == '"')
  63:         {
  64:             int nextSingleQuote = GetSingleQuote(data, fromPos + 1);
  65:             int lines = 1;
  66:             while (nextSingleQuote == -1)
  67:             {
  68:                 data = data + "\n" + objReader.ReadLine();
  69:                 nextSingleQuote = GetSingleQuote(data, fromPos + 1);
  70:                 lines++;
  71:                 if (lines > 20)
  72:                     throw new Exception("lines overflow: " + data);
  73:             }
  74:             StartSeperatorPos = nextSingleQuote + 1;
  75:             string tempString = data.Substring(fromPos + 1, nextSingleQuote - fromPos - 1);
  76:             tempString = tempString.Replace("'", "''");
  77:             return tempString.Replace("\"\"", "\"");
  78:         }
  79:  
  80:         int nextComma = data.IndexOf(',', fromPos);
  81:         if (nextComma == -1)
  82:         {
  83:             StartSeperatorPos = data.Length;
  84:             return data.Substring(fromPos);
  85:         }
  86:         else
  87:         {
  88:             StartSeperatorPos = nextComma;
  89:             return data.Substring(fromPos, nextComma - fromPos);
  90:         }
  91:     }
  92:  
  93:     private int GetSingleQuote(string data, int SFrom)
  94:     {
  95:         int i = SFrom - 1;
  96:         while (++i < data.Length)
  97:             if (data[i] == '"')
  98:             {
  99:                 if (i < data.Length - 1 && data[i + 1] == '"')
 100:                 {
 101:                     i++;
 102:                     continue;
 103:                 }
 104:                 else
 105:                     return i;
 106:             }
 107:         return -1;
 108:     }
 109: }
 110:  

3) put below control in to the aspx page.

<table>
 <tr>
  <td>
   <asp:FileUpload ID="FileUpload1" runat="server" />
  </td>
  <td>
   <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload CSV" />
  </td>
 </tr>
 <tr>
   <td colspan="2">
    <asp:Label ID="lblMsg" Text="Please Select Proper File" runat="server" BorderColor="White"
         Font-Bold="True" ForeColor="Red" Visible="false"></asp:Label>
   </td>
 </tr>
 <tr>
   <td>
    <asp:GridView ID="gv" runat="server"></asp:GridView>
   </td>
 </tr>
</table>

4) In Code Behind File Put Below Code.

   1: protected void Button1_Click(object sender, EventArgs e)
   2:    {
   3:        if (FileUpload1.PostedFile.FileName == string.Empty)
   4:        {
   5:            lblMsg.Visible = true;
   6:            return;
   7:        }
   8:        else
   9:        { 
  10:            //save the file 
  11:            //restrict user to upload other file extenstion
  12:            string[] FileExt = FileUpload1.FileName.Split('.');
  13:            string FileEx = FileExt[FileExt.Length - 1];
  14:            if (FileEx.ToLower() == "csv")
  15:            {
  16:                FileUpload1.SaveAs(Server.MapPath("CSVLoad//" + FileUpload1.FileName));
  17:            }
  18:            else
  19:            {
  20:                lblMsg.Visible = true;
  21:                return;
  22:            }
  23:        }
  24:  
  25:        //create object for CSVReader and pass the stream
  26:        CSVReader reader = new CSVReader(FileUpload1.PostedFile.InputStream);
  27:        //get the header
  28:        string[] headers = reader.GetCSVLine();        
  29:        DataTable dt = new DataTable();
  30:        //add headers
  31:        foreach (string strHeader in headers)
  32:            dt.Columns.Add(strHeader);
  33:  
  34:        string[] data;
  35:        while ((data = reader.GetCSVLine()) != null)
  36:            dt.Rows.Add(data);
  37:        //bind gridview
  38:        gv.DataSource = dt;
  39:        gv.DataBind();
  40:        
  41:    }

5) create Folder In WebSite CSVLoad for Save Uploaded CSV File.

Thnx

« Newer PostsOlder Posts »

Blog at WordPress.com.