Expertize Essentials Innovation through knowledge

16Jul/099

Developing Hello World Application in Blackberry

Those have experience in .net and are new to mobile application development, will find this article useful for developing your first application on blackberry mobile.

For developing blackberry mobile application you need to have pre-requisite installed on your computer (see my other article for installing pre-requites for blackberry development).

For short, you should have installed :

  • Blackberry plug-in for Visual Studio 2005/2008

If you have this plug-in in your visual studio then move ahead.

Step 1.

  • Open Visual Studio
  • On File Menu-> New Project
  • Select Blackberry from left panel -> Blackberry MDS Runtime Application
  • Name your application to BlackberryHelloWold

Note: Please remember when you'll click OK "MDS development server" will start in system tray.

You'll see blackberry mobile screen available on your visual studio along with blackberry controls onto the left side.

Step 2.

  • Drag a TextBox from the toolbox to the blackberry form
  • Click right button of mouse on TextBox and select Properties
  • In Properties window (right side), change name to txtName
  • Now drag a button and drop it to the form just below the txtName (TextBox)
  • Change its name to btnOK
  • Change its Text to OK from Property window
  • Double click on the button (btnOK)
  • Form1_btnOK_Click() will be appeared in .js file (this creates .js file not cs file) and write the following in for display text in dialog box.
function Form1_btnOK_Click()
{
    Dialog.display(Form1.txtName.value);
}
  • Now Run your application (just click play symbol available in your visual studio)

This will start simulator (Just Looks like that you are running your application in mobile). Wait for some time your application will be loaded automatically.

Note: please check with Symentic Client Firewall this should not block your ports, otherwise your application will stuck and will not be run.

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.