Expertize Essentials Innovation through knowledge

15Jul/092

Saving Image in Database (Sql Server) using .NET

I shared and done few efforts to save image in database.

Following the the function to save image to the databse.
Database Table will look like this:

create table userphoto(
photoid int,
photo image
);

The following code will be written in ASPX page.
<asp:FileUpload ID="UploadPhoto" runat="server" CssClass="fileupload" />
<asp:Button ID="btnUpload" runat="server" CssClass="buttonOrangeLight" OnClick="btnUpload_Click" Text="Upload" />


The following method is the code for uploading an image which will be invoked on btnUpload click event.

protected void btnUpload_Click(object sender, EventArgs e)
{
  //Get the extension of your file to be uploaded
  string _fileExtension = UploadPhoto.PostedFile.FileName.Substring( UploadPhoto.PostedFile.FileName.LastIndexOf('.'));
  if (_fileExtension != ".jpg" && _fileExtension != ".gif" && _fileExtension != ".bmp" && _fileExtension !=   ".png")
  {
    ltScript.Text = "Please upload images(jpeg/gif/bmp/png) files";
    return;
  }

  int _filesize = UploadPhoto.FileBytes.Length;
  // Checking file length
  if(_filesize>200000)
  {
    ltScript.Text="Size exeeds the limit of 200 KB, please upload a file with size of maximum 200 KB";
    return;
  }

  FileUpload userImage = (FileUpload)UploadPhoto;
  Byte[] imgByte = null;
  if (userImage.HasFile && userImage.PostedFile != null)
  {
    //To create a PostedFile
    HttpPostedFile File = UploadPhoto.PostedFile;

    //Create byte Array with file len
    imgByte = new Byte[File.ContentLength];

    //force the control to load data in array
    File.InputStream.Read(imgByte, 0, File.ContentLength);
    AddUserPhoto(ID, imgByte); // calling database method
  }
  ltScript.Text = "File has been uploaded...";
}

// Database Method in C#
internal bool AddUserPhoto(string ID, Byte[] Photo)
{
  string conn = "server=yourservername; database=yourdatabasename; uid=userid; pwd=yourpassword;";
  SqlConnection _sqlConnection= new SqlConnection(conn);

  bool _isInserted = false;
  _sqlCommand = new SqlCommand();
  _sqlCommand.Connection = _sqlConnection;
  _sqlCommand.CommandText = "insert into phototable values(@ID, @Photo)";
  _sqlCommand.CommandType = CommandType.StoredProcedure;
  _sqlCommand.Parameters.Add(new SqlParameter("@ID", ID));
  _sqlCommand.Parameters.Add(new SqlParameter("@Photo", Photo ));
  try
  {
    if(_sqlCommand.Connection.State != ConnectionState.Open)
    _sqlCommand.Connection.Open();

    int _result = _sqlCommand.ExecuteNonQuery();
    if (_result > 0)
    {
      _isInserted = true;
    }
  }
  catch (SqlException ex) {
  // Your Error code goes here for exception
  }
  finally
  {
    _sqlCommand.Connection.Close();
    _sqlCommand = null;
  }
  return _isInserted;
}
15Jul/094

Showing Image from Database in ASP.NET

Add the following lines in ASP.NET file

<asp:image id="imgUserPhoto" imageurl="image.ashx?id=xvd21w54" runat="server"/>
or
<img src="http://www.blogger.com/image.ashx?id=xvd21w54" />

Create an image.ashx file and add the following code in it.

<%@ WebHandler Language="C#" %>
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class image : IHttpHandler
{
  public void ProcessRequest(HttpContext context)
  {
    string id;
    if (context.Request.QueryString["id"] != null)
    {
      id = Convert.ToString(context.Request.QueryString["pid"]);
    }
    else
      throw new ArgumentException("No parameter specified");

    context.Response.ContentType = "image/jpeg";
    Stream Photo = GetPhoto(id, photonumber);
    if (Photo != null)
    {
      byte[] buffer = new byte[4096];
      int byteSeq = Photo.Read(buffer, 0, 4096);

      while (byteSeq > 0)
      {
        context.Response.OutputStream.Write(buffer, 0, byteSeq);
        byteSeq = Photo.Read(buffer, 0, 4096);
      }
    }
    else
    {
      //Loading default Image
      Byte[] imgByte = File.ReadAllBytes(context.Server.MapPath("upload_photo.JPG"));

      Photo = new MemoryStream(imgByte);
      byte[] buffer = new byte[4096];
      int byteSeq = Photo.Read(buffer, 0, 4096);

      while (byteSeq > 0)
      {
        context.Response.OutputStream.Write(buffer, 0, byteSeq);
        byteSeq = Photo.Read(buffer, 0, 4096);
      }

    }
    //context.Response.BinaryWrite(buffer);
  }
  public Stream GetPhoto(string Id, string PhotoNumber)
  {
    string conn = "server=yourservername; database=yourdatabasename; uid=userid; pwd=yourpassword;";
    SqlConnection connection = new SqlConnection(conn);

    string sqlQuery = "SELECT Photo FROM userphoto WHERE id=@id";

    SqlCommand cmd = new SqlCommand(sqlQuery, connection);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@id", Id);
    connection.Open();
    try
    {
      object img = cmd.ExecuteScalar();
      return new MemoryStream((byte[])img);
    }
    catch
    {
      return null;
    }
    finally
    {
      connection.Close();
    }
  }
  public bool IsReusable
  {
    get
    {
      return false;
    }
  }
}
15Jul/091

Creating Runtime Image Thumbnail (Asp.NET)

Upload an image and create thumbnail at runtime in ASP.NET


  protected void btnUpload_Click(object sender, EventArgs e)
  {
    //string _fileExtension = VirtualPathUtility.GetExtension(UploadPhoto.PostedFile.FileName);
    string _fileExtension = UploadPhoto.PostedFile.FileName.Substring (UploadPhoto.PostedFile.FileName.LastIndexOf('.'));
    if (_fileExtension != ".jpg" && _fileExtension != ".gif" && _fileExtension != ".bmp" && _fileExtension != ".png")
    {
      ltScript.Text = "Please upload images(jpeg/gif/bmp/png) files";
      return;
    }

    int _filesize = UploadPhoto.FileBytes.Length;
    if (_filesize > 200000)
    {
      ltScript.Text = "Size exeeds the limit of 200 KB, please upload a file with size of maximum 200 KB";
      return;
    }
    FileUpload userImage = (FileUpload)UploadPhoto;
    Byte[] imgByte = null;
    Byte[] _thumbByte = null;
    if (userImage.HasFile && userImage.PostedFile != null)
    {
      //To create a PostedFile
      HttpPostedFile File = UploadPhoto.PostedFile;
      //Create byte Array with file len
      imgByte = new Byte[File.ContentLength];
      //force the control to load data in array
      File.InputStream.Read(imgByte, 0, File.ContentLength);
      _thumbByte = GetThumbnail();

      DatabaseAdapter _dataadapt = new DatabaseAdapter();
      _dataadapt.UpdateUserPhoto(ID, imgByte, _thumbByte);

    }
    ltScript.Text = "File has been uploaded...";

  }
  private Byte[] GetThumbnail()
  {
    //Creating Thumbnail method
    System.Drawing.Image _image = System.Drawing.Image.FromStream
    (UploadPhoto.PostedFile.InputStream);
    float imgWidth = _image.PhysicalDimension.Width;
    float imgHeight = _image.PhysicalDimension.Height;
    float imgSize = imgHeight > imgWidth ? imgHeight : imgWidth;

    //the approximately pixel size of thumbnail image is 100 x 100 based on ratio
    float imgResize = imgSize <= 100 ? (float)1.0 : 100 / imgSize;
    imgWidth *= imgResize; imgHeight *= imgResize;
    //generating the thumbnail
    System.Drawing.Image _thumbnail = _image.GetThumbnailImage((int)imgWidth, (int)imgHeight, delegate() { return false; }, (IntPtr)0);

    // Converting Image File to byte Array
    byte[] imgBytes = null;
    try
    {
      using (MemoryStream ms = new MemoryStream())
      {
        _thumbnail.Save(ms, ImageFormat.Jpeg);
        imgBytes = ms.ToArray();
      }
    }
    catch (Exception ex) { ltLabel.Text = ex.ToString(); }
    return imgBytes;
  }
11Jun/095

Publish Website Command in VsWebDeveloper2008

Visual web developer Express 2008 does not have the facility to publish a website. The following steps will help you to embed this command in Visual Web Developer 2008:

  1. Launch Visual Web Developer Express 2008.
  2. Select Tools, then External Tools which will display the External Tools dialog. In the Title box, enter Publish &Website(non-overwrite).
  3. Click the browse button next to the Command box and browse to aspnet_compiler.exe which will be located in c:\Windows\Microsoft.NET\Framework\v2.0.50727.
  4. Click Open to add the command line for aspnet_compiler.exe.

Now that you've got the correct command line for the aspnet_compiler.exe, it's time to add the arguments that will correctly pre-compile your application. This is where you'll see the true power of the External Tools dialog.

  1. Type -p " in the Arguments box. (That's an opening double-quote after the p.)
  2. Click the right-facing arrow next to the Arguments box and select Project Directory.
  3. Add a trailing double-quote to the Arguments box.
  4. Press the spacebar to add a space at the end of the existing arguments.
  5. Type -v / " after the space you just entered.
  6. Click the right-facing arrow next to the Arguments box and select Project Directory.
  7. Type \..\CompiledApp" after the existing arguments.
  8. At this point, the Arguments box should contain the following:
    -p "$(ProjectDir)" -v / "$(ProjectDir)\..\CompiledApp"
  9. Type -u.
    -p "$(ProjectDir)" -v / "$(ProjectDir)\..\CompiledApp" -u

Hope this will help you guyz to work with VS developer express 2008.