DCSIMG
December 2008 - Posts - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2013 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

December 2008 - Posts

.NET Zone's Top 10 Articles of 2008

.NET Zone's Top 10 Articles of 2008

Today I opened DZone, one DZone Site
of my favorite developer sites, 
and looked at the .NET zone top
10 articles of 2008
post which
was published recently by
Alvin Ashcraft. For my surprise, five of ten articles were my own.
I hope to continue and write interesting materials for you to read.

DotNetKicks Image

Creating Associations Between Objects in ADO.NET Data Services

Creating Associations Between Objects in ADO.NET Data Services

In today’s post I’m Creating Associations Between Objects in ADO.NET Data Services
going to show how to
create an association
between two objects
from a ADO.NET Data
service
.NET client and
how simple it is.

Creating Associations

Data services expose resources (entities) and links (associations). When
we generate a .NET client proxy the links (associations) are built as properties
of the objects. When we associate an object to another object we have to
explicitly tell the proxy to add the association. This is being done by the
SetLink method which is exposed through the generated client proxy.
The SetLink method notifies the DataServiceContext that a new link exists
between the objects it gets as parameters and to which property the link will
be generated. If you will try to insert an object to an association property and 
won’t use the SetLink method you should expect an exception.

Create Association Example

var proxy = new SchoolEntities(
    new Uri(ConfigurationManager.AppSettings["SchoolProxy"]));
proxy.MergeOption = MergeOption.AppendOnly;
 
var department = proxy.Department.First();
var course = new Course
{
    CourseID = 4000,
    Days = "MW",
    Credits = 4,
    Location = "Class A",
    Time = DateTime.Now,
    Title = "Bio Technology",
    Department = department
};
 
proxy.AddObject("Course", course);
proxy.SetLink(course, "Department", department);
proxy.SaveChanges();

In the example, there is an association between course and department.
departments can hold many courses and a course is associated to a specific
department. As you can see I set the Department property of course to be
the first department and then I have to explicitly call the SetLink method and
to indicate the property name (Department) in order to set the link.

Currently Implementation Problems

In the Using Microsoft ADO.NET Data Services article it is indicated that the
currently data services implementation “is designed for minimum footprint and
provides the primitives required to enable mapping data service operations to
.NET objects. For a future release, we are evaluating layering higher level semantics”.
This means that managing modifications to arbitrary object graphs with bidirectional
associations isn’t fully supported right now but will be supported in future releases.

Summary

Lets sum up, I showed in the post that to set an association between two associated
objects is done by using the SetLink method. You need to explicitly call that method
in order to establish the connection between the objects. Not calling that method will
result in an exception. Currently the data services framework is supporting the
minimum functionality to enable mapping but in future releases we should expect
the ability to manage modifications to arbitrary object graphs with bidirectional
associations.



DotNetKicks Image

When Good Developers and Bad Code Collide

When Good Developers and Bad Code Collide

I’m currently working on a major project in Bank Hapoalim.
The project is a mortgage pre and post sale web application which was written five years
ago and as such is full of legacy code. Also, I can tell that the project was badly designed.
Two years ago I started to work there with a new team and we had a primary secret
mission – clean the code from the horrors we saw there. Also, we tried and succeeded
to build a standard architecture and infrastructure from the rubbish that was there before. 
In this post I want to share with you my today’s experience which can tell you a lot
about how was the development in the project in the past.

Today I got to fix a bug that made me choke…

Apparently there is an error that raised its ugly head in a rare scenario which I
succeeded to find. So what was it you say?
In a legacy code I found a code that resemble the following lines:

Server.Execute("../DirName/PageName.aspx");
if (RequestInfo.IsBorrowerValid && RequestInfo.IsGuarantorValid)
{
    // Do Something
}

So probably now you ask yourself what is wrong with this code?
The answer is everything!
that code was written inside a page event and what it meant to do
is to execute another page in the background in order to fill the RequestInfo’s
validation properties and to save it in the session. The RequestInfo in
this code is a property of the calling page that returns the RequestInfo object that
was saved in the session and use the properties.

Why is it so bad?

The code will run another page in the background in order to do a business validation
check. Instead of using a business logic library and call a method inside of it we are
coupled to another page in our application which performs the validation we seek
during it’s page life cycle. Also, when someone changes things in PageName.aspx it
can have an impact on our current page which is the reason for the bug I was fixing
(which was an error in the PageName.aspx page that impacted the current page).
Another problem is that we wait to the executing of another page life cycle and we pay
in the performance of our page.

What can we do to fix this?

Refactor our code and write the business logic inside our BL.
After we have the logic inside the BL, we should call it to validate the things
we need.

What we gain?

More maintainable code. Simple code. No performance issues. No bugs that their source
isn’t in the context of our page and so on. Also, No mad developers like me wanting to
kick other developers or managers butts.

End of Story

I looked in the source safe to see who wrote the code and found out that none of
the current members of the team (I knew that before the check but I wanted to be
sure). I showed the code to the other members of the team and explain them how bad
it is. Also, I promised to cut their fingers if I ever see them write such a bad code
(just kidding).

DotNetKicks Image

My Developer Academy Experience

My Developer Academy Experience

Developer Academy 3

Yesterday I participated in the Microsoft Developer Academy 3 conference.
Microsoft Developer Academy is an annual Microsoft Israeli developers conference
which is dedicated to deliver knowledge about current technologies and about best
practices.
I went to the following sessions:

  • ASP.NET Ajax Internals, Dan Amiga.
    Great lecture! Dan is a great performer and the subject isn’t easy to deliver…
    (Try to deliver Ajax and JavaScript sessions which you write the code during the
    session and then you’ll get my point)
    I really enjoyed the lecture and even learnt some new stuff.
  • HTTP Web Services with Windows Communication Foundation 3.5, Eyal Vardi.
    The lecture was good. I talked with Eyal after the session and explained him my
    thoughts about the Data Services technology which was a little different from
    what he said. Also, I think that the subject is too big to deliver in a one hour
    and ten minutes session but I learnt a few things that I didn’t know. 
  • Concurrent Programming: From Thread Pool to Parallel Extensions, Sasha Goldstein.
    Great lecture! great lecturer! I always like to hear Sasha’s sessions because he
    deliver them with a lot of passion. That passion makes a great sessions.
    If I can minimize Sasha’s agenda in one sentence it will be –
    Start to develop concurrent applications today!
  • Design Patterns – Learn From the Experience of Others, Avi Rot.
    Good lecture. The subject is very hard to deliver and it’s even harder after the
    lunch break. Avi gave a lot of good advices which I hope people will adopt soon
    or else people like me will always have a job…
  • Building Web Sites with ASP.NET MVC Framework, Noam King.
    Great lecture! I heard few sessions about ASP.NET MVC framework in the past and I
    can tell that Noam’s is currently the best. I’m currently studying the subject and I
    got a few tips from the lecture to think about. 

During the sessions breaks I met with some of the Israeli develop community members
and I had fun to talk with them and with former colleagues from my previous job. 
I want to thank Microsoft for inviting me to the conference.
I really had a good time.
See you next time in Microsoft Developer Academy 4.

DotNetKicks Image

Eager Loading and Lazy Loading in ADO.NET Data Services

Eager Loading and Lazy Loading in ADO.NET Data Services

In today’s post I’m goingEager Loading and Delay Loading in ADO.NET Data Services
to explain how to achieve
eager loading and lazy loading
functionality with ADO.NET
data services
.NET clients.

What are Eager Loading and Lazy Loading?

Lazy loading is a design pattern that is commonly used to defer initialization of an
object up until it is needed by the program. The gains of using the pattern include
efficiency (if it’s used right) and sometime performance. Eager loading is the opposite
pattern of lazy loading. In this pattern we initialize the object before hand and don’t
wait to the second we really need it.

Lazy Loading in Data Service Client

The default behavior of a data service’s .NET client is not to load the entities’ associated
objects . When we request an entity we will get it from the service but its associated
objects will not load up at all. Lets say that I have two entities in my program – a course
and a department. The associations between the entities are that a department can have
a lot of courses and a course belongs to one department. When I load a department
it’s list of courses will be empty. trying to iterate the list of courses will give nothing
because the courses will not load until we tell them to be loaded explicitly. This is done by
the LoadProperty method of the data service context. Lets look at an example:

protected void Page_Load(object sender, EventArgs e)

{

    var proxy = new SchoolEntities(

        new Uri(ConfigurationManager.AppSettings["SchoolProxy"]));

    proxy.MergeOption = MergeOption.AppendOnly;

    PrintDepartmentsToResponse(proxy);

}

 

private void PrintDepartmentsToResponse(SchoolEntities proxy)

{

    foreach (var department in proxy.Department)

    {

        Response.Write(string.Format(

            "Department ID: {0}, Department Name: {1}, Department Budget: {2}",

            department.DepartmentID,

            department.Name,

            department.Budget));

        proxy.LoadProperty(department, "Course");

        foreach (var course in department.Course)

        {

            Response.Write(string.Format(

                "Course ID: {0}, Course Title: {1}",

                course.CourseID,

                course.Title));

            Response.Write("<br/>");

        }

        Response.Write("<br/>");

    }

    Response.Write("<br/>");

    Response.Write("<br/>");

}

In the example I’m using a built SchoolEntities proxy. I iterate the list of departments
That will arrive to the client once I loop them in the foreach loop. As you can see
I’m using the proxy.LoadProperty method that gets two parameters – the object to
work with and the property to lazy load. After loading the property I can iterate and
write the courses to the response output. The result of running this code will be
something like:
Running result

Eager Loading in Data Service Client

The lazy loading scenario that I showed in the previous example will send a HTTP request
to the data service’s server for each course list. This lazy load behavior can cause
sometime a decrease in the performance because of extra unnecessary round-trips. In the
previous example we could fetch the courses with the department when we requested the
department. The way to achieve the eager loading behavior is by using the $exapnd Uri
syntax. The $exapnd is used to indicate that we want inline expansion for our objects.
Lets look at the same example from the previous example but in eager loading scenario:

protected void Page_Load(object sender, EventArgs e)

{

    var proxy = new SchoolEntities(

        new Uri(ConfigurationManager.AppSettings["SchoolProxy"]));

    proxy.MergeOption = MergeOption.AppendOnly;

    PrintDepartmentsToResponse(proxy);

}

 

private void PrintDepartmentsToResponse(SchoolEntities proxy)

{

    var departments =

        proxy.Execute<Department>(new Uri("Department?$expand=Course",

            UriKind.Relative));

    foreach (var department in departments)

    {

        Response.Write(string.Format(

            "Department ID: {0}, Department Name: {1}, Department Budget: {2}",

            department.DepartmentID,

            department.Name,

            department.Budget));

        foreach (var course in department.Course)

        {

            Response.Write(string.Format(

                "Course ID: {0}, Course Title: {1}",

                course.CourseID,

                course.Title));

            Response.Write("<br/>");

        }

        Response.Write("<br/>");

    }

    Response.Write("<br/>");

    Response.Write("<br/>");

}

The same result will be printed to the response’s output.

Summary

Lets sum up, in today’s post I explained how to use eager loading and how
to use lazy loading in an ADO.NET data service’s .NET client. The use of these patterns
can have an impact on the program performance and therefore should be use wisely.

DotNetKicks Image

Building a Host for ADO.NET Data Service

Building a Host for ADO.NET Data Service

After you built your Building a Host for ADO.NET Data Service
data service you will
probably want to deploy
it. In the following post
I’m going to explain
how you can build
a simple host for an ADO.NET data service without the use of svc file.

Data Service Hosting

The ADO.NET data services are not autonomous server entities.
They live in the context of their service host such as WCF or ASP.NET.
The data service host is handling the direct interactions with the network
and supports caching, scalability and authentication modules for the data service.

DataServiceHost Class

The first thing to know if you want to deploy a data service is the DataServiceHost
class. The DataServiceHost derives from WCF WebServiceHost class and holds it
capabilities. The WebServiceHost class automatically configures address, binding and
contract for its underlining service and therefore eliminates the need for lots of
configurations. Using the DataServiceHost simplifies the deployment scenario.

A Simple Deployment Example

The following example is a console application the hosts a simple data service:

#region Classes

public class Course

{

    #region Properties

    public int CourseID { get; set; }

    public string Title { get; set; }

    #endregion

}

public class CourseContext

{

    #region Members

    private static List<Course> _courses;

    #endregion

    #region Properties

    public IQueryable<Course> Courses

    {

        get

        {

            return _courses.AsQueryable();

        }

    }

    #endregion

    #region Ctor

    public CourseContext()

    {

        _courses = new List<Course> {

            new Course{ CourseID= 1, Title="Calculus"},

            new Course{CourseID = 1, Title="Data Structures"}

        };

    }

    #endregion

}

#endregion

#region Data Service

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]

public class SimpleDataService : DataService<CourseContext>

{

    // This method is called only once to initialize service-wide policies.

    public static void InitializeService(IDataServiceConfiguration config)

    {

        config.SetEntitySetAccessRule("*", EntitySetRights.All);

    }

}

#endregion

class Program

{       

    static void Main(string[] args)

    {

        Uri baseAddress =

            new Uri(ConfigurationManager.AppSettings["HostLocation"]);

        DataServiceHost host =

            new DataServiceHost(typeof(SimpleDataService),

                new Uri[] { baseAddress });

        host.Open();

        Console.WriteLine(

            string.Format("Host running - {0}",

            ConfigurationManager.AppSettings["HostLocation"]));

        Console.WriteLine("Press any key to shut down service...");

        Console.ReadKey();

        host.Close();

    }

}

The example include an entity class that is called Course, a data context
that is called CourseContext, a data service that is called SimpleDataService
and the program itself. The program creates a new DataServiceHost and
gives it the URI to work with. The URI is located in the application settings of
the web.config file. The value of the HostLocation key is http://localhost:8090/.
That is all. The DataServiceHost will instantiate the data service and will host it
for you.

Summary

Lets sum up, it is very easy to build a WCF hosting environment for our data service
using the DataServiceHost class. In the post I showed a simple deploy example
of how to do it. The post didn’t discuss the regular web deployment scenarios
that you can use to deploy data services (such as deploy an ASP.NET
application/site that includes a data service into IIS for example).

DotNetKicks Image

ADO.NET Data Services Slide Deck

ADO.NET Data Services Slide Deck

Today I had an ADO.NET ADO.NET Data Services Slide Deck
data services session in the
The Israel Visual Basic User Group
(IVBUG)
. The session agenda:

  • Why ADO.NET Data Services at All?
  • Data Services Architecture in a Nutshell
  • Creating and Consuming Data Services

As promised the slide deck and demos (in C# and in VB) can be downloaded from here.
I want to thank Jackie Goldstein for the opportunity to lecture in IVBUG.
Also, I want to thank all the participants of the session.
I really had a good time.

P.S. – a backup of the database that I used in the demos is located in the
solution root.
Enjoy.

DotNetKicks Image