Wriju's BLOG

.NET, Cloud and everything

LINQ to XML : Handling blank or no Element and Attribute

It quite so happen that you are working with XML where you are expecting a specific element in every set. But somehow that is missing in some of the sets. Now at runtime you would get an error.. The XML file which I am targeting <?xml version="1.0" encoding="utf-8"?> <Employees> <Employee Location="Earth"> <Name>Wriju</Name> <Email>a@a.com</Email> </Employee> <Employee… Read more

LINQ : From Basics to Query

Many of us are aware of LINQ today. LINQ is an amazing programming language feature. During my discussions I find a lot of myths around understanding. Here I have tried to demonstrate from some basics of C# 3.0 language enhancements to delegate, anonymous type, lambda expression and finally LINQ. How it has evolved. https://channel9.msdn.com/posts/LINQ-Evaluation-From-Basics-to-Implementation Namoskar!!!… Read more

LINQ to SQL : Windows Forms Dynamic Where Clause

While I was reading the book LINQ in Action, I found this chapter. Below is how we can do in LINQ to SQL. The scenario is if you want to create a LINQ and pass the where clause based on user input from UI, you need to write different queries. Instead, how you can do… Read more

LINQ to CSV : Getting data the way you want

Getting data from CSV is one of the mostly used business in applications/tools development. Here how we can do it in LINQ, You have a table called Emp with the below details, CREATE TABLE [dbo].[Emp](       [Id] [int] IDENTITY(1,1) NOT NULL,       [FirstName] [varchar](50) NOT NULL,       [LastName] [varchar](50) NULL,  CONSTRAINT [PK_Emp] PRIMARY KEY CLUSTERED… Read more

Setup and Deployment : Custom Action to Capture User Input

Purpose Users are allowed to pass Product Key while installing in .msi. During that we want to capture it for registration to avoid piracy. Challenges When we use “Customer Information” dialog in “Start” action, it has “SerialNumberTemplate”. But capturing information from there is really tough as mentioned in the article http://support.microsoft.com/kb/253683/en-us. So we have to… Read more

LINQ to XML : Understanding Annotations

Annotations are used for private use. It does not directly associated and known as Black Box in XML world. This can also be considered as meta tag. Below is an example on how it can be handled. I have created a sample Windows Applications and will try to capture my understanding. /// <summary> /// Class… Read more

LINQ – Uniformity All Over

I have spent a while with LINQ and still feel very new whenever I explore some new power. Here I am going to describe you how LINQ uniformly allows you write for the various types of data.   In-memory data source ++++++++++++++++ List<int> arrInt = new List<int> { 1, 2, 3, 4, 5, 6, 7,… Read more

LINQ to SQL : Understanding Compiled Query

Understanding Compiled Query connects me to my experience in C# 3.0. Based on my personal understanding I am discussing it.   You may be aware of Func<>. And you know it is a flexible delegate which allows you create reusable functions. Exactly the same way we can create compiled query so that we can prevent… Read more

LINQ to SQL : Returning Scalar Value from Stored Procedure

In LINQ to SQL it is not that easy thing to achieve as compared to other features. Let us assume you have a Stored Procedure like, Case 1: With Output Parameter CREATE PROCEDURE [dbo].[GetEmployeeCount]       @OutVal DateTime OUTPUT AS BEGIN       SELECT @OutVal = GetDate() END You need to write code which will look like,… Read more

LINQ to SQL : Using ChangeSet for Audit Trail

Most of the transactional scenario, you may need to add the transaction to some table for ref. many apps does it for admin perspective.   Problem   You can do it in LINQ to SQL with ChangeSet but the problem is with Inserts. It does not give you the Identity field value until and unless… Read more

ADO.NET Entity: LINQ to Entity with Relationship

Relationship and getting data from Entity Framework using Northwind database Simple Query   using (NorthwindEntities ctx = new NorthwindEntities()) {     var query = from o in ctx.Orders                 select o.OrderID;       foreach (var k in query)     {         Console.WriteLine(k);     } }   Now if you want to filter this with the… Read more

ADO.NET Entity: Insert Update and Delete with Relationship

Few days back I had written an article on Insert/Update/Delete for simple standalone tables at ADO.NET Entity: Insert Update and Delete. Now after that many of you had requested me to put article on how it works with relationship.   Here I will use a database created by me. There will be two tables connected… Read more

ADO.NET Entity: Insert Update and Delete

For small blogs, it requires more references and explanation, which sometimes are redundant. So I thought of writing single blog which is combination of topics more or less related to one thing.   I am exploring ADO.NET Entity Framework and have been trying things out there. Here I am planning to demonstrate how to do… Read more

LINQ to SQL vs. ADO.NET – A Comparison

ADO.NET is our contemporary data access component and now we have written many applications. Now there has been a lot of talk on LINQ to SQL. So we are little skeptical about this component and trying to find some relation between existing ADO.NET technology.   Purpose of this post is to give some quick brief… Read more

LINQ to Entity : Querying data using ADO.NET Entity Framework

ADO.NET Entity Framework have evolved since we have released it first time. Now with the Visual Studio 2008 if you install the .NET Framework 3.5 SP1 and Visual Studio 2008 SP1 you will get the fully functional version of ADO.NET Entity Framework. This is post Beta 3 release. To create a .edmx file you have… Read more

LINQ to SQL: Making it N-Tier

You can create your application use LINQ to SQL and make it N-Tier. Go ahead and watch out the MSDN Documents N-Tier and Remote Applications with LINQ to SQL LINQ to SQL N-Tier with ASP.NET LINQ to SQL N-Tier with Web Services LINQ to SQL with Tightly-Coupled Client-Server Applications Implementing Business Logic (LINQ to SQL)… Read more

LINQ to XML : Querying XML with Namespaces

This question arises in one of discussions. If you have a XML document with “xmlns” then LINQ to XML does not return any IEnumerable<T> J. This is strange but true for XPath and XQuery. There is a trick to get it done, Let us assume that you have a XML as follows, <?xml version=“1.0“ encoding=“utf-8“?>… Read more

LINQ : IEnumerable<T> and IQueryable<T>

IEnumerable<T> and IQueryable<T> are the two most used terms of any LINQ discussion. What I am trying to here is that I am trying to simplify the two interfaces depending on their behavior. In LINQ world we generally have few providers available within .NET Framework, like LINQ to Object, LINQ to SQL, LINQ to XML…. Read more

LINQ to XML : Modifying XML document

You have XML document now you want to modify that XML file using LINQ to XML. It is as easy as you generally modify any database column value.   Let us create a dummy XML stream,   //Create dummy XML to work var root = new XElement(“parent”,     from i in new int[] { 1,… Read more

LINQ to XML : Adding Namespace quickly

I have written a post earlier on how to attach Namespaces. After reading my article someone complained about the redundancy of the code. I also realized the pain. I was reading the book C# 3.0 In a Nutshell. There I got a very elegant solution. Let me explain the scenario,   If you create a… Read more

LINQ to XML : Join Xml Data

Let’s say I have created two Xml files using LINQ to XML from Northwind database. I have taken two tables Category and Products and tried to join between two different files.   Category XML   <?xml version=“1.0“ encoding=“utf-8“?> <categories>   <category id=“1“>     <CategoryName>Beverages</CategoryName>   </category>   <category id=“2“>     <CategoryName>Condiments</CategoryName>   </category>   <category… Read more

LINQ to XML : Working with Prefixes

Based on my previous post on LINQ to XML : Working with Namespaces, if you want to add prefixes to your Xml things becomes little crazy. The trick is that you have to use XAttribute() to attach prefixes. So the Xml as below need the following code,     <pfx:root xmlns:pfx=“urn:mynamespace-com“>   <pfx:child /> </pfx:root>… Read more

LINQ to XML : Working with Namespaces

If you are working with complex real world XML then you have to deal with namespaces to disambiguate. There are several ways to implement namespaces in LINQ to XML. One is you can use pure string to add your namespace with each element declaration, like   <root>   <child /> </root>   To create the… Read more

LINQ to SQL Overview Video

Luca, the Microsoft Lead Program Manager, he is one of my favorite presenters. The way he demonstrate uninteresting thing and make fun of himself is one everyone should learn. Please enjoy the through presentation of LINQ to SQL at http://blogs.msdn.com/lucabol/archive/2008/03/03/linq-to-sql-overview-video.aspx   Namoskar!!!… Read more

C# 3.0 Query Expressions by Bruce Eckel and Jamie King

Bruce, a renowned author of the famous book “Thinking in Java” is now exploring C# 3.0. He wrote many other books on Ø       The Hands-On Java Seminar CD ROM (available on the Web site) Ø       Thinking in C++ (PH 1995; 2nd edition 2000, Volume 2 with Chuck Allison, 2003) Ø       C++ Inside & Out (Osborne/McGraw-Hill… Read more

LINQ to XML : Creating complete XML document

LINQ to XML API allows us to create complete XML document as expected with all the elements. So this X-DOM has everything as you expect.   Simple sample looks like,     XDocument doc = new XDocument(     new XDeclaration(“1.0”, “utf-16”, “true”),     new XProcessingInstruction(“test”, “value”),     new XComment(“This is comment by you”),     new… Read more

LINQ to XML : Creating XML from another XML

Based on my previous post if I have to filter the list of customers only in the country “US” and create another XML which may look like,   <?xml version=“1.0“ encoding=“utf-8“?> <usaCustomers>   <usaCustomer>     <title>Marketing Manager</title>     <name>Howard Snyder</name>   </usaCustomer>   <usaCustomer>     <title>Sales Representative</title>     <name>Yoshi Latimer</name>   </usaCustomer>   <usaCustomer>    … Read more

LINQ to XML : Creating complex XML through LINQ

We can generate hierarchical object graph in our memory though LINQ. To be more realistic we can bring data from relational database. So if we consider Northwind database and use LINQ to SQL to bring all the Customers and their Orders and Order Details the query would look like,     //LINQ to SQL way… Read more

LINQ to SQL : Understanding Mapping

In LINQ to SQL you play with pure .NET objects and write your LINQ on top of that. But question might arise how this magic happens. Though we say that it is object, the question might arise in our mind that there has to be a mechanism through which it connects. Yes, there is. That… Read more

Sharing “var” across the method

One of the biggest limitation in “var” is that it cannot be shared across the methods. So if you are doing something using that keyword then you have to stick to the local. I was reading Alex’s Blog where he explained it very nicely,   Here is my implementation,   Create an Extension method  … Read more

LINQ to SQL : What is DataContext.Translate Method

DataContext’s Translate method converts existing IDataReader to an IEnumerable<T>. This is very useful when you may need to run raw SQL Query though System.Data.Linq. I am getting few similarities with DataContext’s ExecuteQuery.   How Translate works +++++++++++++ Assuming I am using Northwind database.     using (NWDataContext db = new NWDataContext()) {     DbConnection conn… Read more

C# 3.0 : Useful keyword “var”

People complain about the keyword “var”. Especially, when we use it with the strict programming language like C# in .NET. Developers also complain about the readability part of it. I totally agree with them, but the scenarios where there will be no options but the “var” when it comes to on the fly projection of… Read more

C# 3.0 : Joining two in-memory collection through LINQ

LINQ allows us to join different collection source provided we are mapping with two properties with the same type. It is easy, it is quick and it is concise.     //Create Employee Class class Employee {     public int ID { get; set; }     public string Name { get; set; }     public… Read more

C# 3.0 Feature Articles

With this exciting release of .NET Framework 3.5 I have been exploring its magic and sharing the finding with you. Here I am compiling all of them together for indexing,   C# 3.0: Vote for the keyword “var”   C# 3.0 Features: Automatic Property C# 3.0 Features: Automatic Property (Part 2) C# 3.0 Features: Automatic… Read more

MSDN Virtual Labs : C# 3.0, Visual Basic 9.0, ASP.NET 3.5

Learn and for installation-free mode and get started with Visual Studio 2008.   MSDN Virtual Lab: Building Web Applications with Visual Studio 2008 MSDN Virtual Lab: What’s new in C# 3.0 MSDN Virtual Lab: What’s new in Visual Basic 9   Namoskar!!!… Read more

C# 3.0 : Exploring Lambda Expression

I started playing with Lambda expression after the TechEd demo by Anders Hejlsberg. Couple of nice things I would like to share with you.   As there might be many definitions for Lambda expression but to me Lambda Expression is the concise way to write functional implementation for Anonymous Method. This is been used by… Read more

LINQ to SQL : Enabling .dbml file for WCF

LINQ to SQL is object relational model and .dbml file generates the class file for all kind of Create, read, update and delete (CRUD) through the mapping mechanism. Ideally this should allow us to enable it for WCF Service. But for that we have to manually add DataContract and DataMember attributes. We can use .dbml’s… Read more

Visual Studio 2008 Training Kit Videos on LINQ

Visual Studio 2008 Training Kit videos are now available on web. Get some real exciting presentations   VS2008 Training Kit: What’s new in C# 3.0? VS2008 Training Kit: What’s new in Visual Basic 9.0? VS2008 Training Kit: .NET Language Integrated Query (LINQ) VS2008 Training Kit: Using LINQ with Relational Data   For more detailed list… Read more

Visual Studio 2008 and LINQ Case Studies

Some of the early adopters case studies are now available,   Xcalia OpenNETCF Consulting Sogeti Group K2   Get some of the quotes from there,     LINQ is an object-oriented language and so fits perfectly with the philosophy of our product, which aims to make technical details of data access transparent to the developer…. Read more

C# 3.0 : Evaluation of Lambda Expression to Language INtegrated Query (LINQ)

From code name “cool” to C# 3.0, it’s been a long journey for this amazing language with .NET Runtime. Here I am going to show you the evaluation step by step.   Let us assume we have generic list of integers and I need to find the even numbers from that list,   List<int> arrInt… Read more

LINQ to SQL: Working with hierarchical data

LINQ to SQL supports hierarchical data and you can easily create a query and get output from there. Let us take an example of Northwind database. Northwind has Category -> Products -> Order_Details tables. -> indicates one to many relationships here. So ideally for a Category can have multiple products and a product can have… Read more

LINQ to SQL : New method DataContext.GetCommand()

LINQ to SQL we can read the generated T_SQL query using DataContext.Log or SQLQueryVisualizer. But If you are working with WebProject the Log property not very much convenient as you have to use TextWriter to dump the generated T-SQL query.   In Orcas Beta 1 we had DataContext.GetQueryText which used to give us the generated… Read more

C# 3.0: Vote for the keyword “var”

You all probably know what is “var”. You might have a question why this new keyword is required in programming language like C#. One of the few strong reasons is to have an Anonymous Type stored in a variable. Whenever you have to initialize a type you have to mention the type before you give… Read more

LINQ to SQL Windows Form Binding Data Step by Step

LINQ to SQL designer in Visual Studio allows us to create mapped class using the drag and drop feature from Server Explorer. Now that is business object which ideally you could use as your datasource and from Visual Studio 2008. So let us have this step by step, Open your Visual Studio 2008 and create… Read more

LINQ to SQL : Some of the best BLOGs

Some of the best blogs on LINQ to SQL I found are available for great learning, Scott Guthrie The Famous LINQ TO SQL Series Part 1: Using LINQ to SQL Part 2: Defining our Data Model Classes Part 3: Querying our Database Part 4: Updating our Database Part 5: Binding UI using the ASP LinqDataSource… Read more

C# 3.0 : Anonymous Type and .NET Reflection Hand-in-Hand

Anonymous Type is nothing but the type which gets defined by CLR (not you). So that type is as rich as any other normal type. Probably the conventional way to find the components of an Anonymous Type through reflection would be clearer to us,   static void Main() {     //Anonymous Type     var anyType… Read more

LINQ to SQL : Change in DataContext from Beta 1 to Beta 2

During the demonstration I have noticed that two major methods of DataContext has changed from Beta 1 to Beta 2.   First one, is the new name for the class DataShape(). Now there is no class called DataShape() but we have DataLoadOptions().     var loadOption = new DataLoadOptions();            loadOption.LoadWith<Customer>(c => c.Orders);   db.LoadOptions =… Read more

LINQ to SQL : Paging Data

When we work with relational database and especially when with larger data we generally go for custom paging. This allows us to create superfast application.   The simple logic for paged query is like,   Let’s suppose you have 100 rows. Now you want to get data of page size 10 for page 2.  … Read more

Have you tried LINQPad (Beta)?

Experiment and learn new concept of LINQ. This is just an exe which requires no extra installation. Pre-requisites Install just .NET Framework 3.5 (minimal impact) Install Visual C# 2008 Express Install the full Visual Studio 2008 Download http://www.albahari.com/LINQPad.exe For more information please visit, http://www.albahari.com/linqpad.html Aha this is from my screen,   Namoskar!!!… Read more

LINQ and C# 3.0 Articles and Samples

LINQ: .NET Language Integrated Query By Don Box, Anders Hejlsberg LINQ to SQL: .NET Language-Integrated Query for Relational Data By Dinesh Kulkarni, Luca Bolognese, Matt Warren, Anders Hejlsberg, Kit George .NET Language-Integrated Query for XML Data By Michael Champion The .NET Standard Query Operators By Anders Hejlsberg, Mads Torgersen Overview of C# 3.0 By Anders… Read more

LINQ to SQL : Caching the query execution

LINQ to SQL executes or generated SQL statement only when you run a foreach statement or you perform to ToList() method to it. If you need to display the output multiple times without executing the real database query, you can store them in memory. This can be done only when you are sure that the… Read more

LINQ to SQL : Deferred and Immediate Loading

LINQ to SQL has support for both deferred and immediate loading. By default it supports deferred loading but you can configure your code to load the data immediately. Let’s consider the Northwind database. As we know the there are two tables Customer and Orders and one customer can have multiple orders. These two tables have… Read more

LINQ to SQL : Writing DML query to perform quick operation

In LINQ to SQL you also can send the DML query to perform the quick database modification.   Caution!!! It is not recommended as it does not support object model so has no compile time checking.   static void Main(string[] args) {     string strConnection = @”Data Source=wriju-orcas\sqlexpress;Initial Catalog=TestDB;”;       TestDB db = new… Read more

LINQ to SQL : Delete data through Object Model

LINQ to SQL support deleting data through object. Continuing with my previous blog on INSERT, let me discuss about the delete method   static void Main(string[] args) {     string strConnection = @”Connection String”;       TestDB db = new TestDB(strConnection);       db.Log = Console.Out;             //Here I am finding the employee with… Read more

LINQ to SQL : Update data through Object Model

LINQ to SQL support updating data through object. Continuing with my previous blog on INSERT, let me discuss about the update method   static void Main(string[] args) {     string strConnection = @”Connection String”;       TestDB db = new TestDB(strConnection);         //Here I am finding the employee with Id 19     var updateQ… Read more

LINQ to SQL support inserting data through object.

LINQ to SQL support inserting data through object.   using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Linq;   namespace Linq2Sql_demo_doc {     /// <summary>     /// Class to represent the SQL Server table     /// Emp     /// Id int     /// Name varchar(50)     /// </summary>    ///     [Table(Name=“Emp”)]     public class… Read more

LINQ to SQL : Executing DML SQL Query

INSERT/DELETE/UPDATE can be performed in LINQ to SQL through normal T-SQL DML queries,   static void Main(string[] args) {     NorthwindDBDataContext db = new NorthwindDBDataContext();   var query = db.ExecuteCommand(“YOUR DML Query”, “Your    Parameter”);       ObjectDumper.Write(query); }   Are you feeling comfortable? Hold on, please try to avoid this as you have better object… Read more

LINQ to SQL : Executing SQL Query

Yes, you can run normal SQL queries in LINQ to SQL. Sample looks like (but not recommended as you do not have statement completion and validation)   static void Main(string[] args) {     NorthwindDBDataContext db = new NorthwindDBDataContext();       var query = db.ExecuteQuery<Customer>(“SELECT * FROM Customers”, “”);       ObjectDumper.Write(query); }   One of… Read more

ADO.NET Entity Framework June 2007 CTP is available

Overview This CTP contains updates to the ADO.NET Entity Framework since the Visual Studio Codename “Orcas” Beta 1 release, including changes in Object Services, Query, Entity Client, and the Entity Data Model Wizard in Visual Studio. Some of the new features include IPOCO, detaching from long-running ObjectContext instances, multiple entity sets per type, support for… Read more

LINQ: Query to SQL, XML and Object and JOIN them

Getting data from SQL, XML and Object and joining them using Language Integrated Query is something you might be looking for. I have created a small application which brings data from SQL Server (table name is Employee), XML (file name is Department.xml) and Object (Generic list containing list of Managers).   My SQL Table Looks… Read more

C# 3.0 and its major design changes for LINQ

C# 3.0 PM Anson Horton discussed about the LINQ and its impact on C# 3.0 covering Lambda Expressions Extension Methods Anonymous Types Implicitly Typed Local Variables Object Initializers Query Expressions Visit the MSDN Magazine article at http://msdn.microsoft.com/msdnmag/issues/07/06/CSharp30/ Namoskar!!!… Read more

C# 3.0 Enhancements: Expression Trees (recording)

I have discussed about the Expression Trees in my previous blog at C# 3.0 Enhancements: Expression Trees. I have done a small recording on that showing the demo there. I have uploaded that to MSN Soapbox and you can find that here.   Video: CSharp 3.0 Expression Trees    Namoskar!!!… Read more

C# 3.0 Enhancements: Expression Trees

Expression Tree is the feature which enables us to write function which can be complied on-demand basis. It stores the function in form of structured data rather than executable code. Since this is structured we can easily iterate through it anytime. This is easier than finding something in IL.   Let’s suppose if you have… Read more

C# 3.0 Enhancements: Lambda Expression (more on what)

Lambda Expression gives us the more concise way of Anonymous Method implementation through functional programming language. Let me share some interesting aspects of Lambda Expression while exploring the C# 3.0 Specification. There it is being clearly described what Lambda Expression is.   (param) => expr   Can be expressed as   param => expr  … Read more

C# 3.0 Enhancements: Collection Initializers

In C# 3.0 we can easily initialize collection. It is smarter and concise way of writing code.   There are couple of things we should consider while initializing the collection. Ø       The collection should implement ICollection<T> Ø       The collection should have a provision to invoke ICollection<T>.Add(T)     Here is couple of them. I am… Read more

C# 3.0 Enhancements: Extension Methods

Extension Methods are different way of implementing static method. In C# 3.0 it allows us to extend any type and add method for that type. While writing extension method you need to Ø       declare a public static method Ø       the first parameter of that method should be the type of the object Ø       “this” keyword… Read more

C# 3. Resources

I found a very nice link on C# 3.0 resources and sharing it for you.   Query Composition using Functional Programming Techniques in C# 3.0 by Eric White   This talks about various aspects of C# 3.0 with details.   Namoskar!!!  … Read more

C# 3.0 Enhancements: Object Initializers

C# 3.0 allows us to initialize object in far better way in one single line. Let’s talk with an example here. Back again to my favorite Customer object.   public class Customer {     public Customer() { }       private int _ID;     public int ID     {         get { return _ID; }… Read more

C# 3.0 Features: Automatic Property (Part 2)

Thank you everyone for showing interest on my blog entry C# 3.0 Features: Automatic Property. Questions like, why this approach? What if there is any condition in property? Let me tell you, we have implemented the higher level of abstraction in C# 3.0. If you are simply creating a property (we often do) then the… Read more