Friday, August 3, 2012

Image Upload in Asp.net ( Client Callback )

Introduction

The uploading of the image file is performed by ASP.NET 4.0 Client Callbacks. If you are not familiar with client callbacks  then I suggest that you take a look at ASP.Net AJAX Control Toolkit AsyncFileUpload Control without page refresh or PostBack in ASP.Net Web Page or ASP.Net AJAX Update Panel. The callback is fired as soon as the file is selected by the user using the file field control.
In this article I will explain how to display images that were uploaded using Asp.net file upload control and how to insert the image path into SQL database, Everything is done using  client side JavaScript and  some server side processing.
Let’s first discuss how we are going to accomplish this task. First we need a page ( ImageUpload.aspx ) which will allow the user to select a file. Once, the user has selected the file we upload the file to the server’s folder ( "Images/logo.png" ) and return the user with the url of the image that corresponds to the server’s folder. 
To download sample program Please click here

Step 1:

Before start to design our main page let's a look to my sql database... In my database, called “ImagePath.mdf”, there is a table “image” that has 4 fields. The table structure:  










Add a page file in your web application and name it "ImageUpload.aspx". It will be used to create 2 Textbox,File upload with default image and submit/remove Links. Add following code in the .aspx file: note that ( ViewStateMode="Enabled" )

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" ViewStateMode="Enabled"CodeFile="ImageUpload.aspx.cs" Inherits="_Default" %>

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script src="Javascript/JScript.js" type="text/javascript"></script>

<script language="javascript" type="text/javascript">

//javascript for upload Image 

//'btnok' clientback

    function ImageUploadClick() {

        document.getElementById('btnOk').click(); }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title>Yatramate:Registration</title>

    <link href="styles/StyleSheet.css" rel="stylesheet" type="text/css" />

     <style type="text/css">

     .style1 {font-weight: bold; } .style3

     {font-weight: bold; color: #000000; 

      font-family: "Times New Roman", Times, serif;

      width: 273px;}

     .style4{font-family: "Times New Roman", Times, serif;

      width: 273px;}

      .style5{font-family: "Times New Roman", Times, serif;

      font-weight: normal;}

      .style6{font-family: "Times New Roman", Times, serif;

       font-weight: normal; color: #000000; }

      .style8{font-weight: bold; color: #000000;

      font-family: "Times New Roman", Times, serif; width: 249px;}

      .style9{font-family: "Times New Roman", Times, serif;

       width: 249px; }

       .style10 { font-weight: bold;color: #000000;

      font-family: "Times New Roman", Times, serif;

       width: 191px;}

      .style11 { font-family: "Times New Roman", Times, serif;

      width: 191px;}

    </style>

  </head>

<body id="Body1" runat="server" style="background-image: url('images/bgrnd.jpg'); background-repeat:no-repeat;">

    <form id="form1" runat="server">

    <table class="style1">

        <tr><td class="style10">&nbsp;</td>  <td class="style3">

  <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />

            </td>

            <td class="style5"> &nbsp;</td>

        </tr> <tr> <td class="style10">

                &nbsp;</td>

            <td class="style3">

                Name</td>

            <td class="style5">

       <asp:TextBox ID="txtName" runat="server" BorderColor="#666666" 

        BorderStyle="Solid" BorderWidth="1px" Height="16px" Width="145px"></asp:TextBox>

            </td>  </tr>

        <tr> <td class="style10">

                &nbsp;</td>  <td class="style3"> Organization</td>

            <td class="style5">

         <asp:TextBox ID="txtOrg" runat="server" BorderColor="#666666" 

              BorderStyle="Solid" BorderWidth="1px" Height="16px" Width="145px"></asp:TextBox>

            <br /> </td> </tr>

        <tr><td class="style11">

                &nbsp;</td>

            <td class="style4">

                <span class="style6"><strong>Photo</strong></span><ul><li>

       <asp:Label ID="Label12" runat="server" Text="Upload Photo:" CssClass="Label"></asp:Label>

    </li> <li>  <asp:FileUpload ID="fupPhoto" runat="server"  contenteditable="false" 

        onchange="ImageUploadClick()" CssClass="btnmargin" />

        <asp:Button ID="btnOk" runat="server" BorderStyle="None" 

        CausesValidation="False" CssClass="txtBox" Height="0px" onclick="btnOk_Click1" 

        Text="ok" Width="0px" />

    </li>  <li class="btnmargin">

        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" 

           onclick="lnkRemove_Click">Remove Photo</asp:LinkButton>

    </li>   </ul>  </td>

            <td class="style5">

          <asp:Image ID="pbPhoto" runat="server" Height="115px" Width="128px" />

           </td> </tr> <tr>

         <td class="style10">

               &nbsp;</td>

          <td class="style3">

         <asp:Button ID="BtnSubmit" runat="server" Text="Submit" 

         onclick="BtnSubmit_Click" style="margin-left: 201px" />

     </td><td class="style8"></td>

   </tr></table>

    </form>

</body>

</html> 

Step 2: 

Before going to code-behind file..create a class file ( C_Image.cs ) under the App_Code folder Following code can be used  to define the size of the image,to determine the image format,determine if landscape or portrait,and set new height and widthof bitmap images.

using System.Drawing; 

using System.Drawing.Imaging;

using System.IO;

using System;

namespace Sample.Content.Items

{

    public class C_Image

    {

        public void ResizeFromStream(string ImageSavePath, int MaxSideSize, Stream Buffer)

        {

            int intNewWidth;

            int intNewHeight;

            Image imgInput = Image.FromStream(Buffer);

            //Determine image format 

            ImageFormat fmtImageFormat = imgInput.RawFormat;

            //get image original width and height 

            int intOldWidth = imgInput.Width;

            int intOldHeight = imgInput.Height;

            //determine if landscape or portrait 

            int intMaxSide;

            if (intOldWidth >= intOldHeight)

            {

                intMaxSide = intOldWidth;

            }

            else

            {

                intMaxSide = intOldHeight;

            }

            if (intMaxSide > MaxSideSize)

            {

                //set new width and height 

                double dblCoef = MaxSideSize / (double)intMaxSide;

                intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);

                intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);

            }

            else

            {

                intNewWidth = intOldWidth;

                intNewHeight = intOldHeight;

            }

            //create new bitmap 

            Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);

            //save bitmap to disk 

            bmpResized.Save(ImageSavePath, fmtImageFormat);

            //release used resources 

            imgInput.Dispose();

            bmpResized.Dispose();

            Buffer.Close();

         }

    }

}


Step 3:

Now add the code behind in the web page ( ImageUpload.aspx.cs ) where  image needs to be Uploaded. Following code snippet can be used:

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

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.Xml.Linq;

using Sample.Content.Items;

using System.IO;

using System.Data.SqlClient;



public partial class _Default : System.Web.UI.Page

{

    SqlConnection cnn;

    protected void Page_Load(object sender, EventArgs e)

    {

        txtName.Focus();

        cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);

        cnn.Open();//Please check the connection string that i can defined in web.config file

        if (!IsPostBack)

        {   //pls do ViewStateMode="Enabled" in sourse code

            ViewState["image"] = null;

            pbPhoto.ImageUrl = "Images/logo.png";//default image

        }

    }

    public void DeleteTempFile()

    {  // for remove/edit before submit to sql database

        try

        {   if (ViewState["image"] != null)

            {

                FileInfo infoFile = new FileInfo(Server.MapPath("Images/Temp/" + ViewState["image"].ToString()));

                if (infoFile.Exists)

                {

                    FileInfo infoFileMain = new FileInfo(Server.MapPath("Images/" + ViewState["image"].ToString()));

                    if (infoFileMain.Exists)

                    {

                        infoFileMain.Delete();

                    }

                    infoFile.MoveTo(Server.MapPath("Images/" + ViewState["image"].ToString()));

                    FileInfo info = new FileInfo(Server.MapPath("Images/Temp/" + ViewState["image"].ToString()));

                    info.Delete();

                    }

        } }

        catch (Exception ex)

        {  }

    }

    public string AttachmentUpload()

    {

        int i = 0;

        string strFileName = "";

        if (fupPhoto.HasFile)

        {   // check image type/extension/path

            string strPath = Server.MapPath("Images/");

            ViewState["strFileExtensionAttachment"] = Path.GetExtension(fupPhoto.FileName).ToLower();

            ViewState["Title"] = Path.GetFileNameWithoutExtension(fupPhoto.FileName).ToLower();

            string[] allowedExtension = { ".png", ".jpeg", ".jpg", ".bmp", ".gif", ".jpe", ".dib", ".jfif", ".tif", ".tiff" };

            bool isFileOk = false;

            for (int inI = 0; inI < allowedExtension.Length; inI++)

            {

                string str = ViewState["strFileExtensionAttachment"].ToString();

                if (ViewState["strFileExtensionAttachment"].ToString() == allowedExtension[inI])

                {

                    isFileOk = true;

                    break;

                }

            }

            if (isFileOk)

            {

            l1:

                i++;//It will Check File Repetation

                strFileName = i + ViewState["strFileExtensionAttachment"].ToString();

                if (System.IO.File.Exists(strPath + strFileName))

                 goto l1;

                fupPhoto.PostedFile.SaveAs(strPath + strFileName);

                UploadResizeImage("Images/Temp/" + strFileName);

            }

            else

            {

                ViewState["strFileExtensionAttachment"] = null;

            }

        }



        return strFileName;

    }

    private void UploadResizeImage(string Path)

    {   //please check App_Code folder

        //Define the size of images on C_Image.cs class

        if (fupPhoto.PostedFile != null)

        {

            HttpPostedFile myFile = fupPhoto.PostedFile;

            int nFileLen = myFile.ContentLength;

            if (nFileLen > 0)

            {

                C_Image objImage = new C_Image();//please check App_Code folder

                objImage.ResizeFromStream(Server.MapPath(Path), 200, myFile.InputStream);

            }

        }

    }

    public void clearAll()

    {

        txtName.Text = "";

        txtOrg.Text = "";

        ViewState["image"] = null;

        pbPhoto.ImageUrl = "Images/logo.png";

    }

    protected void btnOk_Click1(object sender, EventArgs e)

    {

        ViewState["image"] = AttachmentUpload();//client callback

        if (ViewState["image"] != null && ViewState["image"].ToString() != "")

            pbPhoto.ImageUrl = "Images/Temp/" + ViewState["image"].ToString();

        else

           Response.Write("Invalid file");

    }

    protected void BtnSubmit_Click(object sender, EventArgs e)

    {

        string image;

        if (ViewState["image"] == null)

        {

            image = "Images/logo.png";//default image

        }

        else

        {

            image = "Images/"+ViewState["image"].ToString();//image with path

        }

        string str = "INSERT INTO image VALUES('"+txtName.Text+"','"+txtOrg.Text+"','"+image+"')";

        SqlCommand cmd = new SqlCommand(str, cnn);

        cmd.ExecuteNonQuery();

        Response.Write("<script language='javascript'>alert(' Image Uploaded Successfully...! ')</script language>");

        clearAll();



    }

    protected void lnkRemove_Click(object sender, EventArgs e)

    {

        ViewState["image"] = null;

        pbPhoto.ImageUrl = "Images/logo.png";

    }

}


Step 4:

That's all guys...!
To download sample program Please click here 
the final output will shown like this... eNjOy progRamming..!









Regards @
Shanith Thekkayil
shaanzsster@gmail.com

Monday, June 25, 2012

Login with Session and Master Page/Web control

Lot's of my friends asking me that, they are all trouble with  login controls using in asp.net with session..? how it possible with master pages and web controls..? how cookies related with login controls..?

This article, i gonna be explain how all these possible in a simple manner... as an asp.net developer i needed to create a secure login web form but i also needed it to be a easy to implement, not so complicated, and also accomplish the mission
Session are a real impotent thing, that used in many cases we can't even imagine. You can use sessions in passing variables between Webpages instead of query-strings when passing secure values, it can also be used to create secure, and easy login.Sessions can be used to store even complex data for the user just like cookies. Actually sessions will use the cookies for store the data,unless you explicitly tell it not to. Sessions can be used easily in ASP.NET with the Session object. We will re-use the cookie example, and use sessions instead. Keep in mind though, that sessions will expire after a certain amount of minutes, as configured in the web.config file
Here, i need to explain all circumstances behind a login with a web user control.for that i can explain how a simple login works..!it can be detailed thru following program

Download sample program
Step 1 :
At first, set your master page [site.master]  with a web user control [LoginHeader.ascx] the path that i can  used for web control as


<%@ Register Src="~/LoginControls/LoginHeader.ascx" TagName="LoginHeader" TagPrefix="Uc1" %>

All the files such as webforms, database [Register.mdf], that are needed for this program are shown in solution explorer
Most Probably, the .ascx files contain link button and loginview controls and that can access to all web forms  through a masterpage [site.master] 
before that take a look for, how the design parts and code behind works in the .ascx file
LoginHeader.ascx


LoginHeader.ascx.cs































In .cs file convert all the cookie value into a session.. its not obviously termed as 'Convert', get the values from cookies and define all other links like register/edit
 Once the user is authenticated,.. he/she can view the profile and the edit page
Step 2:
before going to LoginHeader.ascx, it may check all users are authorized or not through a web form           [ Login.aspx]
Login.aspx

Login.aspx.cs
here it can assign  the cookie values for session 




Step 3:

For all these program, it has to define the connection string for its database [Register.mdf] and a registration form for inserting new clients

You can Download whole program Here

Now our code is ready for testing. Run your Application with Home.aspx as a start page and enter an incorrect password deliberately and see what message you see and when you enter the correct login you will receive a message that says

"Congratulations...!your session is starts..!"

In this application you can redirect the user to another page and store the Session that you will use through out your application And abondon when the user exit your application. Please note that for some application it is good to enable and disable Controls based on the Session value, meaning that you can check if the user is logged in , and display the benefits that logged in user can get in the same page. 

Thats all enJoY proGraMminG...!


Thank you for visiting http://rocingshani.blogspot.in
Shanith thekkayil-  techshaan2@gmail.com



Saturday, June 16, 2012

Popup calendar Using JQuery/Ajax

This article describes how to demonstrate a popup calendar in asp.net with two ways, that is either 
1) how to to add an Ajax popup calendar to a textbox with the help of the AjaxControlToolkit or 2) with the help of the js(JQuery). This is a simple demonstration with nothing but the required elements on the page so we can study the code and not get confused by other distracting elements

Step 1 : with AjaxControl toolkit
         a)    create a new web form in your web application site ie. Default.aspx
Before anything else, drag and drop an ajax toolscript manager onto your page like shown below,with design.

Above the script manager, drag and drop Text boxes and sets its ID's to txtDateJS and txtDateAjax respectively.
         b)  in the txtDateAjax, you can add a calendar extender from the tag menu, The CalendarExtender is an Asp.net AJAX control that is associated with a TextBox control. When the user clicks on the TextBox, a client-side Calendar control pops up. The user can then set a date by clicking on a day, navigate months by clicking on the left and right arrow and perform other such actions without a postback.
        c) now we can create a css style property for our ajax calendar in the head section
its look like following.
to define your txtDateAjax and calendarextender as follows:-

      d) That's all.. now run the program, we will see how the textbox navigate the popup calendar when the user clicks over..

 Step 2:  With JQuery:-
         a) here, we will see how to use  the jquery calendar popup for an asp.net web application,For every application there is a basic need to select a date from the calendar control. For that we have the AJAX calendar popup extender but this Ajax calendar extender works with our ASP.Net controls but not with HTML controls. As we know, in MVC,we prefer to use HTML controls rather than ASP.Net controls like textboxes. In this application we will see how to use the calendar control of jquery for a HTML textbox when the focus is on the textbox, but in my article i have chosen from asp.net textbox control...
Before starting our work with JQ,.we need to download the custom jquery UI from here
         b) Unzip your downloaded folders and copy all the items into your web application as follows



       c) . We will use this UI and script to build our calendar popup control for MVC/Web application. So let's get started with the calendar popup
you can check out the jquery source code from the above pictures
after running your application you will see the output as follows.....

That's All....
Download sample program from here

Enjoy Programming
Thanks & Regards
techshaan2@gmail.com



          


Thursday, June 14, 2012

How can we use a Captcha in Asp.net

Captcha

What is a captcha how can we use them with either a handler file or .dll file in asp.net 4.0
This article demonstrates how to create such an Captcha image and employ it within an ASP.NET web form.
 What is..?
          - [completely automated public Turing test to tell computers and humans apart] is a program that can tell humans from machines using some type of generated test. A test most people can easily pass but a computer program cannot.You've probably encountered such tests when signing up for an online email or forum account. The form might include an image of distorted text, like that seen above, which you are required to type into a text field. t
The idea is to prevent spammers from using web bots to automatically post form data in order to create email accounts (for sending spam) or to submit feedback comments or guestbook entries containing spam messages. The text in the image is usually distorted to prevent the use of OCR (optical character reader) software to defeat the process. Hotmail, PayPal, Yahoo and a number of blog sites have employed this technique.
you can download a complete captcha program from here  [Link]
 Files we need...!
  •  JpegImage_CS.aspx and JpegImage_CS.aspx .cs- defines the CapchaImage object which actually creates the image. 
  •  captcha.aspx, captcha.aspx.cs - a sample web form.
    button-refresh-captcha.jpg [ an image for button refresh ]
  • Refer the assembly CaptchaDLL.dll in your project --as you can download from here....! CaptchaDLL.dll 
Step 1: Add a page file in your web application and name it "captcha.aspx". It will be used to create Textbox,CAPTCHA image as a bitmap using a class and a dll file. Add following code in the .aspx file: 
  
veryfication styling
<%--Verification
        
Please type the characters you see in the picture :
          
--%>
and

put the following src into a ImageButton!

 runat="server" Height="31px"
   ImageUrl="~/SrcPic/button-refresh-captcha.jpg" OnClick="ibtnRefresh_Click"
        ToolTip="Click here to load a new image" Width="32px" />
                            

and a text box with an id  txtCaptcha

          TextBox ID="txtCaptcha" runat="server" BorderColor="Silver"
     BorderStyle="Solid" BorderWidth="1px" CssClass="style82" Height="20px"
                                    Width="145px">

and with a button
               

Button ID="Button1" runat="server" onclick="Button1_Click" Text="Check" />
                           



Step 2 :
 Now a .aspx file in your web application and name it "JpegImage_CS.aspx ". This  file implements a custom web control which displays the bitmap CAPTCHA image created by the "CaptchaDLL.dll" . Add following code in this file (in the source code itself):
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="CaptchaDLL" %>

and within script paste following codes

private void Page_Load(object sender, System.EventArgs e)
    {
        if (Session["CaptchaImageText"] != null)
        {
            // CREATE A CAPTCHA IMAGE USING THE TEXT STORED IN THE SESSION OBJECT.
            CaptchaImage ci = new CaptchaImage(Session["CaptchaImageText"].ToString(), 200, 50);
           
            //YOU CAN USE THE OTHER OVERLOADED METHODS ALSO
            //CaptchaImage ci = new CaptchaImage(Session["CaptchaImageText"].ToString(), 200, 50, "Courier New");
            //CaptchaImage ci = new CaptchaImage(Session["CaptchaImageText"].ToString(), 200, 50, "Courier New" ,System.Drawing.Color.White, System.Drawing.Color.Red);
           
            // Change the response headers to output a JPEG image.
            this.Response.Clear();
            this.Response.ContentType = "image/jpeg";

            // Write the image to the response stream in JPEG format.
            ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);

            // Dispose of the CAPTCHA image object.
            ci.Dispose();
        }
    }






   


Step3: 

Now define a namespace for the created CAPTCHA dll. To do this, locate the tags in the captcha.aspx.cs file and add a namespace tag as below:
 using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Web.SessionState;
using System.Web.UI.HtmlControls;

using CaptchaDLL;
   

Step4: 

 Now add the code behind in the web page where CAPTCHA image needs to be displayed. Following code snippet can be used:
 

protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

       

{ Session["CaptchaImageText"] = CaptchaImage.GenerateRandomCode(CaptchaType.AlphaNumeric, 6);

 //creating the strting to show in CAPTCHA image

          

        }

        //cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);

        //cnn.Open();

    }

    protected void ibtnRefresh_Click(object sender, ImageClickEventArgs e)

    {

        Session["CaptchaImageText"] = CaptchaImage.GenerateRandomCode(CaptchaType.AlphaNumeric, 6); //generate new string

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        if (Session["CaptchaImageText"] != null &amp;&amp; txtCaptcha.Text.ToLower() == Session["CaptchaImageText"].ToString().ToLower())

        {

            Label1.Text="Well done captcha passed..!";

                  }

        else

        {

            Session["CaptchaImageText"] = CaptchaImage.GenerateRandomCode(CaptchaType.AlphaNumeric, 6);

            txtCaptcha.Text = "";

Label1.Text=" Enter correct characters as shown in image...!";

               }

    }
Visual Verification--- Ok that's all now you can run your program....! enjoy programming Shanith Thekayil  Software Developer Smartzin info venture techshaan2@gmail.com
Twitter Bird Gadget