Category Archives: C#

C# Programming

C#: How to Join Two List Using Lambdas Expression

Joining two Lists using Lambdas expression is very simple, lets say we have a inventory of computer products and we have a bunch of purchase orders to process.

So what I am going to do to demonstrate this is to create a class called Product that will have a string property for storing the product’s name and a decimal property for storing the unit price and a property for the product’s id.

	
public class Product
{
	public int Id {
		get;
		set;
	}
	public string Name {
		get;
		set;
	}
	public decimal UnitPrice {
		get;
		set;
	}
}

Then I create a class called Order that will have a property for the order number as a string, product id as an integer and quantity as a decimal.

public class Order
{
	public int ProductId {
		get;
		set;
	}
	public string Number {
		get;
		set;
	}
	public int Quantity {
		get;
		set;
	}
}

So now I have my classes created I will create a List of products and orders with values. For the Join to work, both lists must have a common reference, and that reference is the Product’s Id.

List<Product> products = new List<Product> {
	new Product { Id = 1, Name = "1TB SSD Drive", UnitPrice = 99 },
	new Product { Id = 2, Name = "Keyboard", UnitPrice = 39.95M },
	new Product { Id = 3, Name = "24 inch Monitor", UnitPrice = 124.99M }
};

As you can see below each order has a referece to a Product Id and a product can 0 to many orders.

List<Order> orders = new List<Order> {
	new Order { Number = "A100", ProductId = 2,  Quantity = 100 },
	new Order { Number = "QZ123", ProductId = 1, Quantity = 10 },
	new Order { Number = "1234", ProductId = 2, Quantity = 55 }
};

To join these two list you would use the Lambdas Join expression. Below I query the orders list and join it with the products list by the order’s ProductId and the product’s Id. Then I return each result with a custom object with all the values in it.

var results = orders.Join (products, o => o.ProductId, p => p.Id, ((o, p) => new { 
	ProductName = p.Name,
	UnitPrice = p.UnitPrice,
	Number = o.Number,
	Quantity = o.Quantity,
	TotalCost = p.UnitPrice * o.Quantity
})); 

To see the finishing result I write a foreach on the results and output the values to the console.

foreach (var order in results) {
	Console.WriteLine ("Order No: {0}, Product: {1}, Qty: {2}, Unit Price: {3}, Total Cost: {4}", order.Number, order.ProductName, order.Quantity, order.UnitPrice, order.TotalCost);
}

Mono: Entity Framework – System.Data.Entity.Core.ProviderIncompatibleException was thrown

Recently I have been playing with Entity Framework on Linux using Mono and my database server is MS SQL 2014. When I attempt to add an entity I receive the “System.Data.Entity.Core.ProviderIncompatibleException was thrown” exception and the following message was displayed:

An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application’s config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure.

So I did some further investigation online and found the following post on how to work around it:

https://entityframework.codeplex.com/discussions/538142

Continue reading

Mono: Entity Framework – Basic Setup Guide

So you have been using Entity Framework on Visual Studio and now you would like to code in Linux using Mono and still be able to use Entity Framework. Well this post will give you some basic steps to setup your SQL server and Mono project to get a simple database going.

Setting SQL Express

Before we can go any further we need to have Microsoft SQL Server Express installed  on a Windows server. For my own setup I already have a virtual machine with Windows Server 2012 running and SQL Server Express 2014 installed. It’s up to you to choose own setup, and it doesn’t have to be the same as mine.

Create Your SimpleDatabase

Now we need to create our test database on SQL Server by running the following SQL statement on your script editor of choice:

CREATE DATABASE SimpleDatabase

 

Screenshot from 2014-06-17 21:19:27

Now you should have a brand spanking new database created and ready to be populated with data. Continue reading

How To: Serialize and Deserialize JSON with .NET Framework

Serializing an Object to JSON

To serialize an object to JSON you will need  to create a data contract, which is a class containing all the properties marked with attributes. To demonstrate this I will create a Person class and apply a DataContractAttribute and DataMemberAttribute.

[DataContract]
internal class Person
{
	[DataMember]
	internal string name;

	[DataMember]
	internal int age;
}

Now we need to write some code to populate the Person class with some data and then use DataContractJsonSerializer to serialize the object to Json and just for you information DataContractJsonSerializer has been available since .NET Framework 3.5. Continue reading

How to Convert JSON to a Class in C#

I have been working on .Net projects where I need to work with JSON to a class in C#. I came across a web site created by Jonathan Keith using the popular JSON.Net library by James Newton-King.

The web site allows me to copy and paste JSON code to a form and by pressing the generate button I was able to get back a class that I can copy and use in my .Net project. This web site is very useful to me since I am also using the JSON.Net library in my current project to Deserialise JSON data in to an object.

http://json2csharp.com

json2csharp_web

C#: Joining an Array of Elements Into One Single String

If you need to convert an array to singe delimited string it is easy to do. Below is an example C# code to demonstrate how to join an array of integer values into a single delimited string:

using System;

namespace JoinArrayElements
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			int[] numbers = new int[] { 1,2,3,4 };

			foreach (int num in numbers)
			{
				Console.WriteLine(num);
			}

			var strJoined = string.Join(",", Array.ConvertAll(numbers, Convert.ToString));

			Console.WriteLine ("Joined Integer Array as a Single String: {0}", strJoined);
		}
	}
}

I am using the string.Join() to join my array, the first parameter would be the delimiter character for this example I am using the comma “,”. Then the second parameter is the array that contains all the elements, but this parameter only takes an array of string. Okay we can fix this by converting the array of integers to an array of strings, by using the Array.ConvertAll() method and passing the array values to be converted and set the data type to convert to. Continue reading

C#: Interface

What is an interface?

Interface is a similar to a class it can contain properties, methods, events and indexers. Each member in an interface must have the public access modifier, and other access modifiers will not work with an interface. Interface do not contain any implementations, the only way to use an interface is by creating a subclass that implements the interface members.

public interface IDisplayMessage {
   public void Show();
}

How do you use an interface?

To use an interface you must create a subclass that inherits the interface and implement it’s members. For example below I have created a subclass called MyClass the implements the IDisplayMessage interface and it’s members. Inside the Show() method I write my own piece of code to output a text message to the console:

public class MyClass : IDisplayMessage {
   private string message;
   public MyClass() {
      message = "Hello, World!";
   }
   public void Show() {
      Console.WriteLine(message);
   }
}
void Main() {
   MyClass myClass = new MyClass();
   myClass.Show();
}

You can implicitly cast an object to any interface that it implements. For example below I am casting myClass to IDisplayMessage and still will be able to call the Show() method.

   IDisplayMessage displayMessage = new MyClass();
   displayMessage.Show();

Summary

Interface is similar to a class, it contains public properties and methods with no implementation. Subclass my using an interface must implement all the members and object can be implicitly cast to an interface that it implements.

 

 

C#: Abstract Class

If you are like me and you don’t like to repeat code in your project, I am going to talk about reusing code by creating an abstract class using c#.

What is an abstract class?

Abstract class is a class that must be declared with the keyword abstract and it can not be instantiated and must be inherited by another class. The abstract class can have abstract methods, abstract properties and virtual methods.

public abstract class MyAbstractClass {
   public abstract string MyProperty { get; set; }
   public abstract void MyAbstractMethod();
   public void MyMethod() {
     Console.WriteLine("Hello World!");
   }
   public virtual void MyVirtualMethod() {
     Console.WriteLine("This method can be overridden.");
   }
}

Why do we use abstract class?

We can use abstract class to implement a common method which will contain reusable code, which then the class can be inherited. For example you I can create a simple abstract class with a method that implements code to print a message  to a console and protected variable to hold a string message:

public abstract class DisplayMessage {
   protected string message;
   public void Show() {
     Console.WriteLine(message);
   } 
}

Now I will create a two classes that inherits my abstract class and define a two different text message inside their constructors:

public class MyClass1 : DisplayMessage {
   public MyClass1() {
     message = "This is my class 1";
   }
}

public class MyClass2 : DisplayMessage {
   public MyClass2() {
     message = "This is my class 2";
   }

Now in the main method I am going to instantiate the two classes and call the Show() method to display each of the message on the console.

void Main() {
   MyClass1 myClass1 = new MyClass1();
   myClass1.Show();

   MyClass2 myClass2 = new MyClass2();
   myClass2.Show();
}

What is a Virtual Method?

A virtual method can contain implementation and must be declared with the keyword virtual. You can override a virtual method from the inherited class to implement code that is completely different from the one in the abstract class. To demonstrate this I will use the DisplayMessage abstract class and modify the Show() to a virtual method:

public abstract class DisplayMessage {
   protected string message;
   public virtual void Show() {
     Console.WriteLine(message);
   } 
}

Now I will create two classes that inherits the DisplayMessage class, but one of the class will override the Show() method to display the text message four times:

public class MyClass1 : DisplayMessage {
   public MyClass1() {
     message = "This is my class 1";
   }
}

public class MyClass2 : DisplayMessage {
   public MyClass2() {
     message = "This is my class 2";
   }
   public override void Show() {
      for(int idx = 0; idx < 5; idx++)
      {
         Console.WriteLine(message);
      }
   }
}

Summary

Abstract class are very useful for implementing reusable code that uses a common method that will be inherited by other classes. Abstract methods and properties has no implementations but can be overridden by the inherited class. Virtual methods can have implementation and can be overridden by the inherited class. 

Remember not duplicate code in your project, reuse code by implementing appropriate design patterns.

 

 

C#: Send an email using Google’s SMTP server.

I want to demonstrate how to write a simple console application that will use Google’s SMTP server to send an email. SMTP stands for Simple Mail Transfer Protocol which is the standard for delivering electronic mails over the Internet.

Before continuing you will need to have an email account with Google first, and if you dont please do it first. (Signup for GMail Account)

Startup Visual Studio and File->New->Project and select Visual C# Console Application Template, enter GoogleSmtpApp as the project name and continue.

In our code I am going to use the System.Net.Mail.SmtpClient class to send an email to a recipient. So in your Main method in your program.cs file create a new instant of the SmtpClient() class, to use this class you also need to enter smtp.gmail.com and port 587 in the class constructor.

var smtpClient = new SmtpClient("smtp.gmail.com", 587);

Before we can send an email there is four properties that needs to be set. UseDefaultCredentials must be set to false this will prevent default credentials sent as part of the request. DeliveryMethod must be set to Network so that the message will be sent through the network to the smtp server. Credentials must contain your Gmail username and password so that it can authenticate when connecting to the smtp server. EableSsl must be set to true so that our connection can be encrypted.

var smptClient = new SmtpClient("smtp.gmail.com", 587)
{
     UseDefaultCredentials = false,
     DeliveryMethod = SmtpDeliveryMethod.Network,
     Credentials = new NetworkCredential("username@gmail.com", "password"),
     EnableSsl = true
};

Finally from the SmtpClient class we can call the method Send(). The Send method has two overloaded method but I will be using the one where I will provided the from, recipient, subject and body as strings. Make sure you replace the appropriate parameters with your own values.

smptClient.Send("from@email.com", "recipient@email.com", "subject", "body");

If you press F5 now to run your console application and wait and check your inbox to see if you have received an email! Anyways I hope this simple demonstration can show you how easily we can use Google’s smtp server to send a basic text email.

You can get the latest source code for this project from my GitHub account here:

GitHub: Google-Smtp-App

How to access a common property from multiple form controls.

Recently I had someone posting a question about how to access the Text properties of a different control. I thought of using reflection, because you don’t need to know the type of control you are handling and you don’t need to type cast the object.

If you are handling one specific control, there is no point using reflection, I would suggest just type cast it.

Below is a code snippet from an example I have written to demonstrate how to share one event method with multiple controls on a form. In the method it will get the string value from the Text property of the selected control.

Source Code: ReflectionExample1.zip

<span style="color: blue">using </span>System;
<span style="color: blue">using </span>System.Collections.Generic;
<span style="color: blue">using </span>System.ComponentModel;
<span style="color: blue">using </span>System.Data;
<span style="color: blue">using </span>System.Drawing;
<span style="color: blue">using </span>System.Linq;
<span style="color: blue">using </span>System.Text;
<span style="color: blue">using </span>System.Windows.Forms;
<span style="color: blue">using </span>System.Reflection;

<span style="color: blue">namespace </span>ReflectionExample1
{
    <span style="color: blue">public partial class </span><span style="color: #2b91af">Form1 </span>: <span style="color: #2b91af">Form
    </span>{
        <span style="color: blue">public </span>Form1()
        {
            InitializeComponent();
        }

        <span style="color: blue">private void </span>DisplayText(<span style="color: blue">object </span>sender, <span style="color: #2b91af">MouseEventArgs </span>e)
        {
            <span style="color: #2b91af">Type </span>type = sender.GetType();
            <span style="color: #2b91af">PropertyInfo </span>pInfo = type.GetProperty(<span style="color: #a31515">"Text"</span>);
            <span style="color: #2b91af">String </span>value = pInfo.GetValue(sender, <span style="color: blue">null</span>).ToString();
            <span style="color: #2b91af">MessageBox</span>.Show(value);
        }
    }
}