Share Blog

Friday, September 15, 2017

Custom Mathematical CAPTCHA in C# Asp.net




<form id="form1" runat="server">
    <div>
    <table cellpadding="2" cellspacing="0" border="1" style="width: 500px; border: dashed 2px #04AFEF;
            background-color: #B0E2F5">
        <tbody><tr>
            <td colspan="2">
                <h3>
                    Give your Details.</h3>
                <asp:ValidationSummary ForeColor="Red" runat="server" ValidationGroup="v" ID="ValidationSummary">
            </asp:ValidationSummary></td>
        </tr>
        <tr>
            <td >
                <b>Name</b>
            </td>
            <td >
                <asp:TextBox runat="server" id="txtName" width="60%"></asp:TextBox>
                <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter Your Name." ForeColor="Red" Display="Dynamic" ControlToValidate="txtName" ValidationGroup="v" >
            </asp:RequiredFieldValidator></td>
        </tr>
        <tr>
            <td>
                <b>Mobile</b>
            </td>
            <td>
                <asp:TextBox runat="server" width="60%" id="txtMobile" MaxLength="10"></asp:TextBox>
                <asp:RequiredFieldValidator id="RequiredFieldValidator2" ControlToValidate="txtMobile" runat="server" ForeColor="Red" ErrorMessage="Please Enter Your Mobile." Display="Dynamic" ValidationGroup="v" >
               </asp:RequiredFieldValidator><asp:RegularExpressionValidator ID="RegularExpressionValidator2"  ControlToValidate="txtMobile"
                                                    runat="server" ValidationGroup="v" ValidationExpression="(\d*-)?\d{10}"
                                                    Display="Dynamic"  ErrorMessage="Invalid Mobile No" ForeColor="Red"></asp:RegularExpressionValidator> </td>
        </tr>
        <tr>
            <td style="vertical-align: top;">
                <b>Description</b>
            </td>
            <td>
                <asp:TextBox runat="server" id="txtDescription" textmode="MultiLine" height="200px" width="100%"></asp:TextBox>
                 <asp:RequiredFieldValidator id="RequiredFieldValidator3" controltovalidate="txtDescription" ForeColor="Red" runat="server" ErrorMessage="Please Enter Your Description." Display="Dynamic" ValidationGroup="v" >
               </asp:RequiredFieldValidator></td>
        </tr>
        <tr>
            <td>
                <b>
                    <asp:label id="lblStopSpam" runat="server"></asp:label> = </b>
            </td>
            <td>
                <asp:TextBox runat="server" id="txtStopSpam"> </asp:TextBox>
                <asp:RequiredFieldValidator id="RequiredFieldValidator4" ForeColor="Red" ErrorMessage="Please enter your answer." Display="Dynamic" validationgroup="v" ControlToValidate="txtStopSpam" runat="server">
                </asp:RequiredFieldValidator><asp:CompareValidator id="CompareValidator1" ForeColor="Red" ErrorMessage="Invalid text format." Display="Dynamic" ValidationGroup="v" ControlToValidate="txtStopSpam" runat="server" Operator="DataTypeCheck" Type="Integer">
            </asp:CompareValidator></td>
        </tr>
        <tr>
            <td>
                 
            </td>
            <td>
                <asp:button id="btnSubmit" text="Submit" runat="server" validationgroup="v" onclick="btnSubmit_Click">
            </asp:button></td>
        </tr>
    </tbody></table>
    </div>
    </form>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //===== Add text to stop spammer.
            generateText();
        }
    }
    void clear()
    {
        txtName.Text = "";
        txtMobile.Text = "";
        txtDescription.Text = "";
        txtStopSpam.Text = "";
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (txtStopSpam.Text == ViewState["cal"].ToString())
        {
            //---- Do your operations here.
            //--- I have shown confirmation message.
            CustomValidator val = new CustomValidator();
            val.ValidationGroup = "v";
            val.IsValid = false;
            val.ErrorMessage = "Congratulations you have successfully solved the CAPTCHA.";
            this.Page.Validators.Add(val);

            //==== Create new spam protection code.
            generateText();
            clear();
        }
        else
        {
            CustomValidator val = new CustomValidator();
            val.ValidationGroup = "v";
            val.IsValid = false;
            val.CssClass = "valFailure";
            val.ErrorMessage = "You have entered invalid captcha code. Please retry.";
            this.Page.Validators.Add(val);

            //---- Generate new captcha code.
            generateText();
        }
    }

    private void generateText()
    {
        Random ran = new Random();
        //--- Here I have used numbers between 1 to 9 you can increase as per your req.
        int firstNumber = ran.Next(1, 100);
        int secondNumber = ran.Next(1, 100);
        ViewState["cal"] = firstNumber + secondNumber;
        lblStopSpam.Text = firstNumber.ToString() + " + " + secondNumber.ToString();
    }

}

Tuesday, April 05, 2016

How to Reverse Each Word in a String Using C#

Example :Sunil Kumar

Reverse String :linuS ramuK

Write a Code


static void Main(string[] args)
        {
            string str = "Sunil Kumar";
            var reversedWords = string.Join(" ",
      str.Split(' ')
         .Select(x => new String(x.Reverse().ToArray()))
         .ToArray());
            Console.WriteLine(reversedWords);
            Console.ReadLine();


        }

Result 




In other words:
·         Split on spaces
·         For each word, create a new word by treating the input as a sequence of characters, reverse that sequence, turn the result into an array, and then call the string(char[]) constructor
·         Depending on framework version, call ToArray() on the string sequence, as .NET 4 has more overloads available
·         Call string.Join on the result to put the reversed words back together again.

Friday, January 29, 2016

Select first,Second Row Data In SQL Server

How to display serial number or we can say record/row number Data In sql server




SELECT TOP 1 * FROM DigiNews WHERE ID NOT IN ( SELECT TOP 1 ID FROM DigiNews ORDER BY ID desc )ORDER BY ID desc


Local and Global Temporary Table in SQL Server

local Temporary Table:A local temporary table, #tableName, exists only for the duration of a user session or the table that created the temporary table.When the user logs off or when the procedure that created the table completes, the local temporary table is lost.


create table #Employee
(
Id int Primary key Not Null,
Name varchar(150)
)

Insert into #Employee values(1,'Jitu')

select * from #Employee


Global Temporary Table:A global temporary table, ##tableName, also exists for the duration of a user session or the table that created the table.When the last user session that references the table disconnects, the global temporary table is lost.

create table ##Employee
(
Id int Primary key Not Null,
Name varchar(150)
)

Insert into ##Employee values(1,'Hemant')

select * from ##Employee






There are a few characteristics of Global Temporary Tables:
1.   Local Temporary ('#') tables are visible only in the current session; Global Temporary('##') tables are visible to all sessions.

2.   It starts with the single hash value "##" as the prefix of the table name and its name is always unique. There is no random number appended to the name.

3.   Global Temporary Tables are visible to all connections of SQL Server.
4.   Global Temporary Tables are only destroyed when the last connection referencing the table is closed (in which we have created the Global Temporary Table).
5.   You can access the Global Temporary Tables from all connections of SQL Server until the referencing connection is open.





Monday, January 11, 2016

How To Changev Male TO Female and Female To Male Using SQL SERVER

Create Table




 Insert Data in Table




Syntax

select * from Emp

Select id,name,
Case Gender
When 'M' Then 'F'
When 'F' Then 'M'
END

From Emp

Result







Update Male TO Female and Female To Male


UPDATE Emp SET gender =
CASE gender
WHEN 'F' THEN 'Male'
WHEN 'M' THEN 'Female'
ELSE
 gender END


Result






Saturday, December 26, 2015

JQuery Bootstrap Autocomplete Textbox from Database Example in Asp.net using C#

Before Implement This Example First Create One Table Leader in your  SQL Database like as Shown Below

CREATE TABLE Leader(
      [LeaderId] [int] IDENTITY(1,1)Primary Key NOT NULL,
      [Leader_Name] [nvarchar](150) NULL,
      [State] [nvarchar](150) NULL,
      [Lok_Sabha_Place] [nvarchar](150) NULL
)



Once we design table in our Database insert some data in your table to use it in our application that would be like as shown below



Now open your aspx page and write the code like as shown below

            <%@ Page Language="C#" AutoEventWireup="true" CodeFile="AutocompleteTextbox .aspx.cs" Inherits="AutocompleteTextbox_" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Bootstrap Autocomplete Textbox Example in Asp.net Using C#</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel = "Stylesheet" href = "https://twitter.github.io/typeahead.js/css/examples.css"></link>

<script type="text/javascript">
    $(function () {
        $('#txtSearch').keyup(function () {
            $.ajax({
                url: "AutocompleteTextbox .aspx/GetAutoCompleteData",
                data: "{'username':'" + $('#txtSearch').val() + "'}",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var val = '<ul id="userlist">';
                    $.map(data.d, function (item) {
                        var itemval = item.split('/')[0];
                        val += '<li class=tt-suggestion>' + itemval + '</li>'
                    })
                    val += '</ul>'
                    $('#divautocomplete').show();
                    $('#divautocomplete').html(val);
                    $('#userlist li').click(function () {
                        $('#txtSearch').val($(this).text());
                        $('#divautocomplete').hide();
                    })
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        })
        $(document).mouseup(function (e) {
            var closediv = $("#divautocomplete");
            if (closediv.has(e.target).length == 0) {
                closediv.hide();
            }
        });
    });
</script>
<style type="text/css">
ul li
{
list-style: none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="position: absolute;left: 30%; z-index: 100; text-align:left;">

    <asp:TextBox ID="txtSearch" runat="server" class="typeahead" placeholder="Type Leader Name to search" autocomplete="off" ></asp:TextBox>
<div id="divautocomplete" class="tt-menu" style="display:none">
</div>
</div>
</form>
</body>
</html>

Now add following namespaces in code behind

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;

After completion of adding namespaces you need to write the code like as shown below

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;

public partial class AutocompleteTextbox_ : System.Web.UI.Page
{
    //SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static List<string> GetAutoCompleteData(string username)
    {
        List<string> result = new List<string>();
        using (SqlConnection con = new SqlConnection("Data Source=lENOVO-pC;Initial Catalog=Digital_Politices;Integrated Security=True"))
        {
            using (SqlCommand cmd = new SqlCommand("select LeaderId,Leader_Name from Leader where Leader_Name LIKE '%'+@SearchText+'%'",con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@SearchText", username);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    result.Add(string.Format("{0}/{1}", dr["Leader_Name"], dr["LeaderId"]));
                }
                return result;
            }

        }
    }
}


DEMO