# Saturday, March 17, 2012
When you are a detached entity returns from the UI, you normally save the update like this:
public void UpdateMovie(Movie movie)
{
    using (var context = new DomainContext())
    {
        //attach it
        context.Movies.Attach(movie);
        //mark it as modified
        context.Entry(movie).State = EntityState.Modified;
        //save - but saves all properties...
        context.SaveChanges();
    }
}
The update property saves all the properties - but what if we only wanted to save certain properties? Like this:
update [dbo].[Movies]
set [BoxOffice] = @0
where ([Id] = @1)

The safest way is to do it manually (and you avoid mass assignment vulnerabilities). You have to reload the entity from the database.
public void UpdateMovieBoxOffice(Movie movie)
{
    using (var context = new DomainContext())
    {
        //get database version
        var databaseMovie = context.Movies.Find(movie.Id);
        //manually copy the values
        databaseMovie.BoxOffice = movie.BoxOffice;
        //save
        context.SaveChanges();
    }
}
The UI may be able to track changes (IPropertyNotifyChanged or similar) and give the data service a list of the changed properties. If so, we can use the context.Entry to specify the modified properties. The SQL UPDATE statement will update only those properties.
public void UpdateMovieProperties(Movie movie, IList<string> propertyNames)
{
    using (var context = new DomainContext())
    {
        //attach it
        context.Movies.Attach(movie);
        //use the context entry
        DbEntityEntry<Movie> entry = context.Entry(movie);
        foreach (var propertyName in propertyNames)
        {
            //modify the specific property states only
            entry.Property(propertyName).IsModified = true;
        }
        //save
        context.SaveChanges();
    }
}

The other way is to detect the changes by comparing them to the database. This is similar to the second method, but we use entry.GetDatabaseValues() to get the database values and then compare them. As only the changed properties are marked as modified, the UPDATE statement uses only those properties.
public void UpdateMovieChangedProperties(Movie movie)
{
    using (var context = new DomainContext())
    {
        //attach it
        context.Movies.Attach(movie);
        //use the context entry
        DbEntityEntry<Movie> entry = context.Entry(movie);
        //do a database call to get the state
        var databaseValues = entry.GetDatabaseValues();
        foreach (var propertyName in databaseValues.PropertyNames)
        {
            //modify the specific property states only
            entry.Property(propertyName).IsModified = true;
        }
        //save
        context.SaveChanges();
    }
}
We don't take account of Complex Properties here (the DbPropertyEntries can be nested).


posted on Saturday, March 17, 2012 11:56:43 AM (Romance Standard Time, UTC+01:00)  #    Comments [0]
# Wednesday, February 22, 2012
In EF Code First, context.SaveChanges() automatically does validations.
But lazy loading can collide with validations.

In our model, a Product must have a Category.

public class Product
{
    [Key]
    public int ProductId { getset; }
 
    [Required]
    [StringLength(40)]
    public string ProductName { getset; }
 
    [Required]
    public virtual Category Category { getset; }
}

Let's try this...
using (var context = new NorthwindContext())
{
    //find a specific product
    var product = context.Products.Find(147);
    //set a new name
    product.ProductName = Guid.NewGuid().ToString();
 
    //ERROR!
    context.SaveChanges();
}


Oh no, System.Data.Entity.Validation.DbEntityValidationException. "Validation failed for one or more entities." How can that be? We just loaded it from the database, it must be correct?
The exception says that Category is null. But it exists in the database.

If you inspect it in the debugger, you can see the category ... and if you continue the SaveChanges succeeds. The debugger triggered a lazy load, so it works.

context.SaveChanges() internally turns off lazy loading before validating. Which is good, because you don't want unnecessary database access. But when the reference is required, the validation doesn't recognise this is a proxy which has a categoryId but hasn't loaded it.

Solution 1- no auto validation


One solution is to turn off validation. When you are setting individual properties with values you've already validated, you do not need it here.

context.Configuration.ValidateOnSaveEnabled = false;
context.SaveChanges();

The SQL, by the way, is update [dbo].[Products] set [ProductName] = @0 where ([ProductID] = @1).
(Check it by hooking up a SQL logger, as described here)

An alternative is to cheat the model- ensure references are not Required.

But if you have a product coming back from a UI for insert or update, you need to manually validate that it always has a category.

Solution 2- ensure required references are loaded


This triggers extra database access, but you can keep the automatic validation.

//find a specific product
var product = context.Products.Find(147);
//make sure it's loaded
context.Entry(product).Reference(p => p.Category).Load();

If you load from a query, you can use an .Include(p => p.Category) which will load the product with a join to the category table, so there is only one sql statement. This will bypass the internal cache so if it was loaded the same product earlier, you can't save any data access.
var product = context.Products
    .Include(p => p.Category)
    .First(p => p.ProductId == 147);

Solution 3- Add a foreign key Id property


You can specify foreign key Id properties in addition to the instance property.
//it's not nullable so it's implicitly required
public int CategoryId { getset; }
 
public virtual Category Category { getset; }


Note the CategoryId is now required. The Category instance isn't. Validation can check the CategoryId, and we can set it directly without having to load the instance.

You have to map this arrangement (unless you like to see an EntityCommandCompilationException with the inner exception message being "More than one item in the metadata collection match the identity 'CategoryId'." - I didn't).
In the EntityTypeConfiguration<Product> the mapping must point to the foreign key id property.
HasRequired(x => x.Category)
    .WithMany()
    .HasForeignKey(p => p.CategoryId);


We've "denormalized" our entity model here, but it makes dealing with detached objects and viewmodels a little easier.

But won't the CategoryId and Category properties get out of step? If you set one, which gets persisted?

Let's set the foreign key id property.
//find a specific product
var product = context.Products.Find(146);
 
//it's category 4 in both
Console.WriteLine(product.Category.CategoryId);
Console.WriteLine(product.CategoryId);
 
//set the categoryId property
product.CategoryId = 1;
 
//we've just set it, so it's 1
Console.WriteLine(product.CategoryId);
//oh no, still says 4!
Console.WriteLine(product.Category.CategoryId);


context.SaveChanges() does the right thing- it saves the new value, 1, assigned to the id property.

Let's set the instance.
//find a specific product
var product = context.Products.Find(146);
 
//it's category 1 in both
Console.WriteLine(product.Category.CategoryId);
Console.WriteLine(product.CategoryId);
 
//set the category instance
product.Category = context.Categories.Find(2);
 
//we've just set it, so it's 2
Console.WriteLine(product.Category.CategoryId);
//oh no, still says 1!
Console.WriteLine(product.CategoryId);


But again, context.SaveChanges() does the right thing- it saves the new value, 2, assigned to the instance.

So it looks like persistence always works as you'd expect, but the properties get out of step. You must be careful in your workflow. This won't work...
product.CategoryId = 1;
var returnMessage = "Category updated to " + product.Category.CategoryName;


Conclusion

In most cases I'd prefer to remove validation on save with context.Configuration.ValidateOnSaveEnabled = false - as long as the values were validated downstream (perhaps in the UI validation framework).

But exposing the foreign key property is undoubtably convenient when the UI just sends you categoryId= 1 and you don't want to load that category from the database just so you can persist product.
posted on Wednesday, February 22, 2012 11:45:48 AM (Romance Standard Time, UTC+01:00)  #    Comments [0]
# Friday, February 17, 2012
There is a risk of unbounded result sets when using navigation collections.

If you try to do paging (Skip/Take) on a navigation collection, you actually load all the related entities and then page in memory. Opps.
//unbounded result set - there could be 1000s!
var products = category.Products
    .OrderBy(p => p.ProductName) //you have to order
    .Skip((page - 1) * pageSize)
    .Take(pageSize);
You have the same issue with a simple .Count, as shown in my last post.

The solutions are the same. You can use a filter directly on the products DbSet.
var pagedProductsByCategory = context.Products
    //have to specify primary keys here- can't match on "category"
    .Where(p => p.Category.CategoryId == category.CategoryId)
    .OrderBy(p => p.ProductName) //you have to order
    .Skip((page - 1) * pageSize)
    .Take(pageSize);
Or you can use the context.Entry(x).Collection(y).Query(). This is the equivalent of an NHibernate CreateFilter.
var pagedProducts = context.Entry(category)
    //from the DbEntityEntry, get the navigation property
    .Collection(x => x.Products)
    //turn it into a query
    .Query()
    //page
    .OrderBy(p => p.ProductName) //you have to order
    .Skip((page - 1) * pageSize)
    .Take(pageSize);
To remove temptation, you might want to remove the collection navigation property. In this case, category has no Products collection (the many end of the foreign key), but Product has a Category property (the 0.1 end of the foreign key).

You can specify the mapping in an EntityTypeConfiguration<Product> class map. Because the many end isn't defined, you use an empty .WithMany().
HasOptional(x => x.Category)
    .WithMany() //.WithMany(c => c.Products)
    .Map(m => m.MapKey("CategoryID"));

Remember you can (and should) be profiling your generated SQL, for instance with the EFTracingProvder as shown here.




posted on Friday, February 17, 2012 7:37:58 AM (Romance Standard Time, UTC+01:00)  #    Comments [0]
# Thursday, February 16, 2012
Watch out for unbounded result sets when using navigation properties.

using (var context = new NorthwindContext()))
{
    var category = context.Categories.Find(1); //Beverages
    Console.WriteLine(category.Products.Count);
}

This loads ALL the products for the category, and then counts them.

Fine for a small result set, not so good if you have 1000s of products per category.

Simple solution: use a filter on products.

Console.WriteLine(context.Products
    .Count(p => p.Category.CategoryId == category.CategoryId));

This generates SQL in the form "SELECT COUNT(*) FROM Products WHERE CategoryID = @p"

Alternative solution: use context.Entry with .Query()

Console.WriteLine(context.Entry(category)
    .Collection(x => x.Products)
    .Query()
    .Count());
posted on Thursday, February 16, 2012 1:53:47 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]
# Tuesday, February 14, 2012
I wanted to log the SQL so I can profile a Entity Framework Code First application.

MVC Mini-Profiler only works in an ASP MVC application- not in console or unit tests.

The tracing and caching providers for Entity Framework expect ObjectContexts (EF 4.0), not DbContexts. But we can make them work.

Scenario:
I have a code first project with my DbContext, called NorthwindContext.
I have a unit test project, with a test that uses NorthwindContext

Here's the steps.

1. Download the providers.
2 (Optional): review the Q&A and apply some of the suggested patches.
3. Build the solution.
4. The unit test project will reference the dlls from the tracing provider
EFProviderWrapperToolkit.dll
EFTracingProvider.dll
5. Add an App.config to the unit test project something like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="NorthwindContext" 
         providerName="System.Data.SqlClient" 
         connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True;Pooling=False;MultipleActiveResultSets=True" />
  </connectionStrings>
  <system.data>
    <DbProviderFactories>
      <add name="EF Tracing Data Provider" 
           invariant="EFTracingProvider" 
           description="Tracing Provider Wrapper" 
           type="EFTracingProvider.EFTracingProviderFactory, EFTracingProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
      <add name="EF Generic Provider Wrapper" 
           invariant="EFProviderWrapper" 
           description="Generic Provider Wrapper" 
           type="EFProviderWrapperToolkit.EFProviderWrapperFactory, EFProviderWrapperToolkit, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
    </DbProviderFactories>
  </system.data>
</configuration>
6. In the DbContext, we need to use two of the base constructors
        public NorthwindContext()
        {
            //default ctor, uses app.config connection string named "NorthwindContext"
        }
 
        public NorthwindContext(DbConnection connection)
            :base(connection,true)
        {
           //ctor uses for tracing 
        }
7. In my test, you need to use the overload that takes the DbConnection.
            using (var context = new NorthwindContext(
                CreateConnectionWrapper(@"name=NorthwindContext")))
            {
 
                //profile this!
                var product = context.ProductCollection.Find(1);
            }
8. And add the CreateConnectionWrapper method:
private static DbConnection CreateConnectionWrapper(string nameOrConnectionString)
{
    var providerInvariantName = "System.Data.SqlClient";
    var connectionString = nameOrConnectionString;
    //name=connectionName format
    var index = nameOrConnectionString.IndexOf('=');
    if (index > 0 && nameOrConnectionString.Substring(0, index).Trim()
        .Equals("name"StringComparison.OrdinalIgnoreCase))
    {
        nameOrConnectionString = nameOrConnectionString
            .Substring(index + 1).Trim();
    }
    //look up connection string name
    var connectionStringSetting =
        ConfigurationManager.ConnectionStrings[nameOrConnectionString];
    if (connectionStringSetting != null)
    {
        providerInvariantName = connectionStringSetting.ProviderName;
        connectionString = connectionStringSetting.ConnectionString;
    }
    //create the special connection string with the provider name in it
    var wrappedConnectionString = "wrappedProvider=" + 
        providerInvariantName + ";" + 
        connectionString;
    //create the tracing wrapper
    var connection = new EFTracingConnection
                            {
                                ConnectionString = wrappedConnectionString
                            };
    //hook up logging here
    connection.CommandFinished +=
        (sender, args) => Console.WriteLine(args.ToTraceString());
    return connection;
}
This should cope with connection strings in the 3 common forms ("Northwind", "name=Northwind" and "Data Source=.\SQLEXPRESS;Initial Catalog=Northwind ...")

Note the line to hook up logging (subscribing to the connection.CommandFinished event). We could simply have used
EFTracingProviderConfiguration.LogToConsole = true;

Or you can hook up to log4net or EntLib logging to those tracing events.



posted on Tuesday, February 14, 2012 2:11:00 PM (Romance Standard Time, UTC+01:00)  #    Comments [1]
# Sunday, February 05, 2012

I wanted to use a many-to-many relationship using Entity Framework Code First (v4.1/4.2).

Using pure code first such as this:

using (var context = new MyContext())
{
    var employee = new Employee { FirstName = "Homer", LastName = "Simpson" };
    var territory = new Territory { TerritoryDescription = "Springfield" };
    employee.Territories.Add(territory);
    context.Employees.Add(employee);

    context.SaveChanges();
}

results in a nice association table

image

How do you map existing database tables? Like Northwind's customer to customer demographic table relationship:

image

This is the code I want to write:

using (var context = new MyContext("name=Northwind"))
{

    var demo = new CustomerDemographic();
    demo.CustomerTypeID = "BERLIN";
    demo.CustomerDesc = "Berliner";
    context.CustomerDemographics.Add(demo);
    //link it to a customer by either end
    var alfki = context.Customers.Find("ALFKI");
    alfki.CustomerDemographics.Add(demo);

    context.SaveChanges();
}

We have to override DbContext's OnModelCreating and add some mapping. For CodeFirst, you map both sides of the relationship, so you can either put the mapping on Customer or CustomerDemographic - or even both if the mappings agree. A normal foreign key relationship is mapped with ".HasMany|HasOptional|HasRequired" followed by a ".WithMany|WithOptional|WithRequired".

So, from the CustomerDemographic entity, a many to many is just .HasMany(x=>x.Customers).WithMany(z=>z.CustomerDemographics).

In addition, we don't have standard names for our association table so we add a .Map element to specify the table and the left and right key columns.

Note the primary key of CustomerDemographics isn't the 'tableName'+"Id" convention that Code First will expect. So I have to define the key for that. As we have that end of the configuration, we'll define the mapping there.

Here's the code.

modelBuilder.Entity<CustomerDemographic>()
    //the key isn't standard so specify it
    .HasKey(x => x.CustomerTypeID)
    //define both sides of the relationship - HasMany.WithMany
    .HasMany(x => x.Customers)
    .WithMany(z => z.CustomerDemographics)
    //specify mapping information
    .Map(map =>
    {
        //the association table name
        map.ToTable("CustomerCustomerDemo");
        //the left side (fk to CustomerDemographic, the entity we're defining)
        map.MapLeftKey("CustomerTypeID");
        //the right side (fk to Customers, the other side)
        map.MapRightKey("CustomerID");
    }
);

If we mapped from the Customer entity, the HasMany and WithMany properties are different, and the mapped left and right keys swap round.

Here's the full DbContext for my mini-Northwind mapping:

class MyContext : DbContext
{
    public MyContext(string connectionName)
        : base(connectionName)
    {
    }

    public DbSet<Employee> Employees { get; set; }
    public DbSet<Territory> Territories { get; set; }

    public DbSet<Customer> Customers { get; set; }
    public DbSet<CustomerDemographic> CustomerDemographics { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());
        Database.SetInitializer<MyContext>(null);
        modelBuilder.Conventions.Remove<System.Data.Entity.Infrastructure.IncludeMetadataConvention>();

        modelBuilder.Entity<CustomerDemographic>()
            //the key isn't standard so specify it
            .HasKey(x => x.CustomerTypeID)
            //define both sides of the relationship - HasMany.WithMany
            .HasMany(x => x.Customers)
            .WithMany(z => z.CustomerDemographics)
            //specify mapping information
            .Map(map =>
            {
                //the association table name
                map.ToTable("CustomerCustomerDemo");
                //the left side (fk to CustomerDemographic, the entity we're defining)
                map.MapLeftKey("CustomerTypeID");
                //the right side (fk to Customers, the other side)
                map.MapRightKey("CustomerID");
            }
        );
    }
}
posted on Sunday, February 05, 2012 9:42:13 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]
# Thursday, January 05, 2012
 
//find the working folder for each TFS
var projectCollections = RegisteredTfsConnections.GetProjectCollections();
 
foreach (var registeredProjectCollection in projectCollections)
{
    Console.WriteLine("Project collection: {0} {1}", 
registeredProjectCollection.Name,
registeredProjectCollection.Uri.AbsoluteUri);     var projectCollection =         TfsTeamProjectCollectionFactory.GetTeamProjectCollection(registeredProjectCollection);     var versionControl = projectCollection.GetService<VersionControlServer>();     // get workspace     var workspace =         versionControl.QueryWorkspaces(null,                 System.Threading.Thread.CurrentPrincipal.Identity.Name,                 Environment.MachineName)                 .FirstOrDefault(x =>                      x.Folders.Length > 0 &&                     //if there is a Work Item Manager, we don't care                     x.Name != "WIM (" + Environment.MachineName + ")");     if(workspace == nullcontinue//no workspace for this server     //there's normally only one     WorkingFolder folder = workspace.Folders.First();     Console.WriteLine("Working folder {0}", folder.LocalItem); }

//old VS 2008 way //using (TeamFoundationServer tfsServer = new TeamFoundationServer(tfsServerName)) //{ //    // Get a reference to version control //    VersionControlServer versionControl = //        (VersionControlServer) tfsServer.GetService(typeof (VersionControlServer)); //    //.... //}
posted on Thursday, January 05, 2012 9:51:17 AM (Romance Standard Time, UTC+01:00)  #    Comments [0]
# Saturday, December 10, 2011

I've just done all 4 of the exams for .Net 4.0 MCPD Web Developer. Overall, I quite enjoyed it. I even learned a bit.

Programmer certifications, and particularly the Microsoft ones, get a lot of criticism. In theory they prove someone is proficient in the technology. In practice, by itself a certificate is unreliable.

Microsoft's Partner program insists that companies have staff with certifications. The body shops put their new recruits through a brief course so they can pass and then be sold on. Often, they memorised the questions and answers from internet dumps. It's disappointing to google the exam codes: apart from the Microsoft syllabus, every link is a site selling the answers.

If you're a consultant, or you're going to change jobs, experienced programmers probably have to do the exams too. If you work for a Microsoft Partner you have to do it, and HR departments filter their CVs using it. Really, the best measure of proficiency is years of experience and types of projects. That's real-world practical knowledge. Okay, I would say that, having been doing this for 25 years. But, as the company I work for needs the certificate points, and they're paying, I'm happy to do the exams.

For .net 1 we had to do exams for ASP, windows forms and web services, but most .net programmers then only worked in one or two of those- certainly never windows forms and ASP. I was actually quite impressed by the .Net 2 foundation exam, which covered a lot of basics: collections, threads, tracing, serialization, globalization, encryption. Specific projects may not involve some of it, but a good .net programmer should know almost all of it (even if you have to google the details). Unfortunately they dropped it for .Net 4, going back to technology areas (asp, web services) just like the original .net 1 exams.  Now for .net 4 "web" we have asp, wcf and data access (ado/entity framework). Broadly I agree you'd expect all web developers to know those topics, so that's not too bad.

One big problem with certification questions is that they pick on obscure APIs and ASP controls. Now, questions on the validation controls is probably a good basic requirement, but frankly the gridview events are a nightmare anyway, so memorizing them for an exam is painful. The .net 4 asp exam wasn't too bad although there was some API questions that in real life you'd just google. One of the jQuery questions annoyed me too, using an unusual API detail (I think an older syntax) when they could have used a better, clearer replacement.

The older exams had sections devoted to things nobody ever uses. On the asp .net 2 exam it was mobile controls, and web parts (cloned from Sharepoint, and never used outside Sharepoint). Fortunately there seems less of that in the .net 4 exams, although there's still some asp ajax library stuff in there, plus some dynamic data. The big problem was that jQuery and MVC have moved on since the exam was written. All the questions were about MVC 2, not 3. It's not that the questions were obsolete (there was nothing much about webform views to confuse those who use Razor), it's just that the pace of change is making exams less relevant.

The other exams had little used topics too. The WCF exam covered MSMQ, which I've never seen used in real life. The data access exam was more problematic. Basic ADO is useful, but there was still material about little used dataset features like constraints and dataRelations. There was not much on Linq2Sql, perhaps just as well, but most of the exam was Entity Framework. I know EF is used out there, but I've yet to encounter EF and it seems to be in second place to NHibernate at least for ORM data access. So I did learn something for this exam, and yes, I passed the exam as a novice with no real world experience of Entity Framework. On the other hand, as an experienced programmer I'd feel comfortable doing EF (even if I'd rather be doing NHibernate.)

Two of the exams - the WCF and the ASP Pro exam - had "testlets" with a case study and a small number of questions about the scenario. The WCF was over-elaborate, with source listings and xml, but for all that I thought it was a little more realistic and actually quite enjoyable.

To study, I used the Microsoft Training Kit books, MSDN and for the areas I was less familiar with - mostly EF and some aspects of WCF - a little practice. The WCF exam didn't have a book, so I had to use the .net 3.5 one and look up a couple of subjects (routing and discovery). I skimmed the bits I knew well (the asp/ web side generally). Generally I found you needed a bit more knowledge than was in the books, but only a few things were really obscure. Overall, studying for the exam was interesting and useful. Learning about WCF routing and discovery and EF, things I haven't actually used, did bring me more up-to-date with the .net 4 stack.

A pity Microsoft's "congratulations" email contains a link to a blog that closed 2 years ago.

posted on Saturday, December 10, 2011 10:15:55 PM (Romance Standard Time, UTC+01:00)  #    Comments [0]
# Friday, July 08, 2011
A brief recap of ASP.Net cache:

//in MVC use HttpRuntime.Cache or HttpContext.Cache
//in webforms Application is the original cache without expiration rules
var category = HttpRuntime.Cache["Category"as CategoryModel;
if (category == null)
{
     category = _dataAccess.Find(1);
     HttpRuntime.Cache["Category"] = category;
     // ...or...
     //monitor some files and/or other cache items
     var cd = new CacheDependency(new[] { @"C:\triggerFolder\" }, new[] { "OtherCacheItem" });
     HttpRuntime.Cache.Insert("Category1", category, 
               cd, //dependencies or null
               DateTime.Now.AddMinutes(5), //absolute expiration (or Cache.NoAbsoluteExporation)
             Cache.NoSlidingExpiration //sliding expiration (timespan)
     );
}
Mocking this in tests (especially for MVC) is a bit ugly (.Net 3.5sp1 has System.Web.Abstractions including HttpContextBase, but caching isn't included)

Now in .Net 4 we can reference System.Runtime.Caching.dll. And the really nice thing is this will run outside Asp.Net.
//get the static "default" cache. You can have multiple named caches.
ObjectCache cache = MemoryCache.Default;
//you can't store null in the cache
var category = cache["Category"as CategoryModel;
if (category == null)
{
    category = _dataAccess.Find(1);
    cache["Category"] = category;
    // ...or...
    var policy = new CacheItemPolicy();
    policy.AbsoluteExpiration = DateTime.Now.AddMinutes(5);
    //monitor some files and/or other cache items
    policy.ChangeMonitors.Add(
        new HostFileChangeMonitor(new List<string> { @"C:\triggerFolder\"})
        );
    //synchronize with another cache item
    policy.ChangeMonitors.Add(
        cache.CreateCacheEntryChangeMonitor(new [] { "OtherCacheItem"})
        );
    cache.Add("Category1", category, policy);
}
For simple caching (no change monitors) you don't even need mocking in your tests - in fact, you can test your caching with a real cache. You can move caching down into your library classes that may be called from web pages, tests, WPF apps and consoles.



posted on Friday, July 08, 2011 10:57:57 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0]
# Friday, June 10, 2011
T4 preprocessed templates are a neat way of generating text at run time, which can be deployed to machines without Visual Studio. Here's MSDN

Here's a simple template, ClassWriter.tt, which must be marked CustomTool = "TextTemplatingFilePreprocessor" in properties (not "TextTemplatingFileGenerator" which is a normal T4).
<#@ template language="C#" #>
<#@ import namespace="System.Linq" #>
<#@ parameter type="Generator.Model.Table" name="table" #>
using System;
 
namespace <#= table.Namespace #>
{
    [Serializable]
    public class <#= table.Name #>
    {
<#  foreach(var column in table.Columns.Where(c=> !c.Hidden)) { #>
        public virtual <#= column.Type #> <#= column.Name #> { get; set; }
<#    } #>
    }
}

At development time, Visual Studio generates the class in the corresponding namespace which you can then call (yeah, it generates code for generating code...).

Notice we're passing a parameter, which has to have the full namespaced name (even "string" has to be "System.String").

The generated class is partial and the parameters are property getters with a backing field. MSDN suggests that to pass in your parameters you should manually code a partial class with conventional properties or a constructor. Actually, there's an easier no-code way. Use the Session property (which is just a Dictionary<string, object>) which you can use with an Initialize() method. Like this:

//create the class generated by TextTemplatingFilePreprocessor 
var generator = new ClassWriter();
//create a session dictionary, fill it and initialize
generator.Session = new Dictionary<stringobject>();
generator.Session.Add("table", table);
generator.Initialize();
//transform!
var text = generator.TransformText();
The key things to watch out for:
  • you must create the Session dictionary (it's not initialized internally)
  • you must call Initialize() after it's populated.

You can also use System.Runtime.Remoting.Messaging.CallContext but weirdly you must still initialize the Session dictionary (Initialize checks Session first, then CallContext).
 
You may be tempted to reuse the T4 template class like this.
//don't do this
var generator = new ClassWriter();
foreach (var item in list)
{
    generator.Session = new Dictionary<stringobject>();
    generator.Session.Add("table", item);
    generator.Initialize();
    var txt = generator.TransformText();
    WriteText(item, txt);
}
The template class actually uses an internal StringBuilder called GenerationEnvironment. So each call returns everything you wrote before. You can't actually reset the StringBuilder (although you can append to it with Write overloads). So, always create the template class within the loop.



posted on Friday, June 10, 2011 1:50:55 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0]