"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

May 06, 2012

.NET 4.0 Working with Tasks

This post is about Task library. This library would be very useful for load simulator. Posted below sample examples.

// -----------------------------------------------------------------------
// <copyright file="LoadSimulator.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Threading.Tasks;

namespace SampleExercises
{
    static class LoadSimulator
    {
        public static int i = 10;
        static void Main(string[] args)
        {
            string status = "";

             //Task with return status
            Task<string> ThreadsCreation = Task<string>.Factory.StartNew(() =>
            {
                status = methodA();
                return status;
            });

            //Wait for Task Completion
            ThreadsCreation.Wait();
            Console.WriteLine("Status value is " + status);
            Console.ReadLine();

            //Taskwith no return status
             var noReturnTask = new Task(() => methodB());

            //Start The Task
            noReturnTask.Start();
            Console.ReadLine();

        }

        public static string methodA()
        {
            Console.WriteLine("i count is" + i++);
            return i.ToString();
        }
        public static void methodB()
        {
            Console.WriteLine(" This is am empty Task");
        }
    }
}


Reference - Link1


Happy Learning!!!

File Backup Copy Script

A quick task came on my plate. Task has to perform

  • File Copy across Network Drive
  • Delete Old Archived Files

Following posts provided good direction to get started

Access network share from within VBScript eg FileSystemObject
VBScript: Delete Old Files and Folders

Final Script was logic from both posts


ServerShare = "\\IPAddress\c$\Files"
UserName = "SystemName\UserName"
Password = "Password"
NumberOfDays = 3

Set NetworkObject = CreateObject("WScript.Network")
NetworkObject.MapNetworkDrive "", ServerShare, False, UserName, Password

Set objFS = CreateObject("Scripting.FileSystemObject")
strSourceFolder = "Drive\SourceFolder"
Set strDestination = objFS.GetFolder(ServerShare)
Set objFolder = objFS.GetFolder(strSourceFolder)

'Delete Files Older than X Days
For Each objFile In objFolder.files
    If DateDiff("d", objFile.DateCreated,Now) > NumberOfDays Then
       WScript.Echo objFile
        objFile.Delete True
        End If
Next

For Each objFile In strDestination.files
    If DateDiff("d", objFile.DateCreated,Now) > NumberOfDays Then
       WScript.Echo objFile
        objFile.Delete True
        End If

Next
Go(objFolder)
Sub Go(objDIR)
  If objDIR <> "\System Volume Information" Then
    For Each eFolder in objDIR.SubFolders      
        Go eFolder
    Next
    For Each strFile In objDIR.Files
        strFileName = strFile.Name
        WScript.Echo strFileName
       objFS.CopyFile strFile , strDestination &"\"& strFileName
    Next   
  End If 
End Sub

Set Directory = Nothing
Set FSO = Nothing
Set ShellObject = Nothing

NetworkObject.RemoveNetworkDrive ServerShare, True, False
Set NetworkObject = Nothing


Happy Learning!!!

.NET Tool Developer Notes - LINQ, DateTime Parsing

Tip #1 – When Input data is in MM/dd/yyyy HH:mm format. Converting it to MM/dd/yyyy HH:mm:ss

Code for parsing Date / Time formats
using System;
using System.Globalization;
namespace ExampleCode
{
    public class ExampleCode
    {
        static void Main()
        {
            try
            {
                CultureInfo provider = CultureInfo.InvariantCulture;
                DateTime dateTime;
                string dateValue = null;
                DateTimeStyles styles;
                styles = DateTimeStyles.None;

                if (DateTime.TryParse("01/01/2001 05:00", provider, styles, out dateTime))
                {
                    Console.WriteLine(dateTime);
                    dateValue = dateTime.ToString();
                    Console.WriteLine(dateValue);
                    Console.ReadLine();
                }
                string dateSet = "01/01/2001 05:00";
                Console.WriteLine(dateSet.Length);
                if (dateSet.Length == 16)
                {
                    dateSet = dateSet + ":00";
                }
                Console.ReadLine();
                System.Console.WriteLine(DateTime.ParseExact(dateSet, "MM/dd/yyyy HH:mm:ss", provider));
                Console.ReadLine();
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message.ToString());
                Console.ReadLine();
            }
        }
    }
}



Tip #2 – DataTable and LINQ Query Example
using System;
using System.Globalization;
using System.Data;
namespace ExampleCode
{
    public class ExampleCode
    {
        static void Main()
        {
            try
            {
                //DataTable TableA
                DataTable dataTable1 = new DataTable();
                //DataTable TableB
                dataTable1.Columns.Add("Name", typeof(string));
                dataTable1.Columns.Add("Age", typeof(int));
                dataTable1.Columns.Add("Place", typeof(string));
                dataTable1.Rows.Add("Raj", "21", "Chennai");
                dataTable1.Rows.Add("Ram", "22", "Chennai");
                dataTable1.Rows.Add("Rick", "24", "Mumbai");
                dataTable1.Rows.Add("James", "15", "Delhi");
                dataTable1.Rows.Add("Andy", "24", "Delhi");

                var queryByCity = from myRow in dataTable1.AsEnumerable()
                              where myRow.Field<string>("Name").Contains("Ra") &&
                               myRow.Field<string>("Place") == "Chennai"
                              select myRow;

                foreach (DataRow dataValues in queryByCity)
                {
                    foreach (object dataValue in dataValues.ItemArray)
                        {
                            if (dataValue is int)
                            {
                                Console.WriteLine("Int: {0}", dataValue);
                            }
                            else if (dataValue is string)
                            {
                                Console.WriteLine("String: {0}", dataValue);
                            }
                            else if (dataValue is DateTime)
                            {
                                Console.WriteLine("DateTime: {0}", dataValue);
                            }
                        }
                }
                Console.ReadLine();
                var queryByAge = from myRow in dataTable1.AsEnumerable()
                                 where myRow.Field<string>("Place") == "Delhi" &&
                                   myRow.Field<int>("Age") > 22
                                  select myRow;

                foreach (DataRow dataValues in queryByAge)
                {
                    foreach (object dataValue in dataValues.ItemArray)
                    {
                        if (dataValue is int)
                        {
                            Console.WriteLine("Int: {0}", dataValue);
                        }
                        else if (dataValue is string)
                        {
                            Console.WriteLine("String: {0}", dataValue);
                        }
                        else if (dataValue is DateTime)
                        {
                            Console.WriteLine("DateTime: {0}", dataValue);
                       }
                    }
                }
                Console.ReadLine();
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message.ToString());
                Console.ReadLine();
            }
        }
    }
}



Tip #3 - Check for Entry in Dictionary

Unexceptional Dictionary Accesses in C#

Tip #4 - Log4J email on Error Sample Code link


Tip #5 - C# Working with Excel. Link1, Link2


Happy Learning!!!

C# Excel, DataTable Basics - Tool Developer Notes - Part 13

Tip #1 - Difference between DataTable and DataSet
DataSet
From MSDN link
  • Derived from System.Data
  • Data obtained form ADO.NET store is stored as In-memory cache data using DataSet
  • DataSet is a collection of DataTables
DataTable
  • Used by DataSet
  • In memory Data Storage
Tip #2 - Load DataTable from FlatFiles, Load DataSet
Sample File Format
C# Sample Code to Load Data from FlatFiles, Populate DataTable, Create DataSet and List Data. Console Application
namespace SampleExercises
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.IO;
    public class DataTableLoading
    {
        static void Main(string[] args)
        {
            //CreateData Table
            DataTable fileData = new DataTable();

            //Add Columns to the DataTable
            fileData.Columns.Add("Name", typeof(string));
            fileData.Columns.Add("Value", typeof(int));

            //Files to be loaded in DataTable
            string[] fileNames = { "E:\\Test1.txt", "E:\\Test2.txt" };

            foreach (string fileName in fileNames)
            {
                string[] fileLines = File.ReadAllLines(fileName);

                //Parse Each Line and Load Data
                bool firstLine = true;
                foreach (string line in fileLines)
                {
                    //Flag to skip column Names
                    if (!firstLine)
                    {
                        string[] dataValue;
                        char[] spliChar = { '\t', ' ' };
                        //Fetch the values for each row
                        dataValue = line.Split(spliChar);
                         //This would change based on number of values, This is only example code
                        //Add Row
                        fileData.Rows.Add(dataValue[0], dataValue[1]);
                    }
                    firstLine = false;
                }
            }
            //Assign to DataSet
            DataSet fileDataSet = new DataSet();
            fileDataSet.Tables.Add(fileData);
            //List Every Row in DataSet
            foreach (DataRow rowDataVal in fileDataSet.Tables[0].Rows)
            {
                Console.WriteLine(rowDataVal["Name"].ToString() + " " + rowDataVal["Value"].ToString());
            }

            Console.ReadLine();
        }
    }
}


Output Window 

Tip #3 - Remove Columns from DataTable
Stackoverflow Link
Tip #4 - Remove DataTables from DataSet
MSDN Link
Tip #5 - Kill Excel Process
There were issues with Excel processing not closing after the program is completed. Following links were useful Link1, Link2
Sample example for Reading from Excel
namespace SampleExercises
{
    using System;
    using Excel = Microsoft.Office.Interop.Excel;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    public class ExcelRead
    {
        static void Main(string[] args)
        {
            Excel.Application exlApp = new Excel.Application();
            Excel.Workbook exlWorkbook = exlApp.Workbooks.Open("E:\\ExcelTemplate.xlsx");
            Console.WriteLine("Excel Work Book Name is " + exlWorkbook.Name);

            foreach (Excel.Worksheet exlWorksheet in exlWorkbook.Worksheets)
            {
                Console.WriteLine("Excel WorkSheet Name is " + exlWorksheet.Name);
            }

            exlApp.Workbooks.Close();

            Marshal.ReleaseComObject(exlApp.Workbooks);

            exlApp.Quit();

            Console.ReadLine();

        }
    }
}


Tip #6 - Working with Types and Date format Validation
Sample console app to validate Date Format, Data Type

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace SampleExercises
{
    class DateCheck
    {
        static void Main(string[] args)
        {
            //#1. DataTypes Check
            string dateValue = "10/10/2012 10:30";
            string dateFormat = "MM/dd/yyyy HH:mm";
            DateTime getDate;
            CultureInfo dateProvider = CultureInfo.InvariantCulture;
            try
            {
                //Verify it is of DateTime
                getDate = DateTime.ParseExact(dateValue, dateFormat, dateProvider);
                Console.WriteLine("Date Value is " + getDate);
                //Verify with Type check
                if (getDate.GetType() == typeof(DateTime))
                {
                  Console.WriteLine("DataType is of type Int, Value for getDate is " + getDate);
                }
            }
            catch(Exception Ex)
            {
                Console.WriteLine("Error is " + Ex.Message.ToString());
            }
            Console.ReadLine();
        }
    }
}

Happy Learning!!!