"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" ;
Showing posts with label Tool Developer Notes. Show all posts
Showing posts with label Tool Developer Notes. Show all posts

December 01, 2012

Tool Developer Notes


Tip #1 - Sending Email on Error using Log4NET

Tip#2 - Append XML Node in C#

Before Code Execution


Post Code Execution



using System;
using System.Globalization;
using System.Data;
using System.IO;
using System.Xml;
namespace ExampleCode
{
    public class ExampleCode
    {
        static void Main()
        {

            //Open XML
            XmlDocument xmlPreCountFileData = new XmlDocument();
            xmlPreCountFileData.Load("E:\\abc.xml");
            XmlElement elmXML = xmlPreCountFileData.CreateElement("Node");

            //Append Node
            //Append Existing XML Node
            string xmlDataElement = @"<A>40</A>";

            elmXML.InnerXml = xmlDataElement;
            xmlPreCountFileData.DocumentElement.AppendChild(elmXML);
            xmlPreCountFileData.Save("E:\\abc.xml");
            Console.ReadLine();
        }
    }
}



Tip #3 - Thread Enhancements in .NET 4.0

Threading made easy in .NET 4.0
C# Mulththreading Improvements in .NET 4.0
.NET 4.0 and System.Threading.Tasks


Happy Learning!!!

May 20, 2012

C# - Excel Reading Data, Optional Method Parameters - Part 12

[Previous Post in Series - C# Basics - Tool Developer Notes Part XI]

 

Tip #1 - Reading from Excel
Please find below template excel with columns and data listed below. Objective to read all the worksheets and display data available in individual sheets

You need to use namespace Microsoft.Office.Interop.Excel.


Console Application in C# provided below (.NET 4.0)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelPOCDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            Program P = new Program();
            P.LoadDataFromExcel();
        }
        public string LoadDataFromExcel()
        {
            try
            {
                Excel.Application ExcelApp = new Excel.Application();
                Excel.Workbook xlWorkbook = ExcelApp.Workbooks.Open("E:\\Book1.xlsx");
                foreach (Excel.Worksheet Sheet in xlWorkbook.Worksheets)
                {
                       Console.WriteLine(" WorkSheet Name is " + Sheet.Name);
                       Excel.Range DataRange = Sheet.UsedRange;
                       int rowCount = DataRange.Rows.Count;
                       int colCount = DataRange.Columns.Count;
                       for (int i = 1; i <= rowCount; i++)
                       {
                            for(int j = 1; j<=colCount; j++)
                            {
                                Console.WriteLine("Value of i is " + i + " Value of J is " + j + " Data is " + DataRange.Cells[i, j].Value2.ToString());
                            }
                        }
                }
                ExcelApp.Workbooks.Close();
                ExcelApp.Quit();
                Console.ReadLine();
                return "0";
            }
            catch(Exception Ex)
            {
                return "-1";
            }
        }
    }
}

Tip #2 - Implementing optional parameters for method calls. Current code is implemented without any method parameter. For a new change I need to pass a method parameters. To support optional parameter implementation please find below example. C# 4.0 example, using namespace System.Runtime.InteropServices, Optional Keyword and Default Value. Simple C# Console Application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace OptionalParameters
{
    public class Program
    {
        static void Main(string[] args)
        {
            Program P = new Program();
            P.method();
            P.method("A");
            Console.ReadLine();
        }
        public void method([Optional, DefaultParameterValue(null)] string ParameterA)
        {
            if (ParameterA != null)
            {
                Console.WriteLine("Parameter sent is " + ParameterA.ToString());
            }
            else
            {
                Console.WriteLine("Parameter sent is null");
            }
        }
    }
}
Output result is


Tip #3 - Count number of files available in a folder - Answer
Tip #4 - Converting a list to a array. How to convert a list to an array

Sample List demo and Array Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListArrayExample
{
    public class Program
    {
        static void Main(string[] args)
        {
            List<string> ElementList = new List<string>();
            ElementList.Add("ElementA");
            ElementList.Add("ElementB");
            ElementList.Add("ElementC");
            ElementList.Add("ElementD");
            string[] Elements;
            Elements = ElementList.ToArray();
            foreach (String Data in Elements)
            {
                Console.WriteLine("Value is " + Data);
            }
            Console.ReadLine();
        }
    }
}
Output Result is


Tip #5 - Clearing elements from an array. Thanks to this post for letting me know on Array.clear method to clear data present in array

Happy Learning!!!

May 06, 2012

C# Basics - Tool Developer Notes Part XI

[Previous Post in Series - C# - Notes - Working in XML in C# - Part X Tool Developer Notes]

Often you learn new things when you re-learn basics. This post is fundamentals of C#. More than statements, for, while loops let’s look on basics of program execution, memory management, basics. Below listed are my notes from Illustrated C# 2010 Book.
Tip #1 - Why .NET is a strongly typed language ?

Type assignments are very strict. You cannot assign different types. Example - You cannot assign string to an integer in C#.
string a;
int b;
b = 10;
a = b;

This would error (Compile time error). Identifying type conversion error during compile time is advantage of strongly typed language.
Tip #2 - What is Unified Type System ?
  • All types are derived from System.Object
  • System.Object contains class, interface, delegate, string etc
  • Value Types are derived from System.ValueType
  • System.ValueType inherits from System.Object
Tip #3 - What is Stored in Stack ? How it works?
  • Stack is used for managing program execution; store certain variables, Store parameters sent for methods
  • LIFO fashion (Data Deleted and Added from Top of Stack - Last In First Out)
Tip #4 - What is a Value Type ?
  • Value Types are Stored in Stack, Use less resource (Managed in Stack itself)
  • Value Types Will not cause Garbage Collection as it is stored in Stack
  • Example of Value Types - int, float, long, double, decimal, struct, enum
More Reads Link

Tip #5 - What is Stored in Heap ? How it works ?
  • Reference Types are stored in Heap. Garbage Collector manages heap memory
  • Memory can be allocated and removed from any order (GC has its own algorithm to clear objects from Heap)
  • Program can store data in Heap. GC removes data from Heap
  • All Reference Type objects are stored in Heap (All the data members of the Object regardless of value type or reference type) they will be stored in Heap
  • Ex- If you declare a class with data members, functions. The data members might belong to int, float data type. All the memory for them would be allocated in heap
  • Example of Reference Types - Object, String, Classes, interface, delegate, array
  • More Reads Link1, Link2

Tip #6 - What is output of below program ?
int i = 20;
object j = i; //(Boxing)
j = 50; //(unboxing)

Value of i will still be 20. It is stored as a value type in stack with 20 as its value. J is stored as reference type in heap with value 50 assigned for J. In C with pointers concepts we can change the value of a variable with pointers

int a = 10;
int *b;
b = &a;
*b = 20;

Now the value of a will be set to 20

Tip #8 - What is Boxing and Unboxing ?
Converting a value type to a reference type is boxing. Boxing means creating a new instance of a reference type. Reference types are always destroyed by garbage collection.
int i = 20;
object j = i; //(Boxing)
Converting a reference type to value type is unboxing
int i = 20;
int k;
object j = i;
k = (int)j; //unboxing

Happy Learning!!!

.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!!!

.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!!!