Simply LINQ: What,Why and How.
Dec24

Simply LINQ: What,Why and How.

Welcome to CodeSpread! What is LINQ? LINQ is Language-Integrated Query (LINQ). It is primarily an extension to the language’s capability where it adds query expressions which processes objects and data. It is a one stop solution to all the query processing as now there is no need to learn a different query language for each type of data source: SQL databases, XML documents etc. Why LINQ? Type safe. IntelliSense support. Tables are available as classes. SQL generated is well structured and optimized. Targets Business rules. Easy to debug with the visual studio’s debugger. Easy to deploy as being a part of DLL. LINQ to SQL parameterizes input so better security. And,best of all, SIMPLE. An example: var Employee= from emp in Employees where emp.name="CodeSpread" select emp; Let’s see the flow, First the ‘from’ clause points to the data source which is ‘Employees’. Next, ‘where’ specifies the filter which is the employee name. Lastly, ‘select’ statement returns the result set. There are three main components of LINQ. Standard Query Operators Language Extensions LINQ Providers Standard Query Operators: The standard query operators can be simply referred to as methods in LINQ .There are two sets of LINQ standard query operators, Operates on objects of type IEnumerable and, Operates on objects of type IQueryable. var result= from emp in Employees orderby emp.empid select emp.name; But it doesn’t look like method, let’s write it again. var result= Employees. Select(emp=>emp.name).OrderBy(emp=> emp.empid); Looks good now. Both of the above examples just vary in syantax. There are many other Standard Query Operators available which we will enlist in a future article. Language Extensions: Implicitly Typed Variables. Anonymous Types. Object Initializers. Lambda Expressions LINQ Providers: These are data source-specific implementations for ex: in-memory object collections, Microsoft SQL Server databases, ADO.NET datasets and XML documents. LINQ to Objects – Executes a LINQ query against a collection of objects For an in-memory object collections like arraylist of employees, var result= from emp  in empList where emp.name="CodeSpread" select emp; LINQ to XML – Executes an XPATH query against XML documents. XElement root= XElement.Load("\..\Employees.xml"); IEnumerable employee= root.Elements(); LINQ to SQL – Executes LINQ queries against Microsoft SQL Server. For a Database called company and table called customers. IQueryable customer = from cust in company.Customers where cust.name== "CodeSpread"  select cust; LINQ to ADO.NET datasets– Executes LINQ queries against ADO.NET DataSets. Same example as above where the data is queried from a dataset instead of directly from a...

Read More
IQueryable: Performance boost over remote Data Access
Apr26

IQueryable: Performance boost over remote Data Access

If we also follow the inheritance principle like OOPS programming, we need to extend our previous discussion “IEnumerable: Power behind Collections”. So this will lead us to write something about IQueryable. What is an IQueryable Interface? We can define it as functionality attached to an element which is used to evaluate queries against a known data source of unknown data type. It is available as public interface IQueryable : IEnumerable As we can see, it extends IEnumerable so we can easily say that all the inherent functionality of IEnumerable is available to IQueryable. What is the difference? IEnumerable: IEnumerable works with in-memory collection. It is a read-only forward-only collection. IQueryable: IQueryable works with remote data source. For example: Case 1 :If the case is to iterate through the in-memory collection, use IEnumerable, Case 2 :if the case is to do any manipulation with the collection like Dataset, use IQueryable. What are the properties available? Provider : Points to the query provider that is associated with the data source like LINQ to SQL provider. Expression: Points to a query expression which is associated with the instance of IQueryable that can be understood by the given query provider. ElementType: Points to the type of the element(s) that are returned when the expression tree associated with this instance of IQueryable is executed. IQueryable is not alone and comes as a package with IEnumberable. Enumeration causes the expression tree associated with an IQueryable object to be executed,but using IQueryable can save a lot of resources. Example Ref: http://sladescross.wordpress.com/2010/07/30/linq-iqueryable-interface/ if you’re working against a remote database, with many ORM systems, you have the option of fetching data from a table in two ways, one which returns IEnumerable, and one which returns an IQueryable. Say, for example, you have a Products table, and you want to get all of the products whose cost is >$25. IEnumerable products = myORM.GetProducts(); var productsOver25 = products.Where(p => p.Cost >= 25.00); What happens here, is the database loads all of the products, and passes them across the wire to the program. Program then filters the data. In essence, the database does a “SELECT * FROM Products”, and returns EVERY product. With the right IQueryable provider, IQueryable products = myORM.GetQueryableProducts(); var productsOver25 = products.Where(p => p.Cost >= 25.00); The code looks the same, but the difference here is that the SQL executed will be “SELECT * FROM Products WHERE Cost >= 25″.  From a performance standpoint, It will only return 2 records across the network instead of...

Read More

C#: Anonymous Type is not anonymous!

Why Anonymous Type? Anonymous types provide you the ease of having set of properties (Read only) into a single object without knowing the type. It’s the job of compiler to generate the type information. Anonymous types can be created by using the keyword new. Say: var test = new { Name = “Jackie”, ID = 123 }; Here ‘var’ keyword plays an important role as the type information won’t be available. Anonymous types are mostly used with the query expressions. This type can contain one or more Pubic read only properties. The most common scenario where Anonymous types are useful is shown below: var details = from data in dt.AsEnumerable() select new { UID = data.Field("id"), FirstName = data.Field("fName"), LastName = data.Field("lName”), Mobileno = data.Field("mno"), Address = data.Field<string>("add") }; Here, the DataTable dt already has some members or properties say. Now let’s say you don’t need to have all the properties or members of dt. Then in that case we will make use of Anonymous type using the new keyword. This causes smaller amount of data to be dealt with. Here we have specified the member names to the upcoming Anonymous type (UID, FirstName etc..)which is not necessary. If at all, we are not passing any names to the members, compiler will use the name of the members of the existing type(id, fname, lname etc..). As this article is based on developer’s experience so Please provide more inputs to improve this...

Read More
C#: Useful JSON in .Net
Dec03

C#: Useful JSON in .Net

Why JSON? All web applications revolve around large chunk of data and availability of that data to our application is of utmost importance. To do that, we have options like fetch data from database and sometimes from XMLs. As a result of which we end up hitting DB/File system several times and ultimately compromises with Page speed and performance. JSON- JSON (JavaScript Object Notation) is the solution to avoid all the difficulties with respect to data. Today we will try our hands on using JSON in .Net: The very first thing which is required to use JSON in our code is a namespace. System.Web.Script.Serialization Now the most important class, JavaScriptSerializer Let the play begin: Consider you have a DataTable dt filled with all your DB contents (Columns: UID, Firstname, Lastname, Mobileno, Address and many more) and you need to have these data handy. Then Query this data by linq query.  CODE: var details = from data in dt.AsEnumerable() select new { UID = data.Field("UID"), FirstName = data.Field("FirstName"), LastName  = data.Field("LastName”), Mobileno = data.Field("Mobileno"), Address = data.Field<string>("Address") }; This code has created an anonymous type (Read more about Anonymous type here ) CODE: Now this variable ‘details’ can be serialized to a JSON string as shown below. string JsonString = string.Empty; JavaScriptSerializer jsSerialize = new JavaScriptSerializer(); JsonString = jsSerialize.Serialize(details); //Created above This ‘Jsonstring’ variable will be available to our .aspx (design view) for display or any other operation as per the request The data in the string looks like this: [ { "UID": 1316134065, "Firstname": Jason, "Lastname": "Bourne", "Mobileno": "1234567890", "Address": "XYZ" }, { "UID": 1316134065, "Firstname": Jason, "Lastname": "Bourne", "Mobileno": "1234567890", "Address": "XYZ" } ] On the similar lines, you can do a vice-versa action too. Wondering how? Let’s see how to parse a JSON object using the same class JavaScriptSerializer. Create an instance of JavaScriptSerializer and then call Deserialize function to work on the JSON string which return a Dictionary object Dictionary. CODE: string json = “[{“Firstname”:”Test”, . . . ”; JavaScriptSerializer jsSerialize = new JavaScriptSerializer (); Dictionary dict = jsSerialize.Deserialize(json); Now you have the Dictionary to play around with the data. Enjoy...

Read More