Thursday, August 23, 2012

Three Dimensional Dictionary in C#

Suppose we need to build a collection of Postal Code in which each postal code contains a collection of Cities. Each City is itself a collection of Street Addresses and each Street contains all the residents and their personal record. We are going to make this whole collection with Dictionary collection which is one of the best data structure from searching efficiency perspective. So our  “Three dimensional dictionary collection” will look like:
Postal Code -> City –> Street Addresses -> Resident’s Records -> SSN, Name, Age, Gender, Occupation

In C#, we can implement the above collection in following way:
class ThreeDimensionalDictionaryDemo
    {
        public Dictionary<string, Dictionary<string, Dictionary<string, List<ResidentRecord>>>> PeopleCollection = new Dictionary<string, Dictionary<string, Dictionary<string, List<ResidentRecord>>>>();

        public void AssemblePersonRecordByPostalCode()
        {
            try
            {
                // A data record file "RecordsFile.txt" is read.
                StreamReader oStreamReader = new StreamReader("RecordsFile.txt");
                string line;
                string postalCode;
                string city;
                string streetAddress;
                ResidentRecord oRecord;

                while ((line = oStreamReader.ReadLine()) != null)
                {
                    // In records file, we keep one person's record in one line and data fields are seperated by TAB
                    // For example:
                    // 933467543    John Smith   24  Male    Business    21093   Timonium    2311 York Rd Suit # 44

                    string[] parsedItem = line.Split('\t');

                    // Retrieving data fields
                    oRecord.SSN = parsedItem[0];
                    oRecord.Name = parsedItem[1];
                    oRecord.Age = Convert.ToInt16(parsedItem[2]);
                    oRecord.Gender = parsedItem[3];
                    oRecord.Occupation = parsedItem[4];
                    postalCode = parsedItem[5];
                    city = parsedItem[6];
                    streetAddress = parsedItem[7];

                    // If we get an already existing Postal Code
                    if (PeopleCollection.ContainsKey(postalCode))
                    {
                        //  If we get an already existing City
                        if (PeopleCollection[postalCode].ContainsKey(city))
                        {
                            //  If  we get an already existing StreetAddress
                            if (PeopleCollection[postalCode][city].ContainsKey(streetAddress))
                            {
                                // Person's record is added into list
                                PeopleCollection[postalCode][city][streetAddress].Add(oRecord);
                            }
                            //  If we get a new StreetAddress
                            else
                            {
                                // Street Address is added and value part is newed up
                                PeopleCollection[postalCode][city].Add(streetAddress, new List<ResidentRecord>());

                                // Person's record is added into list
                                PeopleCollection[postalCode][city][streetAddress].Add(oRecord);
                            }
                        }
                        //  If we get a new city 
                        else
                        {
                            // City is added and value part is newed up
                            PeopleCollection[postalCode].Add(city, new Dictionary<string, List<ResidentRecord>>());

                            // Street Address is added and value part is newed up
                            PeopleCollection[postalCode][city].Add(streetAddress, new List<ResidentRecord>());

                            // Person's record is added into list
                            PeopleCollection[postalCode][city][streetAddress].Add(oRecord);
                        }
                    }
                    // If we get a new postal code
                    else
                    {
                       
                        // Postal code is added and value part is newed up
                        PeopleCollection.Add(postalCode, new Dictionary<string, Dictionary<string, List<ResidentRecord>>>());

                        // City is added and value part is newed up
                        PeopleCollection[postalCode].Add(city, new Dictionary<string, List<ResidentRecord>>());

                        // Street Address is added and value part is newed up
                        PeopleCollection[postalCode][city].Add(streetAddress, new List<ResidentRecord>());

                        // Person's record is added into list
                        PeopleCollection[postalCode][city][streetAddress].Add(oRecord);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }

        }                  
    }

Tuesday, August 7, 2012

C# Programming Tips

          
Calling a new process within a process:

Process commandLineProc = Process.Start(“FileName”, “Argument1 Arguemtn2”);
 
Process oMyOwnProcess = Process.Start("MyOwnProcessExePath");

Not allowing to run multiple processes at the same time:

In a windows app, if we want to allow only one instance of the app, we could do easily in program.cs as following:

static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            
            // -------------- Checking how many instances are running of the same application ------------


            System.Diagnostics.Process oCurrentProcess = System.Diagnostics.Process.GetCurrentProcess();
            System.Diagnostics.Process[] arrProcess = System.Diagnostics.Process.GetProcessesByName(oCurrentProcess.ProcessName);
            if (arrProcess.Length > 1)
            {
                MessageBox.Show("Unable to start multiple applications.", "App Already Running", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            // --------------------------------------------------------------------------------------


            Application.Run(new MyForm());
        }
    }



Converting value to Enumeration:
MyEnumeration oMyEnumeration = (MyEnumeration)Enum.Parse(typeof(MyEnumeration), MyStringToConvert);

 Binary To Decimal conversion:  


 string binaryNum = "101";
 int decimalNum = Convert.ToInt32(binaryNum , 2);

 Decimal to Binary conversion:


int decimalNum = 42; string binaryNum = Convert.ToString(decimalNum, 2);
 
  Checking Stored Procedure Exists or not:


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[StoredProcedureName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[StoredProcedureName]

Continued …

Querying a List by Lambda Expression

Suppose you have a class “Person” and a list “lstPersonsInCity” is a collection of persons in a city as following:

Class Person
{
Public string SSN;
public string Name;
public string Address
public int Age;
}

List<Person> lstPersonsInCity = new List<Person>();


Now you can do perform several types of queries in your list by using lambda expression in a very easy way. Some examples are shown below:

  • // Grab Top 1000 old aged persons from the all the persons in city
List<Person> lstAgedPersonsInCity = lstPersonsInCity.FindAll(e =>
(e.Age >= 60)).Take(1000).ToList();

  • // Remove all the persons record from list that have “SAM” name
lstPersonsInCity.RemoveAll(e => (e.Name == “SAM”));

  • // Find the person whose SSN = 203456876 from the all the persons in city
Person oPerson = lstPersonsInCity.Find(e => (e.SSN == “203456876”));