Pages

Thursday, August 22, 2013

How to Create Captcha in Asp.net

This article we are explaining how to create captcha image or captcha code in asp.net. The Captcha is an acronym based on the word "capture" and standing for "Completely Automated Public Turing test to tell Computers and Humans Apart. Ti implement Captcha image we are using three namespace 'System.Drawing', 'System.Drawing.Imaging' and 'System.Text'.

Step 1
Firstly go in 'Default.aspx' page and add following control. In ImageUrl change your page name. In this example page name is 'CaptchaImg.aspx' so we have added  'CaptchaImg.aspx' in imageUrl.

<form id="form1" runat="server">
        <div>
            <asp:Image ID="ImgCaptcha" runat="server"
                ImageUrl="~/CaptchaImg.aspx" /> <%--change here page name--%>
            <br />
            <br />
            Enter captcha code:
            <asp:TextBox ID="TxtCaptcha" runat="server">
            </asp:TextBox>
            <asp:Button ID="BtnCaptcha" runat="server"
                Text="Validate" OnClick="BtnCaptcha_Click" />
            <br />
            <br />
            <asp:Label ID="lbCaptcha" runat="server" Font-Bold="True"
                Text=""></asp:Label>
        </div>
  </form>

Step 2
In 'Default.aspx.cs' page add following code.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    private Random rand = new Random();

    private string GetRandomText()
    {
        StringBuilder strRendom = new StringBuilder();
        string alphabets = "abcdefghijklmnoporstuvwxyzABCDEFGHIJKLMNOPQRSTOVWXYZ0123456789";
        Random random = new Random();
        for (int i = 0; i <= 5; i++)
        { strRendom.Append(alphabets[random.Next(alphabets.Length)]); }
        Session["CaptchaCode"] = strRendom.ToString();
        return Session["CaptchaCode"] as String;
    }

    private Point[] GetRandomPoints()
    {
        Point[] points = { new Point(rand.Next(0, 150), rand.Next(1, 150)),
        new Point(rand.Next(0, 200), rand.Next(1, 190)) };
        return points;
    }

    private void DrawRandomLines(Graphics grph)
    {
        SolidBrush lineColor = new SolidBrush(Color.Yellow);
        for (int i = 0; i < 20; i++)
        { grph.DrawLines(new Pen(lineColor, 1), GetRandomPoints()); }
    }

    private void CreateCaptchaImage()
    {
        string code = GetRandomText();
        Bitmap bitmap = new Bitmap(200, 60, System.Drawing.Imaging.PixelFormat.Format48bppRgb);
        Graphics graph = Graphics.FromImage(bitmap);
        Pen penColor = new Pen(Color.YellowGreen);
        Rectangle rect = new Rectangle(0, 0, 200, 75);
        SolidBrush rectColor = new SolidBrush(Color.DarkBlue);
        SolidBrush txtColor = new SolidBrush(Color.WhiteSmoke);
        int counter = 0;
        graph.DrawRectangle(penColor, rect);
        graph.FillRectangle(rectColor, rect);

        for (int i = 0; i < code.Length; i++)
        {
            graph.DrawString(code[i].ToString(),
            new Font("Lucida Handwriting", 10 + rand.Next(15, 20), FontStyle.Italic), txtColor,
            new PointF(10 + counter, 10));
            counter += 28;
        }

        DrawRandomLines(graph);
        bitmap.Save(Response.OutputStream, ImageFormat.Gif);
        graph.Dispose();
        bitmap.Dispose();
    }

    protected void BtnCaptcha_Click(object sender, EventArgs e)
    {
        if (Session["CaptchaCode"] != null && TxtCaptcha.Text == Session["CaptchaCode"].ToString())
        {
            lbCaptcha.ForeColor = Color.Green;
            lbCaptcha.Text = "Captcha code is valide";
        }
        else
        {
            lbCaptcha.ForeColor = Color.Red;
            lbCaptcha.Text = "Captcha code is wrong!!";
        }
    }
}

Step 3

Finally run project.

Wednesday, August 21, 2013

How to Upload Large file in Asp.net

In this article we are explaining how to upload large file in asp.net. In previous article we discussed How to upload file in asp.net. But problem is that when we want to upload large file more than 4MB using File Upload control then file is not upload and display an error 'Maximum request length exceeded'. This type of problem is occurring because The 4MB default is set in machine.config. But you can override it in your web.config.

Step 1
Go in solution explorer and double click on 'web.config' file.

Step 2
In 'web.config' file and write following code.

<system.web>
  <httpRuntime executionTimeout="240" maxRequestLength="20480" />
</system.web>

Step 3

Now run project and try to upload large file.

How to Send Mail from Office Email Id in Asp.net

In previous article we discussed How to Send Mail in asp.net where we used Gmail domain for send mail. Buts in this article we are going to explain how to send mail using office email id or office domain. To send mail firstly we have to use a namespace 'System.Net.Mail'. After add namespace write following code on Button click in 'Default.aspx.cs' page.

Send mail using office domain

protected void SendBtn_Click(object sender, EventArgs e)
    {
        MailMessage mailMsg = new MailMessage();

        mailMsg.To.Add(new MailAddress("receiver@gmail.com")); //Receiver Email Id
        mailMsg.From = new MailAddress("sender@companyname.com"); //Your office email id
        mailMsg.Subject = "mail test";
        mailMsg.Body = "Hello Friends";
        mailMsg.BodyEncoding = System.Text.Encoding.UTF8;
        mailMsg.SubjectEncoding = System.Text.Encoding.UTF8;

        SmtpClient smtp = new SmtpClient();
        smtp.Port = 25;
        smtp.Host = "mail.companyname.com"; //Host name of office domain
        System.Net.NetworkCredential nc = new System.Net.NetworkCredential("sender@companyname.com", "password");
        smtp.EnableSsl = true;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = nc;
        smtp.Send(mailMsg);

        try
        {
            smtp.Send(mailMsg);
            Response.Write("Your Mail has been Sent");
        }

        catch (Exception er)
        {
            Response.Write("Error in Mail Sending");
        }

    }

Tuesday, August 20, 2013

How to Create a Simple Windows Store App using C#

This article will explain how to create a simple windows store app using C# and Xaml. To create windows store app must you have a windows 8 computer or higher, visual studio 2012 or higher and Microsoft Account. When you want to create windows store app at first time then its ask developer licence for windows store apps. To get developer licence you must have to login windows store apps with Microsoft Account. After login follow this steps.

Step 1
Start visual studio 2012 or higher and start new project. In new project window find Windows store apps and select 'Blank App' the give the app name and click on 'OK'.



Step 2
In step 2 go in solution explorer and double click on 'MainPage.xaml'.


Step 3
In 'MainPage.xaml' page add control within 'Grid'. Here we have add an Button, Textbox and Textbook.

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Button Content="Click" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="786,242,0,0" Click="Button_Click_1"/>
        <TextBox HorizontalAlignment="Left" Name="txtBox" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Margin="601,242,0,0" Width="180" Height="38"/>
        <TextBlock HorizontalAlignment="Left" Name="lblMsg" FontSize="25" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Margin="601,200,0,0" Width="251" />
    </Grid>

Step 4
At the click of 'Button' in 'MainPage.xaml.cs' page write following code.

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    lblMsg.Text = "Hello "+txtBox.Text;
}

Step 5

Now build and run you project.