How to create treeview from database in asp.nt


Description:-
In this Example we will Show to Create Tree view from Data Base. Tree view is Nothing but graphical control element that presents a hierarchical view of information. Each item can have a number of sub items. This is often visualized by indentation in a list.

Web.config:-
To create Tree-view Create Connection in Web.Config File so we Don't Have to Repeat Each time in Code behind File.

 <connectionStrings>
    <add connectionString="Data Source='YourConnectionString';User ID='Your UserName';Password='Your PassWord'" name="DBCS" providerName="System.Data.SqlClient" />
  </connectionStrings>

Default.aspx:-
Now Create Web Page and Drag Tree view control in Page and Give Some Property for Design Tree view in Web Page.

   <div>
        <h3>
            Vehicle Details</h3>
        <hr />
        <asp:TreeView ID="TreeView1" runat="server" ImageSet="XPFileExplorer" NodeIndent="15">
            <HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
            <NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="2px"
                NodeSpacing="0px" VerticalPadding="2px"></NodeStyle>
            <ParentNodeStyle Font-Bold="False" />
            <SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False" HorizontalPadding="0px"
                VerticalPadding="0px" />
        </asp:TreeView>
   </div>

Create tables:-

VehicleTypes Table

CREATE TABLE [dbo].[VehicleTypes](
    [Id] [int] NOT NULL,
    [Name] [varchar](50) NOT NULL,
 CONSTRAINT [PK_VehicleTypes] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
VehicleSubTypes Table

CREATE TABLE [dbo].[VehicleSubTypes](
    [Id] [int] NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [VehicleTypeId] [int] NOT NULL,
 CONSTRAINT [PK_VehicleSubTypes] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
Default.aspx.cs:-

Now create connection and retrieve data from database. create method getdata and call in pageload event and store that data in datatable.

private DataTable GetData(string query)
{
  DataTable dt = new DataTable();
  string constr = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
  using (SqlConnection con = new SqlConnection(constr))
  {
    using (SqlCommand cmd = new SqlCommand(query))
    {
      using (SqlDataAdapter sda = new SqlDataAdapter())
      {
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        sda.SelectCommand = cmd;
        sda.Fill(dt);
      }
    }
    return dt;
  }
}

Page_Load() method for Calling getData method in first time When Page Load First Time.

protected void Page_Load(object sender, EventArgs e)
{
  if (!this.IsPostBack)
  {
    DataTable dt = this.GetData("SELECT Id, Name FROM VehicleTypes");
    this.PopulateTreeView(dt, 0, null);
  }
}

Now Create PopulateTreeView Method and Bind retrieve Data in treeView Control and Call in Page_Load Method.

private void PopulateTreeView(DataTable dtParent, int parentId, TreeNode treeNode)
{
  foreach (DataRow row in dtParent.Rows)
  {
    TreeNode child = new TreeNode
    {
      Text = row["Name"].ToString(),
      Value = row["Id"].ToString()
    };
    if (parentId == 0)
    {
      TreeView1.Nodes.Add(child);
      DataTable dtChild = this.GetData("SELECT Id, Name FROM VehicleSubTypes WHERE VehicleTypeId = " + child.Value);
      PopulateTreeView(dtChild, int.Parse(child.Value), child);
    }
    else
    {
      treeNode.ChildNodes.Add(child);
    }
  }
}

Output:-

Generate Captcha with refresh Button in Asp.net

Generate Captcha with refresh Button in Asp.net

Description:-

In this article we will see how to generate captcha using web application. In this example I have create captcha in image handler and display in image to fill captcha and user can do action whatever he/she wants to do. Using StringBuilder class I have crated captcha and fill Url to pass page.

When user comes for login then he/she fills detail but stop the hacker to do we have to create captcha for taking some time or else he/she must have to fill captcha before do any action.

Using this we can stop Sql prevention and secure our site to hackers. For registration or any login authentication we have to create captcha images to secure login or some security question for security purpose.

For demo purpose here I have create captcha control to fill before registration and go after fill captcha. Follow below steps to create captcha in your web application.

Step 1: Create your Web Page and Design like what I have done and add Script Manager in your webpage.

<div><asp:ScriptManager ID="SM1" runat="server"></asp:ScriptManager>
     <table style="border: solid 1px black; padding: 20px; position: relative; top: 50px;" align="center">
      <tr><td>Email ID : </td>
 <td><asp:TextBox ID="txtEmailID" runat="server" Width="200px"></asp:TextBox></td></tr>
      <tr><td>Password : </td>
<td><asp:TextBox ID="txtPassword" runat="server" TextMode="Password" Width="200px"></asp:TextBox></td></tr>
      <tr><td>Confirm Password : </td>
        <td><asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" Width="200px"></asp:TextBox></td></tr>
      <tr><td>Enter Below Code : </td><td>
    <asp:TextBox ID="txtCaptcha" runat="server" Width="200px"></asp:TextBox></td></tr>
      <tr><td></td>
      <td valign="middle">
      <asp:UpdatePanel ID="UP1" runat="server">
        <ContentTemplate>
          <table>
          <tr><td style="height: 50px; width: 100px;">
              <asp:Image ID="imgCaptcha" runat="server" /></td>
              <td valign="middle">
              <asp:Button ID="btnRefresh" runat="server" Text="Refresh" OnClick="btnRefresh_Click" /></td></tr>
          </table>
        </ContentTemplate>
      </asp:UpdatePanel></td></tr>
      <tr><td colspan="2" align="center">
<asp:Button ID="btnRegiser" runat="server" Text="Register" OnClick="btnRegister_Click" />
</td></tr></table>
    </div>

Step 2: Now Create FillCaptcha Method and Call in Page_load () event

void FillCapctha()
{
  try
  {
    Random random = new Random();
    string combination = "!@#$%^&*()+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    StringBuilder captcha = new StringBuilder();
    for (int i = 0; i < 6; i++)
    captcha.Append(combination[random.Next(combination.Length)]);
    Session["captcha"] = captcha.ToString();
    imgCaptcha.ImageUrl = "GenerateCaptcha.aspx?" + DateTime.Now.Ticks.ToString();
  }
  catch
  {
    throw;
  }
}

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    FillCapctha();
  }
}

Step 3: Now double Click in Refresh Button to Re-Generate Captcha and Call FillCaptcha () method in Refresh button Click Event.

protected void btnRefresh_Click(object sender, EventArgs e)
{
  FillCapctha();
}

Step 4: Now double click on Register button to generate click event and maintain Captcha in Session to Check TextBox Enter value and Generated Captcha is Equals or What.

protected void btnRegister_Click(object sender, EventArgs e)
{
  if (Session["captcha"].ToString() != txtCaptcha.Text)
    Response.Write("Invalid Captcha Code");
  else
    Response.Write("Valid Captcha Code");
    FillCapctha();
}

Step 5: Now Check Your Web.Config File Image Handle is Generated or What. If Not Then Generate Image Handler to See Captcha Images in webpage. Without Image Hander you can not see Image in Webpage.

Step 6: Now open your webpage in Browser and Enter Details and Fill Details and click register button to Check Validation.

How to generate OTP(One time password) in asp.net

Description:-

A one-time password (OTP) is a password that is valid for only one login session or transaction, on a computer system or other digital device. ... The most important advantage that is addressed by OTPs is that, in contrast to static passwords, they are not vulnerable to replay attacks.

What is OTP number?

It is a unique 6-character code that can only be used once and is sent only to your registered mobile number in BDO Online Banking. After encoding your user ID and password, you will also be required to enter the correct OTP to complete the login process.

What does it mean to OTP?

The Meaning of OTP. OTP means "One True Pairing" So now you know - OTP means "One True Pairing" - don't thank us. YW! ... OTP is an acronym, abbreviation or slang word that is explained above where the OTP definition is given.

Step 1: Create TextBox,Button,Lable Controls like

<div>
   Enter Number of Text :
   <asp:TextBox ID="txtOTP" runat="server" />
   <asp:Button ID="btnGenerateOTP" Text="Generate" runat="server"       OnClick="btnGenerateOTP_Click" />
   <br />
   <asp:Label ID="lblOTP" runat="server" ForeColor="blue" />
</div>

Step 2: Now using JavaScript Code We Will Generate OTP Through Google-API

<script type="text/javascript">
   function googleTranslateElementInit() {   
       new google.translate.TranslateElement({ pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE }, 'google_translate_element');   
   }   
</script>

<script type="text/javascript">
   (function () {   
       var d = "text/javascript", e = "text/css", f = "stylesheet", g = "script", h = "link", k = "head", l = "complete", m = "UTF-8", n = "."; function p(b) { var a = document.getElementsByTagName(k)[0]; a || (a = document.body.parentNode.appendChild(document.createElement(k))); a.appendChild(b) } function _loadJs(b) { var a = document.createElement(g); a.type = d; a.charset = m; a.src = b; p(a) } function _loadCss(b) { var a = document.createElement(h); a.type = e; a.rel = f; a.charset = m; a.href = b; p(a) } function _isNS(b) { b = b.split(n); for (var a = window, c = 0; c < b.length; ++c) if (!(a = a[b[c]])) return !1; return !0 }
   
       function _setupNS(b) { b = b.split(n); for (var a = window, c = 0; c < b.length; ++c) a.hasOwnProperty ? a.hasOwnProperty(b[c]) ? a = a[b[c]] : a = a[b[c]] = {} : a = a[b[c]] || (a[b[c]] = {}); return a } window.addEventListener && "undefined" == typeof document.readyState && window.addEventListener("DOMContentLoaded", function () { document.readyState = l }, !1);
   
       if (_isNS('google.translate.Element')) { return } (function () { var c = _setupNS('google.translate._const'); c._cl = 'en'; c._cuc = 'googleTranslateElementInit'; c._cac = ''; c._cam = ''; c._ctkk = '403687'; var h = 'translate.googleapis.com'; var s = (true ? 'https' : window.location.protocol == 'https:' ? 'https' : 'http') + '://'; var b = s + h; c._pah = h; c._pas = s; c._pbi = b + '/translate_static/img/te_bk.gif'; c._pci = b + '/translate_static/img/te_ctrl3.gif'; c._pli = b + '/translate_static/img/loading.gif'; c._plla = h + '/translate_a/l'; c._pmi = b + '/translate_static/img/mini_google.png'; c._ps = b + '/translate_static/css/translateelement.css'; c._puh = 'translate.google.com'; _loadCss(c._ps); _loadJs(b + '/translate_static/js/element/main.js'); })();   
   })();   
</script>

Step 3: Generate Button Click Event And Code it

protected void btnGenerateOTP_Click(object sender, EventArgs e)
{
    lblOTP.Text = GenerateOTP(Convert.ToInt32(txtOTP.Text.Trim()));
}

Step 4: Create Method to Generate OTP and Call it in Button Click Event

public string GenerateOTP(int Length)
{
    string _allowedChars = "#@$&*abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
    Random randNum = new Random();
    char[] chars = new char[Length];

    for (int i = 0; i < Length; i++)
    {
        chars[i] = _allowedChars[Convert.ToInt32((_allowedChars.Length - 1) * randNum.NextDouble())];
    }
    return new string(chars);
}

Step 5: Now Run Your Application

 Step 5: Now Insert Number of Text in Textbox to Generate OTP