Monday, November 11, 2013

Phone Numbers Comparison in Different Country Formats


In every country phone numbers are represented in its own format. For example : In some country a phone number could be in (914) 575-4231 format whereas in another country the same number could be in 914-575-42131 format. So if we want to compare two numbers represented in different format, we could do this by removing their formatting and compare their actual value.


using System;
using System.Collections;
 
class Program
{
 
    static void Main()
    {
        string num1 = "800-555-1212"; // Format -1
        string num2 = "(800) 555 1212"; // Format -2
 
        if (FetchDigitsOnlyFromPhoneNumber(num1) ==
        FetchDigitsOnlyFromPhoneNumber(num2))
        {
            Console.WriteLine("Number in both the formats are Equal !");
        }
        else
        {
            Console.WriteLine("Unequal Numbers !");
        }
        Console.Read();
    }
 
    private static string FetchDigitsOnlyFromPhoneNumber(string formattedNumber)
    {
        string actualNumber;
 
        actualNumber = formattedNumber;
        actualNumber = actualNumber.Replace("(", string.Empty);
        actualNumber = actualNumber.Replace(")", string.Empty);
        actualNumber = actualNumber.Replace("+", string.Empty);
        actualNumber = actualNumber.Replace("-", string.Empty);
        actualNumber = actualNumber.Replace(" ", string.Empty); //Blank
        actualNumber = actualNumber.Replace(".", string.Empty);
        return actualNumber;
    }
}

One liner Factorial calculating program using recursion in C#


using System;
 
public class Program
{
    //Using recursion
    static long Factorial(long number)
    {
        return ((number <= 1) ? 1 : number * Factorial(number - 1));
    }
 
    static void Main(string[] args)
    {
        long numToFindFact = 6;
        Console.WriteLine("The factorial of " + numToFindFact  + " is: {0}\n", Factorial(numToFindFact));
    }
}

Friday, October 18, 2013

Currency format of String



My article on this topis is at:



 


http://www.c-sharpcorner.com/UploadFile/0f68f2/converting-a-number-in-currency-format-for-different-culture/

Binding DataSource to a ComboBox with DataView


To explain how to bind data source to a ComboBox with DataView, I wrote an article for the following site:



http://www.c-sharpcorner.com/UploadFile/0f68f2/programmatically-binding-datasource-to-combobox-in-multiple/

Binding DataSource to a ComboBox with DataTable


To explain how to bind data source to a ComboBox with DataTable, I wrote an article for the following site:



http://www.c-sharpcorner.com/UploadFile/0f68f2/programmatically-binding-datasource-to-combobox-in-multiple/

Binding DataSource to a ComboBox with DataSet


To explain how to bind data source to a with DataSet, I wrote an article for the following site:



http://www.c-sharpcorner.com/UploadFile/0f68f2/programmatically-binding-datasource-to-combobox-in-multiple/

Binding DataSource to a ComboBox with List


To explain how to bind data source to a ComboBox with List Values, I wrote an article for the following site:



http://www.c-sharpcorner.com/UploadFile/0f68f2/programmatically-binding-datasource-to-combobox-in-multiple/

Binding DataSource to a ComboBox with Array


To explain how to bind data source to a ComboBox with Array values, I wrote an article for the following site:



http://www.c-sharpcorner.com/UploadFile/0f68f2/programmatically-binding-datasource-to-combobox-in-multiple/

Binding DataSource to a ComboBox with Enumeration Values


To explain how to bind data source to a ComboBox with Enumeration Values, I wrote an article for the following site:



http://www.c-sharpcorner.com/UploadFile/0f68f2/programmatically-binding-datasource-to-combobox-in-multiple/

Monday, September 30, 2013

Simple example of IEnumerable and IEnumerator in C#

Here is a simplest example of using IEnumerable and IEnumerator in C#. Since 'String' is an IEnumerable object, so we can enumerate it using IEnumerable and IEnumerator. 'String' object is just chosen for sake of simplicity. The way we are using "IEnumerable and IEnumerator" here can be extended to any IEnumerable object (such as List<T>, Dictionary<TK, TV>, Hashset, SortedSet etc)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
 
namespace IEnumerableDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //The following example illustrates low-level use of IEnumerable and IEnumerator:
            string s = "How to use IEnumerable and IEnumerator";
            
            // Because string implements IEnumerable, we can call GetEnumerator():
            IEnumerator rator = s.GetEnumerator();
            
            // Iterating entire collection one by one until it reaches at the end
            while (rator.MoveNext())
            {
                // Getting the current object and cast it into its corresponding object with which
                // the IEnumerable collection is made (For example: String collection is made with char object)
 
                char curObject = (char)rator.Current;
                Console.Write(curObject + ".");
            }
           
            Console.Read();
        }
    }
}


Feel free to put your comments and concern if any.

Thanks,
Hemant

Tuesday, September 17, 2013

Reading paragraph from a MS Word document using C#


Here I am going to share how we can read paragraphs from a Microsoft Word Documnet using Microsoft.Office.Interop.Word DLL.

(1) Add reference of Microsoft.Office.Interop.Word DLL into your project
(2) With the help of following class, we can read a specific paragraph of a MS Word Document.


   class WordDocReader
    {
        //To read paragraph contents of a Word document using Microsoft.Office.Interop.Word DLL
        public  string ReadFileContent(string path, int paraGraphNum)
        {
            int i = 0;
 
            StringBuilder sb = new StringBuilder();
 
            Microsoft.Office.Interop.Word.ApplicationClass wordApp = new ApplicationClass();
 
            object file = path;
 
            object nullobj = System.Reflection.Missing.Value;
 
            Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open
                                                    (ref file, ref nullobj, ref nullobj,
                                                    ref nullobj, ref nullobj, ref nullobj,
                                                    ref nullobj, ref nullobj, ref nullobj,
                                                    ref nullobj, ref nullobj, ref nullobj);
 
 
            Microsoft.Office.Interop.Word.Paragraphs DocPar = doc.Paragraphs;
 
            // Count number of paragraphs in the file
            long parCount = DocPar.Count;
 
            // Step through the paragraphs
            while (i < parCount)
            {
                i++;
                if (i == paraGraphNum)
                {
                    sb.Append(DocPar[i].Range.Text);
                    break;
                }
            }
 
            doc.Close(ref nullobj, ref nullobj, ref nullobj);
            wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);
            return(sb.ToString());
        }
    }

Thursday, August 1, 2013

Setting background color in WPF RichTextBox


Recently I encountered a situation where I was to highlight a word in WPF RichTextBox. So I thought, I should share a small tip to show how to highlight a word (by setting background color) in a WPF Rich TextBox. Here is the code:

        /// <summary>
        /// This method highlights a word with a given color in a WPF RichTextBox
        /// </summary>
        /// <param name="richTextBox">RichTextBox Control</param>
        /// <param name="word">The word which you need to highlighted</param>
        /// <param name="color">The color with which you highlight</param>
        private void HighlightWordInRichTextBox(RichTextBox richTextBox, String word, SolidColorBrush color)
        {
            //Current word at the pointer
            TextRange tr = new TextRange(richTextBox.Document.ContentEnd, richTextBox1.Document.ContentEnd);
            tr.Text = word;
            tr.ApplyPropertyValue(TextElement.BackgroundProperty, color);
        }


Tuesday, July 16, 2013

Palindrome Checking in C#



Here is a short code to do this:

       private string CheckPalinDrome(string text)
        {
            //Converting into Upper case and remove blank spaces in between
            text = textBox2.Text.ToUpper().Replace(" ", string.Empty);
            string revText = ReverseString(text);
            if (revText == text)
            {
               return("palindrome");
            }
            else
            {
                return ("Not palindrome");
            }
        }

        private string ReverseString(string s)
        {
            char[] arr = s.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }

Wednesday, July 3, 2013

How to set directory path for setup project in visual studio 2010


Here I am going to share how we can set directory path for our installed package.
Suppose you have a setup project already included in your main project. (To know how to add setup project in Visual Studio-2010, you may refer to article at:

http://www.c-sharpcorner.com/Blogs/9817/adding-a-setup-project-in-visual-studio-2010.aspx)








Now you want to set directory path for your install, so that your app get installed in the desired location. In order to do this, you need to follow steps as:

 1.Right Click on your Setup project -> View -> File System

 2.Then Click Application Folder, open property tab

 3.Set 'AlwaysCreate' property to TRUE.
  (This property creates a directory structure for your install, if directory structure doesn’t exist.)

 4.Then Set 'DeafultLocation' property to your desired location (e.g. C:\MyWinApps\).
 (You may choose any directory structure of your choice except some folders/Directories which are protected by Windows Operating System)

Friday, May 24, 2013

Converting DataSet to a Byte Array



Here is the code that can be used for converting a DataSet into its corresponding byte array. Sometimes when we need to send the data across the network through WCF service, we can get advantage of sending our data into a byte array. The reason behind to send the data in Byte Array format is that byte array is the one of the primitive data type available in .Net


        private byte[] ConvertDataSetToByteArray(DataSet dataSet)
        {
            byte[] binaryDataResult = null;
            using (MemoryStream memStream = new MemoryStream())
            {
                BinaryFormatter brFormatter = new BinaryFormatter();
                dataSet.RemotingFormat = SerializationFormat.Binary;
                brFormatter.Serialize(memStream, dataSet);
                binaryDataResult = memStream.ToArray();
            }
            return binaryDataResult;
        }  

Friday, May 3, 2013

Select All, Clear All, Cut, Copy, Paste on List Box


Have you ever imagined our life without “Cut-Copy-Paste” in today’s computer era… specially a Software developer’s life! These clipboard operations are very common and most frequently used, but here I am going to discuss how to code them (on a List Box control) instead of just using them.

In this article, I am going to show some edit operations like: Select All, Clear All, Cut, Copy and Paste on a List Box control. To demonstrate this, I created a simple Win form application with a Menu Strip and a List Box control.   On the menu Strip, all the operations are entered as menu items with short cut keys.
For better understanding, sample code is also attached with this article.


Click to download source code

Here is a screenshot of the GUI.


Select All:

To select all the items in a ListBox, we clear all the selected items firstly and keep on selecting item while iterating the entire list.

     private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)  
     {  
       try  
       {  
         listBox1.SelectedItems.Clear();  
         for (int i = 0; i < listBox1.Items.Count; i++)  
         {  
           listBox1.SetSelected(i, true);  
         }  
       }  
       catch (Exception ex)  
       {  
         MessageBox.Show(ex.Message);  
       }  
     }  

Paste:

To paste the text data into our List Box, we firstly retrieve the text data from buffer using Clipboard class. Since it is a list box where each item in the List Box should correspond to each line in the buffer, so here we parse the Text data by a new line character and then store each line as a new item in the List Box.
     private void pasteToolStripMenuItem_Click(object sender, EventArgs e)  
     {  
       try  
       {  
         // Getting Text from Clip board  
         string s = Clipboard.GetText();  
         //Parsing criteria: New Line  
         string[] lines = s.Split('\n');  
         foreach (string ln in lines)  
         {  
           listBox1.Items.Add(ln.Trim());  
         }  
       }  
       catch (Exception ex)  
       {  
         MessageBox.Show(ex.Message);  
       }  
     }  

Copy:

To copy the text data into buffer, we iterate entire selected item collection and keep on appending items into a StringBuilder object.  To keep every item in a new row, we are using here AppendLine()method after inserting item text into stringbuilder. Then at the end we use Clipboard.SetData() method to copy the data into buffer.
     private void copyToolStripMenuItem_Click(object sender, EventArgs e)  
     {  
        try  
       {  
         StringBuilder sb = new StringBuilder();  
         foreach (object row in listBox1.SelectedItems)  
         {  
           sb.Append(row.ToString());  
           sb.AppendLine();  
         }  
         sb.Remove(sb.Length - 1, 1); // Just to avoid copying last empty row  
          Clipboard.SetData(System.Windows.Forms.DataFormats.Text, sb.ToString());  
       }  
       catch (Exception ex)  
       {  
         MessageBox.Show(ex.Message);  
       }  
     }  

Cut:

Basically cut operation is the combination of copying and removing the selected items. In order to do this, we start copying all the selected items (as above) into buffer.
After copying, we remove all the selected items from the List Box.  For this we need another collection to keep all the selected items. We are creating this separate collection because we can’t delete item from the collection while iterating the same collection using foreach loop.

     private void cutToolStripMenuItem_Click(object sender, EventArgs e)  
     {  
       try  
       {  
         StringBuilder sb = new StringBuilder();  
         // we use this collection to keep all the Selected Items  
         List<object> selectedItemList = new List<object>();  
         foreach (object row in listBox1.SelectedItems)  
         {  
           sb.Append(row.ToString());  
           sb.AppendLine();  
           // Keep on adding selected item into a new List of Object  
           selectedItemList.Add(row);  
         }  
         sb.Remove(sb.Length - 1, 1);  // Just to avoid copying last empty row  
         Clipboard.SetData(System.Windows.Forms.DataFormats.Text, sb.ToString());  
         // Removing selected items from the list box  
         foreach (object ln in selectedItemList)  
         {  
           listBox1.Items.Remove(ln);  
         }  
       }  
       catch (Exception ex)  
       {  
         MessageBox.Show(ex.Message);  
       }  
     }  

Clear All:

This is the simplest operation. We need to just clear all the items from List Box using built-in Clear() method.
     private void clearAllToolStripMenuItem_Click(object sender, EventArgs e)  
     {  
       listBox1.Items.Clear();  
     }  

Thursday, May 2, 2013

Multiline TextBox scroll to bottom automatically



If we want to have our vertical scroll bar in a TextBox (obviously Multiline TextBox) pointing always to the bottom as we write data in the TextBox, we could do this using another way instead of using ScrollToCaret option.

When we write data in TextBox using textBox1.text = “This is my data… bla blah blah….”, by default  the vertical scroll bar always stays at the top. But if we use AppendText propery of textbox, vertical bar automatically comes to bottom whenever data is written in the text box.

                
 textBox1.AppendText(Environment.NewLine);   
 textBox1.AppendText(sMessage);

Thursday, April 18, 2013

Modifying Data in Tables through a View in SQL Server


Can we modify the table data through SQL View? 

The answer is: Yes !

We can modify the data of an underlying base table through a view, in the same manner as we modify data in a table by using UPDATE, INSERT and DELETE statements or by using the BCP utility and BULK INSERT statement. However, the following restrictions apply to updating views, but do not apply to tables:

·         Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table.

·         The columns that are being modified in the view must reference the underlying data in the table columns directly. They cannot be derived in any other way, such as through:

1.       An aggregate function (AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV, STDEVP, VAR and VARP).

2.       A computation; the column cannot be computed from an expression using other columns. Columns formed using set operators (UNION, UNION ALL, CROSSJOIN, EXCEPT, and INTERSECT) amount to a computation and are also not updatable.

·         The columns that are being modified cannot be affected by GROUP BY, HAVING, or DISTINCT clauses.

·         TOP cannot be used anywhere in the select_statement of the view when WITH CHECK OPTION is also specified.

Friday, April 5, 2013

Concatenate strings in MS-Excel


Here we will learn how we can easily concatenate string in MS-Excel which could be useful in many situations. I am going to describe a situation which I encountered once.

Let us assume a situation, we have a huge list of numbers (say Roll number of students in a university) saved in MS-Excel sheet and we want to write a SQL query that updates the section of all the students in that huge list. This we could do easily with a update SQL query using “IN” operator but problem is that we need to have our Student’s Roll number list in a format like ‘RollNum1’, ‘RollNum2’, ‘RollNum3’….. and in Excel sheet, we have a just a list of Roll numbers. Just for sake of understanding the scenario, a sample update query is given below:
UPDATE               TSTUDENTS
SET                         STUDNT_SECTN  =  ‘C2’

WHERE                  ROLL_NUM IN (a comma separated list in which each element is apostrophe enclosed)
So what’s next? Let’s go for the concatenation of strings in MS-Excel. We could do concatenation in Excel by following ways:
(1)    Suppose we have a list in column-A

(2)    On cell B-1, type “,”

(3)    Then Fill the entire column –B using AutoFill handle or select the column-B and use Ctrl+D option to auto fill rest of the cells in column-B

(4)    Now we could apply our concatenation in column-D. Got to Cell D1.

(5)    Concatenate the string either using string built-in concatenate function                

=CONCATENATE("'", A1, "'",B1)  
Or we could use “&” symbol for concatenation as   ="'" & A1 & "'" & B1
(6)    Then Fill the entire column –D using AutoFill handle or select the column-B and use Ctrl+D option to auto fill rest of the cells in column-D.

(7)    That’s it, we are done!
 
  A                     B             C                 D

B12 9

,

 

'B12 9',

B13 0

,

 

'B13 0',

B13 8

,

 

'B13 8',

B13 9

,

 

'B13 9',

B14  6

,

 

'B14  6',

B14 4

,

 

'B14 4',

B14 5

,

 

'B14 5',

B45 0

,

 

'B45 0',

B45 9

,

 

'B45 9',

B46 1

,

 

'B46 1',

B46 2

,

 

'B46 2',

B46 3

,

 

'B46 3',

B47 5

,

 

'B47 5',

B47 6

,

 

'B47 6',

B48 7

,

 

'B48 7',

B49 5

,

 

'B49 5',

B49 6

,

 

'B49 6',

B5 4

,

 

'B5 4',

B5 5

,

 

'B5 5',

B5 6

,

 

'B5 6',

B5 7

,

 

'B5 7',

B50 4

,

 

'B50 4',

B6 4

,

 

'B6 4',

B6 5

,

 

'B6 5',

B6 6

,

 

'B6 6',


 Thanks,

Hemant