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

January 14, 2012

Tool Developer Notes - Part II

Previous Post in Series - .NET App Developer Notes

Bunch of exercises and learning's encountered while developing a Tool for my work. All examples posted as simple console apps. Many of them refer back to stackoverflow learnings. This post is intended for my reference. Try / Catch block and error handling is not included in some cases.

Tip #1 - Reading First Line from a File
Program.cs
using System;
using System.Configuration;
using System.IO;
namespace ServiceExample
{
   class Program
    {
        public static void Main(string[] args)
        {
            string sourceFileNamePath = ConfigurationManager.AppSettings["sourceFileNamePath"];
            string line = "";
            int linecount;
            Program P = new Program();
            line = P.GetLine(sourceFileNamePath, 1);
            Console.WriteLine(line);
            Console.ReadLine();
        }
        public string GetLine(string fileName, int lines)
        {
            using (var sr = new StreamReader(fileName))
            {
                for (int i = 1; i < lines; i++)
                    sr.ReadLine();
                return sr.ReadLine();
            }
        }
    }
}

App.config entry
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
      <appSettings file="" >
            <clear />
            <add key="sourceFileNamePath" value="E:\\TestFiles.csv"/>
      </appSettings>
</configuration>

Tip #2 - Find Duplicates values in a line using Hash method

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
namespace TestExample
{
    class Program
    {
        public static void Main(string[] args)
        {
            char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
            string line = "A A B C D E F G H";
            string[] Attributes = line.Split(delimiterChars);
            var hash = new HashSet<string>(Attributes);
            string[] uniqueAttributes = hash.ToArray();
            if (Attributes.Length == uniqueAttributes.Length)
            {
                Console.WriteLine("No Duplicate Elements present");
            }
            else
            {
                Console.WriteLine("Duplicate Elements present");
            }
            Console.WriteLine(line);
            Console.ReadLine();
        }
        public string GetLine(string fileName, int lines)
        {
            using (var sr = new StreamReader(fileName))
            {
                for (int i = 1; i < lines; i++)
                    sr.ReadLine();
                return sr.ReadLine();
            }
        }
    }
}

Tip #3, #4 - Fetching a Single (Scalar) value from DB and Fetching multiple rows

Note - In case of Error add the Assembly refereces to fix them

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
namespace TestExample
{
    class Program
    {
        public static void Main(string[] args)
        {
            Program P = new Program();
            P.FetchScalarValue();
            P.FetchDBMethod();
        }
        public int FetchDBMethod()
        {
            try
            {
                Console.WriteLine("Fetch Multiple DB Values Example \n");
                SqlCommand comm = new SqlCommand();
                comm = SetUpConnection();
                OpenConnection(comm);
                comm.CommandType = CommandType.Text;
                comm.CommandText = @"SELECT TOP 10 [CustomerID],[NameStyle],[Title],[FirstName],[MiddleName]
                                      ,[LastName],[Suffix],[CompanyName],[SalesPerson],[EmailAddress],[Phone]
                                      ,[PasswordHash],[PasswordSalt],[rowguid]
                                  FROM [AdventureWorksLT2008R2].[SalesLT].[Customer]";
                SqlDataReader oReader = comm.ExecuteReader();
                if (oReader.HasRows)
                {
                    while (oReader.Read())
                    {
                        Console.WriteLine(oReader[2].ToString());
                        Console.WriteLine(oReader[3].ToString());
                        Console.WriteLine(oReader[4].ToString());
                        Console.WriteLine(oReader[5].ToString());
                        Console.WriteLine(oReader[6].ToString());
                        Console.WriteLine(oReader[7].ToString());
                        Console.WriteLine(oReader[8].ToString());
                        Console.WriteLine(oReader[9].ToString());
                        Console.WriteLine(oReader[10].ToString());
                        Console.ReadLine();

                    }
                }
                else
                {
                    return 0;
                }
                oReader.Close();
                CloseConnection(comm);
                return 0;
            }
            catch (Exception EX)
            {
                return 1;
            }
        }
        public void FetchScalarValue()
        {
            try
            {
                Console.WriteLine("Fetch Single DB Values Example \n");
                SqlCommand comm = new SqlCommand();
                comm = SetUpConnection();
                OpenConnection(comm);
                comm.CommandType = CommandType.Text;
                comm.CommandText = @"SELECT COUNT(1)
                                  FROM [AdventureWorksLT2008R2].[SalesLT].[Customer]";
                Console.WriteLine(comm.ExecuteScalar().ToString());
                Console.ReadLine();
            }
            catch (Exception EX)
            {
            }
        }
        public SqlCommand SetUpConnection()
        {
            string strConn = ConfigurationManager.AppSettings["ConnectionString"];
            SqlCommand comm = new SqlCommand();
            comm.Connection = new SqlConnection(
                strConn);
            return comm;
        }
        public void OpenConnection(SqlCommand comm)
        {
            comm.Connection.Open();
        }
        public void CloseConnection(SqlCommand comm)
        {
            comm.Connection.Close();
        }
    }
}

App.Config File

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
      <appSettings file="" >
            <clear />
            <add key="ConnectionString" value="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=AdventureWorksLT2008R2;Data Source=.\SQLSERVER2008R2" />
      </appSettings>
</configuration>

Tip #5 - Best practice use of Try catch Exception handling
I like the stackoverflow question -Is this a bad practice to catch a non-specific exception such as System.Exception? Why?

Tip #6 - Status check for methods
Narrowly focussed on developing a working code without thinking of making it cleaner and better. Transition from DB to C# this is a good
learning. My learning is best described in stack overflow question - return status checking 

More Reads
Custom Load Generator
Debug http 401 Error
How to create load generator for simulating concurent hits?
Simple microbenchmarking in C#
Custom Thread Pool
Custom LoadGenerator Tool Identifies the Issues Your Application Faces Under Stress
Load testing : how to generate per second requests?
Happy Learning!!!

No comments: