Tuesday, January 29, 2013

Updating Dictionary elements while iterating


As we know we can't update dictionary collection element if we are iterating them using foreach loop. For example, we could iterate Dictionary using KeyValuePair in foreach loop but we can't modify them because as per MSDN: "If the iteration variable is a value type, it is effectively a read-only variable that cannot be modified.". So being the iteration variable 'KeyValuePair<TKey, TValue> as a struct type (value type) here, it can't be updated.

But what if we want to iterate the entire dictionary and at the same time also we have a need to modify the Dictionary Elements.Let's see how we can do this:



 
            Dictionary<int, string> ProductCollection = new Dictionary<int, string>();
            
            ProductCollection.Add(1, "AAAAAAAAAAAAAA");
            ProductCollection.Add(4, "BBBBBBBBBBBBBB");
            ProductCollection.Add(7, "CCCCCCCCCCCCCC");
 
            //Iterating entire ProductCollection but we can't update Dictionary element in foreach loop
            foreach (KeyValuePair<int, string> item in ProductCollection)
            {
                Console.WriteLine(item.Key + "\t" + item.Value);
            }
 
            //Grab all the Keys and put it in a list
            List<int> ids = ProductCollection.Keys.ToList();
 
            //Iterate all the Dictionary elements through their keys and modify the dictionary elements
            foreach (int idKey in ids)
            {
                ProductCollection[idKey] += "ChangedBy"+idKey.ToString();
            }
 
 
            foreach (KeyValuePair<int, string> item in ProductCollection)
            {
                Console.WriteLine(  item.Key + "\t"+ item.Value);
            }
 

Monday, January 21, 2013

How to pass variables from one page to another with Query String

Suppose in one web page, we have a TextBox and a 'Search' Button. On this page, user can enter any name in the TextBox to search and hits the Search button. On hitting search button, another web page opens that displayed the searched result in the grid.

Let's see, how we could do this using query string:

In the Search Button (First webpage) event handler put the code like:


        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("Staff.aspx?Name=" + txtBx_Request.Text);
        }


And on the second form page load, get the query string and send the query string to retrieve the data from database. After that we bind the data into a data grid.

        protected void Page_Load(object sender, EventArgs e)
        {
            string reqName = Request.QueryString["Name"];
          
           if (reqName != null && reqName != "")
           {
               Label1.Text = "You queried for the person having name: " + reqName;
               //Getting the data from database
               DataSet resultDataSet = GetDataFromDatabase(storedProcName, reqName);
 
               if (resultDataSet.Tables[0].Rows.Count > 0)
               {
                   GridView1.DataSource = resultDataSet.Tables[0];
                   GridView1.AutoGenerateColumns = true;
                   GridView1.DataBind();
               }
               else
               {
                   Label1.Text += "<br/><br/>Sorry, No data found!";
               }
           }
        }

Get Data using ADO NET DataSet with Stored Procedure

Here is the code:


        DataSet GetDataFromDatabase(string storedProcName, string param1)
        {
            DataSet ds = new DataSet();
 
            //Reading database connection string from Config File
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["HKSConnectionString"].ConnectionString;
 
            // Establishing database connection
            using (SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connectionString))
            {
                // Setting SqlCommand with SQLQuery (in this case it's a stored proc name) and SqlConnection
                using (SqlCommand cmd = new System.Data.SqlClient.SqlCommand(storedProcName, sqlConnection))
                {
                    // Letting the SqlCommand know that CommandType is 'StoredProcedure'
                    cmd.CommandType = CommandType.StoredProcedure;
 
                    // Adding parameters
                    cmd.Parameters.AddWithValue("@Name", param1);;
                    
                    // DataAdapter is bind to Command
                    using (SqlDataAdapter dataAdapter = new System.Data.SqlClient.SqlDataAdapter(cmd))
                    {
                        // Filling the dataset with result data
                        dataAdapter.Fill(ds);
                    }
                }
            }
            return ds;
        }

Wednesday, January 16, 2013

Converting List of objects into Dictionary using Lambda Expression

Suppose we have a class 'Product' as below:


public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public string Location { get; set; }
 
        public Product(int id, string name, double price, string location)
        {
            this.ID = id;
            this.Name = name;
            this.Price = price;
            this.Location = location;
        }
 
        public static List<Product> GetSampleProducts()
        {
            return new List<Product> {
                                          new Product(1, "Mobile", 339.99, "ZZZ-B090-ZZZ-5"),
                                          new Product(2, "Laptop", 514.99, "RRRR-111-RRRR-2"),
                                          new Product(3, "Phone", 112.99, "AAAA-22-AAA"),
                                          new Product(4, "PC", 313.69, "WWW-343-WWWWWWW-03"),
                                          new Product(5, "AC", 413.99, "NNN-80-NNNN-342"),
                                          new Product(6, "Heater", 109.99, "TTTT-318-TTTTTTTT-424")
                                      };
        }
 
        public override string ToString()
        {
            return string.Format("The product '{0}' is at Location : {1} with price Tag : ${2}", Name, Location, Price);
        }
    }

Then we could easily convert that list of objects into a .Net Dictionary in one line if we use an useful extension method available in the List Collection and lambda expression in the following way:

            List<Product> lstProduct = Product.GetSampleProducts();
 
            Dictionary<int, Product> DictCollection1 = lstProduct.ToDictionary(x => x.ID, x => x);
 
 

Wednesday, January 9, 2013

System Shutdown and Restart through C# Code


In this article, I am going to show how we can shutdown, restart, Lock, Logoff, Sleep etc. through C# Code.
Suppose your app needs to perform operations such as shutdown, restart, Logoff, Lock, Hibernation, Sleep through code, then you need to call a process that runs specific executable file (already stored in our system) along with their required arguments.  Here I made a Utility Application ‘PC Controller’ that allows you to do these kind of such operations. A sample code is attached with this article.

After going through this article, we will get to know following points:
 Adding items in ListView Control and showing them as Small Icons
 Shutting Down, restarting, Locking , logging off operation through code

When we run this application, we get following Screen where each operation is showing as an icon in the ListView Control.

Figure-1
Let us see the above application in more detail. On this GUI designing, here a ListView Control is being used.  Just follow the steps below to design GUI:
• To show item as icons, Click the arrow on the right side of the ListViewControl in designer mode and set the View to “SmallIcon”. (See Figure-2)
• Then drop an ImageList Control and add all your icon images in the ImageList Control by setting the “Images” property to folder path where we store our all icons.
• After associating images with ImageList Control, we will see ‘imageList1’ in combo box of “SmallImageList” property. Now set the Small image List property to  ‘imageList1’.
• Now attach event handler for “SelectedIndexChanged” event.


Figure-2
In the “SelectedIndex_Changed” event handler, add the following code. In which we basically call a process by giving the executable file name and its command line arguments.
---------------------------------------------------------------------------------------------------------------
ProcessStartInfo startinfo = new ProcessStartInfo(filename, arguments);
Process.Start(startinfo);
----------------------------------------------------------------------------------------------------------------
Here is the full Code:
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            DoOperation(listView1.SelectedItems[0].Text);
        }
 
 
        private void DoOperation(string oparation)
        {
            string filename = string.Empty;
            string arguments = string.Empty;
 
            switch (oparation)
            {
                case "Shut Down":
                    filename = "shutdown.exe";
                    arguments = "-s";
                    break;
 
                case "Restart":
 
                    filename = "shutdown.exe";
                    arguments = "-r";
                    break;
 
                case "Logoff":
 
                    filename = "shutdown.exe";
                    arguments = "-l";
                    break;
 
                case "Lock":
 
                    filename = "Rundll32.exe";
                    arguments = "User32.dll, LockWorkStation";
                    break;
                case "Hibernation":
 
                    filename = @"%windir%\system32\rundll32.exe";
                    arguments = "PowrProf.dll, SetSuspendState";
                    break;
                case "Sleep":
 
                    filename = "Rundll32.exe";
                    arguments = "powrprof.dll, SetSuspendState 0,1,0";
                    break;
            }
 
            ProcessStartInfo startinfo = new ProcessStartInfo(filename, arguments);
            Process.Start(startinfo);
 
     this.Close();
 
        }
    }

Tuesday, January 8, 2013

Free Bingo Ticket Generator Downlaod


Here I made a Bingo Ticket Generator. Feel free to download this user friendly version by clicking following link:

Download Bingo Ticket Generator!!!

 

Features:

Print: You can easily print a bunch of tickets
Copy-Paste: You may copy the tickets and paste them anywhere e.g. Notepad, MS-Word, MS-Excel
Export: You can directly export a bunch of tickets to a MS-Excel File
Image: You can save them in Image format too and then can print.

On running of this ticket generator app, you would see a screen as below:



Thursday, January 3, 2013

Free Online UML Diagrams Builder Sites


Generally while making a design document of a process, we use some UML Diagrams (e.g. Process Flow diagram, Class Diagram, Event Sequence Diagram etc.) to explain the functionality the system.

With Microsoft Visio, we can draw any kind of UML Diagrams. A 60 days trial version Microsoft Visio can be downloaded at:

http://visio.microsoft.com/en-us/TryBuy/TryVisio2010forFree/Pages/Try_Visio_2010_for_Free.aspx

But what is the alternative of Visio if you don't want to buy. There are some good UML diagram builder sites available that let you design freely your Class Diagram, UML Diagram, Event Sequence diagram etc. and let you also to download those diagrams on your local system after finishing your drawing.

Check the following sites:

For UML Diagram: http://creately.com/Draw-UML-and-Class-Diagrams-Online

For Event Sequence Diagram: http://www.websequencediagrams.com/