Outrageous Self-Promotion :-)

Somehow I've made it to ComputerWeekly's blogging beauty competition - the "IT Blog Awards 08".

Please help this author by adding your vote if you feel that way inclined :-) Click the picture below...

image

Hardware Budgets

The first work development machine that I bought to sit on my desk cost approximately £20K. That was 16 years ago so you'd have to guess that'd be about the equivalent of £40K (or more) today. It was a huge amount of money but, at the time, it was a cost of doing business and so (rightly) no-one questioned that it had to be done if we wanted to get our product built.

It definitely cost more than my salary at the time and I remember that I bought the wrong monitor for it by mistake and felt pretty scared of having to tell my boss who turned out to be very understanding ( thanks :-) ).

Today, hardware is incredibly cheap and staggeringly powerful.

Yet companies (including mine) seem loathe to buy developers/technical types the latest kit?

Why?

It's cheap and it's such a quick win when it comes to making technical people feel valued.

It's even better if you let people choose their own kit as I suspect;

  1. They feel attached to it having selected it themselves.
  2. They're more likely to want to keep it longer because of (1).
  3. They're more likely to try and address any technical short-comings in it having chosen it themselves rather than calling it a "piece of junk" and ringing a helpdesk to see if they can get it replaced because they never liked it in the first place.

Naturally, Joel knows this (and a lot of other things) and wrote it into his guidelines to understanding developers under the category of "Toys";

http://www.joelonsoftware.com/articles/FieldGuidetoDevelopers.html 

From time to time I re-read that article as it always cheers me up - makes me wish I was working for Joel :-)

So...if you're thinking about how to motivate technical people here's a tip - give them a hardware budget and the discretion to spend it. Naturally, you'll need to beat them up if they go and buy the wrong things but the people who do that probably need pushing towards the door anyway ;-)


Filed Under:

On Entity Framework, Concurrency

This is similar but not at all identical to this post about LINQ to SQL because it's using a different framework and that has different capabilities.

Someone mailed and asked how we can detect concurrency problems with Entity Framework in order to ensure that when we submit changes to the DB we first;

  1. Present the user with a list of all the concurrency errors in one go
  2. Present the user with their changes versus the DB's current data
  3. Ask the user how to go about resolving each issue
  4. Repeat until all the changes get to the DB one way or another

I can use the same tables and scripts and so on that I used in the previous post about LINQ to SQL. So...if I've got this table in my DB;

create table Person
(
  id int identity primary key,
  firstName nvarchar(30),
  lastName nvarchar(30),
  timestamp 
)

with data;

insert person(firstname,lastname) values('first1', 'last1')
insert person(firstname,lastname) values('first2', 'last2')
insert person(firstname,lastname) values('first3', 'last3')

and I bring this into an Entity Framework based project using the usual route and I make sure that I'm checking the timestamp for concurrency by altering the properties on the diagram as below;

image

and then I can start to write some code (similar to my LINQ to SQL) code as below;

    using (demoEntities context = new demoEntities())
    {
      Console.WriteLine("Enter a new surname");
      string surname = Console.ReadLine();

      var people = context.Person.ToList();

      foreach (Person p in people)
      {
        p.lastName = surname;
      }
      Console.WriteLine("Now's the time to cause a concurrency violation");
      Console.ReadLine();

      try
      {
        context.SaveChanges();
      }
      catch (OptimisticConcurrencyException ex)
      {
        foreach (ObjectStateEntry item in ex.StateEntries)
        {
          Console.WriteLine("Found an item");
        }
      }
    }

The "problem" that I've got here is that there's no version of SaveChanges on the ObjectContext that allows for you to continue when you hit a concurrency error making it hard for me to build a list of "all the concurrency problems".

So, if I cause a concurrency problem at the Console.ReadLine() above with two of my entities by doing something like;

update person set lastName='anything' where id=2
update person set lastName='else' where id=3
 

then what I'm going to see is 1 an exception containing the details of a single concurrency exception. I'm not going to get to "see" the second concurrency exception until I clear the first one.

How can I clear the first one? By refreshing the entity's original values from the DB whilst keeping my changes.

That's all fine in that I can write code like this but if I wanted to build up a complete list of all my concurrency problems and then present them to a user as a list before making any changes to the data then this code;

    using (demoEntities context = new demoEntities())
    {
      Console.WriteLine("Enter a new surname");
      string surname = Console.ReadLine();

      var people = context.Person.ToList();

      foreach (Person p in people)
      {
        p.lastName = surname;
      }
      Console.WriteLine("Now's the time to cause a concurrency violation");
      Console.ReadLine();

      bool allSaved = false;
      List<object> failedEntities = new List<object>();

      while (!allSaved)
      {
        try
        {
          context.SaveChanges();
          allSaved = true;
        }
        catch (OptimisticConcurrencyException ex)
        {
          // This will only iterate once.
          foreach (ObjectStateEntry item in ex.StateEntries)
          {
            context.Refresh(RefreshMode.ClientWins, item.Entity);
            failedEntities.Add(item.Entity);
          }
        }
      }
      // Spot the problem? It's too late already...
      Console.WriteLine("Encountered {0} concurrency problems along the way",
        failedEntities.Count);
    }

has an obvious problem in that by the time my code has figured out the list of entities that have concurrency problems it's all too late because I've already submitted the changes to the DB without having had any opportunity to consult the user (i.e. the last call to SaveChanges will actually work).

The only way that I can think of stopping that happening is to ensure that the transaction will roll back in the case where SaveChanges fails ( this would happen anyway ) and the case where it succeeds ( this would not happen usually ).

Something along the lines of;

    using (demoEntities context = new demoEntities())
    {
      Console.WriteLine("Enter a new surname");
      string surname = Console.ReadLine();

      var people = context.Person.ToList();

      foreach (Person p in people)
      {
        p.lastName = surname;
      }
      Console.WriteLine("Now's the time to cause a concurrency violation");
      Console.ReadLine();

      bool allSaved = false;

      while (!allSaved)
      {
        bool allTried = false;
        List<object> failedEntities = new List<object>();

        while (!allTried)
        {
          TransactionScope scope = new TransactionScope();

          try
          {
            context.SaveChanges(false);

            allTried = true;

            if (failedEntities.Count == 0)
            {
              scope.Complete();
            }
            scope.Dispose();
          }
          catch (OptimisticConcurrencyException ex)
          {
            scope.Dispose();

            // This will only iterate once.
            foreach (ObjectStateEntry item in ex.StateEntries)
            {
              context.Refresh(RefreshMode.ClientWins, item.Entity);
              failedEntities.Add(item.Entity);
            }
          }
        }
        if (!(allSaved = failedEntities.Count == 0))
        {
          Console.WriteLine("Hit {0} concurrency problems", failedEntities.Count);

          foreach (object entity in failedEntities)
          {
            ObjectStateEntry stateEntry =
              context.ObjectStateManager.GetObjectStateEntry(entity);

            RefreshMode mode = PromptUserForEntityConflict(stateEntry);

            context.Refresh(mode, entity);
          }
        }
      }
      // Finally, we can make current == original.
      context.AcceptAllChanges();
    }

 

with a couple of little functions;

  private static RefreshMode PromptUserForEntityConflict(ObjectStateEntry entry)
  {
    RefreshMode mode = RefreshMode.StoreWins;

    Console.WriteLine("Conflict on entity with key [{0}]",
      EntityKeyToString(entry));

    foreach (string propertyName in entry.GetModifiedProperties())
    {
      Console.WriteLine("\tProperty [{0}], your value [{1}], db value [{2}]",
        propertyName, entry.CurrentValues[propertyName],
        entry.OriginalValues[propertyName]);
    }

    Console.WriteLine("Do you want to keep your values [y] or db values [d]?");

    mode = Console.ReadLine() == "y" ?
      RefreshMode.ClientWins : RefreshMode.StoreWins;

    return (mode);
  }
  private static string EntityKeyToString(ObjectStateEntry entry)
  {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < entry.EntityKey.EntityKeyValues.Length; i++)
    {
      sb.AppendFormat("{0}{1}", i > 0 ? "," : string.Empty,
        entry.EntityKey.EntityKeyValues[i]);
    }
    return (sb.ToString());
  }

This seems to be about the best I can do if I need to present the user with all (current) concurrency problems in a single go and also present them with their values versus the database values.

In a lot of systems, concurrency issues are rare (e.g. generally I'm hoping that when I'm updating my bank account details via a call centre there isn't someone else also updating my details :-)) so this might not be such a common scenario but, with this implementation it means that if you have M modifications to update which cause N concurrency exceptions then you'll need at least N+2 trips to the database (with quite a lot of rolled back transactions) to make this work.

Feel free to suggest improvements and I'll add them here.

Silverlight & Virtual Earth

Fantastic demonstration from IDV solutions;

http://silverlight.idvsolutions.com/

It'd be really cool to be able to copy a link once you've annotated a map and share it with someone else.

I liked the flyout menus on the tools on the right hand side :-)


Filed Under: ,

Give me back my CPU(s)

Too many times I'm seeing this in my system tray;

image

What is that? It's Process Explorer ( I run that instead of Task Manager ) saying that my CPU is pegged ( again ).

The primary culprits are;

  1. My Anti-Virus software. This has never detected a virus for me yet and so, generally, I run the risk and I stop the service and get my CPU back.
  2. The search indexer ( on Vista ). Generally, I fix this by restarting the service.

I wonder how many users throw up their arms and think that either;

  1. The OS is broken.
  2. The PC is broken.

I hope that future versions of Windows do something about run-away processes. It's a tricky problem to solve but when I wrote here about what I was hoping for Vista, this was one of my top "hopes" and I don't think that we've really got there just yet.


Filed Under:

On LINQ to SQL, Concurrency and Timestamps

I came across a bit of a glitch in using timestamps for checking concurrency violations in LINQ to SQL and thought I'd share.

Say I've got a table like;

create table Person
(
  id int identity primary key,
  firstName nvarchar(30),
  lastName nvarchar(30),
  timestamp 
)

so, we have a simple table that has a timestamp on it and I want to use that to detect any concurrency problems that I might have in LINQ to SQL.

Let's populate this table with some data;

insert person(firstname,lastname) values('first1', 'last1')
insert person(firstname,lastname) values('first2', 'last2')
insert person(firstname,lastname) values('first3', 'last3')

 

and then I can bring that into my LINQ to SQL environment and I can check what the concurrency options are set to;

image

So, you can see that we've got Update Check set to Always and that means that the timestamp will be added to any where clauses for Deletes or Updates and if a particular update doesn't find any row to update because of that where clause then we have a concurrency violation.

Note also that Auto-Sync is set to Always which is a good thing because it means that if we insert an entity we'll automatically get the timestamp back and if we update an entity we'll similarly get an updated timestamp so that the timestamp in the original values of our entity in memory will represent the timestamp of the record when we queried/inserted/updated it and will only get "stale" if someone else were to update it (or delete it) in the meantime.

So, with LINQ to SQL we can write some code such as the stuff below which prompts for a new surname, changes the value in the entities that it has queried then tries to do a SubmitChanges and tries to make sure that it captures as many concurrency violations as it can ( the ContinueOnConflict parameter ).

    using (DemoDataContext ctx = new DemoDataContext())
    {
      var people = ctx.Persons.ToList();

      Console.WriteLine("Enter a new surname");
      string surname = Console.ReadLine();

      // Cause some changes.
      foreach (Person p in people)
      {
        p.lastName = surname;
      }
      // HERE...
      Console.WriteLine("Now's the time to cause a concurrency violation");
      Console.ReadLine();

      bool allSaved = false;

      while (!allSaved)
      {
        try
        {
          ctx.SubmitChanges(ConflictMode.ContinueOnConflict);
          allSaved = true;
        }
        catch (ChangeConflictException ex)
        {
          Console.WriteLine("Hit a conflict - fixing it!");

          foreach (ObjectChangeConflict conflict in ctx.ChangeConflicts)
          {
            conflict.Resolve(RefreshMode.KeepChanges);
          }
        }
        catch (Exception ex)
        {
          Console.WriteLine("Hit an unexpected exception [{0}]",
            ex.Message);
        }
      }
    }

When we hit the line of code marked HERE above, I go and run this piece of T-SQL;

update person set lastName='anything' where id=2
update person set lastName='else' where id=3

to cause concurrency problems for row number 2 and number 3 in my database.

What should happen;

  1. We read 3 entities with timestamps T1, T2, T3.
  2. We modify the surnames in our code.
  3. We use T-SQL to modify the timestamps T2, T3 in the database to ( say ) TM2 and TM3.
  4. We submit our changes.
  5. Our modifications for entities 2 and 3 will fail because T2!=TM2 and T3!=TM3. Our transaction is rolled back.
  6. We use Resolve in order to keep any changes that we have made in our code ( i.e. the surname modification ) but to refresh the other entity values from the DB.
  7. We now have in our program entities with timestamps T1, TM2, TM3
  8. We submit our changes.
  9. The code completes.

However, that's not what happens when the code does. What happens is that we hit an unexpected exception at 8 above and my Console.WriteLine writes it out;

Hit an unexpected exception [Value of member 'timestamp' of an object of type 'Person' changed.

What's going on here? I think what's happening here is that when we hit the call to SubmitChanges we go to the database to update 3 entities. The first update works so we update the timestamp. The 2nd update fails and so does the 3rd so we rollback the transaction.

However, we've updated the timestamp on that 1st entity.

We then go and resolve the 2 concurrency violations we've got before calling SubmitChanges again. It takes a look at that first entity which didn't have a concurrency problem but does now have a modified timestamp and still needs updating in the database ( because the transaction was rolled back ) and says "Hey, you're not meant to change generated columns like this!!".

Got it?

Option - Stop LINQ to SQL from Updating the TimeStamp Automatically on Update

The timestamp is only being updated because we have allowed the Auto-Sync property to be default to Always in the mapping information. That means "re-sync this column whenever we insert, update".

We could change this so that we only do Auto-Sync on Insert by setting;

image

Now, our code as it originally stands is going to work just fine if I re-run it under the same conditions where I cause a concurrency violation at the line marked HERE because when we hit the initial call to SubmitChanges which throws a ChangeConflictException we catch that exception, call Resolve on the 2 rows with the problems and then we call SubmitChanges again and we've never updated the timestamp on row number 1.

However...this isn't a free ride.

The problem with switching Auto-Sync to OnInsert means that whenever we actually do a successful update we won't update the timestamp to reflect the latest value that we just generated in the database.

So, whenever we call SubmitChanges for subsequent updates we will see superfluous concurrency exceptions for every row that didn't hit a concurrency exception the last time we called SubmitChanges.

That is, this code (which runs forever) will work;

    using (DemoDataContext ctx = new DemoDataContext())
    {
      var people = ctx.Persons.ToList();

      while (true)
      {
        Console.WriteLine("Enter a new surname");
        string surname = Console.ReadLine();

        // Cause some changes.
        foreach (Person p in people)
        {
          p.lastName = surname;
        }
        // HERE...
        Console.WriteLine("Now's the time to cause a concurrency violation");
        Console.ReadLine();

        bool allSaved = false;

        while (!allSaved)
        {
          try
          {
            ctx.SubmitChanges(ConflictMode.ContinueOnConflict);
            Console.WriteLine("Submitted changes");
            allSaved = true;
          }
          catch (ChangeConflictException ex)
          {
            Console.WriteLine("Hit a conflict - fixing it!");

            foreach (ObjectChangeConflict conflict in ctx.ChangeConflicts)
            {
              conflict.Resolve(RefreshMode.KeepChanges);
            }
          }
          catch (Exception ex)
          {
            Console.WriteLine("Hit an unexpected exception [{0}]",
              ex.Message);
          }
        }
      }
    }

and it'll work regardless of whether I cause concurrency problems at the line marked HERE. However, once the loop has executed once we run the risk of hitting "false" concurrency problems at the call to SubmitChanges for any rows that have out of date timestamps because we did not update them the last time we did an update.

The other thing that comes to mind here is that this all depends on the lifetime of your DataContext. If you just use it for one "unit of work" then this isn't really going to bite you in the same way because Auto-Sync doesn't seem so relevant if you're going to throw your DataContext away after you call SubmitChanges anyway.

And the last thing is that this won't affect you at all unless you're using generated columns like timestamps for concurrency checking.

Silverlight and ADO.NET Data Services ( 2 )

Following on from this last post, if I start to edit the data in the grid and change some value then the property value will change in the underlying class but nothing else will happen. That is, the NorthwindEntities class which is managing my data for me client-side ( which is derived from DataServiceContext ) isn't going to be aware of those modifications.

Why not? If we have a look at a property on a generated class such as this one for the CompanyName on the Customers class;

        public string CompanyName
        {
            get
            {
                return this._CompanyName;
            }
            set
            {
                this.OnCompanyNameChanging(value);
                this._CompanyName = value;
                this.OnCompanyNameChanged();
            }
        }

Now, OnCompanyNameChanging and OnCompanyNameChanged are partial methods with no implementation by default so nothing's going to happen when something like the DataGrid changes a value such as CompanyName.

Similarly, the generated entity classes such as Customers do not implement INotifyPropertyChanged which means that changes in the data will not be reflected in the UI anywhere as the UI doesn't have the necessary events to sync up to. This would also be true of an ADO.NET Data Services client generated for the full .NET framework ( such as WPF ) right now as it's the same tool that's in use.

( It wouldn't be true if you were using generated code from the Entity Framework directly in your UI ( i.e. a 2-tier solution ) because the Entity Framework ObjectContext and generated entity classes do set up a relationship where one "tracks" the other via the ObjectContext's ObjectStateManager and the IEntityWithChangeTracker interface and EntityObject's implementation of it ).

So, we're not going to get automatic, 2-way databinding on these entity classes just yet ( I'm hoping that RTM might do that but I've no inside knowledge on that ) and there's not really any way that you want to try and manually add it if you've got a lot of generated classes with a lot of generated properties - way too much manual work there and ( AFAIK ) datasvcutil.exe isn't extensible.

So you might want to look at something like Josh's script over here which does a crafty search-and-replace for you.

Regardless, if I edit data in my DataGrid as I've got it currently then the edits will make it through to the underlying property on the data bound object. So, if I change my UI to add a "Save" button;

<UserControl
  x:Class="BlogPostSL.Page"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data">
  <Grid x:Name="LayoutRoot" Background="White">
    <Grid.RowDefinitions>
      <RowDefinition
        Height="8*" />
      <RowDefinition />
      <RowDefinition />
      <RowDefinition />
    </Grid.RowDefinitions>
    <data:DataGrid
      x:Name="dataGrid"
      Margin="10"
      AutoGenerateColumns="True"
      ItemsSource="{Binding}" />
    <Button
      Margin="10"
      Content="Get Data"
      Grid.Row="1"
      Click="OnGetData" />
    <Button
      Margin="10"
      Content="Save Data"
      Grid.Row="2"
      Click="OnSaveData" />
  </Grid>
</UserControl>

and then add a little code to my code-behind class ( I've not included the whole class here, just the new method );

 void OnSaveData(object sender, EventArgs args)
    {
      proxy.BeginSaveChanges((asyncResult) =>
        {
          try
          {
            proxy.EndSaveChanges(asyncResult);
          }
          catch (Exception ex)
          {
            // TODO
            Debugger.Break();
          }
        }, null);
    }

Then nothing happens when that code inside my OnSaveData function runs. If I peer inside the proxy instance a little bit with the debugger then I can see a bunch of my Customers entities on a list of EntityDescriptor with a status of Unchanged. So, we need to make sure that our grid is setting the right instance to be updated when it has been updated as in;

    public Page()
    {
      InitializeComponent();

      this.Loaded += OnLoaded;

      dataGrid.AutoGeneratingColumn += OnGeneratedColumn;
      dataGrid.CommittingEdit += OnCommittingEdit;
    }
    void OnCommittingEdit(object sender, DataGridEndingEditEventArgs e)
    {
      proxy.UpdateObject(e.Row.DataContext);
    }

Then, when I update data and click my Save button then I get my data saved back into the database. Naturally, this is being done (AFAIK!) in line with the concurrency options and if I wanted to I could look to do batch updates rather than individual PUTs to make it happen as in;

    void OnSaveData(object sender, EventArgs args)
    {
      proxy.BeginSaveChanges(SaveChangesOptions.Batch, (asyncResult) =>
        {
          try
          {
            proxy.EndSaveChanges(asyncResult);
          }
          catch (Exception ex)
          {
            // TODO
            Debugger.Break();
          }
        }, null);
    }

I can leave that in place and handle deletes by, for instance, trapping the delete keypress on a grid row and then making a call to DeleteObject. I might do that by the following ( again, only listed the added code not the whole code for my Page class );

  public partial class Page : UserControl
  {
    private bool inEdit;

    public Page()
    {
      InitializeComponent();

      this.Loaded += OnLoaded;

      dataGrid.AutoGeneratingColumn += OnGeneratedColumn;
      dataGrid.BeginningEdit += OnBeginningEdit;
      dataGrid.CommittingEdit += OnCommittingEdit;
      dataGrid.CancelingEdit += OnCancellingEdit;
      dataGrid.KeyDown += OnGridKeyDown;
    }
    void OnCancellingEdit(object sender, DataGridEndingEditEventArgs e)
    {
      inEdit = false;
    }
    void OnBeginningEdit(object sender, DataGridBeginningEditEventArgs e)
    {
      inEdit = true;
    }
    void OnCommittingEdit(object sender, DataGridEndingEditEventArgs e)
    {
      proxy.UpdateObject(e.Row.DataContext);
    }
    void OnGridKeyDown(object sender, KeyEventArgs e)
    {
      if ((e.Key == Key.Delete) && (!inEdit))
      {
        // Single select for me.
        if (dataGrid.SelectedItem != null)
        {
          // Tell the DataServiceContext
          proxy.DeleteObject(dataGrid.SelectedItem);

          // Remove from the bound collection, disappears from
          // grid.
          BoundData.Remove(dataGrid.SelectedItem as Customers);
        }
      }
    }
    ObservableCollection<Customers> BoundData
    {
      get
      {
        return (dataGrid.DataContext as ObservableCollection<Customers>);
      }
    }

So, I've a form of update and a form of delete working. Insert can maybe be handlded by just pressing the Insert key, changing that handler to;

    void OnGridKeyDown(object sender, KeyEventArgs e)
    {
      if (!inEdit)
      {
        if (e.Key == Key.Delete)
        {
          // Single select for me.
          if (dataGrid.SelectedItem != null)
          {
            // Tell the DataServiceContext
            proxy.DeleteObject(dataGrid.SelectedItem);

            // Remove from the bound collection, disappears from
            // grid.
            BoundData.Remove(dataGrid.SelectedItem as Customers);
          }
        }
        else if (e.Key == Key.Insert)
        {
          Customers c = new Customers() { Country = "UK" };
          int index = BoundData.IndexOf(dataGrid.SelectedItem as Customers);
          BoundData.Insert(index, c);
          proxy.AddObject("Customers", c);
        }
      }
    }

From there I think the next steps would be to think about inserting related entities ( 1 to many and many-to-many ), checking status codes, handling errors and so on.

Silverlight and ADO.NET Data Services

Someone mailed me to ask whether I had a video on how to put together Silverlight and ADO.NET Data Services.

I don't at the time of writing and I've also got a cold right now ( thank you, Microsoft Manchester office :-) ) so I thought I'd write something rather than record it.

Let's run through a step-by-step thing.

Visual Studio 2008 - File->New->Web Site. I'm going for the filesystem and C# as below;

image

Now, to make it easy to work with ADO.NET Data Services, I'm going to add in an ADO.NET Entity Data Model for Northwind. That is ... Website->Add->New Item;

image

I say "yes" to add it to my app_code folder, then select;

image imageimage

and then I can go and add a new ADO.NET Data Service ( again via Website->Add New Item );

image

and then I can update my service code to read;

public class Service : DataService<NorthwindEntities>
{
  // This method is called only once to initialize service-wide policies.
  public static void InitializeService(IDataServiceConfiguration config)
  {
    config.SetEntitySetAccessRule("*", EntitySetRights.All);
  }
}

and I'm also going to reconfigure my project so that the built-in web server uses a particular port rather than a randomly selected one by selecting the website's properties and changing it;

image

Then I can add a new Silverlight 2 project here by doing File->Add New Project;

image

and then accepting the defaults for the Silverlight options;

image

Now, I need my Silverlight project to call the ADO.NET Data Service from my other project so I do a quick "view on browser" on my Service.svc file just to spin up the web server. Then I can drop to a command line in my c:\demo\BlogPostSL folder and use the datasvcutil.exe tool to generate some proxy code for my Silverlight project;

image

Then I can pop back to Visual Studio and add this as an existing item to my Silverlight project. I also need to add a reference to;

System.Data.Services.Client

in order to make that project ( with the new proxy code ) compile.

Now, I want to build a little bit of UI for Silverlight to display some data. I want to use the DataGrid so the first thing that I need to do is to add a reference to pick up the DataGrid assembly as well. So, that's another reference to the Silverlight project;

System.Windows.Controls.Data

Now I can go and edit some XAML and build up a little piece of UI;

<UserControl
  x:Class="BlogPostSL.Page"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data">
  <Grid x:Name="LayoutRoot" Background="White">
    <Grid.RowDefinitions>
      <RowDefinition
        Height="8*" />
      <RowDefinition />
      <RowDefinition />
    </Grid.RowDefinitions>
    <data:DataGrid
      x:Name="dataGrid"
      Margin="10"
      AutoGenerateColumns="True"
      ItemsSource="{Binding}" />
    <Button
      Margin="10"
      Content="Get Data"
      Grid.Row="1"
      Click="OnGetData" />
  </Grid>
</UserControl>

and then drop some code behind it;

  public partial class Page : UserControl
  {
    public Page()
    {
      InitializeComponent();

      this.Loaded += OnLoaded;
    }
    void OnLoaded(object sender, RoutedEventArgs e)
    {
      proxy = new NorthwindEntities(
        new Uri("http://localhost:32767/BlogPost/Service.svc", UriKind.Absolute));
    }
    void OnGetData(object sender, EventArgs args)
    {
      // I don't think that we can use LINQ here because there's no way then
      // to make it asynchronous. So, let's use the manual way of doing things.
      DataServiceQuery<Customers> query =
        proxy.CreateQuery<Customers>("Customers?$filter=Country eq 'UK'");

      query.BeginExecute((asyncResult) =>
        {
          try
          {
            IEnumerable<Customers> result = query.EndExecute(asyncResult);

            // Doubt if we're on the UI thread so...
            Dispatcher.BeginInvoke(() =>
              {
                ObservableCollection<Customers> data = new ObservableCollection<Customers>();
                foreach (Customers c in result)
                {
                  data.Add(c);
                }
                dataGrid.DataContext = data;
              });
          }
          catch (Exception ex)
          {
            // TODO
            Debugger.Break();
          }
        }, null);
    }
    NorthwindEntities proxy;
  }

and now clicking on my "Get Data" button gets me some data;

image

Now, that Orders column isn't really something that I want so I guess the easiest thing to do there is to hide it. I still want the grid to automatically generate columns though so perhaps I can just get this one removed?

    public Page()
    {
      InitializeComponent();

      this.Loaded += OnLoaded;

      dataGrid.AutoGeneratingColumn += OnGeneratedColumn;
    }
    void OnGeneratedColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
      if (e.Property.Name == "Orders")
      {
        e.Cancel = true;
      }
    }

That's a bit better in that I've got some data on the screen.

As an aside, where I said in that code above that we "can't write this query with LINQ". That wasn't strictly true. I can write something like;

      var query = (DataServiceQuery<Customers>)
        from c in proxy.Customers
        where c.Country == "UK"
        select c;

      query.BeginExecute((asyncResult) =>
        { // .......

and that looks to work fine once you get over the cast.

I'll look at updating, inserting, deleting in subsequent posts otherwise this gets very long very quickly.

Entity Framework - Timestamps and Concurrency

Someone asked me today how you'd go about ensuring that timestamp columns in your database tables show up in your Entity Framework EDMX file with a Concurrency=Fixed attribute on them.

That is - it's very likely that the timestamps are there on the table to enforce concurrency so why not default their Concurrency value to "Fixed" ?

It's a good question but it's not something that the tooling does as far as I'm aware so I tried to have together some LINQ to XML code that would make an attempt at it. I don't claim that this is correct at all but it might be a starting point for this and similar, related pre-processing that you want to do on an EDMX file.

  static void Main(string[] args)
  {
    XElement edmxFile = XElement.Load(args[0]);

    XNamespace edmxNs = XNamespace.Get("http://schemas.microsoft.com/ado/2007/06/edmx");
    XNamespace ssdlNs = XNamespace.Get("http://schemas.microsoft.com/ado/2006/04/edm/ssdl");
    XNamespace mapNs = XNamespace.Get("urn:schemas-microsoft-com:windows:storage:mapping:CS");
    XNamespace csdlNs = XNamespace.Get("http://schemas.microsoft.com/ado/2006/04/edm");

    var timestampCols =
      from ssdlProp in edmxFile.DescendantsAndSelf(ssdlNs + "Property")
      join mapProp in edmxFile.DescendantsAndSelf(mapNs + "ScalarProperty")
      on (string)ssdlProp.Attribute("Name") equals (string)mapProp.Attribute("ColumnName")       
      join csdlProp in edmxFile.DescendantsAndSelf(csdlNs + "Property")
      on (string)mapProp.Attribute("Name") equals (string)csdlProp.Attribute("Name")
      where (string)ssdlProp.Attribute("Type") == "timestamp" && 
        (string)mapProp.Parent.Attribute("StoreEntitySet") == (string)ssdlProp.Parent.Attribute("Name") &&
        (string)mapProp.Ancestors(mapNs + "EntitySetMapping").First().Attribute("Name") 
          == (string)csdlProp.Parent.Attribute("Name")
      select csdlProp;

    foreach (var item in timestampCols)
    {
      item.SetAttributeValue("ConcurrencyMode", "Fixed");
    }
    edmxFile.Save(args[0]);
  }

I then used this inside of VS as a pre-build action to change my EDMX file prior to building the whole project. Seemed to work for my trivial example.

Feel free to take, borrow, tweak, ignore :-) Just don't blame me ( of course ) if it breaks your EDMX file.


Filed Under: ,

Michael Rys in London on Non-Relational Data in SQL Server

The UK, SQL Server User Group has Michael Rys delivering a talk on Monday in London. Michael's a Program Manager in SQL Server.

Go here for the details and to sign up.

I don't know Michael personally but I know that back when I was looking at SQL Server 2005 and I asked any kind of question about the new XML data type it was more-often-than-not an email that came back from Michael with the answer in it so you should be in for a treat if you manage to get yourself signed up for this.


Filed Under: ,
More Posts Next page »