Showing posts with label LLBLGEN. Show all posts
Showing posts with label LLBLGEN. Show all posts

Wednesday, February 27, 2008

ObjectContainerDataSource, FormViews and LLBLGen Entities

I've always run into issues with databinding in ASP.NET 2. It is nice and straightfoward with basic examples, but there always seems to be some scenario that causes an event to fire at an unexpected time, stuffing things up.

I am currently using the Web Client Software Factory (WCSF) by Microsoft patterns & practices and one of the little gems in this is the ObjectContainerDataSource. This datasource implements data binding in a way that easily integrates with the MVP pattern. That is, the Select/Update/Delete events can be passed on and handled by the Presenter. If you are doing web development and are not aware of the WCSF, it is worth checking out.

This all seems fine, until I wanted to bind to an LLBLGen entity (LLBLGen is an easy-to-use and inexpensive O/R mapper). The LLBLGen entity had a Timestamp field on it that was used for optimistic concurrency - it was read-only and the optimistic concurrency checking would ensure that the Timestamp field had not changed on the database since the entity was fetched.

On an Update operation I found the ObjectContainerDataSource was creating a new instance of my entity and updating only the properties that were databound in the FormView on my page. No primary keys, no foreign keys, no timestamp fields; by the time I was trying to handle the Update event in the Presenter, I had an instance that supposedly new, with no relationships. Argh!

I found some related entries in the WCSF Discussions, but no one had a good solution that suited me and my LLBLGen entity.

One of the good things about the WCSF is that you get code, and the ObjectContainerDataSource is provided in its own project. I've now made some modifications to it that works the way I believe it should. Basically, instead of creating a new instance of the type you are binding to and updating the bound properties on that, the current instance (that is cached on the ObjectContainerDataSource after the Selecting event is called) is used and its properties are updated with the new databound values. This gives you the state of the entity as it was when you fetched it with the exception of the changes made through databinding. This is the behaviour I would have expected initially.

Note: to get access to the WCSF source, you'll need to install the source separately after you have installed the WCSF. Default folder is:

C:\Program Files\Microsoft Web Client Factory\Source Code\

So, the new ExecuteUpdate method in ObjectContainerDataSourceView.cs looks like this:


protected override int ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues)
{
Guard.CollectionNotNullNorEmpty(keys, String.Format(CultureInfo.CurrentCulture,
Properties.Resources.NoKeysSpecified), "keys");
Guard.ArgumentNotNull(values, "values");

ObjectContainerDataSourceUpdatingEventArgs updatingEventArgs =
new ObjectContainerDataSourceUpdatingEventArgs(DictionaryHelper.GetReadOnlyDictionary(keys),
values, oldValues);
OnUpdating(updatingEventArgs);
if (updatingEventArgs.Cancel)
return 0;
//
// -------------------------------------------------------------
// This section has been modified to keep the old instance and
// update the appropriate fields on it that changed through
// databinding. If no old instance found, a new instance is
// created.
//
int rowsAffected;
object newInstance;
object oldInstance = FindInstance(keys);
if (oldInstance != null)
{
TypeDescriptionHelper.BuildInstance(values, oldInstance);
rowsAffected = 1;
newInstance = oldInstance;
}
else
{
newInstance = CreateInstance();
TypeDescriptionHelper.BuildInstance(keys, newInstance);
TypeDescriptionHelper.BuildInstance(values, newInstance);
rowsAffected = 0;
}
//
// -------------------------------------------------------------
//
OnDataSourceViewChanged(EventArgs.Empty);

ObjectContainerDataSourceStatusEventArgs updatedEventArgs =
new ObjectContainerDataSourceStatusEventArgs(newInstance, rowsAffected);
OnUpdated(updatedEventArgs);

return rowsAffected;
}

The Delete operation is affected in a similar manner, so it has also been updated:

protected override int ExecuteDelete(IDictionary keys, IDictionary oldValues)
{
Guard.CollectionNotNullNorEmpty(keys, String.Format(CultureInfo.CurrentCulture,
Properties.Resources.NoKeysSpecified), "keys");

ObjectContainerDataSourceDeletingEventArgs deletingEventArgs =
new ObjectContainerDataSourceDeletingEventArgs(DictionaryHelper.GetReadOnlyDictionary(keys),
oldValues);
OnDeleting(deletingEventArgs);
if (deletingEventArgs.Cancel)
return 0;

int rowsAffected;
object instance = FindInstance(keys);
if (instance == null)
{
rowsAffected = 0;
//
// -------------------------------------------------------------
// This section has been modified to only create a new instance
// if an old one cannot be found. Moved up from below this if()
// statement.
//
instance = CreateInstance();
//
// -------------------------------------------------------------
//
}
else
{
Data.Remove(instance);
rowsAffected = 1;
}
TypeDescriptionHelper.BuildInstance(oldValues, instance);
TypeDescriptionHelper.BuildInstance(keys, instance);
OnDataSourceViewChanged(EventArgs.Empty);

ObjectContainerDataSourceStatusEventArgs deletedEventArgs =
new ObjectContainerDataSourceStatusEventArgs(instance, rowsAffected);
OnDeleted(deletedEventArgs);

return rowsAffected;
}

These changes should work with any class, not just LLBLGen entities. For me, retaining the Timestamp value was the most important (for optimistic concurrency as I mentioned earlier), and there is no way to set that externally. I am going to go out on a limb here and say that this probably applies to most O/R mappers.

I'd be glad to here from anyone who has had similar issues or has found a better solution.

Thursday, December 27, 2007

Optmistic Concurrency withTimestamps, LLBLGen and Web Services

Found a great article on how to implement optimistic concurrency with LLBLGEN and SQL Server:

Optmistic Concurrency and Timestamps in SQL Server Using LLBLGen Pro O/R Mapper by David Hayden.

Now, I am using XML Web Services and passing entities back and forth, and what I have found is that the DBValue property on each field is NOT serialized! I have not found a better solution as yet, but I am currently just using the field's CurrentValue. So, assuming the timestamp properties used do not get changed on the client, it will work, but this is a problem that will need to be fixed.

Update: Looks like there was an issue with the deserialization in version 2.5 (October 25 2007 release). The December release has apparently fixed this issue:

http://www.llblgen.com/TinyForum/Messages.aspx?...

Modifications with LLBLGEN 2.5

I am inherently lazy, which is a bad thing when it comes to coding, but the solution described by LLBLGEN's help and David Hayden relies on a factory class for each entity. Sure, we should probably modify the templates and create a new factory class for each of our entities, but for what I wanted, that sounded like too much work.

Now, in LLBLGEN 2.5, all entities are now derived from another generated partial class called CommonEntityBase. And, lets face it, we are probably going to create our timestamp field on every entity and call it the same name (in this case, every entity has a timetamp field called LastModified). So, I created a new partial class definition for CommonEntityBase that allows me to get access to the timestamp field I will use for all entities' concurrency control.

public partial class CommonEntityBase
{
private const string LAST_MODIFIED_FIELD_NAME = "LastModified";

public IEntityField2 LastModifiedField
{
get { return this.Fields[LAST_MODIFIED_FIELD_NAME]; }
}
}

This then allows me to create a single factory for concurrency predicate expressions:
public class EntityConcurrencyFactory : IConcurrencyPredicateFactory
{
public IPredicateExpression CreatePredicate(ConcurrencyPredicateType predicateTypeToCreate,
object containingEntity)
{
IPredicateExpression toReturn = new PredicateExpression();
CommonEntityBase entity = (CommonEntityBase)containingEntity;

switch (predicateTypeToCreate)
{
case ConcurrencyPredicateType.Delete:
case ConcurrencyPredicateType.Save:
// only for updates
toReturn.Add(new FieldCompareValuePredicate(entity.LastModifiedField,
null, ComparisonOperator.Equal, entity.LastModifiedField.CurrentValue));
break;
}
return toReturn;
}
}

Two classes for all entities - sounds good to me. Now, using David's example, there isn't any difference in the code (just every entity uses the same factory):
DataAccessAdapter adapter = new DataAccessAdapter(...);

BlogEntity blog = new BlogEntity();
blog.BlogId = 1;

adapter.FetchEntity(blog);

blog.Name = "New Name";

IPredicateExpression expression = new EntityConcurrencyFactory()
.CreatePredicate(ConcurrencyPredicateType.Save, blog);

adapter.SaveEntity(blog, true, expression);

You can still change optimistic concurrency strategies easily, but it is easier to apply to all of your entities at once.

Tuesday, November 27, 2007

Using LLBLGEN Generated Classes with Web Services

UPDATE: This only applies to version 2.0.

If you are using LLBLGEN with Web Services and you want to return entities and views to the client, you should have configured your machine to work according to the LLGBLGEN article titled Generated code - XML Webservices support.

This works nicely with Entity Classess, and probably Typed Lists (which I haven't used/tested yet), but there is a problem with Typed Views. If you have a Web Method that returns one of your Typed Views, you are probably getting errors generating the proxy classes, or the type specified in the proxy class that is generated does not match the Typed View in your Web Method!

There appears to be a bug in the webServiceHelper.template file that is used by the LLBLGEN generator. You can find this file in the following directory:

C:\Program Files\Solutions Design\LLBLGen Pro v2.0\Templates\SharedTemplates\Net2.x\C#

Open the file in a text editor and look for the following line in the "TypedView Classes" region:

return new XmlQualifiedName("<[CurrentTypedListName]>TypedList", namespaceToUse);

Change the above line to:

return new XmlQualifiedName("<[CurrentTypedViewName]>TypedView", namespaceToUse);

Now instead of having every one of your typed views with an XmlQualifiedName of TypedList, it is actually to the name of the class. Look in WebServiceHelper.cs (or WebServiceHelper.vb) to confirm this change is working.

I generally find that these changes only affect the proxy generation when the service reference is recreated; updating the reference doesn't always work.

Powered By Blogger