In programing we often need to map one object to another. For example, suppose you are working with MVC pattern and you need to map your domain model with view model. This kind of mapping code are time consuming to write and not easy to test. So why not use a tool which take the heavy lifting for us.
Tag Archives: C#
Demo on TDD – new GitHub repository
Today I have published a new repository at GitHub. A demo application on how we should design our application so that we can test it. It is a test driven development approach. Before implementing the actual code write the test case and let that be failed. Then implement the logic to pass the test case. Our development is guided by test cases. This is called test driven approach. Also some programmer call this red-green approach. Red stands for fail at first and green for pass latter on. This approach help our code to be on track and easy to main in future. Because all the layers have to decouple for that. Our actual requirement (test cases) guide our development.
Download data as .CSV format from ASP.NET web application
CSV file is a comma separated file format. That means all the values in the file is comma separated. This is very simple and useful format to exchange data. You can create and read CSV very easily. It is in human readable as well as you can write your program logic to work with this format very easily. You need to place comma after every value in a line and at the time of reading also keep in mind. Many popular software and service also support CSV format. For example Microsoft Outlook, Gmail etc. Keep in mind that it is not hierarchical data rather it is tabular format which we can express in CSV format.
LINQ
Language Integrated Query (LINQ) is a query capability which is integrated in programming languages. The most popular .NET programming languages C# and VB has this capability. LINQ is an abstraction by which we can query heterogeneous data sources with the same syntax. Though LINQ has some small difference depending on the provider. For example not all features supported in LINQ to Entity or LINQ to SQL. Though it is an declarative syntax and easy to learn. LINQ comes in some predefined flavor.
- LINQ to Objects
- LINQ to DataSet
- LINQ to XML
- LINQ to SQL
- LINQ to Entity
Also LINQ is extensible means we can use any third party provider with LINQ. For example we can use any third party provider to query data from facebook using LINQ.
LINQ has the SQL like syntax. The programmer who is familiar with SQL syntax has a easy time with LINQ syntax. No means what type of LINQ you are using the basic syntax and the pattern will same. LINQ can be work on any collection which implements IEnumerable(of T). It has from clause to start the query. There is range variable in which it store the data from the collection. There are other clauses like where to filter result, order by to sort result set, select to return result. The basic syntax of LINQ is follows.
string[] names = new string[] { "rahul", "mita", "bob", "rohit" }; // 'names' is the collection. // 'name' is the range variable. IEnumerable<string> query = from name in names select name; foreach (string item in query) { Console.WriteLine(item); }
Syntax for where clause
IEnumerable<string> query = from name in names where name.StartsWith("r") select name;
Many LINQ query finish with select clause. We can also project the result.
class Student { public string Name { get; set; } public string Subject { get; set; } public byte Age { get; set; } } class Program { public void Main() { IEnumerable<Student> students = new List<Student>() { new Student() { Name = "rahul", Subject = ".NET", Age = 25 }, new Student() { Name = "mita", Subject = "HTML", Age = 22 }, new Student() { Name = "bob", Subject = "C#", Age = 30 }, new Student() { Name = "rohit", Subject = "Java", Age = 27 } }; // Anonymous type. var query = from student in students where student.Age >= 25 select new { student.Name, student.Subject }; foreach (var item in query) { Console.WriteLine(item.Name + " " + item.Subject); } } }
Here we do not want all the properties of Student. We only want the Name and the Subject. So here we create a new anonymous type (a type which creates on the fly, which has no name). Notice the var keyword in the return type. But if we want to use the new type for example for type casting then we have to create a new type for that.
class TempStudent { public string Name { get; set; } public string Subject { get; set; } } class Program { public void Main() { IEnumerable<TempStudent> query = from student in students where student.Age >= 25 select new TempStudent { Name = student.Name, Subject = student.Subject }; foreach (TempStudent item in query) { Console.WriteLine(item.Name + " " + item.Subject); } } }
LINQ use deferred execution. That means the actual result will not retrieve until when the query is executing in for each loop in this case. If we want to perform the actual result retrieval in place (not deferred execution) then we have to use one of the extension method.
IEnumerable<TempStudent> query = (from student in students where student.Age >= 25 select new TempStudent { Name = student.Name, Subject = student.Subject }).ToList(); // Extension method.
We can use join just like we can do in SQL.
class Faculty { public int Id { get; set; } public string Name { get; set; } } class Student { public int Id { get; set; } public string Name { get; set; } public int FacultyId { get; set; } } class Program { static void Main(string[] args) { IEnumerable<Faculty> facs = new List<Faculty>() { new Faculty() { Id = 1, Name = "fac 1" }, new Faculty() { Id = 2, Name = "fac 2" }, new Faculty() { Id = 3, Name = "fac 3" }, new Faculty() { Id = 4, Name = "fac 4" }, }; IEnumerable<Student> stus = new List<Student>() { new Student() { Id = 1, Name = "st 1", FacultyId = 1 }, new Student() { Id = 2, Name = "st 2", FacultyId = 3 }, new Student() { Id = 3, Name = "st 3", FacultyId = 1 }, new Student() { Id = 4, Name = "st 4", FacultyId = 2 }, }; var facQuery = from f in facs join s in stus on f.Id equals s.FacultyId select new { FacName = f.Name, StudentName = s.Name }; foreach (var item in facQuery) { Console.WriteLine(item.FacName + " " + item.StudentName); } } }
We can also do left outer join in LINQ. But this concept is not same with SQL counterpart.
var facQuery = from f in facs join s in stus on f.Id equals s.FacultyId into Students from s in Students.DefaultIfEmpty() // Preserves left-hand elements that have no matches on the right side. select new { FacName = f.Name, StudentName = (s != null) ? s.Name : "(no students)" };
For more information please take a look at 101 LINQ Samples.
Variance and Generic Interface
I wrote about Generics at my previous blog post. It is all about type safety and performance. Generic is a powerful fetcher in C# programming language. Today I am taking about Variance in Generic Interface.
Generic Interface
As we all know about the function of interface in programming language, we can create Generic Interfaces also. The idea is the Interface having one or more type parameter(s) which needs to be replaced by the client code.
// ‘T’ is the type parameter. public interface IList<T> : // Implemented interfaces goes here. { // Members goes here. } // Client code replace type parameter with actual data type. IList<int> empAges = new List<int>(); IList<string> empNames = new List<string>();
Also we can create a custom Generic Interface.
// Generic interface. interface IGen<T> { void Set(T myParam); T Get(); } // Generic class. class Gen<T> : IGen<T> { private T _myData; public void Set(T myParam) { _myData = myParam; } public T Get() { return _myData; } } // Client code. IGen<string> myGen = new Gen<string>(); myGen.Set("my name"); Console.WriteLine(myGen.Get());
Variance
By default C# do not allow variance in Generic.
IGen<object> myGen = new Gen<string>(); // Compilation error.
We know that object is a base class for all the types in .NET Framework. But though we can not compile this line of code.
IGen<object> myGen = (IGen<object>)new Gen<string>(); // Runtime exception.
If we try this it compiles but fails at runtime. C# do this because of type safety. Imagine if C# allow this code then we can set a ‘Circle’ object inside ‘string’.
IGen<object> myGen = (IGen<object>)new Gen<string>(); myGen.Set(new Circle()); // Illogical.
This is unacceptable and illogical.
Covariant Interfaces
Now I am slightly changing my code.
interface IGenWrite<T> { void Set(T myParam); } interface IGenRead<T> { T Get(); } class Gen<T> : IGenWrite<T>, IGenRead<T> { private T _myData; public void Set(T myParam) { _myData = myParam; } public T Get() { return _myData; } }
Now the client code.
Gen<string> gen = new Gen<string>(); IGenWrite<string> write = gen; write.Set("my name"); IGenRead<string> read = gen; Console.WriteLine(read.Get());
We know this is OK. Now if we try the following code then what happened?
Gen<string> gen = new Gen<string>(); IGenRead<object> read = gen; // Compilation error. Console.WriteLine(read.Get());
As usual this is a compilation error. But now in this case if you think logically the previous logic is no longer valid in this case. Because Get() method is readonly. It is just returning the value. It is not doing any manipulation with the value. When this is our case then we can allow variance. Just think if Get() method can return ‘string’ then it should return an ‘object’ also. For that we have to tell our interface to allow variance. We have to give an ‘out’ keyword before the type parameter.
interface IGenRead<out T> { T Get(); }
Now the previous code can be successful.
Gen<string> gen = new Gen<string>(); IGenRead<object> read = gen; // Now OK. Console.WriteLine(read.Get());
This is called Covariance.
Contravariant Interfaces
This is just opposite of Covariance. Look at the following code.
public interface IComparer<in T> { int Compare(T x, T y); }
If we implement this interface in our class.
class ObjectComparer : IComparer<Object> { int IComparer<object>.Compare(Object x, Object y) { int xHash = x.GetHashCode(); int yHash = y.GetHashCode(); if (xHash == yHash) return 0; if (xHash < yHash) return -1; return 1; } }
This interface is for comparison ability in class. In our class when we implement this interface then our class objects can be compare. In the implementation we do not doing any object type specific work. We are using GetHashCode() method to get the hash code of the objects and doing our comparison. GetHashCode() method is in ‘object’ class. So all types can call this method. In this case we can allow variance. Think logically again, if we can compare ‘object’ then we should can compare ‘string’. Because ‘string’ is a special type of ‘object’. That is the basic thing of Inheritance. That is why the ‘IComparer’ interface having an ‘in’ keyword before the type parameter. So the following codes are valid.
// We know it is valid. Object x = ...; Object y = ...; ObjectComparer comparer = new ObjectComparer(); IComparer<Object> objectComparator = comparer; int result = objectComparator.Compare(x, y); // But it is also valid now. IComparer<String> stringComparator = comparer;
Summary
Covariance: If the methods in a generic interface can return strings, they can also
return objects. (All strings are objects.)
Contravariance: If the methods in a generic interface can take object parameters,
they can take string parameters. (If you can perform an operation by using an object,
you can perform the same operation by using a string because all strings are objects.)
Note: We can use only reference types in this procedure. Because value types are not in Inheritance that is why we can not use them in Variance. Also we can use ‘in’ and ‘out’ keywords with ‘Interfaces’ and ‘Delegates’ only.