Friday, 11 January 2013

validation

40280914/05/930   mayur 420------bhushan 929
d133028
b131816
sainathom
SelectedValue=
-------------------------------------------------------------------------------
gaurav rnd date funtion

DateTime.Parse(strinput);
            string[] arr = strinput.Split('/');
            string strNewDate = arr[1] + "/" + arr[0] + "/" + arr[2];

            string strRegex = @"^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$"; // dd/mm/yyyy
            //@"^([0]\d|[1][0-2])\/([0-2]\d|[3][0-1])\/([2][01]|[1][6-9])\d{2}(\s([0-1]\d|[2][0-3])(\:[0-5]\d){1,2})?$"; // MM/dd/yyyy

            Regex re = new Regex(strRegex);

            if (re.IsMatch(strNewDate))
                return (true);
            else
                return (false);
------------------------------------------------------------------------------
[0-9a-zA-Z :]*
.+.(P|p)(D|d)(F|f)$        for pdf file
[^<>]{5,8000}
regular expression allowing alphabets and spaces only

 1 Numbers only regular expression (0-9 regex) – ^[0-9]*$
 2 Decimal numbers with 2 floating point compulsory regular expression (0-9 with decimal) – ^([0-9]*)(\.[0-9]{2})?$
 3 Alphabets only regular expression () – ^[a-zA-Z]*$
 4 Alphanumeric string regular expression – ^[a-zA-Z0-9]*$
 5 Alphanumeric and white space regular expression – ^[a-zA-Z0-9 ]*$

([0-0]{1}[1-9]{1}[0-9]{9})|[1-9]{1}[0-9]{9}  mobile 10 or 11
(?([1-9]{1})?([0]{1}[1-9]{1})?([0-9]{9})   for javascript
 setfocusonerror="true" 

^[!@#$%*()/_+=^&amp;{}|\[\]:;&amp;quot;?.,\'\s`\-~a-zA-z0-9]{2,300}$         commnet  -----------no reload-------------------
   <script type="text/javascript" language="javascript" >

        window.history.forward();

        function noBack() {

            window.history.forward();

        }

    </script>
  
    </head>
    <body onload="noBack();" onpageshow="if(event.persisted) noBack();" onunload="">
-----------------------------------c sharp------
 static bool IsValid(string value)
    {
    return Regex.IsMatch(value, @"^[a-zA-Z0-9]*$");
    }


Regex regex = new Regex(@"\d+");
    Match match = regex.Match("Dot 55 Perls");
    if (match.Success)
    {
        Console.WriteLine(match.Value);
    }
Regex a1 = new Regex(@"^\s+", RegexOptions.Compiled);
Regex a2 = new Regex(@"\s+$", RegexOptions.Compiled);

foreach (object item in _collection) // Example loop.
{
    //
    // Reuse the compiled regex objects over and over again.
    //
    string source = "  Some text ";
    source = a1.Replace(source, "");
    source = a2.Replace(source, ""); // compiled: 3620
}
-----------------------------------------
const string example = @"This string
has two lines";

    // Get a collection of matches with the Multiline option.
    MatchCollection matches = Regex.Matches(example, "^(.+)$", RegexOptions.Multiline);
    Regex regex = new Regex("dotnet.*");
    Console.WriteLine(regex.IsMatch("dotnetperls")); // True
    //
    // Zero or more s letters are allowed.
    //
    regex = new Regex("perls*");
    Console.WriteLine(regex.IsMatch("perl")); // True
    Console.WriteLine(regex.IsMatch("perlssss")); // True
    Console.WriteLine(regex.IsMatch("pert")); // False
    //
    // Use the star with a parentheses grouping.
    // ... Also use the $ sign to signal the terminal.
    //
    regex = new Regex("sam(abc)*$");
    Console.WriteLine(regex.IsMatch("samabcabc")); // True
    Console.WriteLine(regex.IsMatch("sam")); // True
    Console.WriteLine(regex.IsMatch("samab")); // False
-----------------------------------------
static string CollapseSpaces(string value)
    {
    return Regex.Replace(value, @"\s+", " ");
    }

    static void Main()
    {
    string value = "Dot  Net  Perls";
    Console.WriteLine(CollapseSpaces(value));
    value = "Dot  Net\r\nPerls";
    Console.WriteLine(CollapseSpaces(value));
    }

-----------------------------------------
static void Main()
    {
    // 1
    // The string you want to change.
    string s1 = "This string has something at the end<br/>";

    // 2
    // Use regular expression to trim the ending string.
    string s2 = System.Text.RegularExpressions.Regex.Replace(s1, "<br/>$", "");

    // 3
    // Display the results.
    Console.WriteLine("\"{0}\"\n\"{1}\"",
        s1,
        s2);


const string input = "There are 4 numbers in this string: 40, 30, and 10.";
    // Split on one or more non-digit characters.
    string[] numbers = Regex.Split(input, @"\D+");
    foreach (string value in numbers)
    {
        if (!string.IsNullOrEmpty(value))
        {
        int i = int.Parse(value);
        Console.WriteLine("Number: {0}", i);
        }
    }




    }
his string has something at the end
-----------------------------------------

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
    // Input strings.
    const string s1 = "samuel allen";
    const string s2 = "dot net perls";
    const string s3 = "Mother teresa";

    // Write output strings.
    Console.WriteLine(TextTools.UpperFirst(s1));
    Console.WriteLine(TextTools.UpperFirst(s2));
    Console.WriteLine(TextTools.UpperFirst(s3));
    }
}

public static class TextTools
{
    /// <summary>
    /// Uppercase first letters of all words in the string.
    /// </summary>
    public static string UpperFirst(string s)
    {
    return Regex.Replace(s, @"\b[a-z]\w+", delegate(Match match)
    {
        string v = match.ToString();
        return char.ToUpper(v[0]) + v.Substring(1);
    });
    }
}

Output

Samuel Allen
Dot Net Perls
Mother Teresa

-------------------------------------------

public int PageNumber
    {
        get
        {
            if (ViewState["PageNumber"] != null)
                return Convert.ToInt32(ViewState["PageNumber"]);
            else
                return 0;
        }
        set
        {
            ViewState["PageNumber"] = value;

        }
    }

  var filter2 =/^\(?([6-9]{2})?([6-9]{1})?([0-9]{10})$/

    if (document.getElementById("txtmobileno").value!= "")
    {

                if (filter2.test(document.getElementById("txtmobileno").value))
            {
               
            }
            else
            {
                inlineMsg('txtmobileno','The Mobile No. length should be  10 or 12 characters.',7);
                document.getElementById("txtmobileno").value="";
                document.getElementById("txtmobileno").focus();
                return false;
             }
   
    }

  var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;       
            if(reg.test(document.getElementById("txtname").value) == false)
            {        
               inlineMsg('txtname','Please enter a valid email id. You will login to your account using this ID.',7);
             document.getElementById("txtname").focus();
              return false;
            }




function ValidateCheckBox(sender, args) {
            if (document.getElementById("<%=chkTerms.ClientID %>").checked == true) {
                args.IsValid = true;
            } else {
                args.IsValid = false;
            }
        }
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Required Terms and Conditions"
                                ClientValidationFunction="ValidateCheckBox"></asp:CustomValidator>





  function ValidateFile(sender, args)
     {
   
            if (document.getElementById("<%=fileREsume.ClientID%>").value == "")
         {
                args.IsValid = true;
         }
         else
          {
           
                 var file = document.getElementById('<%=fileREsume.ClientID %>');
                var len=file.value.length;
                var ext=file.value;
          
               if(len > 3)
               
                 {
              
                     if((ext.substr(len-3,len)=="doc")||(ext.substr(len-3,len)=="DOC"))
                    {
                      args.IsValid = true;
                    } else
                     if((ext.substr(len-3,len)=="rtf")||(ext.substr(len-3,len)=="RTF"))
                    {
                      args.IsValid = true;
                    } else
                     if((ext.substr(len-3,len)=="ocx")||(ext.substr(len-3,len)=="OCX"))
                    {
                      args.IsValid = true;
                    }
                     else
                     {
                     args.IsValid = false;
                    }
                }
          
              
            }
        }

Wednesday, 9 January 2013

merge two table in one table

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

public partial class TAT_merge2tablein1table : System.Web.UI.Page
{
    DataSet ds = new DataSet();
    public int totalcount_3;
    protected void Page_Load(object sender, EventArgs e)
    {
        // string domainUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
        // string[] paramsLogin = domainUser.Split('\\');
        //Response.Write( paramsLogin[0].ToString());
        BindUserAccounts();
    }

    private void BindUserAccounts()
    {
        OfferDetails _OfferDetails = new OfferDetails();

        _OfferDetails._OfferDetailsCardId = "24";
        //this.CategotynameToMatch; "
        // SqlDataAdapter da = new SqlDataAdapter("select username,lastname from UserProfile ", con);
        ds = _OfferDetails.GetOfferDetails_AllFilter();
        int totalcount_1 = ds.Tables[0].Rows.Count;
        int totalcount_2 = ds.Tables[1].Rows.Count;
        totalcount_3 = totalcount_1 + 1;

        DataTable dt = new DataTable();
        DataColumn colString = new DataColumn("Categoryname");
        colString.DataType = System.Type.GetType("System.String");
        dt.Columns.Add(colString);

        DataColumn colString1 = new DataColumn("Categoryid");
        colString1.DataType = System.Type.GetType("System.String");
        dt.Columns.Add(colString1);

        //DataRow dataRow = dt.NewRow();
        //dataRow["Categoryname"] = "Dining";
        //dataRow["Categoryid"] = "8";
        //dt.Rows.Add(dataRow);

        // Dim i As Integer = 0
        //Dim table As DataTable = ds.Tables(0)
        //table.Columns.Add(New DataColumn("no", GetType(Integer)))
        //Dim rowcount As Integer = table.Rows.Count
        //Dim k As Integer = 1
        //While (i < rowcount)
        //    table.Rows(i)("no") = k
        //    i = i + 1
        //    k = k + 1

        //End While
        int i = 0;
        DataTable dt1 = ds.Tables[0];
        int rowcount = dt1.Rows.Count;
        int k = 1;
        DataTable dt2 = ds.Tables[1];
        int rowcount2 = dt2.Rows.Count;


        foreach (DataRow dr in dt1.Rows)
        {
            DataRow lLang = dt.NewRow();
            lLang["Categoryname"] = dr["CategotyName"].ToString();
            lLang["Categoryid"] = dr["pkCatId"].ToString();
            dt.Rows.Add(lLang);
        }
        foreach (DataRow dr in dt2.Rows)
        {
            DataRow lLang = dt.NewRow();
            lLang["Categoryname"] = dr["CategotyName"].ToString();
            lLang["Categoryid"] = dr["pkCatId"].ToString();
            dt.Rows.Add(lLang);
        }

        GridView1.DataSource = dt;
        GridView1.DataBind();

    }


}

ubmit button enable after fill form

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="http://code.jquery.com/jquery-1.7.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function () {
            $("#submit").attr('disabled', 'disabled');
//            $("#text1").keypress(function () {
//                check();
//            });

            var intv = self.setInterval("check()", 1000);

        });

        function check() {
            if (($("#text1").val().length > 0) && ($("#text2").val().length > 0)) {

                $("#submit").removeAttr('disabled');
             
            }
            else {

                $("#submit").attr('disabled', 'disabled');
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
     <asp:TextBox ID="text1" runat="server"></asp:TextBox><asp:RequiredFieldValidator
            ID="rv1" ControlToValidate="text1" ValidationGroup="v1" runat="server" ErrorMessage="*"></asp:RequiredFieldValidator>
            <asp:RequiredFieldValidator
            ID="rv2" runat="server"  ControlToValidate="text1" ValidationGroup="v2" ErrorMessage="*"></asp:RequiredFieldValidator>
         <asp:TextBox ID="text2" runat="server"></asp:TextBox><br />
    <%--   <asp:RequiredFieldValidator
            ID="rv3" ControlToValidate="text2" ValidationGroup="v1" runat="server" ErrorMessage="*"></asp:RequiredFieldValidator>
    --%>        <asp:RequiredFieldValidator
            ID="rv4" runat="server"  ControlToValidate="text2" ValidationGroup="v2" ErrorMessage="*"></asp:RequiredFieldValidator>
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
        <asp:ListItem Value="0">0</asp:ListItem>
        <asp:ListItem Value="1">9</asp:ListItem>
        </asp:DropDownList>
        <asp:Button ID="submit" runat="server" ValidationGroup="v1"  Text="Button" />
        <asp:Button ID="Button1" runat="server" ValidationGroup="v2"  Text="v2" />
         <asp:Button ID="Button2" runat="server" ValidationGroup="v1"  Text="v1" />
    </form>
</body>
</html>

validation for intger more than zwro

 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
            ErrorMessage="Required Field " Display="Dynamic"></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1"
            ValidationExpression="^[0-9]*$" Display="Dynamic" ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator>
        <asp:CompareValidator ID="CompareValidator1" ValueToCompare="0" Type="Integer" ControlToValidate="TextBox1"
            Operator="GreaterThan" runat="server" Display="Dynamic" ErrorMessage="Compare Validator"></asp:CompareValidator>
        <asp:Button ID="Button1" runat="server" Text="Button" />

post dadat and get data throw jquery


function InsertInteriorPaintdataAdvance() {
    var url1 = "/Handlers/paintcalculatorHandler.ashx"; //?Section=IntAdvancepaintcalculatorWalldatainsert&SR_App=Advanced Paint Calculator&PCQ_Title=Interior&PCQ_PaintTyp=" + PCQ_PaintTyp;
  
    var str = $("#resultinterior").html();
    str = str.replace(/</g, "&lt;").replace(/>/g, "&gt;");
    //document.getElementById('ContentPlaceHolder1_hiddenresultinterior').value = str;
    //document.getElementById('ContentPlaceHolder1_hiddentype').value = type;
    //document.getElementById('ContentPlaceHolder1_hiddenresultinteriorpainttype').value = paint;
    //QuickCalculatorWallimage
    $.ajax({
        type: "POST",
        url: url1,
        data: { hiddenresultinterior: str, hiddentype: type, hiddenresultinteriorpainttype: paint },
        success: function (msg) {

        }
    });

function InsertInteriorPaintdataQuick(PCQ_PaintTyp, PCQ_Prd_Name, PCQ_Area, PCQ_MaterialCoast, PCQ_LabourCoast, PCQ_ApproximateCoast) {

    var url = "/Handlers/paintcalculatorHandler.ashx?Section=IntQuickCalculatorWallidatainsert&SR_App=Quick Paint Calculator&PCQ_Title=Interior Walls&PCQ_PaintTyp=" + PCQ_PaintTyp + "&PCQ_Prd_Name=" + PCQ_Prd_Name + "&PCQ_Area=" + PCQ_Area + "&PCQ_MaterialCoast=" + PCQ_MaterialCoast + "&PCQ_LabourCoast=" + PCQ_LabourCoast
            + "&PCQ_ApproximateCoast=" + PCQ_ApproximateCoast;
    //QuickCalculatorWallimage
    $.getJSON(url,
    function (data) {
       // alert(data);
    });

}

add remove uplaod file throw code on ftp

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

public partial class FTP_upload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }

    protected void btn_WriteAllFileNameLocal_OnClick(object sender, EventArgs e)
    {
        string localPath = Server.MapPath("\\NewRand");
        string[] files = Directory.GetFiles(localPath);
        foreach (string filepath in files)
        {
            string fileName = Path.GetFileName(filepath);
                   Response.Write(fileName + "<br/>");
        }
    }

    protected void btn_deletefile_OnClick(object sender, EventArgs e)
    {
        string fileName = "a.jpg";

        FtpWebRequest requestFileDelete = (FtpWebRequest)WebRequest.Create("ftp://999999999999/httpdocs/" + fileName);
        requestFileDelete.Credentials = new NetworkCredential("idfcmfindigo", "I@fc34mfindo");
        requestFileDelete.Method = WebRequestMethods.Ftp.DeleteFile;

        FtpWebResponse responseFileDelete = (FtpWebResponse)requestFileDelete.GetResponse();
     
    }

    protected void btn_WriteAllFileName_OnClick(object sender, EventArgs e)
    {
        //done
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://9999999/httpdocs/");
        request.Credentials = new NetworkCredential("idfcmfindigo", "I@fc34mfindo");
        request.Method = WebRequestMethods.Ftp.ListDirectory;
        StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());
        string fileName = streamReader.ReadLine();
        while (fileName != null)
        {
            Response.Write(fileName+"<br/>");
            fileName = streamReader.ReadLine();
        }
        request = null;
        streamReader = null;
    }

    protected void btn_export_OnClick(object sender, EventArgs e)
    {
      

        bool res = this.UploadFile( "c.jpg");
        if (res)
        {
            Response.Write("successfully upload");
        }
        else
        {
            Response.Write("error in upload");
        }
    }

    private bool UploadFile( string fileName)
    {
        string localPath = @"D:\Pramod Raising\RND\NewRand\FTP\";
        //string fileName = "arahimkhan.txt";

        FtpWebRequest requestFTPUploader = (FtpWebRequest)WebRequest.Create("ftp://99999/httpdocs/" + fileName);
        requestFTPUploader.Credentials = new NetworkCredential("idfcmfindigo", "I@fc34mfindo");
        requestFTPUploader.Method = WebRequestMethods.Ftp.UploadFile;

        FileInfo fileInfo = new FileInfo(localPath + fileName);
        FileStream fileStream = fileInfo.OpenRead();

        int bufferLength = 2048;
        byte[] buffer = new byte[bufferLength];

        Stream uploadStream = requestFTPUploader.GetRequestStream();
        int contentLength = fileStream.Read(buffer, 0, bufferLength);

        while (contentLength != 0)
        {
            uploadStream.Write(buffer, 0, contentLength);
            contentLength = fileStream.Read(buffer, 0, bufferLength);
        }

        uploadStream.Close();
        fileStream.Close();

        requestFTPUploader = null;
        return true;
    }

    protected void btn_downloadfile_onclick(object sender, EventArgs e)
    {
        string localPath = @"D:\Pramod Raising\RND\NewRand\FTP\";
        string fileName = "c.jpg";

        FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create("ftp://99999999/httpdocs/" + fileName);
        requestFileDownload.Credentials = new NetworkCredential("idfcmfindigo", "I@fc34mfindo");
        requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;

        FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();

        Stream responseStream = responseFileDownload.GetResponseStream();
        FileStream writeStream = new FileStream(localPath + fileName, FileMode.Create);

        int Length = 2048;
        Byte[] buffer = new Byte[Length];
        int bytesRead = responseStream.Read(buffer, 0, Length);

        while (bytesRead > 0)
        {
            writeStream.Write(buffer, 0, bytesRead);
            bytesRead = responseStream.Read(buffer, 0, Length);
        }

        responseStream.Close();
        writeStream.Close();

        requestFileDownload = null;
        responseFileDownload = null;
    }

}

dataset add colum and remove and clone and copy

DataTable GetTable()
    {
        //
        // Here we create a DataTable with four columns.
        //
        DataTable table = new DataTable();
        table.Columns.Add("Dosage", typeof(int));
        table.Columns.Add("Drug", typeof(string));
        table.Columns.Add("Patient", typeof(string));
        table.Columns.Add("Date", typeof(DateTime));

        //
        // Here we add five DataRows.
        //
        table.Rows.Add(25, "Indocin", "David", DateTime.Now);
        table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
        table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
        table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
        table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
        return table;
    }
    protected void Page_Load(object sender, EventArgs e)
    {

        DataTable ds = new DataTable();
        ds = GetTable();
        DataSet ds1 = new DataSet();
        ds1.Tables.Add(ds);
        _FilterAndInsert(ds1);
        //ds.Tables.Add(employees);
        //ds.Tables.Add(payCheckes);
    }
    private void _FilterAndInsert(DataSet sourceSet)
    {
         sourceSet.Tables[0].Columns.Add("ppID", typeof(string));
        ///Apply your filter clauses in Select() function parameter
        DataRow[] rows = sourceSet.Tables[0].Select("Dosage >="+25+"");
        ///Get the structure of source table
        DataTable tempTable = sourceSet.Tables[0].Clone();
        ///Add the filtered rows in temp table
        int i = 0;
        foreach (DataRow row in rows)
        {
            tempTable.Rows.Add(row.ItemArray[0], row.ItemArray[1], row.ItemArray[2], row.ItemArray[3], row.ItemArray[4] = (i+1).ToString());
            i++;
        }
        tempTable.Columns.Remove("Date"); 
        tempTable.AcceptChanges();
        ///Create new dataset
        DataSet resultSet = new DataSet();
        ///Add temp table at first index or modify this code sequence as you require
        resultSet.Tables.Add(tempTable);
        for (int index = 1; index < sourceSet.Tables.Count; index++)
        {
            ///Set the copy of source table in local instance
            DataTable tableToAdd = sourceSet.Tables[index].Copy();
            ///Remove from source to avoid any exceptions
            sourceSet.Tables.RemoveAt(index);
            ///Add the copy to result set
            resultSet.Tables.Add(tableToAdd);
        }
        ///Set the copy to source table from result set
        sourceSet = resultSet.Copy();

        //DataTable tbl;
        //DataTable tbl2 = new DataTable();
        //DataSet ds = new DataSet();
        //ds.Tables.Add(new DataTable());
        //ds.Tables[0].Columns.Add("ID", typeof(int));
        //ds.Tables[0].Columns.Add("Tour_Code", typeof(int));
        //ds.Tables[0].Columns.Add("Tour_Date", typeof(string));
        ////ds.Tables[0].Columns.Add("No_Of_Vehicle", typeof(int));
        //ds.Tables[0].Columns.Add("Vehicle", typeof(string));
        //tbl2 = ds.Tables[0].Clone();
    }