Friday, June 20, 2014

2-Step Verification like Google in ASP.NET C#

In this article I have done a log in function with 2-Step verification as like we see in Google or in Facebook. To send a message I have used Site2SMS API from ASPSnippet.com. You can any others to do the SMS functionality.

First create a database named DBTest and create a table named tblUser.


CREATE TABLE [dbo].[tblUser](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [Email] [nvarchar](50) NULL,
 [Name] [nvarchar](50) NULL,
 [Password] [nvarchar](50) NULL,
 [PhoneNo] [nvarchar] (20)
)

Now create a new project...

add a login page with two panel. One for login and one for mobile verification.

<body>
    <form id="form1" runat="server">
    <div align="center">
        <asp:Panel ID="PanelLogin" runat="server" style="padding: 10px 10px 10px 10px" 
            BorderColor="#0099FF" BorderStyle="Solid" BorderWidth="1px">
            <h1>Login Now</h1>
            <asp:TextBox ID="txtEmail" runat="server" placeholder="Email"></asp:TextBox>
            <br />
            <asp:TextBox ID="txtPassword" runat="server" TextMode ="Password" placeholder="Password"></asp:TextBox>
            <br />
            <asp:Button ID="btnLogin" runat="server" Text="Login" 
                onclick="btnLogin_Click" />
        </asp:Panel>
        <asp:Panel ID="PanelMobile" runat="server" Visible="false"  style="padding: 10px 10px 10px 10px" 
            BorderColor="#0099FF" BorderStyle="Solid" BorderWidth="1px">
            <h1>Code</h1>
            <br />
            <br />
            <asp:TextBox ID="txtCode" runat="server" placeholder="Code"></asp:TextBox>
            <br />
            <asp:Button ID="btnOk" runat="server" Text="Ok" onclick="btnOk_Click" />
        </asp:Panel>
    </div>
    </form>
</body>

In the Code behind part write down the code.



SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["DBCon"].ToString());
 
protected void btnLogin_Click(object sender, EventArgs e)
{
     string sql = "select * from tblUser where email='" + txtEmail.Text.Trim() + "' and  password='" + txtPassword.Text.Trim() + "' ";
     SqlDataAdapter da = new SqlDataAdapter(sql,con);
     DataTable dt = new DataTable();
     da.Fill(dt);
 
     if (dt.Rows.Count > 0)
     {
          PanelLogin.Visible = false;
          PanelMobile.Visible = true;
          Session["Code"] = generate_code();
          Session["TempName"] = dt.Rows[0]["Name"].ToString();
          sendSMS(Session["Code"].ToString(), dt.Rows[0]["PhoneNo"].ToString();
          //txtCode.Text = Session["Code"].ToString();       only for testing purpose
      }
      else
     {
          Response.Write("<script>alert('Wrong username and password');</script>");
     }
}
 
private string generate_code()
{
      var chars = "0123456789";
      var stringChars = new char[5];
      var random = new Random();
 
      for (int i = 0; i < stringChars.Length; i++)
      {
          stringChars[i] = chars[random.Next(chars.Length)];
      }
      var finalString = new String(stringChars);
      return finalString.ToString();
}
 
protected void btnOk_Click(object sender, EventArgs e)
{
      if (txtCode.Text.Trim()==Session["Code"].ToString())
      {
            Session["Name"] = Session["TempName"];
            Session.Remove("TempName");
            Session.Remove("Code");
 
            Response.Redirect("home.aspx");
       }
       else
       {
            Response.Write("<script>alert('Wrong code');</script>");
       }
}
 
private void sendSMS(string code, string phone)
{
       SMS.APIType = SMSGateway.Site2SMS;
       SMS.MashapeKey = "<Your API Key>";
       SMS.Username = "<Login Id>";
       SMS.Password = "<Password>";
       SMS.SendSms(phone, "Your code is " + code + ".");
}

Now add the home page. And your project is ready. To get the SMS API go here in http://www.aspsnippets.com/.
http://www.aspsnippets.com/Articles/How-to-send-free-SMS-from-ASPNet-application-to-Mobile.aspx

You can download the full source code here.

Monday, June 16, 2014

How to add a FB Like box in your ASP.NET project


Here in this article I will show you how to add a Facebook like box in your asp.net project. All you need a Facebook page and a ASP project.

First create a Facebook page and go to bellow line.

https://developers.facebook.com/docs/plugins/like-box-for-pages/

In the Facebook page URL place the URL of your page. Choose theme, height, width and all others thing. Every changes you do that will reflects in your output bellow.

Now click on the "Get Code" button and choose the app first. It will enlisted with the app that you have created. Choose one one of them, and if you does not have the app then create one.

To create a app go to app dashboard. And copy the App Id and App Secret key, add name, email and other details and click on save on the setting.

On the HTML5 tab copy the both codes and place it in your asp.net project.
Don't forget to change the js.src to add "http:". Now your page is ready to display Facebook like box.

Enjoy your Facebook like box... :)


Sunday, June 15, 2014

Generate auto id as column id in a repeater in ASP.NET C#

In this example I will show how to add a auto id number as the column no of a repeater.

Lets take a repeater and bind it with a SQLDataSource or by coding. Now add a column to show the index no of the repeater as per your design.

As my design this is the repeater.


<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div>
   <div><%# Container.ItemIndex + 1 %></div>
   <div>message</div>
</div>
</ItemTemplate>
</asp:Repeater>

Hope you understand which part is creating the index value(column id)..

<%# Container.ItemIndex + 1 %>

Here it is. Place it any where as per your requirement.

Happy coding. :)

Tuesday, June 10, 2014

How to send mail from GoDaddy server in ASP.NET C#


I found some errors in sending mail from a GoDaddy server, and after searching a lot I found the correct solution to send mail.

First add these namespaces in your project





using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.Net.Mail;

Now the send mail method is



public void Send_User_Confirmation_Mail()
{
    MailMessage mail = new MailMessage();
    mail.To.Add("<email to send>");
    mail.From = new MailAddress("<send mail>");
 
    mail.Subject = "Account Created.";
          
    string Body = "<body>";
 
    mail.Body = Body;
    mail.IsBodyHtml = true;
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "relay-hosting.secureserver.net";
    smtp.EnableSsl = true;
    smtp.Credentials =  
      new System.Net.NetworkCredential("<send email>"), "<send password>");
    ServicePointManager.ServerCertificateValidationCallback =  
      delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) 
      { return true; };
    smtp.Port = 25;
    smtp.Send(mail);
}

These are main things to add with your normal mail sending code.



smtp.Host = "relay-hosting.secureserver.net";
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["Send_Mail_From_Email"].ToString(), ConfigurationManager.AppSettings["Send_Mail_From_Password"].ToString());
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
smtp.Port = 25;

Before adding there 3rd line of credential I was getting error of some invalid certificate issue to send a mail. But adding these all the issue become normal and mail is sending without any problem.

Saturday, June 7, 2014

How to create a new GUID in C#

In this small tutorial I will show you how to create a GUID in your ASP.NET application.

But what is actually GUID is?

According to Wikipedia
A Globally Unique Identifier (GUID) is a unique reference number used as an identifier in computer software. The term GUID typically refers to various implementations of the universally unique identifier (UUID) standard.
There are two ways to create a new GUID.
  1. Guid.NewGuid() [NewGuid() method]
  2. new Guid() 
In the first method it always return a valid and unique GUID every time. But the second one is produced a bit of zero(0), like 00000000-0000-0000-0000-000000000000. But in the first one you will get an unique id every time like 8bd3ee4f-8069-4175-a6d1-b990e9e1a633.

So you can use the following code easily to generate a new GUID in your ASP.NET project.

protected void btnGenerateGuid_Click(object sender, EventArgs e)
{
   /* Createing a new Guid */
   String guid = Guid.NewGuid().ToString();
   /* Print the output */
   Response.Write(guid.ToString());
}

Wednesday, June 4, 2014

Add Master page dynamically in your ASP.NET project C#

Here in this tutorial I will show you how to bind a page with a master page dynamically in your ASP.NET project with C#.

First of all create a new project. Then add two new master pages and one web page which will be inheriting any one of those created master page.

Now in the page PreInit event of the web page write the following code.


protected void Page_PreInit(object sender, EventArgs e)
{
    this.Page.MasterPageFile = "~/Site2.master";
}

Now run the project and do your own functionality to add your master page in other events like button click or radio button checked event as per your requirement.

Download the full source code here.

Popular Posts

Pageviews