Wednesday, August 18, 2010

Entity Framework 4.0- Bind Stored Procedure with Result Entity class

Microsoft Entity Framework version 4.0 is a brand new ORM(Object Relational Mapper) from Microsoft. It’s provides now some new features which are not there in the earlier version of Entity framework. Let’s walk through a simple example of a new features which will create a new Entity class based on stored procedure result. We will use same table for this example for which they have used earlier for Linq Binding with Custom Entity.

Below is the table which have simple fields like first name,last name etc.

SQL Table for Entity Example.

Let’s insert some data like following.

Sample data for Entity Framework Example

Below is the stored procedure which I am going to use for this example which will simply fetch data from the table.

CREATE PROCEDURE dbo.GetAllUsers

AS
SET NOCOUNT ON
SELECT
UserId,
UserName,
FirstName,
LastName,
FirstName + ' ' + LastName AS [FullName]

FROM dbo.Users
Now let’s create Entity model class just like below via Project->Add New Item->Go to Data tab and then select ADO.NET Entity Data Model.

Adding a New Enity model class for Entity Framework example

Once you click add a dialog box will appear which will ask for Data Model Contents there are two options Generate From Database and another one is Empty Model. Generate from database will create a Entity model from the ready made database while Empty model enable us to create a model first and then it will allow us to create a database from our model. We are going to use Generate From database for this example. Select Generate From Database like following and click Next.

Generating Model from database for Entity Framework 4.0 Example

After click on the next it will ask for database connection string like following where you need to apply connection string for that. I am already having connection string in my web.config so i just selected like below otherwise you need to create one via clicking on new connection. Also you need to specify the connection string name in web.config so it will put a connection string in connection string section with that name.

MyConnection

Once you click next it will fetch the all database objects information like Tables,Views and Stored Procedure like following. Here our purpose is to work with stored procedure so I just selected the stored procedure and selected the GetAllUsers Stored Procedure.

Selecting Stored procedure

After that it will create a Entity Model class in solution explorer.Now we want to bind the stored procedure with result class so first we need to create function which will call ‘GetAllUser’ stored procedure. To create function we just need to select Our Entity Model class and then go to Model Browser and select the Stored Procedure and right click->Add Function Import like following image.

Importing a function from stored procedure example.

It will start a new wizard and will go to next step like following image which will have four options 1. None 2. Scalars 3. Complex 4. Entities and there will be a button Get Column information once you click it. It will gather all the column information of stored procedure result set and then click ‘Create New Complex Type’ It will create a new complex type from the gathered column information.

Gathering a column info and then

You can also rename that class so I have renamed the class as ‘User Info’ like following.

UserInfo

Now click ok and now it will create function which call the stored procedure and will return Object Result set of Type ‘UserInfo’ which we have just created. Now let’s bind that to a simple grid view to see how its works. So Let’s take a simple grid view like below.

<asp:GridView ID="grdUserList" runat="server">
</asp:GridView> 
Now Let’s bind that grid view like following from the code behind file of asp.net like following.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (BlogEntities myEntity = new BlogEntities())
{
grdUserList.DataSource = myEntity.GetAllUsers();
grdUserList.DataBind();
}
}

}
Just run it with Ctrl + F5 and below it the output in browser.

Output of Entity Framework 4.0 Example

That’s it very easy and simple to bind complex type with stored procedure using ADO.NET Entity Framework 4.0. Hope this will help you.. Happy Programming!!!

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:
Tuesday, August 3, 2010

Binding A Custom Entity Class to stored procedure using Linq-To-SQL

I have already written several post about Linq its a great ORM that we can use in various way. The purpose of this post to demonstrate How we can bind custom entity to stored procedure result with use of Linq-To-SQL. Let’s go through it and you will realize that how easy it will be to bind a Custom Entity to Stored Procedure result.

Let’s first create a simple table to which will hold the user data. It will contain four field like UserId,UserName,FirstName and LastName like following.

SQLTable

Now let’s insert some data into the table like following. SQLTableData

Now let’s create a stored procedure which will return the table data and a new field called Full Name like following. Here full name is a combination of first name and last name

CREATE PROCEDURE dbo.GetAllUsers

AS
SET NOCOUNT ON
SELECT
UserId,
UserName,
FirstName,
LastName,
FirstName + ' ' + LastName AS [FullName]

FROM dbo.Users
After creating a stored procedure it time to create a Linq-To-SQL Right Click Project->Add New Item and Go To->Data and Add LINQ to SQL Classes called MyBlogDataContext.dbml.After creating datacontext class for Linq just drag above store procedure to Linq-To-SQL classes and it will create a function like following.

StoredProcedureInLinqClass

Now let’s add a New Entity Class called UserInfo into Linq-To-SQL DataContext via Right Click Add New Class Just like following.AddClass

After adding class I have added same property as its having in user table and Hence our UserInfo Class will look like following.

UserInfoClass

Now everything is ready Custom Entity Class called UserInfo and we have Our Function ready which will return Stored Procedure output. Here Linq-To-SQL Provides a property called ReturnType If you select function which we have created via dragging a stored procedure in data context class. We just need to select our UserInfo class there just like following and it will bind the stored procedure with that particular UserInfo class. here only condition should be satisfied that Our Custom Entity class should contain all the field with compatible .NET Data types which will return the data. Below is the property which we are talking about.

SelectProperty

Now let’s add grid view to default.aspx page like following and Let’s bind output of stored procedure to that grid view.
<asp:GridView ID="grdUserList" runat="server">
</asp:GridView> 
After placing the Grid View in page here is the code for biding grid view in default.aspx page_load event.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (MyBlogDataContextDataContext myContext =
new MyBlogDataContextDataContext())
{
List<UserInfo> MyUserList =
myContext.GetAllUsers().ToList<UserInfo>();
grdUserList.DataSource = MyUserList;
grdUserList.DataBind(); 
}
}
}
And here is the output which we get in browser after running our web application.

Ouput

That’s it its very easy.. Hope this will help you…

Shout it
Share:
Sunday, August 1, 2010

Visual Studio –>Add Database –> Named pipe Provider Error for SQL Server

Recently I have been working on a article for my blog for that I just tried to add a database file on my solution with visual studio and I have received following error.

An error has occurred while establishing a connection to the server.
(provider: Named Pipes Provider, error: 40 – Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 5)
An error has occurred while establishing a connection to the server.  When connecting to SQL Server 2008, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 – Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 1326)

After checking my configuration I have found that in my machine there was more then one instance of SQL Server and the Default Instance was not properly configured and that’s why I am getting this error. This error was occurred because my Default Instance of SQL Server Express was not having TCP/IP Protocol Enabled. So I have enabled it just like following.

Go to All Programs->Microsoft SQL Server 2008-> Configuration Tools –>SQL Server configuration manager. It will open up windows like following.

SQLServerConfiguration

After that Go To SQL Server Network Configuration and Select Protocols for your default instances and then enabled TCP/IP like following and that’s it. Now error is resolved.

SQL Server TCP/Ip Protol configuration
Hope this will help you…

Technorati Tags: ,
Shout it
kick it on DotNetKicks.com
Share:

TSQL Challenges on beyondrelational.com

My friend and Guide Jacob Sebastian who is an Microsoft SQL Server MVP running a very popular series of TSQL on his site beyondrelational.com. If you know something about SQL Server then this challenge is for you. And if you are master of SQL then this challenge is for you to test you knowledge. If you have some time and If you want to test you knowledge or you want enhance your knowledge challenge then please spare some time to take it. Here is link for that.

http://beyondrelational.com/blogs/tc/archive/2010/07/26/tsql-challenge-35-find-the-total-number-of-full-attendees-in-each-24-hop-session.aspx

Currently he is running TSQL Challenge Number 35 which is about fine number full attendee for a conference.

Shout it
Share:
Friday, July 30, 2010

Reboot require check fails while installing SQL Server 2008 R2 Express

Before some days i was installing SQL Server 2008 R2 Express edition on my machine and every time when it runs checks for required settings it was failing giving error reboot required. I have rebooted my machine several time and result was same. After that i have search it on internet and found that was due to some registry settings. To pass this check you need to remove following entries.

  1. Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager
  2. Then find PendingFileRenameOperations and remove all the data related with it

After that just i just run install the SQL Server 2008 R2 on my machine and through my surprise it was working fine. I found great tip from the following URL through it was for SQL Server 2008 but it works fine with SQL Server 2008 R2 also.

http://blog.dragonsoft.us/2008/11/08/tip-installing-sql-server-2008-reboot-required-check-fails/

Hope this will help you..Happing coding

Shout it
kick it on DotNetKicks.com
Share:
Thursday, July 22, 2010

Why a developer should blog?

I have been blogging since last three year on my BlogSpot blog and it was quite fun writing blogs. I have started a blog as repository of my technical things and  but after some posts I realize that there are lots of people are using it and It’s a great way to express your feelings about Technical things. I have been promoting blogging among my friends and people and lots of people ask me that why a developer should blog if he has good knowledge what ever domain he is working why he should blog? A developer should only concentrate on technical things rather then writing blog or taking part in the community but I am not agree with that. Even some developers has started blogging and after some time they not writing due some reasons. Here are some facts that why a developer should blog.

  • Blogging is a great way to express your feeling about anything that you blog. Whether It’s a technical blog or whatever you are blogging about.
  • Through your blog you can show your technical expertise to real world and you can market your self. Who knows some employer are watching your blog and will offer you a job based on your technical things you are blogging.
  • You can create a repository of your technical things and later on you can retrieve that from your blog whenever you need them.
  • Teaching new things to other people is best way to learn. If you teach people they will have some question and you will become mature in that technology.
  • It will also increase your writing capabilities which will help you to manage document,write document and other things at your professional front. My writing skills are much better then when i write my first blog post.
  • Through blog you are communicating with real world and it will enhance your communication skills.
  • There are some prestigious award Like Microsoft MVP which you can only get if you are doing community work or blogging. I just have been awarded as Microsoft MVP for visual C# because of my blogging and community work.
  • After writing your blog post just read your blog post you will feel proud whatever you did.

I have also seen that lots of developers are started blog and then after some time they have decided to quit from blogging and here are some common reason.

  • I don’t have time to blog. Time management is very important thing and a Google calendar can be your friend. You can write events and notes to calendar and it will remind you that you have blog about this in this time line. One of my Friend and Guide Jacob teach me this technique. He is writer of several SQL Server books and an Microsoft MVP for SQL Server.
  • I am  not an expert of technology or I don’t know about latest technology. Lot’s of people told me what we should blog I don’t know much about latest technology. Here is my answer for that you don’t have to write about latest technology or latest trends you just need to write what you know whether it’s a new or whether its old. I am confess still I don’t know lots of things but I am blogging about whatever i know or whatever i have lean in recent days. Most of visitor of your blog will come for small articles not a advance technical articles.
  • I am not getting page hits  for my blog. Well, you don’t have to blog for page hits or anything else. Just write blog and read your post and feel proud of whatever you did. For page hits you can optimize you blog for search engine and through search engine optimization you will get page hits. 
  • I am not getting positive comments for my blog. Well, People are more negative then being positive for what ever we did. Try to do your best and comment moderation will help you for this. Now days are every blogging plate form is having comment moderation. Just feel proud of whatever you did and then after some time you will realize there are so many peoples are there who are encouraging you to write more. One good comment is more encouraging then three negative comments. You will also find people who is going to tell you are writing blogs and you don’t know simple things you should have this knowledge they all are afraid of you because they know that you are far better then them. So don’t put your concentration on that just ignore them because everyone can not master everything.

Hope this will help you.. Still you have not started blogging then start it right away. 

Technorati Tags: ,,
Shout it
Share:

New MSDN Home Page Layout

As Microsoft MVP Microsoft have provided me MSDN Subscription and I was looking at the content of MSDN. I was browsing the India MSDN page but one interesting I have found that there is different page layout for us then India I like the MSDN layout very much It’s categorized in different categorize like desktop,web,cloud and click on each big Icon it will redirect to particular category content. Here is the screenshot for it.

NewMsdnPage

Technorati Tags:
Shout it
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews