Yasserzaid’s Weblog

December 26, 2009

Email Validation

Filed under: ASP.Net, Javascript — Tags: , — yasserzaid @ 8:34 pm

Hi

try this example to validate Email using Client and Server Side :-

** Using Client Side Validation **

– Example1:-

<script language="javascript" type="text/javascript">
function validateEmail()
{
var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
return regex.test(document.getElementById('<%= txtEmail.ClientID %>').value);
}
</script>

– Example2:-

<script type="text/javascript">
function validateEmail()
{
var obj=document.getElementById('<%= txtEmail.ClientID %>');
var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
if(regex.test(obj.value))
{
//You can also assign stylesheet by
//obj.className='....';
obj.style.backgroundColor = '';
obj.style.backgroundColor = '';
return true;
}
else
{
//Changing Background Color so that user can understand that its invalid
//You can also assign stylesheet by
//obj.className='....';
obj.style.backgroundColor = '#FD5E53';
obj.style.borderColor = '#CD4A4A';
return false;
}
}
</script>

and the HTML Page will be :-

<asp:TextBox ID='txtEmail' runat="server"></asp:TextBox>
<asp:Button id="cmdSave" runat="server" Text="Save" OnClientClick="return validateEmail();" />

** Using Server Side **


public static class Validation
{
public const string EmailStandard = @"^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$";
public static bool ValidateEmail(string emailID)
{
if (emailID != null)
return System.Text.RegularExpressions.Regex.IsMatch(emailID, EmailStandard);
else
return false;
}
}

Now from our aspx page write the below code when user click on a button to proceed.

if (Validation.ValidateEmail(txtEmail.Text))
{
//Valid Email
}
else
{
//Invalid Email
//Notify user
return;
}

Hope this helps

Good Luck.

December 18, 2009

AJAX HTML Editor and validation

Filed under: AJAX, ASP.Net, Javascript — yasserzaid @ 2:21 pm

Hi

try this example to validate AJAX  HTML editor :

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="TestWithValidation.aspx.vb"
    Inherits="SoluTest_HTMLEditor.TestWithValidation" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit.HTMLEditor"
    TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">
<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function test() {
            var a = $find("<%=Editor1.ClientID%>");
            var value = a.get_content();
            if (value == "") {
                $get("result").innerHTML = "Editor's content is empty";
                return false;
            }           
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <cc1:Editor ID="Editor1" runat="server" Width="300" Height="300" ValidationGroup="Editor" />
        <br />
        <span id="result"></span>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Submit" OnClientClick="return test();"
            CausesValidation="true" ValidationGroup="Editor" />
    </div>
    </form>
</body>
</html>

Hope this helps

Good Luck

December 16, 2009

Reset Controls in Web Form

Filed under: ASP.Net, Javascript — yasserzaid @ 5:39 pm

Hi

try this example to reset all controls in web page using javascript

Salient features:

  1. Using this code, you can reset HTML controls as well as ASP controls like text box, text area, radio buttons, etc.
  2. This function can reset the File Upload control as well.
  3. Using this, we can reset .NET Validation Controls too, like RequiredFieldValidater, etc.
  4. This code has no issue with any browser like FireFox, Internet Explorer, Google Chrome, Safari, etc…
<script type="text/javascript">
      
        //function for reset controls
        function ClearAllControls()
        {
            //set your validation controls prefix here.
            var validationControlsPrefix = "req";
            resetmsg(validationControlsPrefix);
              for (i=0; i<document.forms[0].length; i++)
              {
                    doc = document.forms[0].elements[i];
                    switch (doc.type)
                    {
                        case "text" :
                                doc.value = "";
                                break;
                          case "checkbox" :
                                doc.checked = false;
                                break;  
                          case "radio" :
                                doc.checked = false;
                                break;              
                          case "select-one" :
                                doc.options[doc.selectedIndex].selected = false;
                                doc.selectedIndex = 0;
                                break;                    
                          case "select-multiple" :
                                while (doc.selectedIndex != -1)
                                {
                                      indx = doc.selectedIndex;
                                      doc.options[indx].selected = false;
                                }
                                doc.selected = false;
                                break;
                         case "textarea":
                                doc.value = "";
                                break;
                          case "file" :
                              var browser=navigator.appName;
                             if(browser == 'Microsoft Internet Explorer')
                              {
                                 var fil = doc;
                                 //fil.select();
                                 n=fil.createTextRange();
                                 n.execCommand('delete');                         
                              }
                              else
                              {
                                 doc.value='';
                              }
                             break; 
                          default :
                                break;
                    }
              }
        }
      
        //function for reset validation controls
        function resetmsg(validationControlsPrefix)
        {
         
           var spans;
             var browser=navigator.appName;
             if(browser == 'Microsoft Internet Explorer')
              {
                spans = document.all.tags('span');
              }
              else
              {
                spans =  document.getElementsByTagName('span');
              }
            
            if (spans)
             {
                for (var i = 0; i < spans.length; i++)
                 {
                    var prefixLength = "" + validationControlsPrefix.length;
                    var currID = "" + spans[i].id
                    if ((currID != '') && (prefixLength != ''))
                       {
                          if (currID.substring(0,prefixLength) ==
     validationControlsPrefix)
                            {
                                spans[i].style.display = "none";
                             }
                       }
                 }
             }         
          
        }      
        </script> 

Hope  this helps

Good Luck.

Dynamic DropDownList with Month Names

Filed under: ASP.Net — yasserzaid @ 7:17 am

Hi

try this example to fill DropdownList with Month Names

1) create new website and add web page

2) In Default.aspx add dropdownlist control

3) In Code behind add the following code :-

    #region Method to Fill the a DropDownList with Month Names and set the Current Month Selected
    /// <summary>
    /// fills a dropDownlist with month list.
    /// </summary>
    /// The DropDown List that will Hold the Months.
    /// if set to <c>true</c> the Current Month will be selected.
    public void GetMyMonthList(DropDownList MyddlMonthList, bool SetCurruntMonth)
    {
        DateTime month = Convert.ToDateTime("1/1/2000");
        for (int i = 0; i < 12; i++)
        {
            DateTime NextMont = month.AddMonths(i);
            ListItem list = new ListItem();
            list.Text = NextMont.ToString("MMMM");
            list.Value = NextMont.Month.ToString();
            MyddlMonthList.Items.Add(list);
        }
        if (SetCurruntMonth == true)
        {
            MyddlMonthList.Items.FindByValue(DateTime.Now.Month.ToString()).Selected = true;
        }
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetMyMonthList(DropDownList1, false);
        }
    }

Hope this helps

Good Luck.

December 12, 2009

Resizing images without loss of quality in ASP.NET

Filed under: ASP.Net — yasserzaid @ 2:16 pm

Hi

try this example to resize image without loss it’s quality

1) Open VS and create new web project

2) Add web page called : “ImageThumb.aspx” and in code behind add the following code

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 System.IO;
using System.Drawing;
using System.Drawing.Imaging;

public partial class ImageThumb : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            string Image = Request.QueryString["Image"];
            if (Image == null)
            {
                this.ErrorResult();
                return;
            }
            string sSize = Request.QueryString["Size"];
            int Size = 120;
            if (sSize != null)
                Size = Int32.Parse(sSize);
            string Path = Server.MapPath(Image);
            Bitmap bmp = CreateThumbnail(Path, Size, Size);
            if (bmp == null)
            {
                this.ErrorResult();
                return;
            }
            string OutputFilename = null;
            OutputFilename = Request.QueryString["OutputFilename"];
            if (OutputFilename != null)
            {
                if (this.User.Identity.Name == "")
                {
                    // *** Custom error display here
                    bmp.Dispose();
                    this.ErrorResult();
                }
                try
                {
                    bmp.Save(OutputFilename);
                }
                catch (Exception ex)
                {
                    ErrHandler.WriteError(ex.Message);
                    bmp.Dispose();
                    this.ErrorResult();
                    return;
                }
            }
            // Put user code to initialize the page here
            Response.ContentType = "image/jpeg";
            bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            bmp.Dispose();
        }
    }

    private void ErrorResult()
    {
        Response.Clear();
        Response.StatusCode = 404;
        Response.End();
    }

    public static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)
    {
        System.Drawing.Bitmap bmpOut = null;
        try
        {
            Bitmap loBMP = new Bitmap(lcFilename);
            ImageFormat loFormat = loBMP.RawFormat;
            decimal lnRatio;
            int lnNewWidth = 0;
            int lnNewHeight = 0;
            //*** If the image is smaller than a thumbnail just return it
            if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
                return loBMP;
            if (loBMP.Width > loBMP.Height)
            {
                lnRatio = (decimal)lnWidth / loBMP.Width;
                lnNewWidth = lnWidth;
                decimal lnTemp = loBMP.Height * lnRatio;
                lnNewHeight = (int)lnTemp;
            }
            else
            {
                lnRatio = (decimal)lnHeight / loBMP.Height;
                lnNewHeight = lnHeight;
                decimal lnTemp = loBMP.Width * lnRatio;
                lnNewWidth = (int)lnTemp;
            }

            // *** This code creates cleaner (though bigger) thumbnails and properly
            // *** and handles GIF files better by generating a white background for
            // *** transparent images (as opposed to black)
            bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
            Graphics g = Graphics.FromImage(bmpOut);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
            g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
            loBMP.Dispose();
        }
        catch (Exception ex)
        {
            ErrHandler.WriteError(ex.Message);
            return null;
        }
        return bmpOut;
    }
}

to use it

<asp:Image ID="Image1" runat="server" ImageUrl="~/ImageThumb.aspx?Image=Upload/News/1.gif&Size=70" />

Hope this helps

Good Luck

December 5, 2009

AutoComplete from Database using JQuery

Filed under: ASP.Net, Jquery — yasserzaid @ 5:26 pm

Hi

try this example to make JQuery AutoComplete from Database

Step1 :-

First download the following files jquery.autocomplete.js and jquery.autocomplete.css 

Step2 :-

Open VS 2005 and create new website and add new Web page and Web.Config and WebHandler with name “AutocompleteData.ashx”

Step3 :-

In AutocompleteData.ashx add the following code :-

<%@ WebHandler Language="C#" >

using System;
using System.Web;
using System.Data.SqlClient;

public class AutocompleteData : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        string firstname = context.Request.QueryString["q"];
        string sql = "select top 10 FirstName from Employees where FirstName like '" + firstname + "%'";
        using (SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True"))       
        using (SqlCommand command = new SqlCommand(sql, connection))
        {
            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    context.Response.Write(reader.GetString(0) + Environment.NewLine);
                }
            }
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

Note :- i am using Northwind Database in this example

Step4 :-

Open Default.aspx page and Dragr Textbox and change Id = “txt_Search”

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script src="jquery.js" type="text/javascript"></script>
  <link rel="stylesheet" href="jquery.autocomplete.css" type="text/css" />
    <script type="text/javascript" src="jquery.autocomplete.js"></script>
      <script type="text/javascript"> 
      $(document).ready(function(){ 
      $("#txt_Search").autocomplete("AutocompleteData.ashx");  }); 
      </script> 
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Search :- <asp:TextBox ID="txt_Search" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
</html>

and then run your Web page

Hope this helps

Good Lucl.

December 4, 2009

AJAX Cascade DropdownList with Linq

Filed under: AJAX, ASP.Net, Linq — Tags: — yasserzaid @ 4:20 pm

Hi

try this example to create AJAX Cascade DropdownList with Linq :-

Step1 :-

Open SQL Server 2005 and create new database and create the following Tables :-

a) Country table :- 

- Id –> int (Primary Key ) and Auto increment

- Name –> nvarchar(20)

b) City table :-

- Id –> int (Primary Key ) and Auto increment

- Name –> nvarchar(20)

- Country_Id –> int (foreign key)

Step 2 :-

Open Visual Studio 2008 and create new website and add new DataContext class called “DataClasses.dbml”

and drag Country and City table inside it

Step 3 :-

Add new Web Service called “WebService” and  in WebServive.cs add the following code :-

using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using AjaxControlToolkit;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Collections.Specialized;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]

public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public CascadingDropDownNameValue[] GetCountries(string knownCategoryValues, string category)
    {
        DataClassesDataContext db = new DataClassesDataContext();
        IEnumerable<CascadingDropDownNameValue> vals = null;
        short targetID = 0;
        vals = from tp in db.Countries
               select new CascadingDropDownNameValue
               {
                   name = tp.Name,
                   value = tp.Id.ToString(),
               };
        return vals.ToArray<CascadingDropDownNameValue>();
    }

    [WebMethod]
    public CascadingDropDownNameValue[] GetCities(string knownCategoryValues, string category)
    {
         DataClassesDataContext db = new DataClassesDataContext();
        IEnumerable<CascadingDropDownNameValue> vals = null;
        StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        short country_id;
        if (!kv.ContainsKey("Country") || !short.TryParse(kv["Country"], out country_id))
        {
            return null;
        }
        vals = from tp in db.Cities
               where tp.Country_Id == country_id
               select new CascadingDropDownNameValue
               {
                   name = tp.Name,
                   value = tp.Id.ToString(),
               };
        return vals.ToArray<CascadingDropDownNameValue>();
    }
}

Step 4 :-

Add new web page and script Manager control and two DropdownList control and two AJAX CascadingDropDown

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <table style="width: 50%;">
            <tr>
                <td>
                    Select Country :-</td>
                <td>
                    <asp:DropDownList ID="ddl_Country" runat="server">
                    </asp:DropDownList>
                    <cc1:CascadingDropDown ID="ddl_Country_CascadingDropDown" runat="server"
                        Enabled="True"
                        TargetControlID="ddl_Country"
                        LoadingText="Loding ..."
                       PromptText="Select Country"
                       ServiceMethod="GetCountries"
                       ServicePath="WebService.asmx"
                       Category="Country"
                      UseContextKey="True">
                    </cc1:CascadingDropDown>
                </td>
            </tr>
            <tr>
                <td>
                    Select City :-</td>
                <td>
                    <asp:DropDownList ID="ddl_City" runat="server">
                    </asp:DropDownList>
                    <cc1:CascadingDropDown ID="ddl_City_CascadingDropDown" runat="server"
                        Enabled="True"
                        ParentControlID="ddl_Country"
                        TargetControlID="ddl_City"
                        LoadingText="Loding ..."
                       PromptText="Select City"
                       ServiceMethod="GetCities"
                       ServicePath="WebService.asmx"
                       Category="City"
                      UseContextKey="True">
                    </cc1:CascadingDropDown>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Step 5 :-

In Code behind add the following code :-

using System;
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 AjaxControlToolkit;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
    // Country WebMethod
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static CascadingDropDownNameValue[] GetCountry(string knownCategoryValues, string category)
    {
        return new WebService().GetCountries(knownCategoryValues, category);
    }

    // City WebMethod
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static CascadingDropDownNameValue[] GetCity(string knownCategoryValues, string category)
    {
        return new WebService().GetCities(knownCategoryValues, category);
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Hope this helps

Good Luck.

AJAX Calender Date Format Validation

Filed under: AJAX, ASP.Net, Javascript — Tags: , — yasserzaid @ 11:22 am

Hi

Try this example to Validate date format with AJAX Calender Extender Control

1) Open VS 2005 and create new web site

2) Drag TextBox and AJAX Calender Control and Button control

3) Add this Javascript function to validate date format :-

function ValidateForm()
{
if(document.getElementById("txtPurchaseDate"))
{
if(validateInputDate(document.getElementById("txtPurchaseDate").value)==false)
{
alert("Please input purchase date in the format dd-mm-yyyy.");
return false;
}
}
}

//-- case 1:

//Validates date in the format dd-mm-yyyy (e.g. 19-10-2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\-.](0[1-9]1[012])[\-.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}

//-- case 2:

//Validates date in the format dd/mm/yyyy (e.g. 19/10/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\/.](0[1-9]1[012])[\/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}

//-- case 3:

//Validates date in the format dd-mm-yyyy or dd/mm/yyyy (e.g. 19-10-2009 or 19/10/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\- \/.](0[1-9]1[012])[\- \/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}

//-- case 4:

// Validates date in the format mm/dd/yyyy (e.g. 10/19/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])[\/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}

//-- case 5:

// Validates date in the format yyyy-mm-dd or yyyy/mm/dd (e.g. 2009-10-19 or 2009/10/19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\- \/.](0[1-9]1[012])[\- \/.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}

//-- case 6:

// Validates date in the format yyyy-mm-dd (e.g. 2009-10-19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\-.](0[1-9]1[012])[\-.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}

//-- case 7:

// Validates date in the format yyyy/mm/dd (e.g. 2009/10/19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\/.](0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}

Hope this helps

Good Luck.

November 30, 2009

Change Font Dynamically using Javascript

Filed under: ASP.Net, Javascript — yasserzaid @ 2:06 pm

Hi

you can check this previous post

Dynamic font size change using javascript

now i’m going to provide second way to change font dynamically using Javascript

Javascript Function :-

<script type="text/javascript">
    //Specify affected tags. Add or remove from list:
        var tgs = new Array( 'div','td','tr', 'p', 'span', 'font');
        //Specify spectrum of different font sizes:
        var szs = new Array( 'xx-small','x-small','small','medium','large','x-large','xx-large' );
        var startSz = 2;
        function ts( trgt,inc )
        {
         if (!document.getElementById) return
         var d = document,cEl = null,sz = startSz,i,j,cTags;
         sz += inc;
         if ( sz < 0 ) sz = 0;
         if ( sz > 6 ) sz = 6;
         startSz = sz;
         if ( !( cEl = d.getElementById( trgt ) ) ) cEl = d.getElementsByTagName( trgt )[ 0 ];
         cEl.style.fontSize = szs[ sz ];
         for ( i = 0 ; i < tgs.length ; i++ ) {
          cTags = cEl.getElementsByTagName( tgs[ i ] );
          for ( j = 0 ; j < cTags.length ; j++ ) cTags[ j ].style.fontSize = szs[ sz ];
         }
        }
    </script>

HTML Page :-

 <div style =" text-align:left; width:100%; padding:0; margin:0">
      <a href="javascript:ts('main',1)" ><img src="zoom-in.gif" alt="Zoom In" /></a> |
      <a href="javascript:ts('main',-1)"><img src="zoom-out.gif"  alt="Zoom Out" /></a>
   </div>
   <div id="dvKeys" style="display:none">
   </div>
   <div id="main">
    any text here
</div>

Hope this helps

Good Luck

AJAX AsynFile Upload with File Extension Validation

Filed under: AJAX, ASP.Net — Tags: — yasserzaid @ 1:26 am

Hi

try this example to validate uploaded file extenstion using AJAX AsynFileUpload control

   

 <script type="text/javascript">       
        function uploadError(sender, args) {
            //Good practice to put try,catch block. it will avoid javascript error at window status.
            try
            {
                $get("dvFileErrorInfo").style.display='block';
                $get("dvFileInfo").style.display='none';
                $get("<%=lblError.ClientID%>").innerHTML = "File Not Uploaded" + args.get_errorMessage();
            }
            catch(e)
            {
                alert(e.message);
            }
        }
               
        function uploadComplete(sender, args) {
          try
          {
             var fileExtension=args.get_fileName();
             var gif =fileExtension.indexOf('.gif');
             var png =fileExtension.indexOf('.png');
             var jpg =fileExtension.indexOf('.jpg');
             var jpeg =fileExtension.indexOf('.jpeg');
            if( gif > 0 || png > 0 || jpg > 0 || jpeg > 0)
            {
                $get("dvFileInfo").style.display='block';
                $get("dvFileErrorInfo").style.display='none';
                $get("<%=lblSuccess.ClientID%>").innerHTML = "File Uploaded Successfully";
            }
            else
            {
                $get("dvFileErrorInfo").style.display='block';
                $get("<%=lblError.ClientID%>").innerHTML = "Allowed File extension are {.gif,.png,.jpg,.jpeg} supported";
                $get("dvFileInfo").style.display='none';
                return;
            }
          
          }
          catch(e)
          {
            alert(e.message);
          }     
        }
    </script>

    <div>
        <asp:ScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
        <cc1:AsyncFileUpload ID="afuUpload" OnClientUploadError="uploadError" OnUploadedComplete="afuUpload_UploadedComplete"
            OnUploadedFileError="afuUpload_UploadedFileError" runat="server" OnClientUploadComplete="uploadComplete"
            Width="400px" UploaderStyle="Modern" UploadingBackColor="#CCFFFF" ThrobberID="myThrobber" />
        <asp:Label runat="server" ID="myThrobber" Style="display: none;">
                     <img align="absmiddle" alt="" src="Images/uploading.gif" />
        </asp:Label>
        <div style="border-style: solid; display: none; width: 350px" id="dvFileInfo">
            <asp:Label ID="lblStatus" Font-Bold="true" runat="server" Text="Status:-" /><asp:Label
                ID="lblSuccess" ForeColor="Green" runat="server" /><br />
        </div>
        <div style="border-style: solid; display: none; width: 350px" id="dvFileErrorInfo">
            <asp:Label ID="lblErrorStatus" Font-Bold="true" runat="server" Text="Status:-" /><asp:Label
                ID="lblError" ForeColor="Red" runat="server" /><br />
        </div>
    </div>

and in code behind :-

   

public void afuUpload_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
    {
        try
        {
            string savePath = MapPath("~/Images/" + Path.GetFileName(e.filename));
            /*Validation for file extension*/
            bool gif =Path.GetExtension(e.filename).Contains(".gif");
            bool png =Path.GetExtension(e.filename).Contains(".png");
            bool jpg =Path.GetExtension(e.filename).Contains(".jpg");
            bool jpeg =Path.GetExtension(e.filename).Contains(".jpeg");
            if (gif || png || jpg || jpeg)
            {
                afuUpload.SaveAs(savePath);
            }
            else
            {
                return;
            }
          
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void afuUpload_UploadedFileError(object sender, AsyncFileUploadEventArgs e)
    {
        //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "error", "top.$get(\"" + lblErrorStatus.ClientID + "\").innerHTML = 'Error: " + e.statusMessage + "';", true);
    }

Hope this helps

Good Luck

Older Posts »

Blog at WordPress.com.