none


——————————————–Helper.cs—————————————————-
private const string ConnString = @”Data Source=DELL;Initial Catalog=prodinner;Persist Security Info=True;User ID=sa;Password=Admin@123″;

public static string StrQuery { get; set; }

public static string ErrorMessage { get; set; }

/// <summary>
/// Returns the data in datatable for given query.
/// </summary>
/// <returns></returns>
public static DataTable GetData()
{
SqlConnection con = null;
SqlDataAdapter sqlData = null;
try
{
DataTable dtResult = new DataTable();
con = new SqlConnection(ConnString);
if (con.State == ConnectionState.Open) con.Close();
con.Open();

sqlData = new SqlDataAdapter(StrQuery, con);
sqlData.Fill(dtResult);
return dtResult;
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
return null;
}
finally
{
if(con != null) con.Close();
if(sqlData!=null) sqlData.Dispose();
}
}
———————————————————————————————-
********************************************************************************************
—————————————Default————————————————
#region Constants
private const string ASCENDING = ” ASC”;
private const string DESCENDING = ” DESC”;
#endregion

#region Properties & Varialbes

public DataTable dtResult
{
get
{
if (ViewState[“DataResult”] == null)
ViewState[“DataResult”] = new DataTable();
return (DataTable) ViewState[“DataResult”];
}
set
{
ViewState[“DataResult”] = value;
}
}

/// <summary>
/// Stores the Sort Direction in viewstate to perform sorting on gridview.
/// </summary>
public SortDirection GridViewSortDirection
{
get
{
if (ViewState[“sortDirection”] == null)
ViewState[“sortDirection”] = SortDirection.Ascending;

return (SortDirection)ViewState[“sortDirection”];
}
set { ViewState[“sortDirection”] = value; }
}
#endregion

#region Page Events
protected void Page_Load(object sender, EventArgs e)
{

}
#endregion

#region Control events
/// <summary>
/// Handles the submit event of button. Gets the result of query and binds data in grid.
/// Displays error message if any.
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
protected void btnSubmit_Click(object sender, EventArgs e)
{
BindGridView();
}

/// <summary>
/// handles the page index changing event to enable paging.
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
protected void gvData_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
{
gvData.PageIndex = e.NewPageIndex;
BindGridView();
}

protected void gvData_Sorting(object sender, System.Web.UI.WebControls.GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;

if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
#endregion

#region Methods and Functions
/// <summary>
/// Binds the gridview.
/// </summary>
private void BindGridView()
{
try
{
gvData.DataSource = null;
Common.Common.StrQuery = txtQuery.Text.Trim();
dtResult = Common.Common.GetData();
if (dtResult != null)
{
gvData.DataSource = dtResult;
}
else if (!string.IsNullOrEmpty(Common.Common.ErrorMessage))
{
lblError.Text = Common.Common.ErrorMessage;
}
gvData.DataBind();
}
catch (Exception)
{
lblError.Text = Common.Common.ErrorMessage;
}
}

private void SortGridView(string sortExpression, string direction)
{
//  You can cache the DataTable for improving performance
DataTable dt = dtResult;
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;

gvData.DataSource = dv;
gvData.DataBind();
}

#endregion
———————————————————————————————-
********************************************************************************************
—————————————Design————————————————
<p>
Enter Query to Execute:
<asp:TextBox ID=”txtQuery” runat=”server”></asp:TextBox>
<asp:RequiredFieldValidator runat=”server” SetFocusOnError=”True” ControlToValidate=”txtQuery” ErrorMessage=”Please type query to execute.” Text=”Please type query to execute.”></asp:RequiredFieldValidator>
<p>
<asp:Button ID=”btnSubmit” runat=”server” OnClick=”btnSubmit_Click” Text=”Submit” />
</p>
<p>
&nbsp;</p>
<p>
&nbsp;<asp:UpdatePanel runat=”server” ID=”updtGrid”>
<ContentTemplate>
<asp:GridView ID=”gvData” runat=”server” Width=”900px”
AutoGenerateColumns=”True” AllowSorting=”True” AllowPaging=”True” PageSize=”10″
OnPageIndexChanging=”gvData_PageIndexChanging” onsorting=”gvData_Sorting”>
<PagerSettings FirstPageText=”First” LastPageText=”Last” PageButtonCount=”4″ Mode=”NumericFirstLast”></PagerSettings>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</p>
<p>
<asp:Label ID=”lblError” runat=”server”></asp:Label>
</p>

Client side Validation in asp.net


Hello fiends,

Today we will discuss about client side validation. How to validate some control through client side.

First: Validate file Upload control in asp.net.

Below is the code for javascript just past under head tag.


<script type="text/javascript" language="javascript">
 function ValidateFileUpload(Source, args) {
 var fuData = document.getElementById('<%=fUploadCompany.ClientID %>');
 var FileUploadPath = fuData.value;
 if (FileUploadPath == '') {
 // There is no file selected
 args.IsValid = false;
 }
 else {
 var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

if (Extension == "xlsx" || Extension == "xls" || Extension == "XLSX" || Extension == "XLS") {
 args.IsValid = true; // Valid file type
 }
 else {
 args.IsValid = false; // Not valid file type

}
 }
 }
 </script>

Now add below code under html tag.

<asp:FileUpload ID="fUploadCompany" runat="server" />
<asp:CustomValidator ID="cvFileUpload" runat="server" ClientValidationFunction="ValidateFileUpload"
Display="Dynamic" Text="*" ErrorMessage="Please select excel file for job upload">
</asp:CustomValidator>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"  />

Second: Value check is greater then or is less then.

<asp:TextBox ID="txtPassword" runat="server" MaxLength="20" TextMode="Password"></asp:TextBox>
 <asp:RegularExpressionValidator ID="revNewPassword" runat="server" ControlToValidate="txtPassword"
 Text="*" ErrorMessage="Password must be greater than 6 digits" ValidationExpression="^([a-zA-Z0-9'-,*,&,/,_,$,@,#']{6,})$"
 SetFocusOnError="true" Display="Dynamic">
 </asp:RegularExpressionValidator>
 <br />
 <asp:TextBox ID="txtArticleTitle" runat="server" TextMode="MultiLine"></asp:TextBox>
 <ajax:FilteredTextBoxExtender ID="txtArticleTitle_FilteredTextBoxExtender" runat="server"
 Enabled="True" TargetControlID="txtArticleTitle" FilterType="Numbers,LowercaseLetters,UppercaseLetters,Custom"
 FilterMode="ValidChars" ValidChars="-/?.[{}]<>- (),!@%">
 </ajax:FilteredTextBoxExtender>
 <asp:RegularExpressionValidator ID="revTitle" runat="server" ControlToValidate="txtArticleTitle"
 Text="*" Display="Dynamic" ErrorMessage="The article title exceeds the max. limit 100 characters"
 ValidationExpression="^[\s\S]{0,100}$" />

Above code have two validation control one for is greater then value and one for is less then value.
I hope this will help you. Let me know if you have any query.
HAPPY CODING

Comma separated value


Hell friends ,

Today we will learn about comma separated value. How to separated value from comma value.

Situation is that sometimes when we have value like e.g. 10,20,30,40 and etc. so how can we separate them. Below is the code.


string muiltipleVal = "10,20,30,40,50,60,70,80,90,100";
 char[] separator = new char[] { ',' };
 string[] strmuiltipleVal = muiltipleVal.Split(separator);
 for (int i = 0; i < strmuiltipleVal.Count(); i++)
 {
 Response.Write(i + 1 + " value is : " + Convert.ToString(strmuiltipleVal[i]) + "<br />");
 }

I hope this topic is clear to you. let me know if you have any query.

HAPPY CODING

Find Ip Address


Hello friends, welcome back to all after long time. Today I came here with new post i.e. Find Ip address.  So for that below is the function to find Ip address.

Note : The main thing is that in local server u got the only one ip address but when u make it live then u will get any ip Address easily.

Below is the Function.

public static IPAddress GetId()
{
string ipstring;
if (string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]))

{
 ipstring = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
 }
 else
 {
 ipstring = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
 }
 IPAddress result;
 if (!IPAddress.TryParse(ipstring, out result))
 {
 result = IPAddress.None;
 }
 return result;
 }

Below code is for call the above function.

IPAddress value = GetId();
string ipaddress = value.ToString();

I hope this will help you. If you have any doubt then please make comment here i will help you.

Thanks,

Encryption Decryption in asp.net


hi all,

Now there is new and interesting post i.e. how to encryption & decryption of data.

So following is the code of encryption & decryption of data.

  • Encryption Of Data.
public static string EnryptString(string strEncrypted)
{
    byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(strEncrypted);
    string encrypted = Convert.ToBase64String(b);
    return encrypted;
}
  • Decryption Of Data.
public static string DecryptString(string encrString)
{
    byte[] b = Convert.FromBase64String(encrString);
    string decrypted = System.Text.ASCIIEncoding.ASCII.GetString(b);
    return decrypted;
}

Above both function is for encryption and decryption of data. Now How to call them.

string strDemo = EncryptString("Enter your string data that what you want to encrypt.");
Response.Write("<br/>");
Response.Write(strDemo);
Response.Write("<br/>");
Response.Write(DecryptString(strDemo));

So i think you will enjoy this and it will help you.
Happy Codeing.

Check JavaScript Is Enable or not…!


Hi All

Again i came from one new topic and with easy way.

To check java script is enable or disable. Just only with small code.

  • Add Following code in javascript tag.
<script language="javascript" type="text/javascript">

        function checkJavaScriptValidity() {
            document.getElementById("jsEnabled").style.visibility = 'visible';
            document.getElementById("jsDisabled").style.visibility = 'hidden';
        }

    </script>
  • Replace following code with body tag.
<body onload="checkJavaScriptValidity()">
    <form id="form1" runat="server">
    <div id="jsEnabled" style="visibility: hidden">
        JavaScript is enabled
    </div>
    <div id="jsDisabled">
        JavaScript is disabled
    </div>
    </form>
</body>

if you have any query then feel free to ask me.
thanks
enjoy codeing.

Captcha in asp.net


First of all download dll from internt here is link for download.
http://www.mondor.org/captcha.aspx

Now put that dll in bin folder and give reference to it.

Now put following code into page after first line to register the dll in aspx page.

<%@ Register Assembly="MSCaptcha" Namespace="MSCaptcha" TagPrefix="cc1" %>

Following code is for aspx page.

<asp:TextBox ID="txtnewcaptcha" CssClass="txt" runat="server"></asp:TextBox>
<cc1:CaptchaControl ID="ccJoin" runat="server" CaptchaBackgroundNoise="none" CaptchaLength="5"
CaptchaHeight="60" CaptchaWidth="200" CaptchaFontWarping="High" CaptchaChars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
CaptchaLineNoise="None" CaptchaMinTimeout="5" CaptchaMaxTimeout="240" />

Follwoing code comes under web.config file.

<httpHandlers>
<add verb="GET" path="CaptchaImage.axd" type="MSCaptcha.CaptchaImageHandler, MSCaptcha"/>
</httpHandlers>

<system.webServer>
<handlers>
<add name="MSCaptcha" verb="GET" path="CaptchaImage.axd" type="MSCaptcha.CaptchaImageHandler, MSCaptcha"/>
</handlers>
</system.webServer>

Following code is for .cs file.

ccJoin.ValidateCaptcha(txtnewcaptcha.Text.Trim());
if (ccJoin.UserValidated)
{
    //Put Your code here
}
else
{
    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "str", "alert('Enter proper security code(captcha).');", true);
}

Ajax rating in asp.net


Now a days rating is most popular. it is so simple to work following is the code.
Put Following code into css file(design file).

.ratingStar
{
    white-space: nowrap;
    margin: 1em;
    height: 14px;
}

.ratingStar .ratingItem
{
    font-size: 0pt;
    width: 26px;
    height: 25px;
    margin: 0px;
    padding: 0px;
    display: block;
    background-repeat: no-repeat;
    cursor: pointer;
}
.ratingStar .Filled
{
    background-image: url(../images/rating_Active.png);
}
.ratingStar .Empty
{
    background-image: url(../images/rating_blank.png);
}
.ratingStar .Saved
{
    background-image: url(../images/rating_busy.png);
}

Now put following code into aspx file.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
                        <ContentTemplate>
                            <ajaxtoolkit:Rating ID="Rating1" runat="server" MaxRating="5" CssClass="ratingStar"
                                StarCssClass="ratingItem" WaitingStarCssClass="Saved" FilledStarCssClass="Filled"
                                EmptyStarCssClass="Empty" BehaviorID="RatingBhvrId1" OnChanged="Rating1_Changed">
                            </ajaxtoolkit:Rating>
                            <center>
                                <span id="lblResponse" class="rating-txt"></span>
                            </center>

                            <script language="javascript" type="text/javascript">
                                Sys.Application.add_load(function() {
                                    $find("RatingBhvrId1").add_EndClientCallback(function(sender, e) {
                                        var lblCtrl = document.getElementById('lblResponse');
                                        lblCtrl.innerHTML = e.get_CallbackResult();
                                    });
                                });
                            </script>

                        </ContentTemplate>
                    </asp:UpdatePanel>

Now following code is for .cs file.

const int RATING1_MIN = 1;
const int RATING1_MAX = 5;
private void DisplayRating()
    {
        if (Session["userid"] != null) //Session is check for logged user.
        {
            Rating1.CurrentRating = //Here comes value from database.
            Evaluate_Rating1(Rating1.CurrentRating);
        }
        else
        {
            Rating1.CurrentRating = 0;
            Evaluate_Rating1(Rating1.CurrentRating);
        }
    }

Following code is to chaek the already rated and if not then insert in database. read comment carefully and follow comment.

protected void Page_Load(object sender, EventArgs e)
{
       if (!IsPostBack)
        {
             DisplayRating();
        }
}
protected void Rating1_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
    {
        string strMessage = string.Empty;
        if (Session["userid"] != null)
        {
            //here check if this login user is already rated this or not
            if (Exists)//there is no exists property or method but here exists means user rated or not.
            {
                strMessage = "You have already rated this.";
            }
            else
            {
                //here insert rate into database.
                objUserInfo.iRatingCount = int.Parse(e.Value);//Rating field
                Evaluate_Rating1(int.Parse(e.Value));
                objUser.InsertVideoRating(objUserInfo);
                strMessage = "Your have successfully rate this.";
            }
        }
        else
        {
            strMessage = "Please login to rate.";
        }
        e.CallbackResult = strMessage;
    }

    public void Evaluate_Rating1(int value)
    {
        string rate = EvaluateRating(value, Rating1.MaxRating, RATING1_MIN, RATING1_MAX);
        ViewState["ratingcount"] = rate;
    }

    public static string EvaluateRating(int value, int maximalValue, int minimumRange, int maximumRange)
    {
        int stepDelta = (minimumRange == 0) ? 1 : 0;
        double delta = (double)(maximumRange - minimumRange) / (maximalValue - 1);
        double result = delta * value - delta * stepDelta;
        return FormatResult(result);
    }

    public static string FormatResult(double value)
    {
        return String.Format("{0:g}", value);
    }

If u read comment care fully and follow then u can get output without any error and it will work without postbak.