Thursday, August 18, 2016

Synchronous vs Asynchronous Execution

Synchronous (one thread):
1 thread ->   |----A-----||-----B-----------||-------C------|
Synchronous (multi-threaded):
thread A -> |----A-----|   
                        \  
thread B ------------>   ->|-----B-----------|   
                                              \   
thread C ---------------------------------->   ->|-------C------| 
Asynchronous (one thread):
         A-Start ---------------------------------------- A-End   
           | B-Start ----------------------------------------|--- B-End   
           |   |     C-Start -------------------- C-End      |     |   
           V   V       V                           V         V     V      
1 thread-> |-A-|---B---|-C-|-A-|-C-|--A--|-B-|--C--|---A-----|--B--| 
Asynchronous (multi-Threaded):
 thread A ->     |----A-----|
 thread B ----->     |-----B-----------| 
 thread C --------->     |-------C----------|

Synchronized means "connected", or "dependent" in some way. In other words two synchronous tasks must be aware of one another, and one must execute in some way that is dependent on the other. In most cases that means that one cannot start until the other has completed. Asynchronous means they are totally independent and neither one must consider the other in any way, either in initiation or in execution.
As an aside, I should mention that technically, the concept of synchronous/asynchronous really does not have anything to do with threads. Although, in general, it would be unusual to find asynchronous tasks running on the same thread, it is possible, (see below for e.g.) and it is common to find two or more tasks executing synchronously on separate threads... No, the concept of synchronous/asynchronous has to do solely with whether or not a second or subsequent task can be initiated before the other (first) task has completed, or whether it must wait. That is all. What thread (or threads), or processes, or CPUs, or indeed, what hardware, the task[s] are executed on is not relevant. Indeed, to make this point I have edited the graphics to show this.
ASYNCHRONOUS EXAMPLE. In solving many engineering problems, the software is designed to split up the overall problem into multiple individual tasks, and then execute them asynchronously. Inverting a matrix, or a finite element analysis problem, are good examples. In computing, sorting a list is an example. The quick sort routine, for example, splits the list into two lists, and sorts each of them by calling itself recursively. In both of the above examples, the two tasks can (and often were) executed asynchronously. They do not need to be on separate threads. Even a machine with one CPU, and only one thread of execution can be coded to initiate processing of a second task before a first one has completed. The only criterion is that the results of one task are not necessary as inputs to the other task. As long as the start and end times of the tasks overlap, (possible only if the output of neither is needed as inputs to the other), they are being executed asynchronously, no matter how many threads are in use.
SYNCHRONOUS EXAMPLE. Any process consisting of multiple tasks where the tasks must be executed in sequence, but one must be executed on another machine (Fetch and/or update data, get a stock quote from a financial service, etc.). If it's on a separate machine it is on a separate thread, whether synchronous or asynchronous.

Wednesday, March 2, 2016

Alphanumeric sorting using C#




using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AlphanumericSorter
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] highways = new string[]
            {
                "P-1",
                "P-2",
                "P-10",
                "P-11"
            };
            //
            // We want to sort a string array called highways in an
            // alphanumeric way. Call the static Array.Sort method.
            //
            Array.Sort(highways, new AlphanumComparatorFast());
            //
            // Display the results
            //
            foreach (string h in highways)
            {
                Console.WriteLine(h);
            }
            Console.Read();
        }
    }

    public class AlphanumComparatorFast : IComparer
    {
        public int Compare(object x, object y)
        {
            string s1 = x as string;
            if (s1 == null)
            {
                return 0;
            }
            string s2 = y as string;
            if (s2 == null)
            {
                return 0;
            }

            int len1 = s1.Length;
            int len2 = s2.Length;
            int marker1 = 0;
            int marker2 = 0;

            // Walk through two the strings with two markers.
            while (marker1 < len1 && marker2 < len2)
            {
                char ch1 = s1[marker1];
                char ch2 = s2[marker2];

                // Some buffers we can build up characters in for each chunk.
                char[] space1 = new char[len1];
                int loc1 = 0;
                char[] space2 = new char[len2];
                int loc2 = 0;

                // Walk through all following characters that are digits or
                // characters in BOTH strings starting at the appropriate marker.
                // Collect char arrays.
                do
                {
                    space1[loc1++] = ch1;
                    marker1++;

                    if (marker1 < len1)
                    {
                        ch1 = s1[marker1];
                    }
                    else
                    {
                        break;
                    }
                } while (char.IsDigit(ch1) == char.IsDigit(space1[0]));

                do
                {
                    space2[loc2++] = ch2;
                    marker2++;

                    if (marker2 < len2)
                    {
                        ch2 = s2[marker2];
                    }
                    else
                    {
                        break;
                    }
                } while (char.IsDigit(ch2) == char.IsDigit(space2[0]));

                // If we have collected numbers, compare them numerically.
                // Otherwise, if we have strings, compare them alphabetically.
                string str1 = new string(space1);
                string str2 = new string(space2);

                int result;

                if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]))
                {
                    int thisNumericChunk = int.Parse(str1);
                    int thatNumericChunk = int.Parse(str2);
                    result = thisNumericChunk.CompareTo(thatNumericChunk);
                }
                else
                {
                    result = str1.CompareTo(str2);
                }

                if (result != 0)
                {
                    return result;
                }
            }
            return len1 - len2;
        }
    }
}

Awesome Technologies 2016


Sharing a glimpse of awesome new technologies of 2016.

Have a look of these cool technologies:
  • HoloLens
  • Project Jacquard
  • Hoverboard,
  • 3D Simo Mini
  • Holus
  • Pepper
  • PIECE
  • Project Soli
All these technologies are pretty exciting and hope make our world more comfortable and enjoyable!
 
 
 

Tuesday, December 8, 2015

SOLID - An object oriented design technique




 

 

Stands for
(acronym)
Concept
 
S
a class should have only a single responsibility (i.e. only one potential change in the software's specification should be able to affect the specification of the class)
O
“software entities … should be open for extension, but closed for modification.”
L
LSP
“objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.” See also design by contract.
I
ISP
“many client-specific interfaces are better than one general-purpose interface.”
D
DIP                     
one should “Depend upon Abstractions. Do not depend upon concretions.”

Tuesday, October 27, 2015

Sample SQL Database script with data

DB Diagram:




DB Script:

 
create table zipcodes (
  zip int primary key,
  city  varchar(30),
  State varchar(20));
 
 
create table employees (
  eno  varchar(10) primary key,
  ename  varchar(30),
  zip  int references zipcodes,
  hire_date date);
 
 
 
create table books (
  bno  int primary key,
  bname  varchar(30),
  qoh  int not null,
  price  dec(6,2) not null);
 
 
create table customers (
  cno   int primary key,
  cname  varchar(30),
  street varchar(30),
  zip  int  references zipcodes,
  phone  char(12));
 
 
 
create table orders (
  ono  int  primary key,
  cno  int  references customers,
  eno  varchar(10)  references employees,
  received date,
  shipped date
);
 
 
 
create table odetails (
  ono  int  references orders,
  bno  int  references books,
  quantity int not null,
  primary key (ono, bno));
 
insert into zipcodes values (98225, 'Bellingham', 'WA'); 
insert into zipcodes values (95388, 'Winton', 'CA'); 
insert into zipcodes values (44242, 'Stow', 'OH'); 
insert into zipcodes values (61536, 'Hanna city', 'IL'); 
insert into zipcodes values (01254, 'Richmond', 'MA'); 
insert into zipcodes values (95124, 'San Jose', 'CA'); 
insert into zipcodes values (95382, 'Turlock', 'MA'); 
insert into zipcodes values (95380, 'Turlock', 'CA');
 
 
insert into employees values ('P0239400', 'Jones Hoffer',98225, '2000-12-12'); 
insert into employees values ('P0239401', 'Jeffrey Prescott',95388, '2006-01-01'); 
insert into employees values ('P0239402', 'Fred NcFaddeb',95124, '2008-09-01');
 
 
insert into books values (10506, 'Accounting 101',200, 129.99); 
insert into books values (10507, 'Management 101',159, 109.99); 
insert into books values (10508, 'Fraud Cases',190, 179.99); 
insert into books values (10509, 'CPA Review',65, 299.99); 
insert into books values (10601, 'Peachtree for Dummies',322, 49.99); 
insert into books values (10701, 'Financial Accounting',129, 164.99); 
insert into books values (10800, 'Managerial Accounting',155, 114.99); 
insert into books values (10900, 'Cost Accounting',122, 119.99); 
insert into books values (10901, 'Intermediate Accounting',123, 164.99); 
insert into books values (10902, 'XBRL in Nutshell',124, 109.99);
 
insert into customers values (23511, 'Michelle Kuan', '123 Main St.',98225, '360-636-5555'); 
insert into customers values (23512, 'George Myer', '237 Ash Ave.',95124, '312-678-5555'); 
insert into customers values (23513, 'Richard Gold', '111 Inwood St.',95124, '312-883-7337'); 
insert into customers values (23514, 'Robert Smith', '54 Gate Dr.',95388, '206-832-1221'); 
insert into customers values (23515, 'Christopher David', '777 Loto St.',98225, '360-458-9878'); 
insert into customers values (23516, 'Adam Beethoven', '234 Park Rd..',95380, '209-546-7299'); 
insert into customers values (23517, 'Lidwig Bach', '5790 Walnut St.',95382, '209-638-2712');
 
 
insert into orders values (1020, 23511, 'P0239400', '2009-10-18', '2009-10-20'); 
insert into orders values (1021, 23511, 'P0239400', '2009-10-29', '2009-10-31'); 
insert into orders values (1022, 23512, 'P0239401', '2009-11-10', '2009-11-13'); 
insert into orders (ONO, CNO, ENO, RECEIVED) values (1023, 23513, 'P0239402', '2009-11-15'); 
insert into orders (ONO, CNO, ENO, RECEIVED) values (1024, 23511, 'P0239400', '2009-11-16');
 
 
insert into odetails values (1020, 10506,1); insert into odetails values (1020, 10507,2); 
insert into odetails values (1020, 10508,2); insert into odetails values (1020, 10509,3); 
insert into odetails values (1021, 10601,4); insert into odetails values (1022, 10601,1); 
insert into odetails values (1022, 10701,2); insert into odetails values (1023, 10800,4); 
insert into odetails values (1023, 10900,1); insert into odetails values (1024, 10900,7);
 

Thursday, August 7, 2014

How can a totally logical machine like a computer generate a random number?







Have you wondered how a random number is generated in programming languages on a totally logical device like a Computer?
Recently I read an article about it which throws a light on this interesting topic.


Here is the link:
http://computer.howstuffworks.com/question697.htm

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