Monday, May 31, 2010

To Change the Image Randomly On Post Back

use a image control with the name imgRandom and Paste the below scratched code on page Load event

Random rnd = new Random();
switch (rnd.Next(3))
{
case 0:
imgRandom.ImageUrl = “Picture1.gif”;
imgRandom.AlternateText = “Picture 1”;
break;
case 1:
imgRandom.ImageUrl = “Picture2.gif”;
imgRandom.AlternateText = “Picture 2”;
break;
case 2:
imgRandom.ImageUrl = “Picture3.gif”;
imgRandom.AlternateText = “Picture 3”;
break;
}

Functin for Moving Title of Page in JavaScript


<script type="text/javascript">
    var rev = "fwd";
    function titlebar(val) {
        var msg = "Welcome To IndiaMART WebERP";
        var res = " ";
        var speed = 100;
        var pos = val;

        //msg = "   |--- " + msg + " ---|";
        var le = msg.length;
        if (rev == "fwd") {
            if (pos < le) {
                pos = pos + 1;
                scroll = msg.substr(0, pos);
                document.title = scroll;
                timer = window.setTimeout("titlebar(" + pos + ")", speed);
            }
            else {
                rev = "bwd";
                timer = window.setTimeout("titlebar(" + pos + ")", speed);
            }
        }
        else {
            if (pos > 0) {
                pos = pos - 1;
                var ale = le - pos;
                scrol = msg.substr(ale, le);
                document.title = scrol;
                timer = window.setTimeout("titlebar(" + pos + ")", speed);
            }
            else {
                rev = "fwd";
                timer = window.setTimeout("titlebar(" + pos + ")", speed);
            }
        }
    }

    titlebar(0);
</script>

Function To Validate Only Alphabet allowed in JavaScript

function fnAlphabet(e)
{
    var code = e.keyCode ? event.keyCode : e.which ? e.which : e.charCode;
    //alert(code);
    if ((code >= 65 && code <= 90)||(code >= 97 && code <= 122) || code==46 || code==8 || code==17 || code==127 || code==9 || code==16 || code==37 || code==38 || code==39 || code==40)
    {
        checknos = true;
        return (checknos);
    }
    else
    {
        checknos= false;           
        alert("Only Alphabates Allowed !");       
        return (checknos);        }
}

Function To Validate Only Number Allowed in JavaScript

function fnNotAlphabet(e)
{
    var code = e.keyCode ? event.keyCode : e.which ? e.which : e.charCode;       
    //Code Explanation{ 0-9, 45=Insert, 13=Enter, 08=Backspace, 09=Tab}
    if ((code >= 48 && code <= 57)||(code == 45 || code == 13 || code == 08 || code == 09))
    {
        checknos = true;
        return (checknos);
    }
    else
    {
        checknos= false;
        alert("Only Number Allowed !");   
        return (checknos);
    }
}

Function To Validate Mobile No. in JavaScript

function validateMobileNumber(idMobileNumber, idColumnLabelToHighlight)
{
    var varMobileNumber = document.getElementById(idMobileNumber).value;
    if(isNaN(varMobileNumber) || varMobileNumber.indexOf(" ")!=-1)
    {
        alert("Mobile Number : Enter numeric value");
        document.getElementById(idColumnLabelToHighlight).style.color="#ff0000";       
        return false; 
    }
    if (varMobileNumber.length != 10 )
    {
        alert("Mobile Number : Enter 10 characters valid mobile number without 0");
        document.getElementById(idColumnLabelToHighlight).style.color="#ff0000";       
        return false;
    }
   
    if (varMobileNumber.charAt(0)!=8 && varMobileNumber.charAt(0)!=9)
    {
     
        alert("Mobile Number : The number can only start with 8 or 9.");
        document.getElementById(idColumnLabelToHighlight).style.color="#ff0000";       
        return false
    }
   
    document.getElementById(idColumnLabelToHighlight).style.color="#000000";
    return true;
}

Function To Check Adult in JavaScript

function checkIfAdult(idYear, idMonth, idDay, idColumnLabelToHighlight)
{
    var varYear = document.getElementById(idYear).value;
    var varMonth = document.getElementById(idMonth).value;
    var varDate = document.getElementById(idDay).value;

    var toDay = new Date();
    var AgeToCompare = new Date();
   
    AgeToCompare.setDate(varDate);
    AgeToCompare.setMonth((parseInt(varMonth)-1));
    AgeToCompare.setFullYear(varYear);
    //alert("Diff : ");
    var currentYear = toDay.getFullYear();
    var toCompareYear = AgeToCompare.getFullYear();
    //alert("Inside");
    var currentMonth = toDay.getMonth();
    var toCompareMonth = AgeToCompare.getMonth();
    //alert("Inside");

    var currentDay = toDay.getDate();
    var toCompareDay = AgeToCompare.getDate();
    //alert("Inside");
   
    var toReturn = true;
       
    //alert("Diff : " + (currentYear - toCompareYear)) ;
    document.getElementById(idColumnLabelToHighlight).style.color="#000000";   
    if( (currentYear - toCompareYear)  > 17 )   
    {
        //alert("> 17");
        toReturn = true;
    }
    else if( (currentYear - toCompareYear)  == 17 )   
    {
        //alert("= 17");
       //alert("Diff : " + (currentMonth - toCompareMonth)) ;
        if( (currentMonth - toCompareMonth)  > 0 )   
        {
            toReturn = true;
        }
        else if( (currentMonth - toCompareMonth)  == 0 )   
        {
            //alert("Diff : " + (currentDay - toCompareDay)) ;
            if( (currentDay - toCompareDay)  > 0 ) 
            { 
                toReturn = true;
            }   
            else
            {
                toReturn = false;
            }   
        }
        else
        {
             toReturn = false;
        }  
        document.getElementById(idColumnLabelToHighlight).style.color="#000000";
    }
    else
    {
        toReturn = false;
    }
    if(toReturn == false)
    {
        alert("Date Error : Only adults can book use this.");
        document.getElementById(idColumnLabelToHighlight).style.color="#ff0000";
        return false;
    }
    return toReturn;
}

Sending Mail With ASP.NET

One of the common functionalities used in Web development is sending email from a Web page. A common use of sending email from a Web page is allowing site visitors to fill in comments via an HTML form and send them to the Webmaster. The .NET Framework makes the task of sending email from a Web page relatively simple. In order to send an email from an ASP.NET Web page you need to use the SmtpMail class found in the System.Web.Mail namespace, which contains a static method Send.
Sending Email 
The namespace that needs to be imported to send an email is the System.Web.Mail namespace. We use the SmtpMail and MailMessage classes of this namespace for this purpose. The MailMessage class provides properties and methods for constructing an email message. To start, open a Web Forms page, drag a Button control on to the form, switch to code view and paste the following code.

Imports System.Web.Mail
'namespace to be imported

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
Dim mailMessage As New MailMessage()
'creating an instance of the MailMessage class
mailMessage.From = "xyz@mydomain.com"
'senders email address
mailMessage.To = "abc@sendersemail.com"
'recipient's email address
mailMessage.Cc = "carboncopy@sendersemail.com"
'email address of the Cc recipient
mailMessage.Bcc = "blindcarboncopy@sendersemail.com"
'email address of the Bcc recipient
mailMessage.Subject = "Hello"
'subject of the email message
mailMessage.BodyFormat = MailFormat.Text
'message text format. Can be text or html
mailMessage.Body = "This tutorial is sending email with an ASP.NET app."
'message body
mailMessage.Priority = MailPriority.Normal
'email priority. Can be low, normal or high
SmtpMail.SmtpServer = "mail.yourserver.com"
'mail server used to send this email. modify this line based on your mail server
SmtpMail.Send(mailMessage)
'using the static method "Send" of the SmtpMail class to send the mail
Response.Write("Mail sent")
'message stating the mail is sent
End Sub
The above code sends an email when the button is clicked. That's fine for the purpose of learning but when you have a feedback form on your Web site with textboxes, labels, etc, you need to slightly modify the above code. The following is the complete, functional code for an ASP.NET page that sends an email to the Webmaster of the site.
To start, drag seven labels, six textboxes and two buttons on to the Web forms page designer. The user interface for this sample can be found at the bottom of this page. The modified code looks as follows:
Imports System.Web.Mail

Private Sub SendMail_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles SendMail.Click
Dim mailMessage As New MailMessage()
mailMessage.From = TextBox1.Text
mailMessage.To = "admin@startvbdotnet.com"
'you also can set this to TextBox2.Text
mailMessage.Cc = TextBox3.Text
mailMessage.Bcc = TextBox4.Text
mailMessage.Subject = TextBox5.Text
mailMessage.BodyFormat = MailFormat.Text
mailMessage.Body = TextBox6.Text
'textbox6 TextMode property is set to MultiLine
mailMessage.Priority = MailPriority.Normal
SmtpMail.SmtpServer = "mail.yourserver.com"
'mail server used to send this email. modify this line based on your mail server
SmtpMail.Send(mailMessage)
Label6.Text = "Your mail was sent"
'message stating the mail is sent
End Sub

Private Sub Reset_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Reset.Click
TextBox1.Text = " "
TextBox2.Text = " "
TextBox3.Text = " "
TextBox4.Text = " "
TextBox5.Text = " "
TextBox6.Text = " "
'resetting all the value to default i.e null
End Sub

Sunday, May 30, 2010

To Prevent Click Again and Again During Processing....

-------------- On the Page Load Event --------------
Me.btn_Save.Attributes.Add("onclick", "if (confirm('Are You For Save?')){this.value='Please wait...';this.disabled=true;} else {return false;}" & ClientScript.GetPostBackEventReference(Me.btn_Save, "Save"))

Saturday, May 29, 2010

To Do Properly Work AJAX with Asp.net 2005

Download ASPAJAXSETUP 2.0 over Net and install it.
Add a  tab on Toolbar by  the name Ajax Extender.
Right Click on your Toolbar and click on Choose Items. Select Update Panel, Script Manager, Update Progress.

In Web.Config Add Following........

<httpHandlers>
            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
           <add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</httpHandlers>
           
<runtime>
       <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31BF3856AD364E35"/>
                <bindingRedirect oldVersion="3.5.0.0" newVersion="1.0.61025.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31BF3856AD364E35"/>
                <bindingRedirect oldVersion="3.5.0.0" newVersion="1.0.61025.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>         
Now get enjoy with AJAX................

Generate Excel Report

Public Sub GenExlReport(ByVal P_DataSet As Data.DataSet, ByRef P_refdatagrid As DataGrid, ByRef P_HttpResponse As Web.HttpResponse, ByRef P_Page As Page)
        If P_DataSet Is Nothing Then P_HttpResponse.Write("Error in generation of Exl Report") : Exit Sub
        Dim DSList As New Data.DataSet
        Dim MyView As New Data.DataView
        Dim stringWrite As New System.IO.StringWriter
        Dim htmlWrite As New HtmlTextWriter(stringWrite)
        Try
            DSList = P_DataSet
            MyView.Table = DSList.Tables(0)
            With P_refdatagrid
                .DataSource = MyView
                .DataBind()
                .Visible = True
            End With
            With P_HttpResponse
                .Clear()
                .AddHeader("content-disposition", "attachment;filename=FileName.xls")
                .Charset = String.Empty
                .Cache.SetCacheability(HttpCacheability.NoCache)
                .ContentType = "application/vnd.xls"
            End With
            P_refdatagrid.RenderControl(htmlWrite)
            P_HttpResponse.Write(stringWrite.ToString())
            P_refdatagrid.Visible = False
            P_HttpResponse.End()
        Catch ex As Exception
            P_HttpResponse.Write("Error in generation of Exl Report")
        Finally
            DSList.Dispose() : MyView.Dispose()
            stringWrite.Dispose() : htmlWrite.Dispose()
        End Try
End Sub

Hide Extention of Pages in url

In Global.aspx
Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim fullOrigionalpath As String = Request.Url.ToString()
        If (fullOrigionalpath.EndsWith("/Test/Default")) Then
            Context.RewritePath("/Test/Default.aspx")
        ElseIf (fullOrigionalpath.EndsWith("/Test/Default2")) Then
            Context.RewritePath("/Test/Default2.aspx")
        Else
            If fullOrigionalpath.EndsWith(".aspx") Or fullOrigionalpath.EndsWith(".php") Then Context.RewritePath("/Test/CustomError.aspx")
       End If
    End Sub
  
    Protected Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As System.EventArgs)
        If Request.UserHostAddress.StartsWith("198.168") Then
            Context.RewritePath("/Test/right.aspx")
        End If
    End Sub

Friday, May 28, 2010

Generate Random Password

 Public Function CreateRandomPassword(ByVal PwdLength As Integer) As String
        Dim _allowedChars As String = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"
        Dim rndNum As New Random()
        Dim chars(PwdLength - 1) As Char
        Dim strLength As Integer = _allowedChars.Length
        For i As Integer = 0 To PwdLength - 1
            chars(i) = _allowedChars.Chars(CInt(Fix((_allowedChars.Length) * rndNum.NextDouble())))
        Next i
        Return New String(chars)
    End Function

Write Image On the Page

Private Sub WriteImage(ByVal EmpImg As String)
Response.Clear()
Response.ContentType = "image/jpg"
Dim imgBytes As Byte()
Using img As System.Drawing.Image = System.Drawing.Image.FromFile(Server.MapPath(EmpImg))
Dim ms As IO.MemoryStream = New IO.MemoryStream()
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
ms.Close()
imgBytes = ms.GetBuffer()
End Using
Response.OutputStream.Write(imgBytes, 0, imgBytes.Length)
Response.Flush()
Response.End()
End Sub