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”));

Importing and exporting Fixed Width data in Excel-2010


How to import “Fixed Width” data from a text file to Excel

·         Select all the contents in .txt file and copy them.
·         Paste them in Excel Sheet. This will be pasted in one column (say Column A)
·         Select the Column A and go to “Data” tab and click “Text To Column” option.
·         Select the Fixed Width Format option and click “Next”.
·         Here you would see in grid that data is separated by some columns.  These columns are identified by the MS-Excel by default. In case, if you see column distribution is not proper, you may add/move/delete the column as per columns width mentioned in your data dictionary.
·         Click finish, it will convert one column contents into desired columns.

How to export “Fixed Width” data from Excel to text file

·         Go to File-> Save AS
·         Select option Formatted Text (Space Delimited) option
·         Set file extension “.prn”
·         Click “SAVE AS” button. A file (i.e. MyExportedData.prn) will be saved with .prn extension .
·         Now go to the property of the MyExportedData.prn file by right clicking the file.
·         Remove the current file extension (i.e. .prn) and put the file extension “.txt” extension in front of your file name. The changing file extension is done in “General” page of the property window.

Monday, August 6, 2012

How to delete a windows service


These commands are useful when we are not able to uninstall any windows service. In this situation, we could use following commannds to delete the service:

The syntax used to delete a service is as:
sc delete ServiceName

If your service name has spaces in it, you’ll need to wrap the service name in quotes, like this:
sc delete “Adobe LM Service”

SQL Logical Operators

Logical Operators (Transact-SQL)

In T-SQL, we have following logical operators:
Operator
Meaning
ALL
TRUE if all of a set of comparisons are TRUE.
AND
TRUE if both Boolean expressions are TRUE.
ANY
TRUE if any one of a set of comparisons are TRUE.
TRUE if the operand is within a range.
TRUE if a subquery contains any rows.
IN
TRUE if the operand is equal to one of a list of expressions.
TRUE if the operand matches a pattern.
NOT
Reverses the value of any other Boolean operator.
OR
TRUE if either Boolean expression is TRUE.
TRUE if some of a set of comparisons are TRUE.


For example , we have two tables as following:

Address table

P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Srivastava
Hemant
Cranbrook 104
Cockeysville
5
Kumar
Sunil
York 40
Towson


Age table

P_Id
Age
1
22
2
25
3
22
4
30
5
25


 

·       IN Operator


SELECT * FROM ADDRESS WHERE P_Id IN(2,4)

P_Id
LastName
FirstName
Address
City
2
Svendson 
Tove     
Borgvn 23
Sandnes  
4
Srivastava
Hemant   
Cranbrook 104
Baltimore



SELECT * FROM ADDRESS WHERE P_Id IN(SELECT P_Id FROM AGE WHERE AGE >= 25)
P_Id
LastName
FirstName
Address
City
2
Svendson 
Tove     
Borgvn 23
Sandnes  
4
Srivastava
Hemant   
Cranbrook 104
Baltimore
5
Kumar    
Sunil    
York 40
Towson   


·       LIKE OPERATOR


SELECT * FROM ADDRESS WHERE LastName LIKE '%en'
P_Id
LastName
FirstName
Address
City
1
Hansen   
Ola      
Timoteivn 10
Sandnes  
3
Pettersen
Kari     
Storgt 20
Stavanger


·       NOT OPERATOR

Negates the value of the Boolean expression. NOT (Boolean Expression)
SELECT * FROM ADDRESS WHERE LastName NOT LIKE '%en'
Is same as
SELECT * FROM ADDRESS WHERE NOT (LastName  LIKE '%en')
P_Id
LastName
FirstName
Address
City
2
Svendson 
Tove     
Borgvn 23
Sandnes  
4
Srivastava
Hemant   
Cranbrook 104
Baltimore
5
Kumar    
Sunil    
York 40
Towson