Tuesday, October 20, 2009

Dotnet Coding Standards

We Fallow the Coding Standards to enforce consistent style and formatting in developing the applications. Here I am explaining the following things.
  • Naming Conversions and Style
  • Coding Practices
  • Error Handling
  • Data Access
  1. Naming Conversions and Style
    1. Use Pascal casing for type and method and constants
    2. Ex: public class SomeClass
      {
      const int DefaultSize= 100;
      public SomeMethod ()
      { }
      }

    3. Use camel casing for local variable names and method arguments
    4. Ex:
      int number;
      void MyMethod (int someNumber)
      { }

    5. Prefix member variables with m_. Use Pascal casing for the rest of a member variable name following the m_.
      Ex:public class SomeClass
      {
      private int m_Number;
      }

    6. Name methods using verb-object pair, such as ShowDialog ().
    7. Method with return values should have a name describing the value returned, such as GetObjectState ().
    8. Use descriptive variable names
    9. Always use C# predefined types rather than the aliases in the System Namespace.
    10. For Example:
      object NOT Object
      string NOT String
      int NOT Int32.
    11. Use meaningful namespace such as the product name or the company name.
    12. Avoid fully qualified type names. Use the using statement instead.
    13. Avoid putting a using statement inside a namespace.
    14. Group all framework namespaces together and put custom or third-party namespaces underneath.
    15. Example: 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 MyCompany;
      using MyControl;
    16. Maintain strict indentation. Do not use Tabs or non standard indentation. Such as one space. Recommended values are three or four spaces, and the value should be uniformed across.
    17. Indent comment at the same level of indentation as the code you are documenting.
    18. All comments should pass spell checking. Misspelled comments indicate sloppy development.
    19. All member variables should be declared at the top, with one line separating them from the properties or methods.
    20. public class MyClass
      {
      int m_Number;
      string m_Name;
      public void SomeMethod1()
      { }
      public void SomeMethod2()
      { }
      }
    21. Declare a local variable as close as possible to its first use.
    22. A file name should reflect the class it contains.
    23. Always place an open curly ({) in a new line.

  2. Coding Practices:
    1. Avoid putting multiple classes in a single file.
    2. A single file should contribute types to only a single namespace. Avoid having multiple namespaces in the same file.
    3. Avoid files with more than 500 lines (Excluding machine-Generated code)
    4. Avoid method with more than 25 lines.
    5. Avoid methods with more than 5 arguments. Use structures for passing multiple arguments.
    6. Do not manually edit any machine generated code.
    7. If modifying machine generated code, modify the format and style to match this coding standard.
    8. Use partial classes whenever possible to factor out the maintained portions.
    9. Avoid comments that explain the obvious. Code should be self-explanatory. Good code with readable variables and method names should not require comments.
    10. Document only operational assumptions, algorithms insights and so on.
    11. Avoid method level documentation.
    12. With the exception of zero or one, never hard-code a numeric value; always declare a constant instead.
    13. Use the const directive only on natural constants such as the number of days of the week.
    14. Avoid using const on read-only variables. For that, use the readonly directive.
    15. Every line of code should be walked through in a “white Box” testing manner.
    16. Catch only exceptions for which you have explicit handling.
    17. Avoid error code as method return values.
    18. Avoid defining custom exception classes.
    19. Avoid multiple Main () methods in a single assembly.
    20. Make only the most necessary types public. Mark other as internal.
    21. Avoid friend assemblies. As they increases inter assembly coupling.
    22. Avoid code that relies on an assembly that running form a particular location.
    23. Minimize code in application assemblies (EXE client assemblies). Use class libraries instead to contain business logic.
    24. Always use a curly brace scope in an if statement, even if it contains a single statement.
    25. Always use zero based arrays.
    26. Do not provide public or protected member variables. Use properties instead.
    27. Avoid using “new” inheritance qualifier. Use “override” instead.
    28. Never use unsafe code. Except using interop.
    29. Always check a delegate for null before invoking it.
    30. Classes and Interfaces should have at least 2:1 ratio of methods to properties.
    31. Avoid Interfaces with one member. Strive to have three to five members per interface. Don’t have more than 20 members per interface.12 is probably principle limit.
    32. Prefer using explicit interface implementation.
    33. Never hardcode strings that might change based on deployment such as connection strings.
    34. When building a long string use “StringBuilder”, not “String”.
    35. Don’t use late binding invocation when early-binding is possible.
    36. Use application logging and tracing.
    37. Never use “go to” unless in a switch statement fall-through.
    38. Don’t use the “this” reference unless invoking another constructor from within a constructor.
    39. Avoid casting to and from “System.Object” in code that uses generics. Use constraints or the “as” operator instead.
    40. Do not use the base word to access base class members unless you wish to resolve a conflict with a subclasses member of the same name or when invoking a base class constructor.

  3. Error Handling:
    1. Error handler should be present whenever you anticipate possibility of error.
    2. Do not use Try-catch for flow- control.
    3. Never declare an empty catch block.
    4. Error Message should be user friendly, simple and understandable.
    5. Errors should be raised in the routines present in the components and captured in the application’s GUI.
    6. Use Try-Catch statements in each and every function you write. Adhere to it strictly with out fail.
    7. Use dispose on types holding scarce resources, i.e., files, database connections.

  4. Data Access:
    1. ANSI SQL 92 standards have to be followed for writing queries.
    2. Do not put order by clause in the query unless required.
    3. Do not encapsulate readonly database operations in transactions.
    4. Use a stored procedure with output parameters instead of single record SELECT statements when retrieving one row of data.
    5. Stored procedure execution is fast when we pass parameters by position (the order in which the parameters are declared in the stored procedure) rather then by name.
    6. After each data modification statement inside a transaction, check for an error by testing the global variable @@ERROR
    7. Verify the row count when performing DELETE operation
    8. Use RETURN statement in stored procedures to help the calling program know whether the procedure worked properly.
    9. Key words should be capital. For example; SELECT, UPDATE, DELETE, INSERT, FROM, AND WHERE, etc.
    10. Do not use “SELECT * FROM” type of query. If all the columns of the table are to be selected, list all columns in the SELECT in same order as they appear in the table definition.
    11. While writing a query as a string, do not put any space after single quote (‘). There should be a single space between every two words. There should not be a space between the last word and the concluding single quote (‘).
    12. Where multiple columns are selected, there should be a single space after every ‘,’ between two columns.
    13. All the major keywords should come on the new lines
    14. The number of columns in a SELECT statement should not be more than 6. The line separator should be placed in this case after the (,) of the last column of this line and a single space.
    15. For any new line separator, the separator should come after a single space after the last word of the line.
    16. Place a tab after each key word on a new line.

Tuesday, July 14, 2009

CodeSnip: How to Display Sum Total in the Footer of the GridView Control

Introduction

In this article, we will see how to display the sum total of a column in the footer of the GridView control using Visual Studio 2005.

For the purpose of this article, we will use the Products Table from the Northwind Database and the GridView control for data binding. The GridView control will display the data and SqlDataSource is supplied in the web.config file as shown in Listing 1.

Listing 1
Our goal is to display the total of the column UnitPrice in the footer as shown in Figure 1.


By default, the GridView's Showfooter property is set to false. We'll change it to true. As we are calculating the field UnitPrice, we'll use TemplateField's ItemTemplate to display UnitPrice and FooterTemplate to display the total.

Listing 2: Display Sum Total in Footer of GridView Control
<asp:GridView ID="GridView1"   ShowFooter="true" DataKeyNames="ProductId"   AutoGenerateColumns="false" runat="server"   DataSourceID="SqlDataSource1"> <Columns> <asp:BoundField DataField="Productid" HeaderText="Product Id" /> <asp:BoundField DataField="ProductName" FooterText="Total" HeaderText="Product Name" /> <asp:TemplateField HeaderText="Unit Price" FooterStyle-Font-Bold="True"> <ItemTemplate>   <%# GetUnitPrice(decimal.Parse(Eval("UnitPrice").ToString())).ToString("N2") %> ItemTemplate> <FooterTemplate>   <%# GetTotal().ToString("N2") %> FooterTemplate> asp:TemplateField> Columns> asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server"  ConnectionString="<%$ ConnectionStrings:DummyDB %>" SelectCommand="Select * from Products"> asp:SqlDataSource>

Finally, we'll use Helper functions named GetUnitPrice and GetTotal to display the UnitPrice in the ItemTemplate and Total in the FooterTemplate. For instance, for each row of the GridView, a price value is passed to the GetUnitPrice function returning variable Price.

Listing 3: Using Helper Functions

[Visual Basic .NET]
Dim TotalUnitPrice As Decimal = 0.0
Function GetUnitPrice(ByVal Price As Decimal) As Decimal
TotalUnitPrice += Price
Return Price
End Function
Function GetTotal() As Decimal
Return TotalUnitPrice
End Function
C#
decimal TotalUnitPrice; decimal GetUnitPrice(decimal Price)  {     TotalUnitPrice += Price;   return Price; } decimal GetTotal() {   return TotalUnitPrice; }

Conclusion

In this article, you have learned how to display the sum total of a column in the footer of the GridView control with the help of an example.

Tuesday, June 23, 2009

date time format in VB and C#

Visual basic
Module DateToStringExample
Public Sub Main()
Dim dateValue As Date = #6/15/2008 9:15:07PM#
' Create an array of standard format strings.
Dim standardFmts() As String = {"d", "D", "f", "F", "g", "G", _
"m", "o", "R", "s", "t", "T", _
"u", "U", "y"}
' Output date and time using each standard format string.
For Each standardFmt As String In standardFmts
Console.WriteLine("{0}: {1}", standardFmt, _
dateValue.ToString(standardFmt))
Next
Console.WriteLine()

' Create an array of some custom format strings.
Dim customFmts() As String = {"h:mm:ss.ff t", "d MMM yyyy", "HH:mm:ss.f", _
"dd MMM HH:mm:ss", "\Mon\t\h\: M", "HH:mm:ss.ffffzzz" }
' Output date and time using each custom format string.
For Each customFmt As String In customFmts
Console.WriteLine("'{0}': {1}", customFmt, _
dateValue.ToString(customFmt))
Next
End Sub
End Module
' This example displays the following output to the console:
' d: 6/15/2008
' D: Sunday, June 15, 2008
' f: Sunday, June 15, 2008 9:15 PM
' F: Sunday, June 15, 2008 9:15:07 PM
' g: 6/15/2008 9:15 PM
' G: 6/15/2008 9:15:07 PM
' m: June 15
' o: 2008-06-15T21:15:07.0000000
' R: Sun, 15 Jun 2008 21:15:07 GMT
' s: 2008-06-15T21:15:07
' t: 9:15 PM
' T: 9:15:07 PM
' u: 2008-06-15 21:15:07Z
' U: Monday, June 16, 2008 4:15:07 AM
' y: June, 2008
'
' 'h:mm:ss.ff t': 9:15:07.00 P
' 'd MMM yyyy': 15 Jun 2008
' 'HH:mm:ss.f': 21:15:07.0
' 'dd MMM HH:mm:ss': 15 Jun 21:15:07
' '\Mon\t\h\: M': Month: 6
' 'HH:mm:ss.ffffzzz': 21:15:07.0000-07:00

C#
using System;

public class DateToStringExample
{
public static void Main()
{
DateTime dateValue = new DateTime(2008, 6, 15, 21, 15, 07);
// Create an array of standard format strings.
string[] standardFmts = {"d", "D", "f", "F", "g", "G", "m", "o",
"R", "s", "t", "T", "u", "U", "y"};
// Output date and time using each standard format string.
foreach (string standardFmt in standardFmts)
Console.WriteLine("{0}: {1}", standardFmt,
dateValue.ToString(standardFmt));
Console.WriteLine();

// Create an array of some custom format strings.
string[] customFmts = {"h:mm:ss.ff t", "d MMM yyyy", "HH:mm:ss.f",
"dd MMM HH:mm:ss", @"\Mon\t\h\: M", "HH:mm:ss.ffffzzz" };
// Output date and time using each custom format string.
foreach (string customFmt in customFmts)
Console.WriteLine("'{0}': {1}", customFmt,
dateValue.ToString(customFmt));
}
}
// This example displays the following output to the console:
// d: 6/15/2008
// D: Sunday, June 15, 2008
// f: Sunday, June 15, 2008 9:15 PM
// F: Sunday, June 15, 2008 9:15:07 PM
// g: 6/15/2008 9:15 PM
// G: 6/15/2008 9:15:07 PM
// m: June 15
// o: 2008-06-15T21:15:07.0000000
// R: Sun, 15 Jun 2008 21:15:07 GMT
// s: 2008-06-15T21:15:07
// t: 9:15 PM
// T: 9:15:07 PM
// u: 2008-06-15 21:15:07Z
// U: Monday, June 16, 2008 4:15:07 AM
// y: June, 2008
//
// 'h:mm:ss.ff t': 9:15:07.00 P
// 'd MMM yyyy': 15 Jun 2008
// 'HH:mm:ss.f': 21:15:07.0
// 'dd MMM HH:mm:ss': 15 Jun 21:15:07
// '\Mon\t\h\: M': Month: 6
// 'HH:mm:ss.ffffzzz': 21:15:07.0000-07:00

Sunday, March 15, 2009

Saving Images in a SQL database using ASP.Net

The ability to display images in a web application is a common requirement. There are two ways you can do this, either store images in a SQL database using the Binary Large Object (commonly know as BLOB) data type, or store the image on the disk. There are pro’s and cons to each of these methods, but in this article we’re going to learn how to store images into a SQL database.
For the purpose of this article I have created a table in SQL Server called Images, with three columns, Image Name, Image Type and the Image itself. Now let’s take a look at the form we are going to use, to upload images to this table.
Note: that the form enctype is multipart/form-data. This is necessary when we upload client files to a server.
So far, this looks pretty straightforward. Let’s take a look at the code which will process this request. To start with we see that File1 is derived from theHtmlInputfileclass

protected System.Web.UI.HtmlControls.HtmlInputFile File1;
This allows programmatic access to the HTML element on the server. We are going to use the PostedFile class to get the properties of the client image file. In the following piece of code we use the ContentLength and ContentType methods of this class to get the length, and type of the image file.

HttpPostedFile selectedFile = File1.PostedFile;
int imageLength = selectedFile.ContentLength;
string imageType = selectedFile.ContentType
If we were going to save this file to the server, all we need to do, is use the SaveAs method. In this case we are going to store the image in a SQL database, so we need to convert it into a format that SQL can understand. We are going to create a byte array. The size of the array is the length of the image that we were able to retrieve using the Contentlength property of the HttpPostedFile class.

binaryImagedata = new byte[imageLength];
The HttpPostedFile class also has an InputStream method, which returns the image data in bytes. We are going to use this to populate our byte array

selectedFile.InputStream.Read(binaryImagedata,0,imageLength);

We now have all the fields needed (imageLength, File1.PostedFile.FileName and binaryImagedata) to populate the database.
This covers the basics of how to upload an image to a database. In a real application, there are other things we might want to do, for example some validation checks. By checking the value of selectedFile.ContentLength you can enforce size restrictions on the image file. A ContentLength of 0, indicates that the file either does not exist or an empty file is being uploaded. The following code would check for empty files :

if (selectedFile.ContentLength==0)
{
errs ="0 length file ";
}
Note: The default file size that can be uploaded is 4MB, and a larger size will cause .Net to throw an exception. To change the default size for all applications on the server, the machine.config file will need to be modified. In the httpRuntime section, there is a maxRequestLength attribute,. Change the length to whatever new default you need.
If you want to make the change for only a single application however, then this setting can be overridden in the web.config file of the application in question. You would need to create a section and add the maxRequestLength attribute with the size you require. For further information on this topic, see the documentation for the
HttpRuntime element
We can also check the value of selectedFile.ContentType and verify if the file type is one we allow to be uploaded. The ContentType returns the MIME encoding in string format of the request. This is typically in category / subcategory format. Some common types include
"text/HTML" or "image/GIF". To ensure that the user can only upload GIF files, add the following code

if (selectedFile.ContentType.ToLower() != @"image/gif")
{
errs +="Invalid filetype";
}
In some cases we might also need to check for the dimensions of the image. Often, an application has a pre-determined space to display the image, and you might want to ensure that the height and width of the image match the allotted space. The HttpPostedFile class is not limited to just image files, so does not provide for any methods to retrieve this information. To retrieve further information about images, we are going to use the image class in the System.Drawingnamespace. For the purpose of this article we are only interested in the length and width of the image, however there is a lot more that you can do with this class, refer to System.Drawing.Image . To start with we create an Image object

System.Drawing.Image drawingImage = null;
The next step is to read the byte array binaryImagedata into our Image object.

drawingImage = System.Drawing.Image.FromStream(new System.IO.MemoryStream(binaryImagedata));
Now we have access to both the height and width of the array, so if your application requires your images have a length and width of 300 px you would use the following code
If ((drawingImage.Width != 300) && (drawingImage.Height != 300)) {
Errs = “Image is the wrong size”;
}

Hopefully this article covers all the basic elements of uploading images to a SQL database. To retrieve images to display in a web form - Displaying SQL Images in an ASP.Net datagrid,
The ability to display images in a web application is a common requirement. There are two ways you can do this, either store images in a SQL database using the Binary Large Object (commonly know as BLOB) data type, or store the image on the disk. There are pro’s and cons to each of these methods, but in this article we’re going to learn how to store images into a SQL database.
For the purpose of this article I have created a table in SQL Server called Images, with three columns, Image Name, Image Type and the Image itself. Now let’s take a look at the form we are going to use, to upload images to this table.

Saving Images in a SQL database using ASP.Net

The ability to display images in a web application is a common requirement. There are two ways you can do this, either store images in a SQL database using the Binary Large Object (commonly know as BLOB) data type, or store the image on the disk. There are pro’s and cons to each of these methods, but in this article we’re going to learn how to store images into a SQL database.
For the purpose of this article I have created a table in SQL Server called Images, with three columns, Image Name, Image Type and the Image itself. Now let’s take a look at the form we are going to use, to upload images to this table.

Saving Images in a SQL database using ASP.Net

The ability to display images in a web application is a common requirement. There are two ways you can do this, either store images in a SQL database using the Binary Large Object (commonly know as BLOB) data type, or store the image on the disk. There are pro’s and cons to each of these methods, but in this article we’re going to learn how to store images into a SQL database.
For the purpose of this article I have created a table in SQL Server called Images, with three columns, Image Name, Image Type and the Image itself. Now let’s take a look at the form we are going to use, to upload images to this table.

FileUpload in asp.net using C#

Uploading image to a database using datatype image

Intro
Uploading images to a Sql Server database is extremely easy using ASP.NET and C#. A couple of months ago I wrote a similar article, using VB.NET. This article will show you how to upload Images (or any Binary Data ) to a Sql Server database using ASP.NET and C#. Part II, Retrieving Images from a Database ( C# ) , will show you how extract images from a database.

Building the Database Table
We start out by building our database table. Our image table is going to have a few columns describing the image data, plus the image itself. Here is the sql required to build our table in SQL Server or MSDE.
Building the Database Table
We start out by building our database table. Our image table is going to have a few columns describing the image data, plus the image itself. Here is the sql required to build our table in SQL Server or MSDE.
CREATE TABLE [dbo].[image] (
[img_pk] [int] IDENTITY (1, 1) NOT NULL ,
[img_name] [varchar] (50) NULL ,
[img_data] [image] NULL ,
[img_contenttype] [varchar] (50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[image] WITH NOCHECK ADD
CONSTRAINT [PK_image] PRIMARY KEY NONCLUSTERED
(
[img_pk]
) ON [PRIMARY] GO
I'm a great fan of having a single column primary key, and making that key an Identity column, in our example, that column is img_pk. The next column is img_name, which is used to store a friendly name of our image, for example "Mom and Apple Pie". img_data is actually our image data column, and is where we will be storing our binary image data. img_contenttype will be used to record the content-type of the image, for example "image/gif" or "image/jpeg" so we will know what content-type we need to output back to the client, in our case the browser.

Building our Webform
Now that we have a warm, fuzzy place to store our images, lets build a webform to upload our images into the database.
Enter A Friendly Name



Select File To Upload:



Working with the Uploaded Image
Once the user posts the data, we have to be able to parse the binary data and send it to the database. Along with the main body of the code, we use a helper function called SaveToDB() to achieve this.
private int SaveToDB(string imgName, byte[] imgbin, string imgcontenttype)
{
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
SqlCommand command = new SqlCommand( "INSERT INTO Image (img_name,img_data,img_contenttype) VALUES ( @img_name, @img_data,@img_contenttype )", connection );

SqlParameter param0 = new SqlParameter( "@img_name", SqlDbType.VarChar,50 );
param0.Value = imgName;
command.Parameters.Add( param0 );

SqlParameter param1 = new SqlParameter( "@img_data", SqlDbType.Image );
param1.Value = imgbin;
command.Parameters.Add( param1 );

SqlParameter param2 = new SqlParameter( "@img_contenttype", SqlDbType.VarChar,50 );
param2.Value = imgcontenttype;
command.Parameters.Add( param2 );

connection.Open();
int numRowsAffected = command.ExecuteNonQuery();
connection.Close();

return numRowsAffected;
}
In this function we are passing in 3 different parameters
imgName - the friendly name we want to give out image data
imgbin -- the binary or Byte array of our data
imgcontenttype - the content type of our image. For example: image/gif or image/jpeg

There are 3 parameters as SQLParameters and defines the type. Our first SQLParameter is @img_name and is defined as a VarChar with a length of 50. The 2nd parameter, @img_data, is the binary or Byte() of data and is defined with a data type of Image. The last parameter is @img_contenttype, is defined as a VarChar with a length of 50 characters. The remainder of the function opens a connection to the database and executes the command by calling command.ExecuteNonQuery().

Calling our Functions
Ok, now that we have our worker functions written, let's go ahead and get our image data.
Stream imgStream = UploadFile.PostedFile.InputStream;
int imgLen = UploadFile.PostedFile.ContentLength;
string imgContentType = UploadFile.PostedFile.ContentType;
string imgName = txtImgName.Value;
byte[] imgBinaryData = new byte[imgLen];
We need to access three important pieces of data for our example. We need the image:
Name (imgName_value)
Content-Type (imgContentType)
and the Image Data. (imgBindaryData)
First we access to the image stream, which we are able to get by using the property UploadFile.PostedFile.InputStream. (Remember, UploadFile was the name of our upload control on the webform). We also need to know how long the Byte array we are going to create needs to be. We can get this number by calling UploadFile.PostedFile.ContentLength, and storing it's value in imgLen. Once we have the length of the image, we create a byte array by byte[] imgBinaryData = new byte[imgLen]; We access the content type of the image by accessing the ContentType property of UploadFile.PostedFile. Lastly we need the friendly name we are going to use for the image.

The Good Stuff
Ok, we know how to connect to the database, we know how to insert data into the database, and we have access to the uploaded image's properties. But how do we pass the stream of the image to SaveToDB(). Again, .NET comes to the rescue. With 1 line of code we are able to access the image stream and convert it to a Byte array.
int n = imgStream.Read(imgBinaryData,0,imgLen);
The stream object provides a method called Read(). Read() takes 3 parameters:
buffer - An array of bytes. A maximum of count bytes are read from the current stream and stored in buffer.
offset -The byte offset in buffer at which to begin storing the data read from the current stream.
count - The maximum number of bytes to be read from the current stream.
So we pass in our Byte array, imgBinaryData; the place to start at, 0; and the amount of bytes we want to read. n number of bytes read into our array is returned.
Extending Beyond Images
Because we are able to access the binary stream of data, images are not the only object we can store in the database. Some other objects might be streaming video, com objects, or sound clips. As an example I also uploaded a streaming avi into my database. I ran a select query to show the results.


Conclusion
So there we have it, ASP.NET provides us some easy functionality for uploading images into a database. In Part II, we will actually look at pulling these images out of a database and sending them to a browser. The complete code used for this article can be found below.
Image SQL
CREATE TABLE [dbo].[image] (
[img_pk] [int] IDENTITY (1, 1) NOT NULL ,
[img_name] [varchar] (50) NULL ,
[img_data] [image] NULL ,
[img_contenttype] [varchar] (50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[image] WITH NOCHECK ADD
CONSTRAINT [PK_image] PRIMARY KEY NONCLUSTERED
(
[img_pk]
) ON [PRIMARY]
GO
UploadImage.aspx
<%@ Page language="c#" Src="UploadImage.aspx.cs" Inherits="DBImages.UploadImage" %>







The ASPFree Friendly Image Uploader


Enter A Friendly Name



Select File To Upload:







UploadImage.aspx.cs ( codebehind file)
using System;
using System.Configuration;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.IO;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace DBImages
{
public class UploadImage : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button UploadBtn;
protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
protected System.Web.UI.HtmlControls.HtmlInputText txtImgName;
protected System.Web.UI.HtmlControls.HtmlInputFile UploadFile;

public UploadImage() { }

private void Page_Load(object sender, System.EventArgs e){ }

public void UploadBtn_Click(object sender, System.EventArgs e)
{
if (Page.IsValid) //save the image
{
Stream imgStream = UploadFile.PostedFile.InputStream;
int imgLen = UploadFile.PostedFile.ContentLength;
string imgContentType = UploadFile.PostedFile.ContentType;
string imgName = txtImgName.Value;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData,0,imgLen);

int RowsAffected = SaveToDB( imgName, imgBinaryData,imgContentType);
if ( RowsAffected>0 )
{
Response.Write("
The Image was saved");
}
else
{
Response.Write("
An error occurred uploading the image");
}

}
}


private int SaveToDB(string imgName, byte[] imgbin, string imgcontenttype)
{
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
SqlCommand command = new SqlCommand( "INSERT INTO Image (img_name,img_data,img_contenttype) VALUES ( @img_name, @img_data,@img_contenttype )", connection );

SqlParameter param0 = new SqlParameter( "@img_name", SqlDbType.VarChar,50 );
param0.Value = imgName;
command.Parameters.Add( param0 );

SqlParameter param1 = new SqlParameter( "@img_data", SqlDbType.Image );
param1.Value = imgbin;
command.Parameters.Add( param1 );

SqlParameter param2 = new SqlParameter( "@img_contenttype", SqlDbType.VarChar,50 );
param2.Value = imgcontenttype;
command.Parameters.Add( param2 );

connection.Open();
int numRowsAffected = command.ExecuteNonQuery();
connection.Close();

return numRowsAffected;
}
}
}
Web.Config







Sunday, February 15, 2009

The basics.ASP.net Tutorial