Entity Framework validation with partial updates

I had this issue today, basically Entity Framework always validate all the entity, so if you want to make a partial update using Attach/Entity State way, you can’t do it if you have configured validation on your model and you don’t fill all your entity with good values, but we want to do a partial update without do another query before, and also without filling up all the entity with data I don’t have, so how to do it?

The most easiest and fastest way is to completely disable the validation for your operation, but this is not the ideal way, what about validating the property I’m near to udpate?

using (var db = new NorthwindDbContext())
{
    // disable the validation for this operation
    db.Configuration.ValidateOnSaveEnabled = false;

    var customer = new Customer
    {
        CustomerId = "ALFKI"
    };
    db.Customers.Attach(customer);

    customer.PostalCode = "123456789000";

    // throw sql exception because PostalCode goes over 10 chars maximum
    // String or binary data would be truncated.
    await db.SaveChangesAsync();
}

Thanks to Shimmy I found what I think is the most elegant solution:

protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
    var result = base.ValidateEntity(entityEntry, items);

    var falseErrors = result.ValidationErrors
                            .Where(error =>
                            {
                                if (entityEntry.State != EntityState.Modified) return false;
                                var member = entityEntry.Member(error.PropertyName);
                                var property = member as DbPropertyEntry;
                                if (property != null) return !property.IsModified;
                                return false;
                            });

    foreach (var error in falseErrors.ToArray())
    {
        result.ValidationErrors.Remove(error);
    }

    return result;
}

To the Shimmy sample I’ve added the condition “if (entityEntry.State != EntityState.Modified) return false;” to avoid bypass the validation when adding an entity.

Now if you test the same code as before, you will receive an entity framework exception and no round-trip will be made on sql server:

using (var db = new NorthwindDbContext())
{
    var customer = new Customer
    {
        CustomerId = "ALFKI"
    };
    db.Customers.Attach(customer);

    customer.PostalCode = "123456789000";

    // Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
    // The field PostalCode must be a string or array type with a maximum length of '10'.
    await db.SaveChangesAsync();
}

Fast and easy deployment with WiX 3.10 for Visual Studio 2015

Nino Crudele's Blog

Wix is a great toolset which able to provide all we need to create a great deployment, I’m preparing the setup for jitGate, now in private beta test and I’m using WiX 3.10, this version support Visual Studio 2015, the installation is very simple and the 3.10 build is available here.

Essentially WiX is a toolset completely based on top of Windows Installer and it is completely base on XML scripting, here the name Windows Installer XML Toolset, WiX Toolset.

WiX is free and open source and the framework is able to cover all the large number of features and options offered by Microsoft Windows Installer, it also provide a large number of tool to made easy creating our deployment database and WiX already offers a large number of setup dialog forms ready and we can also customize them.

WiX is able to offer a great WPF setup interfaces, the Wix setup…

View original post 173 more words

Web Browser Control – Specifying the IE Version

Thanks to Rick Strahl for this :)

http://weblog.west-wind.com/posts/2011/May/21/Web-Browser-Control-Specifying-the-IE-Version

Straight to the point:

Feature Delegation via Registry Hacks

Fortunately starting with Internet Explore 8 and later there’s a fix for this problem via a registry setting. You can specify a registry key to specify which rendering mode and version of IE should be used by that application. These are not global mind you – they have to be enabled for each application individually by writing a registry value for each specific EXE that is hosting the WebBrowser control.

This setting can be made for all users on local machine registry key or per user in the current user key of the registry.

For the Current User:

I’d recommend using the current user setting, as this setting can be made in one place and doesn’t require admin rights to write to the registry. This means you can actually make this change from within your application even if you don’t use an installer or run under an Admin account.

You do have to restart the app to see the change.

The key to write to is:

HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION

Value Key: DWORD  YourApplication.exe

Note that the FeatureControl and FEATURE_BROWSER_EMULATION keys may not exist at all prior to installation, so you may have to install that whole branch.

For all Users:

There are two different sets of keys for 32 bit and 64 bit applications.

64 bit or 32 bit only machine:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

Value Key: DWORD – YourApplication.exe

32 bit on 64 bit machine:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

Value Key: DWORD YourApplication.exe

The value to set this key to is (taken from MSDN here) as decimal values:

11001 (0x2AF9)
Internet Explorer 11. Webpages are displayed in IE11 Standards mode, regardless of the !DOCTYPE directive.

11000 (0x2AF8)
Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.

10001 (0x2711)
Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.

10000 (0x2710)
Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.

9999 (0x270F)
Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.

9000 (0x2328)
Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.

8888 (0x22B8)
Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.

8000 (0x1F40)
Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.

7000 (0x1B58)
Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.

The added key looks something like this in the Registry Editor:

RegistryEditorEmulation_2

Note that the 32 bit and 64 bit settings are significant depending on the type of application you are running. If you are running a 32 bit application on a 64 bit machine you need to use the Wow6432Node key to register this setting. If you’re running a 32 bit application on a 32 bit machine, or 64 bit application on a 64 bit application, then the standard registry key should be used.  This means if you’re installing a 32 bit application using an installer you probably will want to set both the Wow64 key and the regular key on the machine.

With this in place my Html Html Help Builder application which has wwhelp.exe as its main executable now works with HTML 5 and CSS 3 documents in the same way that Internet Explorer 9 does.

Incidentally I accidentally added an ‘empty’ DWORD value of 0 to my EXE name and that worked as well giving me IE 9 rendering. Although not documented I suspect 0 (or an invalid value) will default to the installed browser. Don’t have a good way to test this but if somebody could try this with IE 8 installed that would be great:

  • What happens when setting 9000 with IE 8 installed?
  • What happens when setting 0 with IE 8 installed?

Don’t forget to add Keys for Host Environments

If you’re developing your application in Visual Studio and you run the debugger you may find that your application is still not rendering right, but if you run the actual generated EXE from Explorer or the OS command prompt it works. That’s because when you run the debugger in Visual Studio it wraps your application into a debugging host container. For this reason you might want to also add another registry key for yourapp.vshost.exe on your development machine.

If you’re developing in Visual FoxPro make sure you add a key for vfp9.exe to see the rendering adjustments in the Visual FoxPro development environment.

Web Api: enable XML documentation for your subproject (external assembly)

I would admit that this post it’s simply a copy/paste of a stackoverflow response, that was really well done and IMHO should also be in the documentation! of course I up-voted that post :)

There is no built-in way to achieve this. However, it requires only a few steps:

  1. Enable XML documentation for your subproject (from project properties / build) like you have for your Web API project. Except this time, route it directly to XmlDocument.xml so that it gets generated in your project’s root folder.
  2. Modify your Web API project’s postbuild event to copy this XML file into your App_Data folder:
    copy $(SolutionDir)SubProject\XmlDocument.xml $(ProjectDir)\App_Data\Subproject.xml

    Where Subproject.xml should be renamed to whatever your project’s name is plus .xml.

  3. Next open .Areas.HelpPage.HelpPageConfig and locate the following line:
    config.SetDocumentationProvider(new XmlDocumentationProvider(
        HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));

    This is the line you initially uncommented in order to enable XML help documentation in the first place. Replace that line with:

    config.SetDocumentationProvider(new XmlDocumentationProvider(
        HttpContext.Current.Server.MapPath("~/App_Data")));

    This step ensures that XmlDocumentationProvider is passed the directory that contains your XML files, rather than the specific XML file for your project.

  4. Finally, modify ./Areas/HelpPage/XmlDocumentationProvider in the following ways:
    1. Replace the _documentNavigator field with:
      private List<XPathNavigator> _documentNavigators = new List<XPathNavigator>();
    2. Replace the constructor with:
      public XmlDocumentationProvider(string appDataPath)
      {
          if (appDataPath == null)
          {
              throw new ArgumentNullException("appDataPath");
          }
      
          var files = new[] { "XmlDocument.xml", "Subproject.xml" };
          foreach (var file in files)
          {
              XPathDocument xpath = new XPathDocument(Path.Combine(appDataPath, file));
              _documentNavigators.Add(xpath.CreateNavigator());
          }
      }
    3. Add the following method below the constructor:
      private XPathNavigator SelectSingleNode(string selectExpression)
      {
          foreach (var navigator in _documentNavigators)
          {
              var propertyNode = navigator.SelectSingleNode(selectExpression);
              if (propertyNode != null)
                  return propertyNode;
          }
          return null;
      }
    4. And last, fix all compiler errors (there should be three) resulting in references to _documentNavigator.SelectSingleNode and remove the _documentNavigator. portion so that it now calls the new SelectSingleNode method we defined above.

    This Last step is what modifies the document provider to support looking within multiple XML documents for the help text rather than just the primary project’s.

    Now when you examine your Help documentation, it will include XML documentation from types in your related project.

EF7 Provider Building Blocks

One Unicorn

In this post I’ll outline the basic building blocks needed for an EF7 provider. The idea is not to show how everything should be implemented, but rather to show what pieces are needed and how they fit together. The best examples of EF7 providers are the SQL Server and SQLite providers, which ca both be found in the EF repro on GitHub.

EF7 providers should be shipped as NuGet packages. This post does not cover NuGet packaging, but you can look at the GitHib repro for some ideas on how to do this.

Note that EF7 is still very much pre-release software and the types and APIs described here are likely to change as we evolve towards the RTM release.

Dependency Injection

EF7 makes extensive use of dependency injection (DI). That is, EF is a collection of services that work together and depend on each other largely through constructor injection…

View original post 1,176 more words