Apr 18, 2011

Session state -- Cookies

Cut and paste the code as Shown

default.aspx
<%--<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>--%>


default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
    {

        //how to check browser supports cookies
        if (Request.Browser.Cookies)
        {
            Response.Write("Browser supports cookies");
        }
        else
        {
            // Web browser not supports cookies
        }


        string MyCookieValue="hello";
        // We need to perform this check first, to avoid null exception
        // if cookie not exists
        if (Request.Cookies["MyCookieName"] != null)
            MyCookieValue = Request.Cookies["MyCookieName"].Value;
        Label1.Text = MyCookieValue;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        // Use this line when you want to save a cookie
        Response.Cookies["MyCookieName"].Value = TextBox1.Text ;
        // How long will cookie exist on client hard disk
        Response.Cookies["MyCookieName"].Expires = DateTime.Now.AddDays(1);

        // To add multiple key/value pairs in single cookie
        Response.Cookies["VisitorData"]["FirstName"] = "Richard";
        Response.Cookies["VisitorData"]["LastVisit"] = DateTime.Now.ToString();

    }
//  HttpCookie MyGreatCookie = new HttpCookie("MyCookieName");
//  MyGreatCookie.Value = "Some cookie value";
//  MyGreatCookie.Expires = DateTime.Now.AddDays(100);
//  Response.Cookies.Add(MyGreatCookie);


//    Cookie size is limited to 4096 bytes. It is not much, so cookies are used to store
//    small amounts of data, often just user id.

//    Also, number of cookies is limited to 20 per website.
//    If you make new cookie when you already have 20 cookies, browser will delete oldest one.

Validation control in Asp.Net 3.5

Remove Comments

default.aspx

<%--<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Validation Server Controls</title>
<script type="text/javascript">
function validatenumber(oSrc,args)
{
        var str = document.getElementById('<%=TextBox5.ClientID%>').value;

        alert(str.length);
        args.IsValid = (args.Value % 6 == 0)
       
}

</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h3>RequiredFieldValidator checks to see that textbox has data before you click submit button.In essence,it enforces Mandatory field rule <br/></h3>
    <h3>When Validation fails, "Required!" will be displayed</h3>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1"  Text="Required!" runat="server" ValidationGroup="Submit" ErrorMessage="Required!" ControlToValidate="TextBox1">
        </asp:RequiredFieldValidator>
        <asp:Button ID="Button1" runat="server" ValidationGroup="Submit" Text="Submit"/>
    </div>
    <div>
    <h3>CompareFieldValidator,as name says, compares two form element's values against each other.It enforces "Same-As" rule.</h3>
        <table>
        <tr>
        <td>
        <asp:Label ID="Label1" runat="server" Text="Enter Password"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="TextBox2"  TextMode="Password" runat="server"></asp:TextBox>
        </td>
        </tr>
        <tr>
        <td>
        <asp:Label ID="Label2" runat="server" Text="Confirm Password"></asp:Label>
        </td>
        <td>
            <asp:TextBox ID="TextBox3" TextMode="password" runat="server"></asp:TextBox>
        </td>
        <td>
        <asp:Button ID="Button2" runat="server" Text="Login"/>
        </td>
        </tr>
        </table>
        <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="Passwords don't match!" ControlToValidate="TextBox3"
        ControlToCompare="textbox2" ></asp:CompareValidator>
    </div>
    <div>
    <h3>RangeValidators enforces that values you enter fall under specified range.It enforces "Between-the" rule.</h3>
        <asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="Value must be between 20 and 30" ControlToValidate="RangeTextbox"
        Type="Integer" MinimumValue="20" MaximumValue="30"  Text="*">
        </asp:RangeValidator>
        <asp:TextBox ID="RangeTextbox" runat="server"></asp:TextBox>
        <asp:Button ID="CheckRange" runat="server" Text="CheckRange" />
    </div>
    <div>
    <h3>RegularExpressionValidator checks for a specific pattern.It enforces "As-is" rule.</h3>
        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" Text="*"  ControlToValidate="Textbox4" runat="server"
        ErrorMessage="You must enter an email address" ValidationGroup="CheckMail" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
        <asp:Button ID="Button3" runat="server" ValidationGroup="CheckMail" Text="CheckMail"/>
    </div>
    <div>
    <h3>CustomValidator control to implement custom tailored Validations. It enforces "My-Own" rule.</h3>
        <asp:CustomValidator ID="CustomValidator1" runat="server"
        ControlToValidate="textbox5"  ClientValidationFunction="validatenumber"
        ErrorMessage="Number is not divisible by 6"></asp:CustomValidator>
        <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
        <asp:Button ID="Button4" runat="server" Text="Divisible" />
        </div>
        <asp:ValidationSummary ID="ValidationSummary1" DisplayMode="BulletList"  HeaderText="You received following errors" runat="server" />
    </form>
</body>
</html>
--%>

Dynamic control in asp.net 3.5

default.aspx
<!--
 <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
            style="height: 26px" />
 </div>
--!>

default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
    {
        TextBox new_textbox = new TextBox();
        new_textbox.ID = "txt" + 1;
        new_textbox.Text = "";
        PlaceHolder1.Controls.Add(new_textbox);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string OptionID = "txt" + 1;
        TextBox tb = (TextBox)PlaceHolder1.FindControl(OptionID);
        Response.Write(tb.Text);
   
    }






Apr 16, 2011

Asp. net 2.0/3.5/4.0 Email code for gmail/hotmail/yahoo-1

default.aspx page

<%--<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
        <br />
        Subject :&nbsp;
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
        <br />
        Email :
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
        <br />
        Msg : &nbsp;&nbsp;
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Send" /></div>
    </form>
</body>--%>

default.aspx.cs page
public partial class _Default : System.Web.UI.Page
{
    EmailClass email = new EmailClass();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string file1 = FileUpload1.PostedFile.FileName;
        email.SendMail(TextBox3.Text, TextBox2.Text, TextBox1.Text);
        if (email.a)
        {
            Label1.Text = "Mail Sent !!";
        }
        else
        {
            Label1.Text = "Not Sent";
        }
    }
}

put this class file in app_code folder and save with name :  Email.cs

hello
public class EmailClass
{
    public bool a;
    public EmailClass()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public void SendMail(string msg, string to, string subject)
    {
        //try
        //{
        MailMessage mail = new MailMessage();
        mail.To.Add(to);
        mail.From = new MailAddress("abc@gmail.com");
        mail.Subject = subject;

        string Body = null;
        Body = msg;
        mail.Body = Body;
        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        //smtp.UseDefaultCredentials = false;
        smtp.Host = "smtp.gmail.com";
           smtp.Credentials = new System.Net.NetworkCredential("abc@gmail.com", "password");
        smtp.EnableSsl = true;

        smtp.Send(mail);
        a = true;
        //}
        //catch (Exception ex)
        //{
        //ex.ToString();
        //a = false;
        // }


    }


}






Asp. net 2.0/3.5/4.0 Email code for gmail/hotmail/yahoo

just copy the default.aspx code and remove the comment

default.aspx code

<%--<body>
    <form id="form1" runat="server">
    <div>
    <fieldset style="width: 500px; padding: 10px;">
        <legend>Sending email from GMail</legend>
        <div align="left" style="padding: 5px;">
            Your Gmail EmailID<br />
            <asp:TextBox ID="TextBoxSenderEmailId" runat="server" Width="250px"></asp:TextBox><font color=silver>Please enter your GMailId <br />(e.g yourId@gmail.com)</font><br /><br />
            Friend's EmailId<br />
            <asp:TextBox ID="TextBoxReceiverEmailId" runat="server" Width="250px"></asp:TextBox><font color=silver>Please enter your friend's emailId<br />(e.g abc@xyz.com)</font><br />
            <br />
            Subject<br />
            <asp:TextBox ID="TextBoxSubject" runat="server" Width="350px"></asp:TextBox><br />
            <br />
            Body<br />
            <asp:TextBox ID="TextBoxBody" Width="350px" TextMode="MultiLine" Rows="5" runat="server"></asp:TextBox><br /><br />
            <asp:Button ID="btnSendEmail" runat="server" OnClick="btnSendEmail_Click" Text="Send" />
        </div>
    </fieldset>

    </div>
    </form>
</body>--%>


just copy the sendemail button code and put it in button click event
and make necessary changes

default.aspx.cs

protected void btnSendEmail_Click(object sender, EventArgs e)
    {
        try
        {
            //MailMessage class are used to construct e-mail messages
            MailMessage message = new MailMessage();

            // Collaboration Data Objects (CDO) library allows you to access the Global Address
            // List and other server objects, in addition to the contents of mailboxes
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);

            //basic authentication
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "abc@gmail.com");

            //set your username here
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "password");

            //set your password here
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "True");

            message.From = "xyz@gmail.com";
            message.To = "abc@gmail.com";
            message.Subject = TextBoxSubject.Text ;
            message.Body = TextBoxBody.Text ;

            //if (!txtAttach.Text.Equals("")) //adding attachments.
            //{
            //    MailAttachment attach = new MailAttachment(txtAttach.Text);
            //    if (attach != null)
            //    {
            //        message.Attachments.Add(attach);
            //    }
            //}
            SmtpMail.SmtpServer = "smtp.gmail.com";
           
            //The real server goes here
            SmtpMail.Send(message);

            Response.Write("Your message has been sent.");
            //MessageBox.Show("Your message has been sent.", "Mail Sent",MessageBoxButtons.OK, MessageBoxIcon.None);
        }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    //I have to attach a file so,I created a button called btnAttach.
    private void btnAttach_Click_1(object sender, EventArgs e)
    {
        //DialogResult clicked = OpenattachDialog.ShowDialog();
        //if (clicked.Equals(DialogResult.OK))
        //{
        //    txtAttach.Text = OpenattachDialog.FileName;
        //}
    }//btnAttach






Image Gallery - Image Add/Delete/Preview - Single Page App -

https://github.com/TheKalin/jQuery-File-Upload.MVC5 Helper Class / Models   public class FilesHelperDB     {         dbImageGallery...