Development & Training in .NET
For the love of C# .NET
Using BindingNavigator & BindingSource
May 4th
One of the students in our online .NET training program wanted to know about the usage of BindingNavigator and BindingSource controls. We thought it would be useful to write an article demonstrating the usefulness of these controls. We plan to add more such articles to the articles section of our website.
Have any questions? Ask them in our .NET forum.
Incoming search terms:
ASP.NET 4.5 and Visual Studio 11 Developer Preview is here
Jan 3rd
We have plans on bringing Visual Studio 11 and .NET Framework 4.5 as part of our training program. For those eagerly waiting to know about the next big release of Visual Studio 11, take a peek here:
http://msdn.microsoft.com/en-us/vstudio/hh127353
http://www.asp.net/vnext/whats-new
Visual studio shortcuts for the .NET developer
Aug 12th
Almost every student asks me how to remember the namespaces for the classes. It’s plain simple, Visual Studio has a very useful shortcut for finding the namespace of a class. It comes in very handy when you are working on projects and you need to be fast typing code. So here are the steps to use it.
Type the name of the Class, highlight it and press Shift + Alt + F10, phew! you got your namespace.
Use the drop down displayed to do the following:
1. Add the namespace displayed to the usings clause
2. Fully qualify your class
3. Generate a new class
4. Generate a new type
The other shortcut that I find very useful is for declaring properties:
To declare a property just type prop and press TAB TAB. Now type in the datatype and a the name for the property.
There’s also a shortcut to implement interfaces automatically. This would save you tons of time in implementing interfaces.
Declare the class and type the name of the interface. Now, highlight the interface that you’d like to implement and press Shift + Alt + F10. Select the corresponding option in the dropdown – Implement interface (or) Explicitly implement interface
Felix.J, PMP
View Upcoming Dot Net Courses by WAFY
Incoming search terms:
Retrieving Data by Using the EntityClient Provider
Jul 13th
A simple snippet that let’s you know how to retrieve data by using Entity Client Provider. You can refer to the DataModel image in the earlier post.
// Retrieving Data by Using the EntityClient Provider
// Entity Connection, Command and Parameter objects
using (EntityConnection connection =
new EntityConnection("name=EMSEntities"))
{
connection.Open();
// Note that "Order" is the actual table name
const string queryString = @"SELECT VALUE r FROM
EMSEntities.Orders as r WHERE r.OrderID=@OrderID";
EntityCommand cmd = new EntityCommand(queryString,
connection);
EntityParameter p = new EntityParameter() {
ParameterName = "OrderID", Value = 1 };
cmd.Parameters.Add(p);
EntityDataReader reader =
cmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (reader.Read())
{
string orderID = reader.GetInt32(0).ToString();
string orderDate = reader.GetDateTime(1).ToString();
Debug.WriteLine(String.Format("Order ID = {0}, " +
" Order Date = {1}", orderID, orderDate));
}
}
Incoming search terms:
Retrieving Data by using Entity SQL
Jul 13th
A simple snippet that let’s you know how to retrieve data by using Entity SQL. You can refer to the DataModel image in the previous post.
// Retrieving Data by using Entity SQL
// Note that "Orders" used in the query is an Entity
using (EMSEntities context = new EMSEntities())
{
const string queryString = @"SELECT VALUE r from " +
"Orders as r WHERE r.OrderID=@OrderID";
ObjectQuery<Order> orderQuery =
new ObjectQuery<Order>(queryString, context);
orderQuery.Parameters.Add(
new ObjectParameter("OrderID", 1));
List<Order> results = orderQuery.ToList();
string orderID = results[0].OrderID.ToString();
string orderDate = results[0].OrderDate.ToString();
Debug.WriteLine(String.Format("Order ID = {0}, " +
" Order Date = {1}", orderID, orderDate));
EntityCollection<OrderDetail> details =
results[0].OrderDetails;
Debug.WriteLine(String.Format(
"Order Detail Count = {0}", details.Count));
}
Incoming search terms:
Retrieving Data by Using LINQ to Entities
Jul 13th
A simple snippet that let’s you know how to retrieve data by using LINQ to Entities. Just follow it through, I guess it’s self-explanatory.
// Retrieving Data by using LINQ to Entities
using (EMSEntities context = new EMSEntities())
{
ObjectQuery<Order> orders = context.Orders;
IQueryable<Order> query = from c in orders where
c.OrderID == 1 select c;
List<Order> results = query.ToList();
string orderID = results[0].OrderID.ToString();
string orderDate = results[0].OrderDate.ToString();
Debug.WriteLine(String.Format("Order ID = {0}, " +
" Order Date = {1}", orderID, orderDate));
EntityCollection<OrderDetail> details =
results[0].OrderDetails;
Debug.WriteLine(String.Format(
"Order Detail Count = {0}", details.Count));
}
Incoming search terms:
Data Access – Entity Framework – Retrieving Complex Types
Jun 30th
Using the EDM, we created a Complex type for storing/re-using addresses. We also discussed about the advantages of complex types over Entity. Entity requires a key as opposed to complex types, which don't need a key. Given below is a sample snippet on how you can access complex types in an entity.
EMSEntities context = new EMSEntities();
var addresses = from address in context.Addresses
where address.ContactID == 1
select address;
foreach (Address address in addresses)
{
Console.WriteLine("Contact Id: " + address.ContactID);
Console.WriteLine("Contact's address1: " +
address.AddressComplex.Address1);
Console.WriteLine("Contact's address2: " +
address.AddressComplex.Address2);
}
Incoming search terms:
Training on Queue, Stack, HashTable, SortedList and Indexer
Apr 29th
The below is the code that was discussed and created during the training session about using the collections and List available in .NET like Queue, Stack, HashTable and SortedList. In the process, using Indexers were also covered. Students were asked to create a small application using everything learnt. The extract of that code is given below.
private void RunExample()
{
// Queue Example
QueueExample();
// Stack Example
StackExample();
// Hash Table Example
HashTableExample();
// Hash Table Example
SortedListExample();
// Indexer Example
Indexer();
}
private void QueueExample()
{
Queue<Employee> employeeQueue = new Queue<Employee>();
// Load Applicants
for (int i = 1; i <= 10; i++)
{
Employee employee = new Employee() { Name = "Employee No. " + i.ToString() };
employeeQueue.Enqueue(employee);
lstEmployeeQueue.Items.Add(employee.Name);
}
// Select 5 applicants based on their order in the queue
for (int i = 1; i <= 5; i++)
{
Employee queuedEmployee = employeeQueue.Dequeue();
lstEmployeeSelected.Items.Add(queuedEmployee.Name);
}
}
private void StackExample()
{
Stack<Employee> seniorityStack = new Stack<Employee>();
// Load Employees
for (int i = 10; i >= 1; i--)
{
Employee employee = new Employee() { Name = "Employee Exp: " + i.ToString() + " Years."};
seniorityStack.Push(employee);
lstSeniority.Items.Add(employee.Name);
}
// Select 5 junior employees based on their level of seniority
for (int i = 1; i <= 5; i++)
{
Employee juniorEmployee = seniorityStack.Pop();
lstTerminated.Items.Add(juniorEmployee.Name);
}
}
private void HashTableExample()
{
country.Add("US", "United States");
country.Add("UK", "United Kingdom");
country.Add("IN", "India");
country.Add("AU", "Australia");
country.Add("CA", "Canada");
cmbCountry.Items.Add(country["US"].ToString());
cmbCountry.Items.Add(country["UK"].ToString());
cmbCountry.Items.Add(country["IN"].ToString());
cmbCountry.Items.Add(country["AU"].ToString());
cmbCountry.Items.Add(country["CA"].ToString());
}
private void cmbCountry_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (DictionaryEntry de in country)
{
if (de.Value.Equals(cmbCountry.Text))
{
lblCode.Text = de.Key.ToString();
lblCountry.Text = de.Value.ToString();
return;
}
}
}
private void SortedListExample()
{
// Load employees into ArrayList that's unsorted
ArrayList employeeListUnSorted = new ArrayList();
employeeListUnSorted.Add(new Employee() { Name = "Lakshman" });
employeeListUnSorted.Add(new Employee() { Name = "Richard" });
employeeListUnSorted.Add(new Employee() { Name = "Arjun" });
employeeListUnSorted.Add(new Employee() { Name = "John" });
employeeListUnSorted.Add(new Employee() { Name = "Rajesh" });
employeeListUnSorted.Add(new Employee() { Name = "Kareem" });
foreach (Employee employee in employeeListUnSorted)
{
lstUnSorted.Items.Add(employee.Name);
}
// Create Sorted List from UnSorted list
SortedList<string, Employee> employeeListSorted = new SortedList<string, Employee>();
foreach (Employee employee in employeeListUnSorted)
{
employeeListSorted.Add(employee.Name, employee);
}
// Display the employees in SortedList
foreach (string key in employeeListSorted.Keys)
{
lstSorted.Items.Add(key);
}
}
private void Indexer()
{
// The Employee class has an indexer for address defined
Employee employee = new Employee { Name = "Rakesh" };
employee[0] = "Address 1";
employee[1] = "Address 1";
employee[2] = "Address 1";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++)
{
sb.AppendLine(employee[i]);
}
MessageBox.Show(sb.ToString());
}
Incoming search terms:
C# Training on Threading using an example
Mar 17th
Today’s session was about System.Threading. We spoke about the ways in which threading can help develop better applications.
1. Faster code
2. Parallel processing
3. Background processing
4. Priority setting
5. Keep application responding to user inputs, while the thread processes many other functions.
6. Common real-time scenarios in which threads are the most practical solutions.
The above application uses the WorkerThread class to increment the progress bars. The progress bars are incremented to form a sine wave visual. The application when executed will create the illusion of a wave flowing. The full source code is provided to help you understand the concept.
#region Usings
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
#endregion
namespace ThreadApplication
{
class WorkerThread
{
#region Private Variables
private Thread _thread;
public SineForm sineForm { get; set; }
#endregion
#region Properties
public bool IsAlive
{
get
{
return _thread.IsAlive;
}
}
#endregion
#region Constructor
public WorkerThread()
{
_thread = new Thread(Work);
}
#endregion
#region Public Methods
public void Start(object progressBars)
{
_thread.Start(progressBars);
}
public void Stop()
{
_thread.Abort();
}
private void Work(object progressBars)
{
int loopCount = 1;
int max = loopCount;
bool alternate = false;
while (true)
{
// Set defaults
if (loopCount == 1)
{
for (int i = 9; i >= 0; i--)
{
ProgressBar bar = (ProgressBar)((ArrayList)progressBars)[i];
Increment(bar, max);
max++;
}
}
else
{
int prevValue = 0;
for (int i = 9; i >= 0; i--)
{
ProgressBar bar = (ProgressBar)((ArrayList)progressBars)[i];
int prev = bar.Value;
if (i == 9)
{
Increment(bar, max);
}
else
{
Increment(bar, prevValue);
}
prevValue = prev;
}
}
Thread.Sleep(50);
loopCount = (!alternate) ? loopCount + 1 : loopCount - 1;
if ((loopCount < 1) || (loopCount > 10))
{
loopCount = (alternate) ? 1 : 10;
alternate = !alternate;
}
max = loopCount;
}
}
private void Increment(ProgressBar progressBar, int max)
{
Delegate resetDelegate = new EventHandler(Reset);
progressBar.Invoke(resetDelegate);
sineForm.Value = max;
Delegate setDelegate = new EventHandler(sineForm.SetValue);
progressBar.Invoke(setDelegate);
}
#endregion
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
#endregion
namespace WindowsFormsApplication1
{
class WorkerThread
{
#region Private Variables
private Thread _thread;
public SineForm sineForm { get; set; }
#endregion
#region Properties
public bool IsAlive
{
get
{
return _thread.IsAlive;
}
}
#endregion
#region Constructor
public WorkerThread()
{
_thread = new Thread(Work);
}
#endregion
#region Public Methods
public void Start(object progressBars)
{
_thread.Start(progressBars);
}
public void Stop()
{
_thread.Abort();
}
private void Work(object progressBars)
{
int loopCount = 1;
int max = loopCount;
bool alternate = false;
while (true)
{
// Set defaults
if (loopCount == 1)
{
for (int i = 9; i >= 0; i–)
{
ProgressBar bar = (ProgressBar)((ArrayList)progressBars)[i];
Increment(bar, max);
max++;
}
}
else
{
int prevValue = 0;
for (int i = 9; i >= 0; i–)
{
ProgressBar bar = (ProgressBar)((ArrayList)progressBars)[i];
int prev = bar.Value;
if (i == 9)
{
Increment(bar, max);
}
else
{
Increment(bar, prevValue);
}
prevValue = prev;
}
}
Thread.Sleep(50);
loopCount = (!alternate) ? loopCount + 1 : loopCount – 1;
if ((loopCount < 1) || (loopCount > 10))
{
loopCount = (alternate) ? 1 : 10;
alternate = !alternate;
}
max = loopCount;
}
}
private void Increment(ProgressBar progressBar, int max)
{
Delegate resetDelegate = new EventHandler(Reset);
progressBar.Invoke(resetDelegate);
sineForm.Value = max;
Delegate setDelegate = new EventHandler(sineForm.SetValue);
progressBar.Invoke(setDelegate);
}
#endregion
}
}
Incoming search terms:
C# Training on LINQ – Filtering employees in a collection
Mar 17th
We taught the students on how to use LINQ in Visual studio 2010 .NET. It was more hands on and the students tried creating the below example application in C# .NET. They were taught the best practices in creating such applications and were able to create the below application using a professional approach. See for yourself the program screenshot and the code created for the same.

#region Info
// An example of filtering employees in a collection using LINQ
#endregion
#region Usings
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
#endregion
namespace EMS
{
public partial class FilterEmployee : Form
{
#region Private Variables
private List<Employee> _employeeList;
#endregion
#region Constructor
public FilterEmployee()
{
InitializeComponent();
}
#endregion
#region Private Methods
private void FilterEmployee_Load(object sender, EventArgs e)
{
// Set the default value to StartsWith
cmbCondition.SelectedIndex = 0;
// Load default employees list
LoadDefault();
}
private void LoadDefault()
{
// Create employees list
_employeeList = new List<Employee>();
// Load Employees
Employee employee = new Employee() { Name = "Max", DOB = Convert.ToDateTime("12/12/1966") };
_employeeList.Add(employee);
employee = new Employee() { Name = "Muller", DOB = Convert.ToDateTime("1/12/1942") };
_employeeList.Add(employee);
employee = new Employee() { Name = "Roman", DOB = Convert.ToDateTime("12/7/1986") };
_employeeList.Add(employee);
// Assign employees list to data grid
dataGridView.DataSource = _employeeList;
}
private void Filter(string name, DateTime from, DateTime to)
{
// Logic to filter employees
IEnumerable<Employee> result;
switch (cmbCondition.SelectedIndex)
{
case 0:
// Starts with option has been selected
if (txtName.Text.Trim().Length > 0)
{
result = _employeeList.Where<Employee>(employee => employee.Name.StartsWith(txtName.Text));
}
else
{
result = _employeeList.Where<Employee>(employee => (employee.Name.StartsWith(txtName.Text) &&
((employee.DOB >= dtpFrom.Value) && (employee.DOB <= dtpTo.Value))));
}
break;
case 1:
// Contains option has been selected
if (txtName.Text.Trim().Length > 0)
{
result = _employeeList.Where<Employee>(employee => employee.Name.Contains(txtName.Text));
}
else
{
result = _employeeList.Where<Employee>(employee => (employee.Name.Contains(txtName.Text) &&
((employee.DOB >= dtpFrom.Value) && (employee.DOB <= dtpTo.Value))));
}
break;
default:
// Ends with option has been selected
if (txtName.Text.Trim().Length > 0)
{
result = _employeeList.Where<Employee>(employee => employee.Name.EndsWith(txtName.Text));
}
else
{
result = _employeeList.Where<Employee>(employee => (employee.Name.EndsWith(txtName.Text) &&
((employee.DOB >= dtpFrom.Value) && (employee.DOB <= dtpTo.Value))));
}
break;
}
// Do not use the existing collection - create a new collection for the results
List<Employee> searchResults = new List<Employee>();
foreach (Employee employee in result)
{
searchResults.Add(employee);
}
// Assign filtered employees list to data grid
dataGridView.DataSource = searchResults;
}
private void btnSearch_Click(object sender, EventArgs e)
{
// Filter existing employees
Filter(txtName.Text, dtpFrom.Value, dtpTo.Value);
}
private void btnDefault_Click(object sender, EventArgs e)
{
// Load default values
LoadDefault();
}
#endregion
}
}


