Friday, November 16, 2007

Making Entity Framework work with a Web Application

Making Entity Framework (EFW) work with a web application was the toughest (relatively) of the lot (Win App, Console App etc).

To get it working for any type of app, these 2 steps are sufficient:
  1. Add the app.config of the EFW project to your app. If you already have a app.config, then add only the "connectionStrings" node of it.
  2. Copy the c/m/s (.csdl, .msl and .ssdl) files to the bin directory, where the executable of the app resides.

But if you have to get this working for a web app, then

  1. Add the "connectionStrings" node to your web app's web.config.
  2. Copy c/m/s files to App_Data folder
  3. Change the string in "connectionStrings" node From
    ".\EFWSampleDb.csdl.\EFWSampleDb.ssdl.\EFWSampleDb.msl"
    To
    "DataDirectoryEFWSampleDb.csdlDataDirectoryEFWSampleDb.ssdlDataDirectoryEFWSampleDb.msl"

Alternately, instead of "|DataDirectory|EFWSampleDb.csdl" you can also say "~\App_Data\EFWSampleDb.csdl". ("~" refers to the root directory of the web app). So, this essentially means that you can have the m/s/l files in any directory, and not necessarily in App_Data, and reference it in web.config.


Failing to do the above steps may error out saying:

"The specified metadata path is not valid. A valid path must be either an existing directory, an existing file with extension '.csdl', '.ssdl', or '.msl', or a URI that identifies an embedded resource."


OR

"The specified named connection is either not found in the configuration, not intended to be used with the EntityClient Provider, not valid."

Wednesday, October 24, 2007

C# 3.0 Features: Lambda Expressions

C# 3.0 Lambda expressions come very handy to developers. One important consideration (which is beautiful) is that all these features (LINQ, C# 3.0 features, Entity Framework etc) come with no change in CLR. That means your old CLR, which executes your .Net 2.0 apps can execute your new apps too. And that implies that the IL that is emitted hasn't changed. So, though you use Lambda expressions instead of anonymous methods, the IL generated is the same in both cases. (Wow!!! Now I can feel the beauty of the IL concept and design.)

Coming back to Lambda expressions, what are they basically? They are not just a syntactic substitute to anonymous methods. You can read more about Lambda expressions (and an interesting topic of how to pronounce them!!) in Eric White's blog. I will deal with two important things of Lambda expressions (in context of LINQ) which you may not find often on the web.
  1. Writing whole blocks of code in Lambda expressions. (Remember that Lambdas are expressions, hence writing more than one statement may sound little odd)
  2. Returning subtypes (or columns) of a type on which the LINQ query is fired.

Writing whole blocks
Lambda expressions definitely make writing anonymous methods easy. Using Lambda you can do all that you can with anonymous and even more. So, if you can write a proper function with different control statements and logic using anonymous, you can do the same with lambda. Most of the lambda examples you see would be something like this:

var existingAccount = repository.Accout.Where(a => a.AccountId == "1");

You can write quite an amount of logic here, something like this:

var existingAccount = repository.Accout.Where(a =>
{
if (a.AccountId == "1" && a.AccountName == "Pavan")
return true;
else
return false;
});

The above code snippet will return an Account object after processing all the logic, accordingly. So, as you can see, it's just like any other (anonymous) function.

Now, if you carefully observe the snippet above, we are returning a boolean value from within the lambda but what existingAccount contains is an Account object. How did this happen? Well, it's pretty simple. If you carefully inspect signature of "Where" method being called on Account, you can understand.


What Where expects is a Linq.Expressions.Expression parameter which, in turn, expects a delegate that takes an input parameter as InsuranceDBWrapper.Account and returns a boolean. And this delegate's return value decides whether to return the object (in our case Account) on which Where is being called. And that's exactly what our lambda does - to return a boolean telling whether to return the (Account) object or not. Note that you can pass the delegate directly also without any expression in between.

Returning Subtypes (or columns)
What if you don't want the whole type (or object) to be returned but just some columns or subtypes of it? You can as well do that, but not using Where. Where has 4 overloads of which two take expressions and the other two, directly delegates. But the sig for these delegates involves atmost two input parameters (first parameter is the type on which Where is applied and which is inferred automatically, second an int which gives the index of an item) and always returns a boolean (which tells whether to return the whole object or nothing). So, there is no means here to select and return specific columns. Since you return a boolean, it's either the complete object or nothing - that is returned.

What you need to use in this case is a Select:

var existingAccount = repository.Accout.Where(a => a.AccountId == "1").Select(b => new {b.AccountId, b.Name, b.IsLocked});

This returns an anonymous type with three properties (AccountId, Name, IsLocked).

Select is used to filter on columns and Where is used to filter on rows.

Lambdas can be used in Expression trees (which will be in a separate post :))

Workflow with id not found in persistance store

For couple of days now I've been doing extensive debugging of a (Windows) Workflow. And time and again I've been facing this error. So I thought I will elaborate more on this. There are three primary reasons why this might happen:

  1. Your workflow has actually terminated. It could have terminated or finished execution, but since you wouldn't try to load a finished workflow, in all probablities, it would have terminated (due to some unhandled exception). You can check this by going to your WorkflowInstance table in your persistence store and check the DbEndDateTime for your workflow instance. If it is null, then you can move to next points :-) else you have found the culprit. All you have gotta do is to debug into your workflow and fix your code.
  2. Workflow changes. If you make any changes to your workflow and then try to load previous instances of it, you will see this error. You will have to apply the changes done on the workflow to the old instances also.
  3. Try to connect to remote persistence store. If you are trying to load a workflow instance from a remote store, this error will come up. Make sure that your remote (store) server DTC is configured to allow this.
Hopefully, this will help people in saving time trying to find why the workflow doesn't load. Pls be aware that this error can come up due to many other reasons and not only the three mentioned above.

C# 3.0 Features: Var

"var" is one feature of C# 3.0 that has called for much debate. What is "var" and when can it be used, has already been dealt in many blogs and Microsoft documentation. So, I'll not be writing about it here. What I'll talk about is why var is not allowed to be passed around in functions i.e. why do you get this compile-time error:

the contextual keyword var may only appear within a local variable declaration

when you try to accept a parameter of type var. Considering that var can accept anonymous types, it is very convenient to tossing it around in function calls. But that isn't allowed. Let's see why:

Let's approach this using the Contradiction theory. Let's assume that this doesn't give any error and is allowed. Now, when the code is built the actual type of var has to be resolved. And since the var, in our case, hasn't been initialized (remember it's a function parameter), the compiler doesn't know to what type the var should be resolved. And that's why the compiler can't allow this. Let's also assume that the compiler is intelligent enough to infer its type from the invocation call of the method i.e.

..........
ExectueThis(5)
..........

private void ExecuteThis(var intVar)
{
}

Looking at "ExectueThis(5)", let's say, the compiler infers intVar is of Int32 type. Looks good to me if the compiler could do it. But what if ExecuteThis is called from somewhere else also and a string is being passed to it.

ExecuteThis("abc")


Probably we can say that don't allow the second call as from the first call we have already determined intVar to be Int32. But what if all this is in a class library, where you can't determine the sequence of function calls i.e we don't know whether first function call will be made first or the second one will be made first.

So, essentially, there is no way the compiler can tell, for sure, what type the var parameter is. And thus var can't be passed around in functions. I don't see a great use of var in general programming except if you are using LINQ. It helps you to avoid declaring custom types for each resultset that is returned from a LINQ query. var is more tailored for use with LINQ

Thursday, October 4, 2007

VS 2005 C# projects in Orcas Beta 2

Opening a VS 2005 C# project (.csproj) in Orcas Beta 2 may sometimes throw you this error:

"Make sure the application for the project type (.csproj) is installed."

I tried googling on this but did not find much information except that, this might happen if your project is under source control. My projects were under source control and hence I was elated as the post did carry a solution for the same (http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=8461&SiteID=1). But my elation was short-lived as the work-around didn't help me.

After breaking my head for sometime I came with a work-around that resolved the issue. Here are the steps:
  1. Delete the solution file and any associated source control bindings.
  2. Open one of the projects (open the .csproj file)
  3. Orcas will prompt for migration to new version. Finish it.
  4. Now add all the remaining projects to the newly created solution.
  5. Once you re-create your solution structure save it to the location from where you deleted the original one.
The solution can now be built.

Also, do not forget to change the target framework to 3.5 in your project properties unless you aren't using any of 3.5 features.

Wednesday, September 26, 2007

10 Things You Should Know About LINQ

10 fundamental things that you should know about LINQ

1. LINQ is Language INtegrated Query where the queries to data sources are written as part of the High Level .NET programming Language (like C# or VB.NET).

2. The queries, which are the language constructs, can be compiled using the language compilers. This ensures type-safety. The queries can also be debugged using the Visual Studio debugger (an awesome feature, I believe)

3. Intellisense can be used to access tables and their columns of a database. This feature is not present in the CTP versions but would be delivered with the Orcas release.

4. LINQ provides Standard Query Operators (SQOs) (like select, union, where etc) to retrieve data from any object whose class implements the IEnumerable interface. This is called "LINQ to Objects". The object, or rather data source, can be virtually anything: a registry collection or a File collection or a database.

5. LINQ also provides SQOs to work with relational data, also called as "LINQ to ADO.NET or DLINK". It is comprised of three parts: “LINQ to SQL”; to query relational databases like SQL Server, “LINQ to DataSet”; supports queries using ADO.NET datasets and datatables and “LINQ to Entities”; to query ADO.NET 3.0 entities (Entities are part of Entity Framework of ADO.NET 3.0)

6. LINQ provides SQOs for XML documents, called "LINQ to XML or XLINK". It also provides a host of new XML-specific features for XML document creation and queries. It can be considered as a powerful replacement for DOM and XPath.

7. WebLINQ, also known as BLINQ, creates CRUD ASP.NET pages (infact, a complete website) against a database using LINQ. It also preserves relationships between tables by providing an option on the aspx pages to view the related records from the related tables. I would suggest you to check this wonderful feature.

8. LINQ not just supports simple queries but also stored procedures.

9. LINQ can be used to query on a join of different datasources. For example an RSS feed of a Blog, a collection object (like registry) and a bunch of rows from a database can all be joined together (using a SQO) and then be queried on.

10. LINQ maintains object identity. In other words, if two queries return the same information (say form a table), only one instance of that table “as an object” is maintained. This makes sure that objects are not created unnecessarily. This is a classic issue in ORM models, which is eliminated here.

With every release of a framework, life for developers is being made easier. With LINQ, so much code has been made simple to write and manage, that it cannot be put in less than a bible. I wonder if someday I would be jobless!

Three cheers to LINQ!

(Reproduced from my Infosys Blog)

Tuesday, September 18, 2007

Wealth of SilverLight Resources

There is a wealth of tutorials on SilverLight at
Almost everything on SilverLight is covered; from SilverLight 1.0 to SilverLight 1.1 to Expression Blend. Also, there are some really good (links to) tutorials from different websites.
Do check them out.

Friday, August 10, 2007

Can not retrieve values from grid view

Working with grid view, I faced an issue!

I had a gridview in which I had to hide few columns and use them later on for some conditional checks. The hiding part was quite easy and straight-forward but the conditional check was tricky. When I tried to get the values of the hidden column using
row.Cells[0].Text
where the hidden column index is 0, null was being returned. This looked strange to me as I was setting the values properly i.e. a datatable was being bound to the gridview and the datatable was properly constructed.

It turned out that ability to retrieve values from hidden columns has been chopped off in the new gridview. The logic that I found out (after a bit of gooling) was that, since most of the users hide primary key columns in the datatable, it is not safe to allow the column values to be retrieved. I guess the first part of the logic is very much right, that primary key columns are the best prospects to hiding. The second part may also be correct, that it is unsafe to expose them. But these two parts together, cause more harm than good!

First of all, inconvenience to devs as the regular functionality is changed. Second, how are the devs expected to identify the rows that the user is operating on? Often, the data in the gridview has a mapping table and if the dev can't retrieve its primary key, what operations are possible on it? And what use is the grid off?

Solution
Anyways, there is an easy workaround for this though. If you are in hurry, don't worry about all the blabber above. Just do the hiding of columns after you finish the binding of data. This works!

Monday, July 16, 2007

State-Machine Workflow Part II

We have the following on the host app:
  1. A service class that implements communication-service interface
  2. The workflow runtime and its services which are instantiated and added respectively in the host app.
Service Class
The service class basically implements the communication-service interface, promising the interface that it understands which events the workflow would support and that it will raise them. For each of the events that is supported the service class just raises them. That's it!

Workflow Runtime
We come to the centre of the pizza! Workflow runtime is the actual component that hosts the workflow. In effect, it's the translator between the workflow and the rest of the world.

Many services can be registered while instantiating the runtime. Services for External Data Exchange, tracking etc (the list of services can be easily googled) are provided to add extra functionality to the bare-bone runtime. But it's very important to choose the services judiciously as a service without purpose brings down the performance.

Friday, July 13, 2007

State-Machine Workflow Part I

State-machine WorkflowThis dia helps me very nicely in understanding how to implement a state-machine workflow (which relies on external events). Let me see if I understand each of the components in the dia :)

Let us start with the workflow part and then move to the host application part (prob in the next post if this one becomes too long):

The workflow part has only a couple of things:
  1. The workflow itself, and
  2. An interface
The Interface
The interface, also sometimes called as communication-service interface, is used to tell the outer world as to what events the workflow would respond to. To elaborate on this, the workflow is expected to handle events that are generated from the host application. Hence the host app needs to know which events the workflow is prepared to handle or, in other words, what functionality is the workflow capable of handling. The same is exposed through a set of events. Essentially, it (the interface) is nothing more than a communication contract, which helps the host app to understand what events it can raise. The interface, at the minimum, is supposed to do two things:
  • Is marked with ExternalDataExchange attribute: This attribute tells the WF that this interface should be used as a contract. A simple example would be:
[ExternalDataExchange]
public interface IAnalyzeNameService
{
event EventHandler AnalyzeName;
}
  • Give a list of all the events that the workflow would respond to.
That's it on the interface end! Quite simple!

The Workflow
On the workflow end, in addition to the actual workflow that it would contain, it should also define the custom EventArgs that has been used while defining the event in the service interface. (One can consider this activity to be outside of workflow also. ) But there are few things that should be taken care of:
  • It should inherit from ExternalDataEventArgs: Unless this is done the custom event args is not accepted. The obvious reason is that this pre-defined type has some information, like the instaced id, that needs to be propogated to the WF infrastructure to raise the event on the appropriate workflow instance.
  • This class should be marked as serilizable: If this is not done, an EventDeliveryFailedException is thrown.
  • InstanceID of the workflow instance should be passed (in addition to any custom info that would be required to be passed), for reasons mentioned already.
That does the job on the workflow side. There are a couple of things that should be done on the host app side and we are ready with a state-machine workflow running with the host app and the workflow communication in full flow.

Thursday, July 12, 2007

Error loading workflow: Runtime capabilities are not available with this type

I just started-off with coding on workflows and the first error that I see:

I did quite a bit of googling but couldn't find any answer. Usually in these kind of errors, the error (written in blue) is given with link which would take the dev to the error line. But here the link doesn't work i.e. you don't go anywhere :)

So the resolution?
Well, just rebuild the whole application. And it works like magic. Now, what's going on here: The scenario was that we were two guys working on same code using TFS. He had checked-in code which was not properly building (he was infact in the middle of making some changes). Once he checked-in properly building code things started working properly.

Wednesday, July 4, 2007

Going Forward...

Long time that I've updated my blog. I was actually busy with a personal work and couldn't concentrate on this.

Well, as Shakespeare said, All is well that ends well, I'm now going to resume my blog. But going forward the posts would be relating to Windows Workflow Foundation (WF), Windows Communication Foudnation (WCF) and Windows Presentation Foundation (WPF) rather than just C#. Though the theme of the posts would be same, "Not So Obvious..."

Monday, March 26, 2007

Every Type is derived from...

A simple question...

Which is the type from which every other type is derived? Think before you look forward!
If you are answer is System.Object, then it's partially correct. The actual answer is System.Object if it's a reference type. If it is a value type then it derives from System.ValueType.

Saturday, March 24, 2007

Multiple Entry Points

A dot net program has a single point of entry (which is generally the Main function).
public static void Main(int args[])

A well-known fact:The execution of the program starts from here. If we look at the sig of the function we see that the Main function is publi. But ever wondered what happens if the sig is: private static void Main(int args[])?

The Main method is invoked from outside of the program. So it is, obviously, essential that the method be public. But would the program compile if it was private? The answer is: YES. It would compile. For some reason, not so obvious to me, the compiler/runtime doesn't see difference between a public and a private Main method. All it needs is a Main method.

So what if, in a program, we have two Main methods, either private or public or both? The compiler/runtime is confused. It doesn't know which is the actual point of entry. So, ambiguity! Hence, errors!

But what if for some reason you want to have two main methods? Can you make things work or is it the end of the road? It's definitely not the end. You can still make it work, with as many Main methods you want. Only condition being, the fully qualified name of the method (or the type containing it) should be different from each of the other Main methods.
namespace MainNamespace
{
class FirstMain
{
public static void Main(int args[]) {}
}

class SecondMain
{
public static void Main(int args[]) {}
}
}

To build this program use:
csc.exe Program.cs /main:MainNamespace.FirstMain

This will do the trick for you.
The next obvious question is how would we compile it using VS 2005? I would take this in my next post.

Friday, March 23, 2007

Software and Writing - A Bad Combination!!

For many know that I work in software but few know that I'm into writing too. And since I'm into Dot Net Framework, this is actually a real bad combination, for reasons that I discovered only yesterday.

Not that anything is wrong with software or writing. But both require me to be highly intellectual (of course, which I'm :-)). So my intellectuality is as follows:
class intellectuality
{
attention to detail; //for example
}

Now that I'm an intellectual, software and writing to me would be

class software : intellectuality
{
}

class writing : intellectuality
{
}


And I would become
class individual : software, writing
{
}
a clear example of multiple inheritence (Mind you! dot net framework doesn't allow this and "why" is what I'll try to address).

Now, I have a software class and a writing class defining me. And each of these two classes are, in turn, defined by one intellectuality class each. When we create an instance of "individual" class, instances of "writing" and "software" are implicitly created. And since writing derives from "intellectuality" an instance of "intellectuality" is also created. Same happens for software also. So, two intellectuality classes, one writing class and one software class define me.

Now where is all this (intellectuality) going to? Since all this, yet, doesn't make any sense, let's drill into it lil' more and see if this is of any use (otherwise you can always leave your brickbats in comments).

First problem here is, though I'm an individual with ability to code and write and strong intellectual skills, I'm being represented by two intellectual classes and not one. Mind you! I'm an intellect. i.e. Since "individual" derives from "writing" and "software", it should essentially have 3 base classes (writing, software and intellectuality) but it has 4 base classes (writing, software and two intellectuality classes).

Second, if I had to use my "attention to detail" ability from my "intellectuality", I do not know which one of the two intellectuality classes to make use of! Should I make use of intellectuality class of writing or of software? (personally I would prefer writing :-)) i.e. if we had to use a method or property of the base class "intellectuality" the runtime doesn't know from which instace to refer to (we have 2 instances created)!

Third, let's say I want to fill in my "intellectuality" with abilities in my "individual". So, I do
intellectuality intellect = new individual();
I'm essentially creating a base class as an instance of child class.
We have problems here. As we have already seen, "individual" ends up having two "intellectuality" sub classes and hence the compiler doesn't know which "intellectuality" object I'm trying to refer to!

These seem to be the "not so obvious" reasons for dot net framework banning Multiple Inheritence. This is also called as the "Diamond" problem. And as far as my life is concerned, it's far more simple and easier and, of course, devoid of "Diamond"(s)!!! :-) :-)

Thursday, March 22, 2007

An Obvious Mistake

class MyClass
{
private void Sample()
{
int i=10;
int i=20;
}
}

Will this code compile?
Obviously it wouldn't!!

But why wouldn't it compile?
Obviously because i has multiple declarations!!

But what is not so obvious is the reason behind not allowing multiple declarations. To talk about those not so obvious reasons, first of all one basic point. What happens when you say int i=10?

4 bytes of memory gets allocated, 10 is stored in it and the identifier 'i' points to it. Simple!

Now let's say we do multiple declarations for i, like in the above program. int i=10 allocates 4 bytes of memory and i points to it. Then we have int i=20. Another 4 bytes is allocated, 20 stored in it and, again, identifier 'i' points to this new memory. So when you use 'i' again anywhere, the compiler or runtime doesn't know which chunk of memory you are trying to reference to! Hence, undesired results!

This is the not so obvious reason for the program not compiling!