Friday, August 12, 2011

Some Useful Regular Expression Validations

1) http(s)://www.examplesite.com
    ValidationExpression="http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"

2) Email Address
    ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"

Solution to Page_Load event not fire

Add following code in your page:

#region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //
        InitializeComponent();
        base.OnInit(e);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion





Thursday, August 11, 2011

Solution to UpdateProgress bug in Safari

Fisrt Create one js file with name SafariSolution.js with follwing code

Sys.Browser.WebKit = {};
if( navigator.userAgent.indexOf( 'WebKit/' ) > -1 )
{
  Sys.Browser.agent = Sys.Browser.WebKit;
  Sys.Browser.version = parseFloat( navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
  Sys.Browser.name = 'WebKit';
}

After add path to ScriptManager :
__________________________________

<asp:ScriptManager ID="ScriptManager1" runat="server">
     <Scripts>
         <asp:ScriptReference Path="~/Scripts/SafariSolution.js" />
     </Scripts>
</asp:ScriptManager>

after that add PostBackTrigger code to Button :
________________________________________________

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
   <ContentTemplate>
        <Triggers>
                <asp:PostBackTrigger ControlID="btnNewTestimonial" />               
        </Triggers>
   </ContentTemplate>
</asp:UpdatePanel>

Tuesday, July 19, 2011

SEO Optimization

These are useful urls.

Videos:

http://www.google.co.in/search?q=seo+tips+and+tricks&start=10&hl=en&sa=N&biw=1003&bih=584&prmd=ivns&source=univ&tbm=vid&tbo=u&ei=uTCsTbkYgsa9A_KB_Z0K&ved=0CFoQqwQ4Cg

Techniques:

http://webdesign.about.com/od/seo/tp/seo_tips_and_tricks.htm

http://www.dirstats.com/101-seo-tips-and-tricks-article.htm

http://www.searchenginejournal.com/55-quick-seo-tips-even-your-mother-would-love/6760/

Finding/Displaying current City and state dynamically

By using this we can get current City and state.

Name spaces to Add:
----------------------
using System.Net;
using System.Text;

Code to Add:
--------------
string strCity = "", strState = "";
try
        {
            Response.Cache.SetNoStore();
            Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
            Response.AddHeader("Pragma", "No-Cache");// 'Tell proxy servers not to cache the page.   
            Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
            string IPADR = "";
            if (Request.QueryString["IP"] != null)
                IPADR = Request.QueryString["IP"].ToString();
            else
                IPADR = Request.ServerVariables["REMOTE_ADDR"];
            WebClient objWebClient = new WebClient();
            UTF8Encoding objUTF8 = new UTF8Encoding();
            String strRequestState;
            strRequestState = objUTF8.GetString(objWebClient.DownloadData("http://www.thewebhelp.com/tools/geoip/?ip_box=" + IPADR));

            String strRequestCity;
            strRequestCity = objUTF8.GetString(objWebClient.DownloadData("http://batchiplocator.webatu.com/api/locate.php?ip=" + IPADR));

            string[] strCityName = GetClientCity(strRequestCity);
            string[] strStateName = GetClientState(strRequestState);

            if (strCityName.Length > 0)
            {
                if (strCityName[0] != null)
                    strCity = strCityName[0].ToString().TrimStart().TrimEnd();
            }
       if (strStateName.Length > 0)
            {
                if (strStateName[0] != null)
                    strState = strStateName[0].ToString().TrimStart().TrimEnd();
            }           
        }
        catch (Exception ex)
        {

        }
Methods to Add :
------------------
public static string[] GetClientCity(string strClientData)
    {
        int arrLength = 3;
        string[] strData = new string[arrLength];

        string strTotData = strClientData.Substring(strClientData.IndexOf("city", 0));
        string[] strDetails = strTotData.Split(',');
        if (strDetails.Length > 3)
        {
            if (strDetails[0].IndexOf("null") == -1)
            {
                string strShortData = strDetails[0].Replace("city", "").Substring(3);
                int Length = strDetails[0].Replace("city", "").Substring(3).Length;
                strData[0] = strShortData.Substring(0, Length - 1);
            }
        }
        return strData;
    }

public static string[] GetClientState(string strClientData)
    {
        int arrLength = 3;
        string[] strData = new string[arrLength];

        string strTotData = strClientData.Substring(strClientData.IndexOf("<td bgcolor=", 0));
        string strShortData = strTotData.Substring(strTotData.IndexOf("<td bgcolor=", strTotData.IndexOf("</tr>", 0)));
        string[] strDetails = strShortData.Split('\n');
        if (strDetails.Length > 3)
        {
            strData[0] = Strip(strDetails[2]).TrimStart();
            strData[1] = Strip(strDetails[3]).TrimStart();
        }
        return strData;
    }

Friday, June 3, 2011

How to Post data to other sites using iFrame and Post Method

First Add this in Design
-------------------------

<iframe style="display: none" width="0px" height="0px" id="ifrmNewPage" runat="server"></iframe>

using System.Xml;
using System.IO;
using System.Web.Script.Serialization;

public class RemotePost
    {      

        private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();


        public string Url = "";
        public string Method = "post";
        public string FormName = "form1";
        public string UserID= "";       

        public void Add(string name, string value)
        {
            Inputs.Add(name, value);
        }       
        public string ConstructPostString()
        {

            StringBuilder strPostString = new StringBuilder();

            strPostString.Append("<html><head>");           

            strPostString.Append(string.Format("</head><body onload=\"document.{0}.submit();\">", "form1"));
            strPostString.Append(string.Format("<form id=\"{0}\" name=\"{0}\" method=\"{1}\" action=\"{2}\" >", "form1", Method, Url));
            for (int i = 0; i < Inputs.Keys.Count; i++)
            {
                strPostString.Append(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\" />", Inputs.Keys[i], Inputs[Inputs.Keys[i]]));
            }
           
            strPostString.Append(string.Format("<input name=\"{0}\" type=\"hidden\" />", FormName));
            strPostString.Append("</form>");
            strPostString.Append("</body></html>");


            return strPostString.ToString();
        }        
    }

public string WriteText(string strPostString)
    {                           
        string strFileName = Server.MapPath(".\\"FolderName"\\HTML\\" + "FileName" + ".html");

        using (StreamWriter sw = new StreamWriter(strFileName, false, Encoding.ASCII))
        {
            sw.AutoFlush = true;
            TextWriter tw = sw;
            tw.WriteLine(strPostString.ToString());
            tw.Flush();
            tw.Dispose();
            tw.Close();
        }
        return ".\\"FolderName"\\HTML\\" + "FileName" + ".html";
    }



RemotePost myremotepost = new RemotePost();
myremotepost.Url = "Action URL";
myremotepost.FormName = "FormName";
myremotepost.Method = "post";

//myremotepost.Add("FieldName", "value");
myremotepost.Add("Name", "John");
myremotepost.Add("Gender", "Male");

Session["ResponseString"] = myremotepost.ConstructPostString();
string strPath = WriteText(Session["ResponseString"].ToString());

ifrmNewPage.Attributes.Add("src", strPath);

To Remove file after Posting
----------------------------

strFileName = Server.MapPath(".\\"FolderName"\\HTML\\" + "FileName" + ".html");
    if (File.Exists(strFileName))
        File.Delete(strFileName);

Sunday, May 22, 2011

How to retrieve Webmethod from XmlDataDocument

using System.Xml;
using System.Text;

XmlNode Node = oWebMethod.GetResults(Value);
                    DataSet dtResult = ConvertYourXmlNodeToDataSet(Node);


public static DataSet ConvertYourXmlNodeToDataSet(XmlNode xmlnodeinput)
    {
        DataSet dataset = null;
        if (xmlnodeinput != null)
        {
            XmlTextReader xtr = new XmlTextReader(xmlnodeinput.OuterXml, XmlNodeType.Element, null);
            dataset = new DataSet();
            dataset.ReadXml(xtr);
        }
        return dataset;
    }

How to Convert Webservice Method to XmlDataDocument

using System.Xml;

[WebMethod(Description = "This is to Get Result", EnableSession = false)]
    public XmlDataDocument GetResults(string Value)
    {
        try
        {
            using (SqlConnection oCon = new SqlConnection(CONN_STRING_SQL))
            {
                DataSet odsWebService = new DataSet();
                SqlDataAdapter oAdap = new SqlDataAdapter("USP_WebService", oCon);               
                oAdap.SelectCommand.CommandType = CommandType.StoredProcedure;
                oAdap.SelectCommand.Parameters.AddWithValue("@iMode", 101);
                oAdap.SelectCommand.Parameters.AddWithValue("@Value", Value);               
                oCon.Open();
                oAdap.SelectCommand.ExecuteNonQuery();
                oAdap.Fill(odsWebService);
                oCon.Close();               
                result = new XmlDataDocument(odsWebService);
            }
        }
        catch (Exception ex)
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Message"));
            DataRow oDr = dt.NewRow();
            oDr["Message"] = "Please provide valid data, Thanks.";
            dt.Rows.Add(oDr);
            dt.AcceptChanges();
            ds.Tables.Add(dt);
            result = new XmlDataDocument(ds);
        }
        return result;
    }

Friday, May 20, 2011

Validate File Extensions using Javascript

function checkFileExtension(elem)
            {
            var filePath = elem.value;

            if(filePath.indexOf('.') == -1)
                return false;
           
            var validExtensions = new Array();
            var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
            //Add valid extentions in this array
            validExtensions[0] = 'xls';
            validExtensions[1] = 'xlsx';
            for(var i = 0; i < validExtensions.length; i++) {
                if(ext == validExtensions[i])
                    return true;
            }
            
            alert('The file extension ' + ext.toUpperCase() + ' is not allowed!');
            return false;
        }

FileUpload1.Attributes.Add("onchange", "checkFileExtension(" + FileUpload1.ClientID + ")");

Get Sheet Names in Excel

using System.Data.OleDb;

public DataTable ExcelSheetNames(string excelFile)
        {
            OleDbConnection objConn = null;
            System.Data.DataTable dt = null;
            try
            {
                String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                    "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
                objConn = new OleDbConnection(connString);
                objConn.Open();
                dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (dt == null)
                {
                    return null;
                }
                return dt;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {               
                if (objConn != null)
                {
                    objConn.Close();
                    objConn.Dispose();
                }
                if (dt != null)
                {
                    dt.Dispose();
                }
            }
        }


Excel to Dataset

using System.Data.OleDb;

private static DataSet ExceltoDataset(string FileName,string strSheet)
    {       
        string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                         FileName + ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\"";

        DataSet output = new DataSet();

        using (OleDbConnection conn = new OleDbConnection(strConn))
        {
            conn.Open();

            DataTable schemaTable = conn.GetOleDbSchemaTable(
              OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

            foreach (DataRow schemaRow in schemaTable.Rows)
            {
                string sheet = schemaRow["TABLE_NAME"].ToString();
                if (sheet == strSheet)
                {
                    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
                    cmd.CommandType = CommandType.Text;

                    DataTable outputTable = new DataTable(sheet);
                    output.Tables.Add(outputTable);
                    new OleDbDataAdapter(cmd).Fill(outputTable);
                }
            }
        }
        return output;
    }

Monday, May 16, 2011

Generating CSV file using dotnet

using System.Xml;
using System.IO;
using System.Web.Script.Serialization;

 private void CreateANDSaveCSV()
    {
        #region CreateANDSaveCSV
        string strHeaders = "FirstName,LastName,Gender";
        string strData = "Test First Name,Test Last Name,Test Gender";
        string strFinalData = strHeaders + Environment.NewLine + strData;
        File.WriteAllText(Server.MapPath(".\\FolderName\\CSV\\" + "FileName_" + Session["USER"].ToString() + ".csv"), strFinalData);
        #endregion
    }
      

Solution to Free tetbox error while using update panel

 <script language="javascript" type="text/javascript">
    function FTB_RemoveEvent(obj, evType, fn, useCapture) {
    if (useCapture==undefined) useCapture=true;

    try
    {
        if (obj.removeEventListener) {
            obj.removeEventListener(evType, fn, useCapture);
        } else if (obj.detachEvent) {
        obj.detachEvent('on' + evType, fn);
    }

    }
    catch(err) {   
               }
    };
    FTB_RemoveEvent("FreeTextBoxName","onload","","");
    </script>

Thursday, May 12, 2011

Generating JSON file using dotnet

using System.Xml;
using System.IO;
using System.Web.Script.Serialization;

 public class USER
    {
        public string FirstName, LastName, Gender;       
    }

#region Convert to JSON
    JavaScriptSerializer oJavaScriptSerializer = new JavaScriptSerializer();
    USER ouser = new USER();
    ouser.FirstName = "Test First Name";
    ouser.LastName = "Test Last Name";
    ouser.Gender = "Test Gender";                   
    string strJSON = oJavaScriptSerializer.Serialize(ouser);
    if (Session["USER"] != null)
    {
        if (File.Exists(Server.MapPath(".\\FolderName\\JSON\\") + "FileName_" + Session["USER"].ToString() + ".json"))
        {
            File.Delete(Server.MapPath(".\\FolderName\\JSON\\") + "FileName_" + Session["USER"].ToString() + ".json");
        }
        File.WriteAllText(Server.MapPath(".\\FolderName\\JSON\\" + "FileName_" + Session["USER"].ToString() + ".json"), strJSON);
    }
#endregion

Generating XML file using dotnet

using System.Xml;
using System.IO;
using System.Web.Script.Serialization;

private void CreateANDSaveXML()
    {      

        string xmlString = "<?xml version='1.0' encoding='UTF-8'?>";
        xmlString += "<Details>";
        xmlString += "<FirstName>" + "Test First Name" + "</FirstName>";
        xmlString += "<LastName>" + "Test Last Name" + "</LastName>";
        xmlString += "<Gender>" + "Test Gender" + "</Gender>";       
        xmlString += "</Details>";

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlString.Replace("&nbsp;", ""));
        if (Session["USER"] != null)
        {
            if (File.Exists(Server.MapPath(".\\FolderName\\XML\\") + "FileName_" + Session["USER"].ToString() + ".xml"))
            {
                File.Delete(Server.MapPath(".\\FolderName\\XML\\") + "FileName_" + Session["USER"].ToString() + ".xml");
            }
            doc.Save(Server.MapPath(".\\FolderName\\XML\\") + "FileName_" + Session["USER"].ToString() + ".xml");
        }
       
    }

Wednesday, May 11, 2011

Useful Utility Functions

using System.Text.RegularExpressions;

public static bool IsNumeric(string sValue)
        {
            if (sValue.Trim() == "")
                return false;
            else
                return Regex.Match(sValue, "(-{0,1}[0-9]+){0,1}(file://.%7b0,1%7d[0-9]+)%22).value/ == sValue;
        }
        public static bool IsWholeNumeric(string sValue)
        {
            if (sValue.Trim() == "")
                return false;
            else
                return Regex.Match(sValue, "(-{0,1}[0-9]+)").Value == sValue;
        }
 public static bool IsValidSSN(string sValue)
        {
            if (sValue.Trim().Length == 0)
                return false;
            else
                return (Regex.Match(sValue, @"^\(\d{3}\)-\d{2}-\d{4}$").Success || Regex.Match(sValue, @"^\d{3}-\d{2}-\d{4}$").Success);
        }
public static bool IsDecimalNumeric(string sValue)
        {
            if (sValue.Trim() == "")
                return false;
            else
                return Regex.Match(sValue, "(-{0,1}[0-9]+){0,1}(.{0,1}[0-9]+)").Value == sValue;
        }
        public static bool IsValidEmail(string sValue)
        {           
            if (sValue.Trim().Length == 0)
                return false;
            else
                return Regex.Match(sValue, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$").Value == sValue;
        }
 public static bool IsValidPhoneNumber(string sValue)
        {
            if (sValue.Trim().Length == 0)
                return false;
            else
                return (Regex.Match(sValue, @"^\(\d{3}\) \d{3}-\d{4}").Success || Regex.Match(sValue, @"^\d{3}\d{3}-\d{4}").Success);
        }

Monday, May 9, 2011

Javascript Date comparison and Check Numaric Browser Compatabulity

<script type="text/javascript" language="javascript"> 
         function CheckDates(source, arguments)
       {      
             var date1= document.getElementById('<%= txtfromDate.ClientID %>').value;
            var date2= document.getElementById('<%= txttoDate.ClientID %>').value;  
           var frmdates=date1.split('/')[1]+'/'+date1.split('/')[0]+'/'+date1.split('/')[2];
           var Todates=date2.split('/')[1]+'/'+date2.split('/')[0]+'/'+date2.split('/')[2];      
          varSanctionedDate=new Date(frmdates);
          varEndDate=new Date(Todates);           
            if(varSanctionedDate > varEndDate) 
                 arguments.IsValid = false;
            else
                 arguments.IsValid = true;
     }    
    </script>
<asp:CustomValidator ID="CVEndDate" runat="server" ValidationGroup="Save" ErrorMessage="To Date must be greater than End Date."
                                                    ControlToValidate="txttoDate" ClientValidationFunction="Check" ValidateEmptyText="false">&nbsp;</asp:CustomValidator>

function CheckNumeric(e)
        {
            var key
            if (window.event)
                key = event.keyCode
            else
                key = e.which                       
            if (key > 47 && key < 58 || key == 8)
                return;
            else
                if (window.event) //IE
                window.event.returnValue = null; else //Firefox
                e.preventDefault();
        }
Calling Method in TextBox : onkeypress="return CheckNumeric(event)"