Wednesday, October 20, 2010

Working with Entity Framework 1.0 and Stored Procedures - map complex data types

Working with Entity Framework 1.0 and Stored Procedures – how to deal with complex data  types
Last months  I worked on a ASP.NET project with Entity Framework.


The key requirement for a project was to use .NET Framework 3.5 not 4.0, so I used older version of EF that was included in .NET Framework 3.5 Service Pack 1.
 I also must use SQL Server with Stored Procedures, instead of great features from the EF - LINQ.
Entity Framework is not a nice tool. But the problem is when I started to use Stored Procedures instead of generated SQL queries from LINQ.

To get started I recommend following articles:

Microsoft documentation - Quickstart (Entity Framework)
ADO.NET Entity Framework Tutorial and Basics:
ADO.NET team blog: Stored Procedure Mapping

Many examples in Microsoft documentation and blog posts does not show, how to deal with complex types by using Entity Framework and Stored Procedures?

The biggest drawback is, that the references are not automatically loaded by creating instances of objects. This means that child collection and child objects references are equal to null.
(This is not a problem when you are using LINQ. You write a LINQ query, SQL query will be generated and objects hierarchy is populated as you need: See example here.)

When working with EF 1.0 with Stored Procedure, you must deal with a problem manually.



1)      Write  “Select”  Stored Procedures  for object type you need and for all object types you need to reference.
- Select SP for root object - that return one data row by ID
- Select SP for single child objects - that return one data row by a parent ID
- Select SP for child collections - that returns a list of data rows by a parent ID

Because references are empty, you need to realize it with SQL Inner Joins, and query objects by a parent ID.

Example:

When we have such object hierarchy:




Select SP for root Account type:

Create Procedure [dbo].[usp_Account_SelectRow]
      @ID bigint
As
Begin
      Select
            [ID],
            [Name],                
            [AccountTypeId],
            [Supervisor],          
            [ManagerName],
            [Created],
            [Modified]
      From Account
      Where
            [ID] = @ID
End

GO

                Select SP for child type Account Type. Here important is that you load AccountType data by Account.ID by using inner join ( 1 to N relation)

Create Procedure [dbo].[usp_AccountType_SelectRowsByAccountId]
 @AccountID bigint
As
Begin
 Select
  AccountType.ID,
  [Code],
  AccountType.Name as Name
 From AccountType inner join Account on AccountType.ID = Account.AccountTypeId
 Where
  Account.ID = @AccountID
End

GO

Select SP for child collection accountObjectives is similar, the difference is, that it return whole list of data rows (N to N relation)
CREATE Procedure [dbo].[usp_AccountObjective_SelectRowsByAccountId]
      @AccountId bigint
As
Begin
      Select
            [ID],
            [AccountId],
            [ProductId],           
            [Titel],
            [Ranking],
            [Created],
            [Modified]
      From AccountObjective
      Where
            [AccountId] = @AccountId
      Order by [Ranking]
End

SET ANSI_NULLS ON

GO

2)      Map all “Select”Stored Procedures to the Methods using “Function Import” in Visual Studio EF Model browser.





3)      Loading root object by using Imported select function. Attach needed child objects and child collections
In this example I load Account object and its referenced AccountType child object.

        public Account FindById(long id)
        {
             SelectedItem = _dataContext.FindAccountById(id).First();           

            var accountType = _dataContext.GetAccountTypeForAccount(id).ToList();
            if(accountType.Any())
            {
                SelectedItem.AccountTypeReference.Attach(accountType.First());  
            }

            if(IsAuthorizedForSelectedAccount)
            {
                return SelectedItem;   
            }
            else
            {
                throw new ApplicationException("The user does not have permission for selected Account.");
            }           
        }

Friday, October 8, 2010

UpdateProgress in AJAX , how to get an animated icon?

Recently I had to use some AJAX controls in ASP.NET application.

To user friendly handle waiting for a server response,   I use ProgressBar Control.
On Scott Guthrie blog I found nice link to a page, where you can create your own animated icon

http://www.ajaxload.info/


I placed my ProgressBar control on a master page, so I have a solution for a whole web application in one place. Below my complete Master page:


DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title><asp:Literal ID="LiteralTitle" runat="server" Text="" />title>
    <link href="./css/eA.css" type="text/css" rel="stylesheet" />
head>
<body onkeydown = "return (event.keyCode!=13)">
    <form id="form" runat="server">
        <asp:ToolkitScriptManager ID="ToolkitScriptManager" runat="server" ScriptMode="Release" EnableScriptLocalization="true" EnableScriptGlobalization="true" />
        <asp:UpdateProgress ID="progress1" runat="server">
            <ProgressTemplate>       
                <div class="Progress">               
                    <img src="Images/ajaxloader.gif"/>Please wait ...
                div>       
            ProgressTemplate>       
        asp:UpdateProgress> 
        <div class="TopNavigation">
            <eA:TopNavigationControl Id="TopNavigationControl" runat="server"/>
        div>
        <div class="TopNavigation">
            <eA:SubMenuNavigationControl Id="SubMenuNavigationControl" runat="server"/>
        div>               
        <div class="BasicDataView">
            <eA:AccountBasicDataShortControl Id="AccountBasicDataShort" runat="server"/>
        div>     
        <asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server">asp:ContentPlaceHolder>
        <div class="Footer">
            <eA:FooterControl ID="FooterControl" runat="server"/>
        div>
    form>
body>
html>

Thursday, April 22, 2010

SharePoint object model explorer

After reading "Building the SharePoint User Experience" the book of  Bjørn Christoffer Thorsmæhlum Furuknap, I start using new tool - SharePoint Manager 2007/2010

It is SharePoint object model explorer available for free on codeplex:
http://spm.codeplex.com/

"Ghosted" and "unghosted" files. How exactly it works?

Last weeks I still improve my knowledge and skills in SharePoint development
I also  try to get better understanding about SharePiont architecture

I always known about "ghosted" and "unghosted" files in SharePoint, but here this is very good explained by Andrew Connell (Microsoft MVP)

Understanding and Creating Customized and Uncustomized Files in Windows SharePoint Services 3.0

Monday, March 29, 2010

Back to the world of SharePoint

After many months break, I start to work with SharePoint technologies again,
I jump into the new version SharePoint 2010.

Helpful ressources to start learning new Sharepoint are on the MSDN Sharepoint Developer Center

To get better understanding how SharePoint work and how to implement SP solutions I recommend this book:

Building the sharepoint user experience

My favorite SharePoint blogs are:

http://www.andrewconnell.com/blog/Default.aspx
http://blogs.msdn.com/sharepointdeveloperdocs/default.aspx
http://www.sharepoint-tips.com/
http://blogs.msdn.com/sharepoint/default.aspx
http://blogs.msdn.com/sridhara/default.aspx

Thursday, February 25, 2010

Reporting Services - very helpful blog

This is very helpful blog about Reporting Services

http://blogs.msdn.com/chrishays/

Reporting Service 2005 - top values? - limit the number of displayed data rows

Sometimes I need to show only top 5 values from defined data source in the data table, without setting the number of rows in SQL query (top statement).

In data table set visibility expresion for a table row to:

=iif(RunningValue(Fields!Id.Value, CountDistinct, nothing) > 5, true, false)

Thursday, February 11, 2010

Dynamic LINQ

Scott Hanselman blogs about dynamic linq query generation.


I find this article very interesting


I already worked on the similar problem some times ago and I blogged my solution  here :

LINQPad

LINQPad


Very nice tool for to query Database with LINQ

Wednesday, January 20, 2010

Reporting services: show value with line breaks between words

I need to display value as a list separated with coma and line break.


I found great tip, how to realize line breaks in reporting services here:
http://www.kodyaz.com/articles/reporting-services-add-line-break-between-words-custom-code.aspx

very helpful custom code function:

Public Function AddLineBreakBetweenWords(words As String) As String
Dim rsRegEx as System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex("\s+")
words = rsRegEx.Replace(words, " ")
return words.Replace(" ", vbCrLf).Trim()
End Function
 
 
 

Thursday, January 14, 2010

Cool web designer tool

http://www.artisteer.com/

This is web designer tool for people like me, who are software developer not web designers.

Whole web site you can easly export to ASP.NET as the Visual Studio solution

Manipulate multiple object in sql server management studio

I had a problem to select more the one object in management studio,
in object explorer you can select only one item.

I found a very helpful tip described by Ken Simmons http://www.mssqltips.com/tip.asp?tip=1911

Just open Object Explorer details view (by default its a window on the right) and there you can select and manage multiple objects