Archive

Archive for December, 2009

Email Validation

December 26, 2009 Leave a comment

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.

AJAX HTML Editor and validation

December 18, 2009 3 comments

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

Categories: AJAX, ASP.Net, Javascript

Reset Controls in Web Form

December 16, 2009 2 comments

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.

Categories: ASP.Net, Javascript

Dynamic DropDownList with Month Names

December 16, 2009 1 comment

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.

Categories: ASP.Net

Resizing images without loss of quality in ASP.NET

December 12, 2009 Leave a comment

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

Categories: ASP.Net

AutoComplete from Database using JQuery

December 5, 2009 16 comments

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.

Categories: ASP.Net, Jquery

AJAX Cascade DropdownList with Linq

December 4, 2009 11 comments

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.