Thursday, 1 December 2011

email Validation in Javascript

var email = $("#<%= txtEmail.ClientID %>").val().trim();
                var emlExp = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
                if (!email.match(emlExp)) {
}

Wednesday, 16 November 2011

convert Numbers to aphabets Useful for Excel

 static string CharacterIncrement(int colCount)
    {
        int TempCount = 0;
        string returnCharCount = string.Empty;

        if (colCount < 26)
        {
            TempCount = colCount;
            char CharCount = Convert.ToChar((Convert.ToInt32('A') + TempCount));
            returnCharCount += CharCount;
            return returnCharCount;
        }
        else
        {
            var rev = 0;

            while (colCount >= 26)
            {
                colCount = colCount - 26;
                rev++;
            }

            returnCharCount += CharacterIncrement(rev - 1);
            returnCharCount += CharacterIncrement(colCount);
            return returnCharCount;
        }
    }

Tuesday, 8 November 2011

Remember Me

Code Behind:
 HttpCookie Cookie = new HttpCookie("Login");
                    if (cbRemember.Checked)
                    {
                        Cookie.Values.Add("UserName", user.Value);
                        Cookie.Values.Add("Password", pwd.Value);
                        Cookie.Values.Add("RememberMe", "1");
                        Cookie.Expires = DateTime.Now.AddDays(60);
                    }
                    else
                    {
                        HttpContext.Current.Request.Cookies.Remove("Login");
                        Cookie.Expires = DateTime.Now.AddDays(-10d);
                    }
                    Response.Cookies.Add(Cookie);

Javascript

function fnCookie() {
                if (document.cookie && document.cookie != null) {

                    var cookies = document.cookie;
                    cookies = cookies.substring(6);
                    var cookiArry = cookies.split('&');

                    for (i = 0; i < cookiArry.length; i++) {
                        if (i == 0) {
                            $("#ctl00_user").val(cookiArry[i].substring(9));
                        }
                        if (i == 1) {
                            $("#ctl00_pwd").val(cookiArry[i].substring(9));
                        }
                        if (i == 2) {
                            var rem = cookiArry[i].substring(11);
                            if (rem == 1)
                                $("#ctl00_cbRemember").attr('checked', true);
                            else
                                $("#ctl00_cbRemember").attr('checked', false);
                        }
                    }
                }
            }
 or
 Code Behind:
if(!isPostback)
{
  HttpCookie myCookie = Request.Cookies["Login"];
                if (myCookie != null)
                {
                    this.user.Value = myCookie["UserName"];
                    PassWord.Value = myCookie["Password"];
                    ScriptManager.RegisterStartupScript(this, GetType(), System.Guid.NewGuid().ToString(), "fnSetPWD();", true);
                    cbRemember.Checked = Convert.ToBoolean(int.Parse(myCookie["RememberMe"].ToString()));
                }
}

Log off when you close the browser

 /*in master page Javascript*/

        $(document).ready(function() {
            debugger;
            var hdf = $('#ctl00_hdflog').val();
            if (hdf == '1') {
                $('body').attr("onunload", "javascript:removesessions();");
            }
        });

        function removesessions() {
            $.ajax({
                url: window.location.href + (window.location.href.toString().indexOf('?') > -1 ? '&close=force' : '?close=force'),
                async: false
            });
        }

/*You need a hidden field */
<input type="hidden" runat="server" id="hdflog" value="0" />
  
  /*Cs file on page load*/
            if (Request.QueryString["close"] != null && Request.QueryString["close"] == "force")
            {
                FormsAuthentication.SignOut();
                Session.Abandon();
                Session.Clear();
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Cache.SetAllowResponseInBrowserHistory(false);
            }

Tuesday, 1 November 2011

Text Box allowing only alphabets

<asp:TextBox runat="server" ID="txtFirstName" onkeypress="javascript:return CheckText(event.keyCode);"></asp:TextBox>

function CheckText(evt) {
            var keyCode = (evt.which) ? evt.which : event.keyCode
            if (keyCode == 8 || (keyCode >= 65 && keyCode <= 122)) {
                return true;
            }
            return false;
        }

Friday, 28 October 2011

Alternate for Oninit Method


 CommonUtils commonUtil;

protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
   commonUtil = new CommonUtils();
        }

public wpCaptureServices()
        {
            commonUtil = new CommonUtils();
        }


Both Methods are same

Monday, 26 September 2011

Encryption and Decryption for Passwords

 public static string EncryptText(string strText)
        {
            return Encrypt(strText, "my salt key");
        }
       
        public static string DecryptText(string strText)
        {
            return Decrypt(strText, "my salt key");
        }

        //The function used to encrypt the text
        private static string Encrypt(string strText, string strEncrKey)
        {
            byte[] byKey = { };
            byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
            try
            {
                byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(1, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }

            catch (Exception ex)
            {
                GlobalUtility.Logger.Error(ex);
                return ex.Message;
            }

        }

        //The function used to decrypt the text
        private static string Decrypt(string strText, string sDecrKey)
        {
            byte[] byKey = { };
            byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
            byte[] inputByteArray = new byte[strText.Length + 1];
            try
            {
                byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(1, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;
                return encoding.GetString(ms.ToArray());
            }

            catch (Exception ex)
            {
                GlobalUtility.Logger.Error(ex);
                return ex.Message;
            }

        }
 

JavaScript to validate controls in ASP.NET

 function fnValidate()
{
            var bool = true;
-----------------for textbox ----------------------
            if ($('#txtbox').val().trim() = = '') {
                $("#divError").css("display", "block");
                $("#divError").text('Please Enter value');
                bool = false;
            }


----------------for DDL---------------------------
if ($("#<%= ddl1.ClientID %>").val() == '') {
                $("#error1").css("display", "block");
                bool = false;
            }
else{
  $("#error1").css("display", "none");
}
           if (bool == true) {
                $("#<%= btnSubmit.ClientID %>").click();---------- this is aspcontrol
            }
}
           <asp:TextBox runat="server" ID="txtbox" ></asp:TextBox>
             <div id='divError' style="display: none; color: red"></div>                             

<input type="button" value="Save" runat="server"  id="btnSub" onclick="javascript:fnValidate();" />
 <asp:Button ID="btnSubmit" runat="server" Style="display: none" OnClick="btnSubmit_Click" />
                                                   

Thursday, 15 September 2011

Alter Table

alter table tablename alter column colname uniqueidentifier not null

Allowing textbox to accepts only Numbers



          
$(document).ready(function(){
$("#txtNumbers").keydown(function(event) {
   if(event.shiftKey)
        event.preventDefault();
   if (event.keyCode == 46 || event.keyCode == 8) {
   }
   else {
        if (event.keyCode < 95) {
           
          if (event.keyCode < 48 || event.keyCode > 57) {
              if (event.keyCode >= 37 && event.keyCode <= 40) { 
               }
              else
              {
                event.preventDefault();
              }
          }
        }
        else {
              if (event.keyCode < 96 || event.keyCode > 105) {
                  event.preventDefault();
              }
        }
      }
   });
});

Friday, 19 August 2011

Wednesday, 17 August 2011

to call java script from the code behind

   public void callscript()
        {
            ClientScript.RegisterStartupScript(this.GetType(), "confirmScript", "$(document).ready(function() {{ ConfirmRegisterUser(); }} );", true);
        }

Tuesday, 16 August 2011

validate checkbox listbox

javascript:
function validateRegionlist(source, args) {
            var chkListRegions = document.getElementById('<%= cblRegion.ClientID %>');
            var chkListinputs = chkListRegions.getElementsByTagName("input");
            for (var i = 0; i < chkListinputs.length; i++) {
                if (chkListinputs[i].checked) {
                    args.IsValid = true;
                    return;
                }
            }
            args.IsValid = false;
        }
________________________________________________________________________________

Html
<div id="dProductID" style="width: 210px; height: 70px; overflow: scroll; background-color: White;
                                            color: Black">
                                            <asp:CheckBoxList ID="cblProductID" runat="server">
                                            </asp:CheckBoxList>
                                        </div>
_________________________________________________________________________________
Validator    
<asp:CustomValidator runat="server" ID="cvRegion" ClientValidationFunction="validateRegionlist"
                                            ErrorMessage="Please select Region" ValidationGroup="CreateITSol"></asp:CustomValidator>
                               


Wednesday, 20 July 2011

adding Serial Numbers in GridView or ListView

<asp:TemplateField HeaderText="#">
                                <ItemTemplate>
                                    <%#Container.DataItemIndex +1 %>
                                </ItemTemplate>
                                <ItemStyle Width="2%" />
                            </asp:TemplateField>

Friday, 15 July 2011

Redirect after alert message

 public void showmessage(string msg, string pageName)
        {
            ScriptManager.RegisterStartupScript(this, GetType(), System.Guid.NewGuid().ToString(), "alert('" + msg + "');window.location='" + pageName + ".aspx';", true);
        }

Tuesday, 12 July 2011

Clear controls contents in a page

 public void clearall(Control pg)
        {
            try
            {
                Control ctrl = new Control();
                ContentPlaceHolder cph = new ContentPlaceHolder();

                foreach (Control ctr in pg.Controls)
                {

                    if (ctr.Controls.Count > 0)
                    {
                        clearall(ctr);
                    }
                    else
                    {
                        string stype = ctr.GetType().ToString();
                        stype = stype.Substring(26);
                        if (stype == "TextBox")
                        {
                            TextBox tb = new TextBox();
                            tb = (TextBox)ctr;
                            tb.Text = "";
                        }
                        if (stype == "DropDownList")
                        {
                            DropDownList ddl = new DropDownList();
                            ddl = (DropDownList)ctr;
                            ddl.ClearSelection();
                        }
                        if (stype == "CheckBoxList")
                        {
                            CheckBoxList cbl = new CheckBoxList();
                            cbl = (CheckBoxList)ctr;
                            cbl.ClearSelection();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

Sunday, 10 July 2011

Import CSS file within a child page

<% Response.Write(" <link href='ChildPageStylesheet.css' type='text/css' />"); %>

Sunday, 26 June 2011

About me

Hi everyone,

saying about me is long story, in short am Raghavendra a Software Professional, About this blog this is the my blog to exchange the code snippets in .Net, SQL, JavaScript,Linq2sql