Wednesday, October 21, 2015

How to use Parallel Loops in C# how it improves performance??



This example shows how to use a Parallel.ForEach loop to enable data parallelism over anySystem.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> data source.





 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ParallelLoopSample
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> Large_List1 = new List<string>();
            List<string> Large_List2 = new List<string>();
            Object myList = new Object();


            //Time taken by Loop to Write to List1
            var watch1 = Stopwatch.StartNew();

            for (Int64 i = 0; i <= 10000000; i++)
            {
                Large_List1.Add(i.ToString());
            }

            watch1.Stop();
            var elapsedMs = watch1.ElapsedMilliseconds;

            Console.WriteLine("Total Time Taken to Finish Loop1:{0}", elapsedMs);


            //Time Taken by Loop to Read List1 and Write to List2
            var watch2 = Stopwatch.StartNew();

            Parallel.ForEach(Large_List1, new ParallelOptions() { MaxDegreeOfParallelism = 10 }, sel =>
            {                
                try
                {
                    lock (myList)
                    {
                        Large_List2.Add(sel);
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

            });


            watch2.Stop();
            var elapsedMs2 = watch2.ElapsedMilliseconds;

            Console.WriteLine("Total Time Taken to Finish Loop2:{0}", elapsedMs2);

            Console.ReadLine();
        }
    }
}


Output:

Sunday, October 11, 2015

Grouping List using Linq



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GroupingValues
{
    public class Employee
    {
        public int EmpId;
        public string EmpName;
        public int LocationID;
        public string EmpDeptName;
    }
    class Program
    {       
        static void Main(string[] args)
        {
            List<Employee> EmpList = new List<Employee>();

           //Add IT Employees

            for(int i = 0; i<50;i++)
            {
                if(i < 10)
                 EmpList.Add(new Employee { EmpId = i, EmpName = "ITDeptEmp" + i.ToString(), LocationID = 1, EmpDeptName = "Information Technology" });
                else
                    EmpList.Add(new Employee { EmpId = i, EmpName = "ITDeptEmp" + i.ToString(), LocationID = 2, EmpDeptName = "Information Technology" });
         
            }

            //Add HR Employees

            for (int i = 50; i < 60; i++)
            {
                if(i<55)
                EmpList.Add(new Employee { EmpId = i, EmpName = "HRDeptEmp" + i.ToString(), LocationID = 2, EmpDeptName = "Human Resource" });
                else
                   EmpList.Add(new Employee { EmpId = i, EmpName = "HRDeptEmp" + i.ToString(), LocationID = 3, EmpDeptName = "Human Resource" });
            }

            //Add Accounts Employees

            for (int i = 60; i < 70; i++)
            {
                EmpList.Add(new Employee { EmpId = i, EmpName = "AccountsDeptEmp" + i.ToString(), LocationID = 3, EmpDeptName = "Accounts" });
            }

            //Now Group Employees by Department

            var EmployeeByDeptName = EmpList.ToLookup(x => x.EmpDeptName);

            foreach (IGrouping<string, Employee> Employee in EmployeeByDeptName)
            {
                Console.WriteLine("EMployees in {0} Department", Employee.Key);

                List<Employee> lstsGroupEmployee = new List<Employee>();
                lstsGroupEmployee = Employee.Select(item => item).ToList<Employee>();

                foreach (Employee Emp in lstsGroupEmployee)
                {
                    Console.WriteLine("EmployeeID:{0},EmployeeName:{1}", Emp.EmpId, Emp.EmpName);
                }
            }

            //Now Group Employees by Location ID

            var EmployeeByLoc= EmpList.ToLookup(x => x.LocationID);

            foreach (IGrouping<int, Employee> Employee in EmployeeByLoc)
            {
                Console.WriteLine("EMployees in {0} Location", Employee.Key);

                List<Employee> lstsGroupEmployee = new List<Employee>();
                lstsGroupEmployee = Employee.Select(item => item).ToList<Employee>();

                foreach (Employee Emp in lstsGroupEmployee)
                {
                    Console.WriteLine("EmployeeID:{0},EmployeeName:{1}", Emp.EmpId, Emp.EmpName);
                }
            }

            Console.ReadLine();
        }
    }
}


Output:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
EMployees in Information Technology Department
EmployeeID:0,EmployeeName:ITDeptEmp0
EmployeeID:1,EmployeeName:ITDeptEmp1
EmployeeID:2,EmployeeName:ITDeptEmp2
EmployeeID:3,EmployeeName:ITDeptEmp3
EmployeeID:4,EmployeeName:ITDeptEmp4
EmployeeID:5,EmployeeName:ITDeptEmp5
EmployeeID:6,EmployeeName:ITDeptEmp6
EmployeeID:7,EmployeeName:ITDeptEmp7
EmployeeID:8,EmployeeName:ITDeptEmp8
EmployeeID:9,EmployeeName:ITDeptEmp9
EmployeeID:10,EmployeeName:ITDeptEmp10
EmployeeID:11,EmployeeName:ITDeptEmp11
EmployeeID:12,EmployeeName:ITDeptEmp12
EmployeeID:13,EmployeeName:ITDeptEmp13
EmployeeID:14,EmployeeName:ITDeptEmp14
EmployeeID:15,EmployeeName:ITDeptEmp15
EmployeeID:16,EmployeeName:ITDeptEmp16
EmployeeID:17,EmployeeName:ITDeptEmp17
EmployeeID:18,EmployeeName:ITDeptEmp18
EmployeeID:19,EmployeeName:ITDeptEmp19
EmployeeID:20,EmployeeName:ITDeptEmp20
EmployeeID:21,EmployeeName:ITDeptEmp21
EmployeeID:22,EmployeeName:ITDeptEmp22
EmployeeID:23,EmployeeName:ITDeptEmp23
EmployeeID:24,EmployeeName:ITDeptEmp24
EmployeeID:25,EmployeeName:ITDeptEmp25
EmployeeID:26,EmployeeName:ITDeptEmp26
EmployeeID:27,EmployeeName:ITDeptEmp27
EmployeeID:28,EmployeeName:ITDeptEmp28
EmployeeID:29,EmployeeName:ITDeptEmp29
EmployeeID:30,EmployeeName:ITDeptEmp30
EmployeeID:31,EmployeeName:ITDeptEmp31
EmployeeID:32,EmployeeName:ITDeptEmp32
EmployeeID:33,EmployeeName:ITDeptEmp33
EmployeeID:34,EmployeeName:ITDeptEmp34
EmployeeID:35,EmployeeName:ITDeptEmp35
EmployeeID:36,EmployeeName:ITDeptEmp36
EmployeeID:37,EmployeeName:ITDeptEmp37
EmployeeID:38,EmployeeName:ITDeptEmp38
EmployeeID:39,EmployeeName:ITDeptEmp39
EmployeeID:40,EmployeeName:ITDeptEmp40
EmployeeID:41,EmployeeName:ITDeptEmp41
EmployeeID:42,EmployeeName:ITDeptEmp42
EmployeeID:43,EmployeeName:ITDeptEmp43
EmployeeID:44,EmployeeName:ITDeptEmp44
EmployeeID:45,EmployeeName:ITDeptEmp45
EmployeeID:46,EmployeeName:ITDeptEmp46
EmployeeID:47,EmployeeName:ITDeptEmp47
EmployeeID:48,EmployeeName:ITDeptEmp48
EmployeeID:49,EmployeeName:ITDeptEmp49
EMployees in Human Resource Department
EmployeeID:50,EmployeeName:HRDeptEmp50
EmployeeID:51,EmployeeName:HRDeptEmp51
EmployeeID:52,EmployeeName:HRDeptEmp52
EmployeeID:53,EmployeeName:HRDeptEmp53
EmployeeID:54,EmployeeName:HRDeptEmp54
EmployeeID:55,EmployeeName:HRDeptEmp55
EmployeeID:56,EmployeeName:HRDeptEmp56
EmployeeID:57,EmployeeName:HRDeptEmp57
EmployeeID:58,EmployeeName:HRDeptEmp58
EmployeeID:59,EmployeeName:HRDeptEmp59
EMployees in Accounts Department
EmployeeID:60,EmployeeName:AccountsDeptEmp60
EmployeeID:61,EmployeeName:AccountsDeptEmp61
EmployeeID:62,EmployeeName:AccountsDeptEmp62
EmployeeID:63,EmployeeName:AccountsDeptEmp63
EmployeeID:64,EmployeeName:AccountsDeptEmp64
EmployeeID:65,EmployeeName:AccountsDeptEmp65
EmployeeID:66,EmployeeName:AccountsDeptEmp66
EmployeeID:67,EmployeeName:AccountsDeptEmp67
EmployeeID:68,EmployeeName:AccountsDeptEmp68
EmployeeID:69,EmployeeName:AccountsDeptEmp69
EMployees in 1 Location
EmployeeID:0,EmployeeName:ITDeptEmp0
EmployeeID:1,EmployeeName:ITDeptEmp1
EmployeeID:2,EmployeeName:ITDeptEmp2
EmployeeID:3,EmployeeName:ITDeptEmp3
EmployeeID:4,EmployeeName:ITDeptEmp4
EmployeeID:5,EmployeeName:ITDeptEmp5
EmployeeID:6,EmployeeName:ITDeptEmp6
EmployeeID:7,EmployeeName:ITDeptEmp7
EmployeeID:8,EmployeeName:ITDeptEmp8
EmployeeID:9,EmployeeName:ITDeptEmp9
EMployees in 2 Location
EmployeeID:10,EmployeeName:ITDeptEmp10
EmployeeID:11,EmployeeName:ITDeptEmp11
EmployeeID:12,EmployeeName:ITDeptEmp12
EmployeeID:13,EmployeeName:ITDeptEmp13
EmployeeID:14,EmployeeName:ITDeptEmp14
EmployeeID:15,EmployeeName:ITDeptEmp15
EmployeeID:16,EmployeeName:ITDeptEmp16
EmployeeID:17,EmployeeName:ITDeptEmp17
EmployeeID:18,EmployeeName:ITDeptEmp18
EmployeeID:19,EmployeeName:ITDeptEmp19
EmployeeID:20,EmployeeName:ITDeptEmp20
EmployeeID:21,EmployeeName:ITDeptEmp21
EmployeeID:22,EmployeeName:ITDeptEmp22
EmployeeID:23,EmployeeName:ITDeptEmp23
EmployeeID:24,EmployeeName:ITDeptEmp24
EmployeeID:25,EmployeeName:ITDeptEmp25
EmployeeID:26,EmployeeName:ITDeptEmp26
EmployeeID:27,EmployeeName:ITDeptEmp27
EmployeeID:28,EmployeeName:ITDeptEmp28
EmployeeID:29,EmployeeName:ITDeptEmp29
EmployeeID:30,EmployeeName:ITDeptEmp30
EmployeeID:31,EmployeeName:ITDeptEmp31
EmployeeID:32,EmployeeName:ITDeptEmp32
EmployeeID:33,EmployeeName:ITDeptEmp33
EmployeeID:34,EmployeeName:ITDeptEmp34
EmployeeID:35,EmployeeName:ITDeptEmp35
EmployeeID:36,EmployeeName:ITDeptEmp36
EmployeeID:37,EmployeeName:ITDeptEmp37
EmployeeID:38,EmployeeName:ITDeptEmp38
EmployeeID:39,EmployeeName:ITDeptEmp39
EmployeeID:40,EmployeeName:ITDeptEmp40
EmployeeID:41,EmployeeName:ITDeptEmp41
EmployeeID:42,EmployeeName:ITDeptEmp42
EmployeeID:43,EmployeeName:ITDeptEmp43
EmployeeID:44,EmployeeName:ITDeptEmp44
EmployeeID:45,EmployeeName:ITDeptEmp45
EmployeeID:46,EmployeeName:ITDeptEmp46
EmployeeID:47,EmployeeName:ITDeptEmp47
EmployeeID:48,EmployeeName:ITDeptEmp48
EmployeeID:49,EmployeeName:ITDeptEmp49
EmployeeID:50,EmployeeName:HRDeptEmp50
EmployeeID:51,EmployeeName:HRDeptEmp51
EmployeeID:52,EmployeeName:HRDeptEmp52
EmployeeID:53,EmployeeName:HRDeptEmp53
EmployeeID:54,EmployeeName:HRDeptEmp54
EMployees in 3 Location
EmployeeID:55,EmployeeName:HRDeptEmp55
EmployeeID:56,EmployeeName:HRDeptEmp56
EmployeeID:57,EmployeeName:HRDeptEmp57
EmployeeID:58,EmployeeName:HRDeptEmp58
EmployeeID:59,EmployeeName:HRDeptEmp59
EmployeeID:60,EmployeeName:AccountsDeptEmp60
EmployeeID:61,EmployeeName:AccountsDeptEmp61
EmployeeID:62,EmployeeName:AccountsDeptEmp62
EmployeeID:63,EmployeeName:AccountsDeptEmp63
EmployeeID:64,EmployeeName:AccountsDeptEmp64
EmployeeID:65,EmployeeName:AccountsDeptEmp65
EmployeeID:66,EmployeeName:AccountsDeptEmp66
EmployeeID:67,EmployeeName:AccountsDeptEmp67
EmployeeID:68,EmployeeName:AccountsDeptEmp68
EmployeeID:69,EmployeeName:AccountsDeptEmp69

Thursday, October 8, 2015

GenericShape or Polygon Area Calculator in C#



Shape.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericAreaCalculator
{
    public class Shape
    {
        public Dictionary<int,int> x;
        public Dictionary<int, int> y;

        public Shape()
        {
            x = new Dictionary<int, int>();
            y = new Dictionary<int, int>();
        }
    }
}


Area.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericAreaCalculator
{
    public class Area:Shape
    {
        public float CalculateArea(Shape Shapes,int sides)
        {
            float area = 0;
             int x1 = 0;
             int y2 = 0;
             int y1 = 0;
             int x2 = 0;

            if (sides > 1)
            {
                for (int index = 1; index < sides; index++)
                {
                     x1 = Shapes.x[index];
                     y2 = Shapes.y[index + 1];
                     y1 = Shapes.y[index];
                     x2 = Shapes.x[index + 1];
                    area = area + (((x1 * y2)) - ((y1 * x2)));

                }

                 int xn = Shapes.x[sides];              
                 y1 = Shapes.y[1];
                 int yn = Shapes.y[sides];
                 x1 = Shapes.x[1];
                 area = (area + (((xn * y1)) - ((yn * x1))))/2;
                
            }
            else if (sides == 1)
            {
                area = (float)(3.14 * Shapes.x[0] * Shapes.x[0]);
            }
            

            

            return Math.Abs(area);
        }
    }
}


Program.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericAreaCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            Shape shapeobj = new Shape();

            shapeobj.x.Add(1, 0);
            shapeobj.x.Add(2, 10);
            shapeobj.x.Add(3, 10);
            shapeobj.x.Add(4, 0);

            shapeobj.y.Add(1, 0);
            shapeobj.y.Add(2, 0);
            shapeobj.y.Add(3, 10);
            shapeobj.y.Add(4, 10);

            Area area = new Area();

            float ShapeArea = area.CalculateArea(shapeobj, 4);

            Console.WriteLine("Area of Square is:{0}", ShapeArea);

            shapeobj.x.Clear();
            shapeobj.y.Clear();

            shapeobj.x.Add(0, 10);

            ShapeArea = area.CalculateArea(shapeobj, 1);

            Console.WriteLine("Area of Circle is:{0}", ShapeArea);

            Console.ReadLine();
        }
    }
}


Output:

Tuesday, October 6, 2015

Pseudo for using Observer Pattern to Notify Database Connection Across Multiple Threads



What is Observer Pattern ?

The observer design pattern enables a subscriber to register with and receive notifications from a provider. It is suitable for any scenario that requires push-based notification. The pattern defines a provider (also known as a subject or an observable) and zero, one, or more observers. Observers register with the provider, and whenever a predefined condition, event, or state change occurs, the provider automatically notifies all observers by calling one of their methods. In this method call, the provider can also provide current state information to observers. In the .NET Framework, the observer design pattern is applied by implementing the generic System.IObservable(Of T) and System.IObserver(Of T) interfaces. The generic type parameter represents the type that provides notification information.



Example :

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace ObserverPatternDBHandler
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection objconnection = new SqlConnection("Data Source=devserv,1499;Network Library=DBMSSOCN;Initial Catalog=dev;User ID=dev;Password=dev123;");
            // Configure Observer pattern
            ConcreteSubject s = new ConcreteSubject();

            s.Attach(new ConcreteObserver(s, "DBUsingThread1"));
            s.Attach(new ConcreteObserver(s, "DBUsingThread2"));
            s.Attach(new ConcreteObserver(s, "DBUsingThread3"));

            // Change subject and notify observers
            objconnection.Open();
            s.SubjectState = objconnection.State==System.Data.ConnectionState.Open?true:false;
            s.Notify();
            objconnection.Close();
            s.SubjectState = objconnection.State == System.Data.ConnectionState.Open ? true : false;
            s.Notify();
            // Wait for user
            Console.ReadKey();
        }      

    }

    abstract class Subject
    {
        private List<Observer> _observers = new List<Observer>();

        public void Attach(Observer observer)
        {
            _observers.Add(observer);
        }

        public void Detach(Observer observer)
        {
            _observers.Remove(observer);
        }

        public void Notify()
        {
            foreach (Observer o in _observers)
            {
                o.Update();
            }
        }
    }

    /// <summary>
    /// The 'ConcreteSubject' class
    /// </summary>
    class ConcreteSubject : Subject
    {
        private bool _subjectState;

        // Gets or sets subject state
        public bool SubjectState
        {
            get { return _subjectState; }
            set { _subjectState = value; }
        }
    }

    /// <summary>
    /// The 'Observer' abstract class
    /// </summary>
    abstract class Observer
    {
        public abstract void Update();
    }

    /// <summary>
    /// The 'ConcreteObserver' class
    /// </summary>
    class ConcreteObserver : Observer
    {
        private string _name;
        private bool _observerState;
        private ConcreteSubject _subject;

        // Constructor
        public ConcreteObserver(
          ConcreteSubject subject, string name)
        {
            this._subject = subject;
            this._name = name;
        }

        public override void Update()
        {
            _observerState = _subject.SubjectState;
            Console.WriteLine("Observer {0}'s new state is {1}",
                _name, _observerState?"Connected":"Disconnected");
        }

        // Gets or sets subject
        public ConcreteSubject Subject
        {
            get { return _subject; }
            set { _subject = value; }
        }
    }
}


Output:

Sunday, September 27, 2015

How do I scroll 2 listview objects together?



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System.Windows.Forms;
 
namespace ListViewSharedScroll
{
    class CustListView : ListView 
    {
        public event ScrollEventHandler Scroll;
        private const int WM_HSCROLL = 0x114;
        private const int WM_VSCROLL = 0x115;
        protected virtual void OnScroll(ScrollEventArgs e)
        {
            ScrollEventHandler handler = this.Scroll;
            if (handler != null) handler(this, e);
        }
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == WM_VSCROLL)
            { // Trap WM_VSCROLL
                OnScroll(new ScrollEventArgs((ScrollEventType)(m.WParam.ToInt32() & 0xffff), -1, 0, ScrollOrientation.VerticalScroll));
            }
            else if (m.Msg == WM_HSCROLL)
            {
                OnScroll(new ScrollEventArgs((ScrollEventType)(m.WParam.ToInt32() & 0xffff),-1,0,ScrollOrientation.HorizontalScroll));
            }
        }
 
       
       
    }
}


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
 
namespace ListViewSharedScroll
{
    
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
 
        int TopItemIndex = 0;
        CustListView ListView1 = new CustListView();
        CustListView ListView2 = new CustListView();
        private void Form1_Load(object sender, EventArgs e)
        {
            
 
            ListView1.Size = new Size(201, 146);
            ListView1.Margin = new Padding(3, 3, 3, 3);
            ListView1.Location = new Point(48, 85);
            ListView1.Scrollable = true;
            ListView1.View = View.Details;
            
            
 
            ListView2.Size = new Size(201, 146);
            ListView2.Margin = new Padding(3, 3, 3, 3);
            ListView2.Location = new Point(280, 85);
            ListView2.Scrollable = true;
            ListView2.View = View.Details;
 
            ListView1.Columns.Add("Header", 100);
            ListView1.Columns.Add("Details", 100);
 
            ListView2.Columns.Add("Header", 100);
            ListView2.Columns.Add("Details", 100);
 

            for (int i = 0; i < 50; i++)
            {
            
                ListView1.Items.Add(new ListViewItem(new string[] { "Alpha"+i.ToString(), "Some details"+i.ToString() }));
                ListView1.Items.Add(new ListViewItem(new string[] { "Bravo" + i.ToString(), "More details" + i.ToString() }));
 
                ListView2.Items.Add(new ListViewItem(new string[] { "Alpha" + i.ToString(), "Some details" + i.ToString() }));
                ListView2.Items.Add(new ListViewItem(new string[] { "Bravo" + i.ToString(), "More details" + i.ToString() }));
            }
 
            
 
            ListView1.Scroll += ListView1_Scroll;
            ListView2.Scroll += ListView1_Scroll;
 
            this.Controls.Add(ListView1);
            this.Controls.Add(ListView2);
 

        }
 
        private void ListView1_Scroll(object sender, ScrollEventArgs e)
        {
 
            if (e.ScrollOrientation == ScrollOrientation.VerticalScroll)
            {
                if (TopItemIndex != ListView1.TopItem.Index || TopItemIndex !=  ListView2.TopItem.Index)
                {
                    if (TopItemIndex != ListView1.TopItem.Index)
                    {
                        ListView1.EnsureVisible(ListView1.TopItem.Index);
                        ListView2.EnsureVisible(ListView1.TopItem.Index);
                        TopItemIndex = ListView1.TopItem.Index;
                    }
                    else
                    {
                        ListView1.EnsureVisible(ListView2.TopItem.Index);
                        ListView2.EnsureVisible(ListView2.TopItem.Index);
                        TopItemIndex = ListView2.TopItem.Index;
                    }
 
                    
                }
            }
 
            if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
            {
                ScrollH(1);          
            }
            
        }
 
        private void ScrollH(int pixelsToScroll)
        {
            const Int32 LVM_FIRST = 0x1000;
            const Int32 LVM_SCROLL = LVM_FIRST + 20;
            SendMessage(ListView1.Handle, LVM_SCROLL, (IntPtr)pixelsToScroll, IntPtr.Zero);
            SendMessage(ListView2.Handle, LVM_SCROLL, (IntPtr)pixelsToScroll, IntPtr.Zero);
        }
 

       
    }
}

Refernced articles:
  http://stackoverflow.com/questions/1851620/handling-scroll-event-on-listview-in-c-sharp http://stackoverflow.com/questions/626315/winforms-listview-remembering-scrolled-location-on-reload
http://stackoverflow.com/questions/473148/c-sharp-listview-how-do-i-add-items-to-columns-2-3-and-4-etc
  http://stackoverflow.com/questions/7146567/winforms-listview-not-showing-items-in-detailsview http://stackoverflow.com/questions/372034/how-do-i-listen-for-scrolling-in-a-listview http://stackoverflow.com/questions/372034/how-do-i-listen-for-scrolling-in-a-listview http://bytes.com/topic/c-sharp/answers/255418-scrolling-listview

Wednesday, April 29, 2015

Integer Complemet of a Number or Once Complemet of a Integer

This was a program given to me in an interview unfortunately I was not able to complete it in very short time hence I am writing this code here so that this may help any one ;-)

C++ Source :

#include<iostream>
#include<conio.h>
#include<string>

using namespace std;

int GetIntegerComplement(int nInputNum)
{
int nRemider = 0, nCompRem = 0, nSum = 0, nCompSum=0, nTempNum;
int nPos=1;
string strComp="";
char ChArray[2];
size_t Size = 1;
nTempNum = nInputNum;
do
{
nRemider = nTempNum % 2;

if (nRemider == 0)
{
nCompRem = 1;

}
else
{
nCompRem = 0;
}

nSum = nSum + (nPos*nRemider);
nCompSum = nCompSum + (nPos*nCompRem);
_itoa(nCompRem,ChArray,10);
strComp = strComp + string(ChArray);
nTempNum = nTempNum / 2;
nPos = nPos * 10;

} while (nTempNum>0);

cout << "\n The Binary equivalent of " << nInputNum << " is " << nSum;

int nIntComp = 0;

nPos = 0;
nRemider = 0;

while (nCompSum > 0)
{
nRemider = nCompSum % 10;

nIntComp = nIntComp + pow(2,nPos)*nRemider;

nCompSum = nCompSum / 10;

nPos++;

}

reverse(strComp.begin(),strComp.end());

cout << "\n The complement Binary equivalent" << " is " << strComp;

return nIntComp;
}

void main()
{
int nNumber;
cout << "\n Enter a number to Convert to Binary";
cin >> nNumber;
cout << "\n The Integer complement of " << nNumber << " is " << GetIntegerComplement(nNumber);

_getch();
}


C# Source:


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

namespace DecimalOnceComplement
{
    class Program
    {

        static int GetIntegerComplement(int nInputNum)
        {
           int nRemider = 0, nCompRem = 0, nSum = 0, nCompSum=0, nTempNum;
           int nPos=1;
           string strComp="";
           nTempNum = nInputNum;
        do
           {
           nRemider = nTempNum % 2;

           if (nRemider == 0)
           {
           nCompRem = 1;

           }
           else
           {
           nCompRem = 0;
           }

               nSum = nSum + (nPos*nRemider);
               nCompSum = nCompSum + (nPos*nCompRem);
                        strComp = strComp + nCompRem.ToString();
               nTempNum = nTempNum / 2;
               nPos = nPos * 10;

          } while (nTempNum>0);

           Console.WriteLine(" The Binary equivalent of {0} is {1}",nInputNum,nSum);

           int nIntComp = 0;

           nPos = 0;
           nRemider = 0;

          while (nCompSum > 0)
          {
           nRemider = nCompSum % 10;

           nIntComp = nIntComp + (int)(Math.Pow(2,nPos))*nRemider;

           nCompSum = nCompSum / 10;

           nPos++;

       }

               strComp = ReverseString(strComp);

        Console.WriteLine( " The complement Binary equivalent is {0}",strComp);

       return nIntComp;
       
        }

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

        static void Main(string[] args)
        {
            int nNumber;
            string strInput;
            Console.WriteLine(" Enter a number to Convert to Binary:");
            strInput = Console.ReadLine();
            nNumber = Convert.ToInt32(strInput);
            Console.WriteLine(" The Integer complement of {0} is {1}" ,nNumber,GetIntegerComplement(nNumber));

            Console.ReadLine();
        }
    }
}


Out Put :



Monday, April 27, 2015

Friend function in C++ vs internal function in C#

There is no friend function in C# instead you can achieve same functionality using internal keyword

C++ Source :

#include<iostream>
#include<conio.h>
#include<string>

using namespace std;

class access
{
// String Variable declared as internal
public:
void SetName(string Name);
friend void print(access objAcess);
private:
string name;


};

void access::SetName(string Name)
{
name = Name;
}

void print(access objAcess)
{
cout << "\nMy name is " << objAcess.name;
}

void main( )
{
access objAcess;
objAcess.SetName("Sreeyush");
print(objAcess);
 
_getch();

}


C# source :

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

namespace InternalKeywordEx
{
    class access
    {
        // String Variable declared as internal
        private string name;
        internal void print()
        {
            Console.WriteLine("\nMy name is " + name);
        }

        internal void SetName(string Name)
        {
            name = Name;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            access objAcess = new access();

            objAcess.SetName("Sreeyush");

            objAcess.print();

            Console.ReadLine();


        }
    }
}


static in C++ vs Static class in C#

There is no static class in c++ like in C# , instead we can declare static members and fuctions inside a class in c++

C++ Source :

#include<iostream>
#include<conio.h>
#include<string>

using namespace std;

class TemperatureConverter
{
public :
static double CelsiusToFahrenheit(std::string temperatureCelsius)
{
// Convert argument to double for calculations.
std::string::size_type sz;
double celsius = std::stod(temperatureCelsius, &sz);

// Convert Celsius to Fahrenheit.
double fahrenheit = (celsius * 9 / 5) + 32;

return fahrenheit;
}

static double FahrenheitToCelsius(std::string temperatureFahrenheit)
{
// Convert argument to double for calculations.
std::string::size_type sz;
double fahrenheit = std::stod(temperatureFahrenheit, &sz);

// Convert Fahrenheit to Celsius.
double celsius = (fahrenheit - 32) * 5 / 9;

return celsius;
}
};

void main()
{
cout<<"Please select the convertor direction\n";
cout << "1. From Celsius to Fahrenheit.\n";
cout << "2. From Fahrenheit to Celsius.\n";
cout << ":";

string selection;
int selectionType;
cin >> selection;
double F, C = 0;

if (selection.compare("1") == 0)
{
selectionType = 1;
}
else if (selection.compare("2") == 0)
{
selectionType = 2;
}
else
{
selectionType = 3;
}

std::string value;

switch (selectionType)
{

case 1:
cout<<"Please enter the Celsius temperature:";
cin >> value;
F = TemperatureConverter::CelsiusToFahrenheit(value);
printf("Temperature in Fahrenheit:%0.2f",F);
break;

case 2:
cout << "Please enter the Fahrenheit temperature:";
cin >> value;
C = TemperatureConverter::FahrenheitToCelsius(value);
printf("Temperature in Celsius:%0.2f", C);
break;

default:
cout << "Please select a convertor.";
break;
}

// Keep the console window open in debug mode.
cout <<"\nPress any key to exit.";
_getch();
}



C# source :

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

namespace StaticClassSln
{

    public static class TemperatureConverter
    {
        public static double CelsiusToFahrenheit(string temperatureCelsius)
        {
            // Convert argument to double for calculations.
            double celsius = Double.Parse(temperatureCelsius);

            // Convert Celsius to Fahrenheit.
            double fahrenheit = (celsius * 9 / 5) + 32;

            return fahrenheit;
        }

        public static double FahrenheitToCelsius(string temperatureFahrenheit)
        {
            // Convert argument to double for calculations.
            double fahrenheit = Double.Parse(temperatureFahrenheit);

            // Convert Fahrenheit to Celsius.
            double celsius = (fahrenheit - 32) * 5 / 9;

            return celsius;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please select the convertor direction");
            Console.WriteLine("1. From Celsius to Fahrenheit.");
            Console.WriteLine("2. From Fahrenheit to Celsius.");
            Console.Write(":");

            string selection = Console.ReadLine();
            double F, C = 0;

            switch (selection)
            {
                case "1":
                    Console.Write("Please enter the Celsius temperature: ");
                    F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
                    Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
                    break;

                case "2":
                    Console.Write("Please enter the Fahrenheit temperature: ");
                    C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine());
                    Console.WriteLine("Temperature in Celsius: {0:F2}", C);
                    break;

                default:
                    Console.WriteLine("Please select a convertor.");
                    break;
            }

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
}

Wednesday, March 18, 2015

C++ list vs C# list

C++ Source code :

#include<iostream>
#include<conio.h>
#include<list>

using namespace std;


void main()
{

list<int> mylist;

mylist.push_back(1);
mylist.push_back(2);
mylist.push_back(3);

list<int>::iterator itrlst;

for (itrlst = mylist.begin(); itrlst != mylist.end(); itrlst++)
{
cout << *itrlst << "Element" << *itrlst<<"\n";
}


_getch();

}

output :

1 Element 1
2 Element 2
3 Element 3


C# souce code :

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

namespace Project2
{
    
    public class Class1
    {
       
        static void Main()
        {
            
            var mylist = new List<int>();

            mylist.Add(1);
            mylist.Add(2);
            mylist.Add(3);

            foreach(int element in mylist)
            {
                Console.WriteLine("{0} Element:{0}", element, element);
               
            }

            Console.ReadLine();

            return;
        }
    }
}


output :

1 Element 1
2 Element 2
3 Element 3

virtual function of base called from derived class

#include<iostream>
#include<conio.h>


using namespace std;

class Area
{
public:
virtual double GetArea(int length, int breadth)
{
return length * breadth;
}
};

class Rectangle : Area
{
public:
double  GetArea(int length, int breadth)
{
return Area::GetArea(length, breadth);
}
};

class Triangle : Area
{

public:
double GetArea(int length, int breadth)
{
return 0.5 * Area::GetArea(length, breadth);
}
};

void main()
{
Rectangle oRectangle;
Triangle oTriangle;

cout<<"\nArea of Rectangle:"<< oRectangle.GetArea(10, 2);
cout << "\nArea of Triangle:"<<oTriangle.GetArea(10, 2);

_getch();

}

Out Put :
Area of Rectangle: 20
Area of Triangle:10

C# source code :

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

namespace Project2
{
    public abstract class Area
    {
        public virtual double GetArea(int nlenght, int nbreadth)
        {
            return nlenght * nbreadth;
        }
    }

    public class Rectangle : Area
    {
        public override double GetArea(int nlength, int nbreadth)
        {
            return base.GetArea(nlength, nbreadth);
        }
    }

    public class Triangle : Area
    {
        public override double GetArea(int nlength, int nbreadth)
        {
            return 0.5 * base.GetArea(nlength, nbreadth);
        }
    }
    public class Class1
    {
     
        static void Main()
        {
            Rectangle oRectangle = new Rectangle();
            Triangle oTriangle = new Triangle();

            Console.WriteLine("Area of Rectangle:{0}",oRectangle.GetArea(10, 2));
            Console.WriteLine("Area of Triangle:{0}",oTriangle.GetArea(10, 2));

            Console.ReadLine();

            return;
        }
    }
}


Out Put :
Area of Rectangle: 20
Area of Triangle:10