-->

Friday, December 25, 2015

Solve Application not responding problem

In this article, I will show you how to fix computer hanging problems. Generally, we all know about "Not Responding" problem. When processor takes time to execute the process then thats type of problem occurs. By using this article, I will resolve this issue.




Windows Form Design:

Solve Application not responding problem
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        private readonly SynchronizationContext synchronizationContext;
        private DateTime previousTime = DateTime.Now;
        public Form1()
        {
            InitializeComponent();
            synchronizationContext = SynchronizationContext.Current;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (var i = 0; i <= 1000000; i++)
            {
                label1.Text = @"Count : " + i;
            }
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            button2.Enabled = false;
            var count = 0;

            await Task.Run(() =>
            {
                for (var i = 0; i <= 1000000; i++)
                {
                    UpdateUI(i);
                    count = i;
                }
            });
            label1.Text = @"Count : " + count;
            button1.Enabled = true;
            button1.Enabled = false;
        }
        public void UpdateUI(int value)
        {
            var timeNow = DateTime.Now;

            //Here we only refresh our UI each 50 ms
            if ((DateTime.Now - previousTime).Milliseconds <= 50) return;

            //Send the update to our UI thread
            synchronizationContext.Post(new SendOrPostCallback(o =>
            {
                label1.Text = @"Count : " + (int)o;
            }), value);

            previousTime = timeNow;
        }
    }
}

Wednesday, January 8, 2014

How to Create and Use of Iterators, yield: CSharp Programming

Programmer often use some type of iterators that are used to iterate steps in the programming language. An iterator often use yield keyword to return individual element, this is possible only if it have the current location in the cache.

C# Programming uses these iterators to execute some steps continuously like returning a value continuously from a method. Following program is creating an iterator in c# language.

public Form()
{
InitializeComponent();
foreach (int number in SomeNumbers())
{
string str = number.ToString() + " ";
}
}
public static System.Collections.IEnumerable SomeNumbers()
{
yield return 1;
yield return 2;
yield return 3;
}

Yield keyword keeps the current position of the currently executing statement, so that the iteration can be performed.

Here Foreach keyword is used for looping statements in c# programming language, but it is also used as iterators. Each time when the SomeNumbers() method is called in this loop, the yield keyword will return the specified number and will back to the current position.

That is why the resulting string in str variable will be "1 2 3". There may be many ways to creating iterators like:

Using Collection Class: As the well-known class collection is used to automatically called GetEnumerator method which returns IEnumerable type of data. The same process can be easily implemented using this collection class.

Using Generic List: As GetEnumerator method returns an array of specified elements. Generic method is inherited from IEnumerable interface. Using this method iterators can easily be implemented as in above program.

Tuesday, December 24, 2013

How to Delete Multiple Records from DataGridView in Winforms: C#

To remove multiple records from the DataGridView, programmer need to write some line of code, code may be written in a button's click event that is outside of the DataGridView. The article shows about how to select multiple records of DataGridView and the c# code to remove them with a single mouse click.

When a programmer have to remove a single record entry from the DataGridView, then a command button can be added as discussed. Removing a single record can be performed by the index of the record. Through the index programmer can easily get all the unique values about the record which helps to perform the action.


To remove multiple records, follow the steps written below:
  • Drag-n-Drop DataGridView on the form and set its MultiSelect property to True.
  • Create a list of records (Student Class) and bind this DataGridView with that list.
  • Create a button outside of this DataGridView and generate its click event.
  • Write following C# code in the click event of button to remove multiple records:
private void removeButton_Click(object sender, EventArgs e)
{
DataContext dc = new DataContext();
foreach (var item in dataGridView1.Rows)
{
DataGridViewRow dr = item as DataGridViewRow;
if (dr.Selected)
{
string name = dr.Cells["Name"].Value.ToString();
var student = dc.Student.FirstOrDefault(a => a.Name.Equals(name));
if (student != null)
{
dc.Student.Remove(student);
}
}              
}
dataGridView1.DataSource = null;
dataGridView1.DataSource = dc.Student;
}
  • Run the form and select some of the records as in the image:
How to Delete Multiple Records from DataGridView in Winforms: C#

  • Click on the remove button and all these selected records will be deleted. A single record remain safe shown in the image:
How to Delete Multiple Records from DataGridView in Winforms: C#


So all these simple steps are used to delete multiple as well as single record from the DataGridView. Programmer can also use a confirmation message for the surety of the deletion by the user. To do that, just place all the above code in between the below c# code:

if (MessageBox.Show("Are you sure you want to remove all these records?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString() == "Yes")
{
//above code
}

When the programmer will click on the button then a confirmation message will be shown. After clicking on the "Yes" button, all the selected records will be deleted otherwise none of them.

Monday, December 16, 2013

Computer Programming : Nullable types, Null coalescing operator in c# Programming

In Computer Programming, C# Data types are divided into two broad categories such as Value types and Reference type. In Value types, some inbuilt types such as int, float, double, structs, enum etc. These all are non-nullable types, it means these types don't hold null value. In other hand Reference types such as string, Interface, Class, delegates, arrays etc. can hold null value.
By default value types are non nullable. To make them nullable use, programmer have to use ?
  • int a=0   a is non nullable, so a cannot be set to null, a=null will generate compiler error
  • int ?b=0  b is nullable int, so b=null is legal

Operator Need

If programmer want to assign null value to non-nullable data types then there are some operators explained with an example. 

Lets take an simple example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a;
            int? b = 100;
            a = b ?? 0;
            System.Console.WriteLine(a);
            Console.ReadKey();
        }
    }
}
Computer Programming : Nullable types, Null coalescing operator in c# Programming

Output show that if b hold some value like 100 then Null coalescing operator assign value to variable (a). If b hold null value then Null coalescing operator assign default value, which is zero to variable a. 

Replace the declaration of variable b with the following line:
            int? b = Null;
This will outputs zero (default value).

Friday, December 13, 2013

Computer Programming: Operators in c# console application

Introduction

It is a symbol, which is performed operation on operands, operation can be mathematical or logical. In c#, operators are categories in three basic parts first one is unary operator and second one is binary operator and last one is ternary operator. In unary operator we use single operand like.
++a // here a is a "operand"
In Binary operator we use two operand. Like
a+b;
In ternary operator we use three operand like
a>b?a:b

Assignment Operator (=)

if we create a variable of type integer also we want to initialize it with some value then we should use assignment operator like.

int a=10;

Here, variable a is initialized with value 10. It means you can say the right hand side value is copy to left hand side variable using assignment operator.

Arithmetic Operators ( +,-,*,/,%)

Basically arithmetic operators are used for doing mathematical calculation like addition of two or more numbers , multiplication, division, subtraction, and remainder. lets take a simple example to understand arithmetic operators. If the total collection by five students is five thousand then find the average value?.
int collected_money=5000;
int total_student =5;
int avg=collected_money/total_student;


Ternary operator (?, : )

In ternary operator we have three operands, in which first operand is used for check the condition and other two operands is used for giving results. Let’s take a simple example to understand the ternary operator.

Int firstnumber=10;
Bool result;
Result = firstnumber>10? True: false;

In the preceding example, if condition becomes true or you can say if firstnumber is greater than to 10 then ternary operator gives  ‘true’ in results otherwise gives ‘false’.
 

Comparison Operators (< , > ,<=,>=,!=,==)

using comparison operator you can perform Boolean operation between operands known as comparison operator. Lets take an simple to understand comparison operator
 
 class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            if (a==10)
            {
                Console.WriteLine(string.Format("The value of variable ={0}", a));
  
            }
            Console .ReadKey (false);
        }
    }
 
Computer Programming : Operators in c# console application Here, condition if check equality operation between operands, a and constant value 10. If condition becomes true, output comes "The value of variable=10".


 

  

  Logical operator (&&,|| )

Perform logical operation between Boolean operands known as logical operator. Lets take a simple example
 
  class Program
    {
        static void Main(string[] args)
        {
            bool a = true;
            bool b = true;
            if (a&&b)
            {
                Console.WriteLine("condition becomes true");
  
            }
            Console .ReadKey (false);
        }
    }
 

Saturday, June 1, 2013

Change textbox value according to Combo Box in c# programming: WinForms

In our previous post we have learnt perform binding Combo Box and Listbox, now it’s time to get access their values and use them to bind another controls in winforms. I am binding a combo box with an employee list and them access data in textbox in c# programming.


For example we have a c# class Employee having following properties:

public class Employee
{
        public int No { get; set; }
        public string Name { get; set; }
}

Create an object of type List of employee (in our Form1.cs file) that will be used to in binding of combo Box

List<Employee> empList = new List<Employee>();

To bind with combo Box this list should have some set of items, so we will add some employees with use of following code in our Form1's constructor:

empList.Add(new Employee() { No = 111, Name = "Venkatesh" });
empList.Add(new Employee() { No = 222, Name = "Muthu Kumaran" });
empList.Add(new Employee() { No = 333, Name = "Murli Prasad" });
empList.Add(new Employee() { No = 444, Name = "Ghosh Babu" });
empList.Add(new Employee() { No = 555, Name = "Jacob Martin" });

Now using following two lines of code we will bind our comboBox with this above list of item

comboBox1.DataSource = empList;
comboBox1.DisplayMember = "No";

When Form1 will run, combo Box will have above list of items and textbox will be empty. To display related value of employee name we have to write these two lines of code with combo Box binding:

Employee selectedEmployee = comboBox1.SelectedItem as Employee;
textBox1.Text = selectedEmployee.Name;

Now our article’s main aim is to binding a textbox with combo Box selected value, so there is an Event of combo Box i.e. comboBox_SelectionChanged event. So I will repeat the most recent two lines of code in this event as written below:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
     Employee selectedEmployee = comboBox1.SelectedItem as Employee;
     textBox1.Text = selectedEmployee.Name;
}

Check your windows form application, when you change the selected item of combo Box it will also change the related name of Employee in textbox’s text property.

Download Example

How to Perform Binding with DataGridView in WinForms

The DataGridView control provides a powerful and easiest way to display our data in tabular format with entity framework 5. We can use DataGridView as we want to, like we can use it to simply show our read-only data or we can use it with editable views of our data, in c# programming. Access data from the database and perform binding steps to show them in datagridview.

To do binding on DataGridView with our data is straight-forward and in many cases it is as simple as setting the DataSource property of DataGridView. As DataGridView supports standard binding model, so it will bind to some instances of c# classes like DataSet, DataTable, BindingList and BindingSource etc.

The first way to bind our datagridview to table of database is:

studentDataGridView.DataSource = "DataSet Name";
studentDataGridView.DataMember = "Table Name";


Let’s suppose we have a c# class Student having some properties like following:

public class Student
{
       public int Id { get; set; }
       public string Name { get; set; }
       public string RollNo { get; set; }
       public string Branch { get; set; }
}

Now we will bind datagridview to list of students as:

DataContext dc = new DataContext();
var studentList = dc.Student;
studentDataGridView.DataSource = studentList.ToList();

Here ToList() method is used to convert our DbSet<Student> type of data to List<Student> type of data, because DbSet<> type of data cant be directly bind with any control.
Now if we want to bind only Name and Branch column of Student class then:

DataContext dc = new DataContext();
var studentList = from d in dc.Student
select new
{
d.Name,
d.Branch
};
studentDataGridView.DataSource = studentList.ToList();

We can bind our desired columns to datagridview as we have done in above code. DataGridView doesn’t have any mean where is data come from, so we can use conditions in our queries also.

See Also: DataGridView binding with DataSet

Monday, May 27, 2013

Combo Box or List Box Binding with Database, Entity Framework 5

Most often when we have a list of items and want to select a single item at a time then we can use Combo Box or List Box in winforms application. The basic difference in both is: In List Box one can select an item only from existing list of items whether in Combo Box one can write his/her own new data that can be added to our binding list.

There are some properties that are used to bind a list of items in c# programming i.e

  • Data Source
  • Display Member
  • Value Member
DataSource property will decide the list of data that is to be bind. It may be a Database, Web Service and an object. When this property is set, the item collection cannot be modified at run time.

DisplayMember property indicates the name of an object contained in DataSource property. It denotes what object will be displayed to the user. The default value is empty string.

ValueMember property is used to get the value associated with the control when we are accessing the selected item property.

Let's suppose we have an employee class with properties as shown below c# class:

public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }

Now following code is used to get all records of employee from Database into a var type of variable named employees as given below:

DataContext dc = new DataContext();
var employees = from emp in dc.Employees
                          select emp;

In the above code employees variable have IEnumerable<Employee> type of data and this type of data cannot directly bind to data source property of a control in our programming language. So we have to convert it to a List<Employee>.
To convert this simple type of data a ToList() method is sufficient.

In case of Combo Box

ComboBox1.DataSource = employees.ToList();
ComboBox1.DisplayMember = "Name";
ComboBox1.ValueMember = "Id";

In case of List Box

ListBox1.DataSource = employees.ToList();
ListBox1.DisplayMember = "Name";
ListBox1.ValueMember = "Id";

Here ToList() method is used to convert IEnumerable<Employee> type of data to List<Employee>.
Now when we run our project we will see the list of employees Names in the item collection of Combo Box or ListBox.

How to Perform LINQ in C# Programming to Get Records using Entity Framework 5

LINQ stands for Language INtegrated Queries in the context of sql programming. These are like SQL queries used to manipulate collection of objects through entity framework. LINQ are queries that can be directly written in c# programming language and will be translated to SQL statements and executed against the database. It simplify the complex process of database developer to query in databases.

These type of queries are executed on collection of IEnumerable<T> or IQueryable<T> and as results are returned new collection of IEnumerable<T> objects. In this post I will explain some example that show how to use LINQ on collection of objects in c# programming.

Let’s suppose we have a c# class Student having two properties i.e. Name and Age and of course a primary key Id. Now to get all records of students from database we have to write:

var students = from student in dc.Student
               select student;

In above code it will extract all columns from Student table like Id, Name and Age also. If we want only name and Age column then:

var students = from student in dc.Student
               select new
               {
                   student.Name,
                   student.Age
               };

It will show only Name and Age columns of all the records.

It’s very simple to get some records having where condition like in sql programming. In below code if we want to get all records having age = "25" then the following code should be written:

var students = from student in dc.Student
                     where student.Age == 25
                     select student;

Now at the last if you want to get records having age = "25" and name = "Rahul" then following line of code has to be written:


var students = from student in dc.Student
               where student.Age == 25 && student.Name == "Rahul"
               select student;

So according to above examples, LINQ is very simple language to be queried with databases. Here dc is used for data context that is created through entity framework 5.

Sunday, May 26, 2013

How to Update and Delete record from database using EntityFramework in c# programming

Sometimes database developer have to change some of the properties of table, due to insertion mistakes. As we have inserted records into Database using entity framework 5, it's time to modify that record and delete that if required through c# programming language.

We (database developer) all know that update and delete query required a condition through which they retrieve an instance on which action is to be performed.

Update: The update operation is quite simple in entity framework 5. First retrieve an instance of specified Entity object, then edit the properties of that instance and finally save the changes to that context and done. It have a little bit complex syntax in sql programming.



Let’s suppose we have an entry of student named “Student 1” and we want to change his/her name and age then:

DataContext dc = new DataContext();
Student student = dc.Student.First(s = > s.Name.Equals("Student 1"));
student.Name = "Student 2";
student.Age = 25;

dc.SaveChanges();

Execute the code and check the database, you have successfully made changes through the above c# programming code.

Delete: The delete operation is little bit different from Update operation. First retrieve an instance of specified Entity object, then delete that instance from context and finally save changes to context and done.

Let’s suppose we have an entry of student named “Student 2” and we want to delete then:

DataContext dc = new DataContext();
Student student = dc.Student.First(s = > s.Name.Equals("Student 1"));
dc.Student.Remove(student);

dc.SaveChanges();

Execute the above code of c# programming and check the database, there is no student named "Student 2".

Note: "When we are retrieving an instance of Student class and if that student has not been found then there may be an Exception. So better be use 'try catch' block".

Insert Entities into database Table using Entity Framework 5: C# programming

After creating databases with foreign key constraints in entity framework 5, its time to insert some records and save them for further references. In this article i will cover up, how to add entities and how entity framework processes these during saveChanges method. A database developer often use this method to insert records.


As i have added Student table which is a c# class in our solution, i will insert a record in the same table directly through code. I am using the same Winforms Application that we have used in previous article so make sure you have studied Creating databases in entity framework 5.

Note: "You must create an object of DataContext class in Form1's Constructor in order to insert some data in Student class."

To insert a record in database we will use the method i.e. EntityCollection<TEntity>.Add(). Lookout the c# programming code given below:

DataContext dc = new DataContext();
Student newStudent = new Student();
newStudent.Name = "Student 1";
newStudent.Age = 24;

dc.Student.Add(newStudent);
dc.SaveChanges();

All we are doing here is create a new instance of Student class and populate its properties. Then add that instance to Students set using EntityCollection<TEntity>.Add() method.

In above code Add() method is used to add newly created instance in database, and SaveChanges() method is used to save all the changes you have done with database.

Finally, go to your database and check, you will find the above instance there in Students table.

Download Source Code.

Update n Delete Entities in Entity Framework 5

Saturday, May 25, 2013

Create Foreign key in database using Entity Framework 5 in C# Programming

In the context of relational database management system (RDBMS), foreign key is a field in one table that uniquely identifies a row of another table. In sql programming, foreign key is a column which points to the primary key of another table.

An entity can be related referenced with other entities through this foreign key, in entity framework. This can be done through an association between the tables. As we have studied in our Previous Post how to create databases and tables in it. In this article i will create a foreign key in the table.

Steps of creating foreign key in entity framework 5.

Here above i have mentioned the version of entity framework, because it is the stable version currently. Follow these steps and it will add a reference of student in address class.
  • In our Previous post we have created a table Student. We will use this table here. 
  • In that same project add a new class Address and create some properties (fields in context of databases).
  • In the Address class create a property type of Student having keyword virtual as written here:
    public virtual Student Student { get; set; }
  • Now repeat the same procedure of creating an object of DataContext class in Form1's Constructor.
  • And Finally we have successfully created a foreign key in Address table by running Form1.

Thursday, May 23, 2013

Create Databases using EntityFramework 5 in C# programming

Entity Framework is an open source object-relational (ORM) framework for ADO.NET. It allows user to create a model by writing code in EF designer. The releases are improving from entity framework 3.5 and onwards. Entity Framework 5 is the stable version for visual studio 2010 and 2012 and updated soon with the latest features.

The main advantages of using Entity Framework 5 are:
  • Speed - You do not have to worry about creating a DB you just start coding. Good for developers coming from a programming background without much DBA experience.
  • Simple - you do not have a edmx model to update or maintain.
Entity framework 5 released with some advanced features like enum support, table-valued functions and performance improvements. In this article we will create a database using entity framework 5 code first approach.

Steps of Creating Database through Entity Framework
  • Create a Project ClassLibrary in Visual Studio.
  • Install EntityFramework from Package Manager Console (required internet connection) using
    • PM> install-package entityframework 
  • Remove InBuilt Class i.e "Class1".
  • Add a new class “Student”.
  • Add another class DataContext (Name may be change) inherited by DbContext
    • DbContext is in System.Data.Entity Namespace.
  • Write the below code in DataContext class 
j
public DataContext()
          :base("Database Name")
{
    if(!Database.Exists("Database Name"))
        Database.SetInitializer(new DropCreateDatabaseAlways<DataContext>());
}
public DbSet<Student> Student { get; set; }

  •  Add a new project2 (Window Form Application) that will be used to execute constructor of DataContext class.
  • Install Entity Framework 5 in this new project also.
  • Create an object of DataContext class in Form1 Constructor.
  • Now run project2 and your Database has been created.
When we will execute the given command to install entity framework, it will execute the stable version i.e. entity framework 5.

Download code file

Insert foreign key in database
© Copyright 2013 Computer Programming | All Right Reserved