1. private DataTable ReadAsDataTable(string file, bool hasHeader, char seperator)
    {
    DataTable dt = new DataTable();

    StreamReader reader = new StreamReader(file);
    string line = string.Empty;
    string[] data = null;
    int counter = 0;

    while (reader.Peek() != -1)
    {
    line = reader.ReadLine();
    data = line.Split(seperator);

    if (hasHeader)
    {
    if (counter == 0)
    {
    foreach (string item in data)
    {
    dt.Columns.Add(item);
    }
    }
    else
    dt.Rows.Add(data);
    }
    else
    dt.Rows.Add(data);

    counter++;
    }

    reader.Close();
    return dt;
    }


    Calling function
    DataTable result = ReadAsDataTable(@"C:\temp\data.csv", true, ',');
    0

    Add a comment

  2. //A simple RegEx validotor.


    private bool RegExValidator(string expression, string toMatch, RegexOptions options = RegexOptions.None)
    {
    bool isValid = true;
    try
    {
    Regex validator = new Regex(expression, options);
    isValid = validator.IsMatch(toMatch);
    }
    catch (Exception ex)
    {
    //error handler can go here;
    isValid = false;
    }
    return isValid;
    }

    Calling method:
    bool isValid = RegExValidator(@"^[-+]?[0-9]\d{0,11}(\.\d{1,2})?%?$", "1234", RegexOptions.None);




    C# Regular Expressions Cheat Sheet
    Cheat sheet for C# regular expressions metacharacters, operators, quantifiers etc

    (Source: http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet)



    Character Description

    \ Marks the next character as either a special character or escapes a literal. For example, "n" matches the character "n". "\n" matches a newline character. The sequence "\\" matches "\" and "\(" matches "(".



    Note: double quotes may be escaped by doubling them: ""

    ^ Depending on whether the MultiLine option is set, matches the position before the first character in a line, or the first character in the string.

    $ Depending on whether the MultiLine option is set, matches the position after the last character in a line, or the last character in the string.

    * Matches the preceding character zero or more times. For example, "zo*" matches either "z" or "zoo".

    + Matches the preceding character one or more times. For example, "zo+" matches "zoo" but not "z".

    ? Matches the preceding character zero or one time. For example, "a?ve?" matches the "ve" in "never".

    . Matches any single character except a newline character.

    (pattern) Matches pattern and remembers the match. The matched substring can be retrieved from the resulting Matches collection, using Item [0]...[n]. To match parentheses characters ( ), use "\(" or "\)".

    (?pattern) Matches pattern and gives the match a name.

    (?:pattern) A non-capturing group

    (?=...) A positive lookahead

    (?!...) A negative lookahead

    (?<=...) A positive lookbehind .

    (?<!...) A negative lookbehind .

    x|y Matches either x or y.
    For example, "z
    wood" matches "z" or "wood". "(z
    w)oo" matches "zoo" or "wood".

    {n} n is a non-negative integer. Matches exactly n times. For example, "o{2}" does not match the "o" in "Bob," but matches the first two o's in "foooood".

    {n,} n is a non-negative integer. Matches at least n times. For example, "o{2,}" does not match the "o" in "Bob" and matches all the o's in "foooood." "o{1,}" is equivalent to "o+". "o{0,}" is equivalent to "o*".

    {n,m} m and n are non-negative integers. Matches at least n and at most m times. For example, "o{1,3}" matches the first three o's in "fooooood." "o{0,1}" is equivalent to "o?".

    [xyz] A character set. Matches any one of the enclosed characters. For example, "[abc]" matches the "a" in "plain".

    [^xyz] A negative character set. Matches any character not enclosed. For example, "[^abc]" matches the "p" in "plain".

    [a-z] A range of characters. Matches any character in the specified range. For example, "[a-z]" matches any lowercase alphabetic character in the range "a" through "z".
    [^m-z] A negative range characters. Matches any character not in the specified range. For example, "[m-z]" matches any character not in the range "m" through "z".

    \b Matches a word boundary, that is, the position between a word and a space. For example, "er\b" matches the "er" in "never" but not the "er" in "verb".

    \B Matches a non-word boundary. "ea*r\B" matches the "ear" in "never early".
    \d Matches a digit character. Equivalent to [0-9].
    \D Matches a non-digit character. Equivalent to [^0-9].
    \f Matches a form-feed character.
    \k A back-reference to a named group.
    \n Matches a newline character.

    \r Matches a carriage return character.
    \s Matches any white space including space, tab, form-feed, etc. Equivalent to "[ \f\n\r\t\v]".

    \S Matches any nonwhite space character. Equivalent to "[^ \f\n\r\t\v]".

    \t Matches a tab character.
    \v Matches a vertical tab character.

    \w Matches any word character including underscore. Equivalent to "[A-Za-z0-9_]".

    \W Matches any non-word character. Equivalent to "[^A-Za-z0-9_]".

    \num Matches num, where num is a positive integer. A reference back to remembered matches. For example, "(.)\1" matches two consecutive identical characters.

    \n Matches n, where n is an octal escape value. Octal escape values must be 1, 2, or 3 digits long. For example, "\11" and "\011" both match a tab character. "\0011" is the equivalent of "\001" & "1". Octal escape values must not exceed 256. If they do, only the first two digits comprise the expression. Allows ASCII codes to be used in regular expressions.

    \xn Matches n, where n is a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, "\x41" matches "A". "\x041" is equivalent to "\x04" & "1". Allows ASCII codes to be used in regular expressions.

    \un Matches a Unicode character expressed in hexadecimal notation with exactly four numeric digits. "\u0200" matches a space character.
    \A Matches the position before the first character in a string. Not affected by the MultiLine setting
    \Z Matches the position after the last character of a string. Not affected by the MultiLine setting.

    \G Specifies that the matches must be consecutive, without any intervening non-matching characters.

    0

    Add a comment

  3. private DateTime GetDate(DateTime inputDate, string differenceType, bool add, int difference)
    {
    DateTime result = inputDate;

    if (!add)
    {
    //Substraction
    difference = -1 * difference;
    }

    switch (differenceType.ToUpper())
    {
    case "DAYS":
    result = new DateTime(inputDate.Year, inputDate.Month, inputDate.Day).AddDays(difference);
    break;

    case "MONTHS":
    result = new DateTime(inputDate.Year, inputDate.Month, inputDate.Day).AddMonths(difference);
    break;

    case "YEARS":
    result = new DateTime(inputDate.Year, inputDate.Month, inputDate.Day).AddYears(difference);
    break;
    }
    return result;
    }

    Calling function:
    DateTime result = GetDate(DateTime.Now, "DAYS", false, 15);
    0

    Add a comment

  4. private void AddImageToThumbnail(string[] images)
    {
    int top = 0;
    int ht = 150;
    int counter = 0;

    PictureBox[] pictures = new PictureBox[images.Length];

    if (images.Length > 0)
    {
    //The panel pnlThumbnail will hold thumbnail pictures.
    pnlThumbnail.AutoScroll = true;

    foreach (string image in images)
    {
    try
    {
    pictures[counter] = new PictureBox();
    pictures[counter].Parent = pnlThumbnail;
    pictures[counter].Top = top;
    pictures[counter].Height = ht;
    pictures[counter].Width = pnlThumbnail.Width - 10;
    pictures[counter].Image = new Bitmap(image);
    pictures[counter].BorderStyle = BorderStyle.FixedSingle;
    top += pictures[counter].Size.Height + 5;

    pictures[counter].SizeMode = PictureBoxSizeMode.StretchImage;
    pictures[counter].Show();

    //If user clicks on a picture then this event gets triggered, it can be used to display the current image.
    pictures[counter].Click += new EventHandler(fImage_Click);
    pictures[counter].ImageLocation = image;

    counter++;
    textThumbnailCount.Text = counter.ToString();
    }
    catch
    {
    //Error handler
    }
    }

    //Show the first image in the thumbnail
    //fImage_Click(pictures[0], null);
    }
    }


    Calling function:
    string[] images = Directory.GetFiles(@"C:\Temp\Images\", "*.tif");
    AddImageToThumbnail(images);
    0

    Add a comment

  5. public string[] GetAllFilesInDirectory(string path, string pattern = "*.*", SearchOption options = SearchOption.TopDirectoryOnly)
    {
    if (path.Trim().Length == 0)
    return null; //Error handler can go here

    if ((pattern.Trim().Length == 0) || (pattern.Substring(pattern.Length - 1) == "."))
    return null; //Error handler can go here

    if (Directory.GetFiles(path, pattern).Length == 0)
    return null; //Error handler can go here

    return Directory.GetFiles (path, pattern, options);
    }
    0

    Add a comment

  6. public string GetLastFileInDirectory(string directory, string pattern = "*.*")
    {
    if (directory.Trim().Length == 0)
    return string.Empty; //Error handler can go here

    if ((pattern.Trim().Length == 0) || (pattern.Substring(pattern.Length - 1) == "."))
    return string.Empty; //Error handler can go here

    if (Directory.GetFiles(directory, pattern).Length == 0)
    return string.Empty; //Error handler can go here

    //string pattern = "*.txt"

    var dirInfo = new DirectoryInfo(directory);
    var file = (from f in dirInfo.GetFiles(pattern) orderby f.LastWriteTime descending select f).First();

    return file.ToString();
    }


    Calling Function:
    string lastFile = GetLastFileInDirectory("C:\\Temp", "*.*");
    3

    View comments

  7. using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.IO;
    using System.Xml.Serialization;
    //using System.Data;
    using System.Data.SqlClient;
    namespace zSharp2010.XMLToDB
    {
        public class Employee
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public DateTime DOB { get; set; }
        }
       
        public class cXMLToDB
        {
            public cXMLToDB(string serverName, string dbaseName)
            {
                List<Employee> emps = new List<Employee>();
                Employee emp = new Employee();
                emp.ID = 1;
                emp.Name = "George";
                emp.DOB = Convert.ToDateTime("1/1/1990");
                emps.Add(emp);

                emp = new Employee();
                emp.ID = 2;
                emp.Name = "John";
                emp.DOB = Convert.ToDateTime("2/2/1990");
                emps.Add(emp);

                emp = new Employee();
                emp.ID = 3;
                emp.Name = "Thomas";
                emp.DOB = Convert.ToDateTime("3/3/1990");
                emps.Add(emp);

                StringWriter sw = GetDataInXMLFormat(emps);

                SqlConnection cnn  = new SqlConnection("SERVER=" + serverName + ";Integrated Security=true;DATABASE=" + dbaseName);
                SqlCommand cmd = new SqlCommand("zTest", cnn);

                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@xmlData", sw.ToString());

                cnn.Open ();
                SqlDataReader dr = cmd.ExecuteReader();
                cnn.Close();
                //dr can then be used
            }

            private StringWriter GetDataInXMLFormat(List<Employee> emps)
            {
                XmlSerializer xSerializer = new XmlSerializer(emps.GetType());
                StringWriter sw = new StringWriter();
                XmlTextWriter tw = new XmlTextWriter(sw);
                xSerializer.Serialize(tw, emps);
                return sw;
            }
        }
    }

    ___________________________________________

    The Stored Procedure:


    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO

    ALTER PROCEDURE zTest
    @xmlData nVarchar (max)
    AS
    BEGIN

    DECLARE @hdoc INT
    CREATE TABLE #Emp (ID Int, Name VarChar(50), DOB DateTime)

    IF NOT (@xmlData IS NULL)    
    BEGIN   
     EXEC @xmlData = sp_xml_preparedocument @hdoc OUTPUT, @xmlData   
     IF @xmlData <> 0   
      BEGIN RAISERROR('System was unable to parse the xml data', 16, 1) RETURN END   
    END

    INSERT INTO #Emp (ID, Name, DOB)   
    SELECT  ID, Name, DOB 
    FROM OPENXML(@hdoc, '/ArrayOfEmployee/Employee', 2)     
    WITH  (ID INT, Name VARCHAR(50), DOB DateTime)  --The fields from XML are case sensitive

    SELECT *
    FROM #Emp

    DROP TABLE #Emp
    END
    GO
    0

    Add a comment

  8. Let me first define the Person Class
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    namespace zSharp2010.Serializer
    {
        [Serializable()]
        public class Person
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public DateTime DOB { get; set; }
            public string City { get; set; }
        }
    }

    The serialization class has two functions, Serializer and DeSerializer.
    We pass the xml file name and a list of person class to Serialize function to be serialized.
    The deserialized function returns a list of persons, we provide the xml file name.

    class cSerializer
    {
     public void Serialize(string file, List<Person> persons)
     {
      XmlSerializer xmlSerializer = new XmlSerializer(persons.GetType());
      StreamWriter writer = new StreamWriter(file);
      xmlSerializer.Serialize(writer, persons);
      writer.Close();
     }

     public List<Person> DeSerialize(string file)
     {
      List<Person> persons = new List<Person>();
      Person person = new Person();
      XmlSerializer xmlSerializer = new XmlSerializer(typeof (List<Person>));
      StreamReader reader = new StreamReader (file);
      persons = (List<Person>) xmlSerializer.Deserialize (reader);
      return persons;
     }
    }

    The calling methods might look like this:
    public partial class fSerializer : Form
    {
     string file = @"C:\temp\Serializer.xml";
     public fSerializer()
     {
      InitializeComponent();
     }

     private void cmdSerialize_Click(object sender, EventArgs e)
     {
      cSerializer serializer = new cSerializer();
      List<Person> persons = GetPersons();
      serializer.Serialize(file, persons);
     }

     private void cmdDeSerialize_Click(object sender, EventArgs e)
     {
      cSerializer serializer = new cSerializer();
      List<Person> persons = serializer.DeSerialize(file);
      string msg = String.Empty;
      foreach (Person person in persons)
       msg += String.Format("ID : {0}, Name : {1}, DOB : {2}, City : {3}\r\n", person.ID, person.Name, person.DOB, person.City);
      MessageBox.Show( msg);
     }

     private List<Person> GetPersons()
     {
      Person person = new Person();
      List<Person> persons = new List<Person>();
      person.ID = 1;
      person.Name = "George";
      person.DOB = Convert.ToDateTime("01-01-2001");
      person.City = "Mt. Vernon";
      persons.Add(person);
      person = new Person();
      person.ID = 2;
      person.Name = "John";
      person.DOB = Convert.ToDateTime("01-01-2002");
      person.City = "Quincy";
      persons.Add(person);
      person = new Person();
      person.ID = 3;
      person.Name = "Thomas";
      person.DOB = Convert.ToDateTime("01-01-2001");
      person.City = "Montecello";
      persons.Add(person);
      return persons;
     }
    }
    0

    Add a comment

  9. SELECT *
    FROM TableName
    WHERE NOT (FieldName IS NULL)
    0

    Add a comment

  10. In VB6 you may catch err as:
    Private Sub DivideByZero()
    On Error GoTo Err_Handler
        Dim num As Integer
        Dim zero As Integer
       
        num = 100 / zero
       
    Exit_Eop:
        Exit Sub
    Err_Handler:
        MsgBox ("Error Code : " & Err.number & vbCrLf & "Error Message : " & Err.Description)
    End Sub

    In C# the equivalent would be:
    using System.Reflection;
    private void DivideByZero()
    {
     try
     {
      int zero = 0;
      int num = 100 / zero;
     }
     catch (Exception ex)
     {
      Type type = typeof(Exception);
      int errNo =  (int)type.InvokeMember("HResult", System.Reflection.BindingFlags.DeclaredOnly   | BindingFlags.NonPublic | BindingFlags.Instance |  BindingFlags.GetProperty, null, ex, null);
      string errMsg =String.Format ("Error Code : {0}\r\nError Message : {1}",errNo, ex.Message);
      MessageBox.Show(errMsg);
     }
    }
    Please note that the error code in C# would not match with what you get in VB6.


    Thanks to : Willy Denoyette
    at: http://www.techtalkz.com/c-c-sharp/121497-get-error-number-2.html
    2

    View comments

Blog Archive
Topics
Topics
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.