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)"