Open XML SDK Tool to analyse documents and generated C# code

Yesterday I discovered Package Explorer for opening up OpenXML documents, validating and editing. Today I have found OpenXml SDK Tool.

SDK Tool is a great software from Microsoft for every developer working with OpenXml. SDK Tool is similar to Package Explorer, but you don’t have edit functionality. And validation messages are not as good. But you get an instant access to documentation about any possible element you can imagine.
And the killer function is CODE GENERATION! It generates C# code for any element that is available on the page.

You can create a Word Document, open it up in SDK Tool and it will produce you a full C# listing to create exactly the same document from your code! This is just fantastic! Using this tool today I was discovering how things done in a simple way: add page numbers to an empty Word-doc, open it up in SDK Tool, find the part about page numbers (probably this was the hardest part), copy the generated code, slightly refactor and I had page numbers in my generated documents. All it took about 15 minutes and I did not use Google or any other documentation.

Anyway, download SDK Tool from here: http://www.microsoft.com/en-gb/download/details.aspx?id=30425. Select only SDK Tool to download, you won’t need anything else available on the page.

Once installed find Open XML SDK Productivity Tool in your start menu and open a Word document.

You can select any element of the document and see documentation to that, with all available child node types

Documentation

You can run validation of any element in the document:

Validation

And the promised killer feature – Generated code:

See_Generated_Code

Another quite useful function is to compare the documents. Yesterday I had to do that to find out how a particular feature is implemented. Now, when you have a generated code, this may be not so useful, but you can compare 2 Word documents and it’ll show you the differences in containing XML.

Validating of OpenXml generated documents or The file cannot be opened because there are problems with contents.

Stackoverflow is useful until you have a quite specific question and you have used Google before asking a question. My last 11 questions were left with no answers for one or another reason.

Today was not an exception. My question about debugging process during OpenXml development was left unnoticed. So I had to figure out for myself! Sigh!

UPDATE: I have discovered Open XML SDK Tool that adds a lot of features to this game

Anyway, I digress. My current task involves generating a MS Word document from C#. For that I’m using OpenXml library available in .Net. This is my first time touching OpenXml and maybe I’m talking about basic stuff, but this was not easily googleable.

Many times after writing a Word file, I try to open it and see this message:

The file .docx cannot be opened because there are problems with the contents. Details: Unspecified error

The file .docx cannot be opened because there are problems with the contents. Details: Unspecified error

Continue reading

Inside of Entity Framework Migrations or How to View Generated Xml-Schema

Entity Framework migrations are very clever. But cleverness can come out from the wrong end sometimes. Over last 2 days I’ve spent at least a day debugging my migration scripts and not getting anywhere.

The trouble was in EF thinking that there is a migration pending, but nothing given to me to migrate: when I run Add-Migration, all I got was empty migration:

public void Up()
{
}
public void Down()
{
}

But still, on every attempt to use domain context, I was thrown an exception:

Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.

That was soul destroying. I’ve spent hours banging my head against the keyboard with no results.

When I had to fix other problems I kinda put out the fire temporarily by saying

Database.SetInitializer<DomainContext>(null);

This is a hack, it makes the exception to go away, but does not fix the problem with migration. So I only put that in place as a quick fix to move forward a bit.

Continue reading

How We Do Database Integration Tests With Entity Framework Migrations

There is a follow-up article about integration tests in 2016. Recommended for reading if you are using VSTS and looking at Cake build system

Unit tests are fine and dandy, but if you persist your data in database, persistence code must be tested as well. Some possible bugs will never be picked up only by unit tests. One of the issues I’ve been burned by is entity validation, another is a missing foreign key relationship.

Validation issues can burn you very easy. Look at this bit of code:

public class Person 
{
    [Key]
    public Guid PersonId { get; set; }

    [Required]
    public String FirstName { get; set; }

    [Required]
    public String LastName { get; set; }
}

public void CreatePerson(string firstName, string lastName)
{
    var newPerson = new Person();
    newPerson.FirstName = firstName;

    // dbContext was injected via constructor
    dbContext.Persons.Add(newPerson); 
    dbContext.SaveChanges();
}

NB: This is just a sample code. Nowhere in my projects we do such things.

Continue reading

Attempt to do View Compilation for Azure Web Role

We are hitting the deck with our site performance and optimisation. It is fast, but we want it uber-fast! So next stage is to have IIS up and active all the time with all the views being compiled and ready before any user comes to them.

By default, IIS compiles views only when a request for that view comes in. So first time a user visits some rare page in your application, user is waiting a bit longer while IIS does Just-In-Time compilation. And actually if you look under the hood IIS does stacks of things before it shows you a web-site.

Despite of common believe, IIS does not run your web-application from /bin folder, it copies all required files to a temp folder. To be more specific, it copies files to c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\. Reason for that – file locking. For just-in-time compilation, it needs to update binaries, but in /bin folder binaries can be locked.

Continue reading

Implementing HTTPS Everywhere in ASP.Net MVC application.

HTTPS everywhere is a common theme of the modern infosys topics. Despite of that when I google for implementation of HTTPS in ASP.Net MVC applications, I find only a handful of horrible questions on StackOverflow, about how to implement HTTPS only on certain pages (i.e. login page). There have been numerous rants about security holes awaiting for you down that path. And Troy Hunt will whack you over your had for doing that!

See that link above? Go and read it! Seriously. I’ll wait.

Have you read it? Troy there explains why you want to have HTTPS Everywhere on your site, not just on a login page. Listen to this guy, he knows what he is talking about.

Continue reading

Resharper vs Visual Studio

Resharper is becoming more and more monstrous. Soon it will be an IDE in itself and won’t need Visual Studio at all!

When a new 8.1 version was out, I was overly excited with it. Even paid almost 100 quid for a licence out of my own pocket (for my personal use). After using it for 2-3 months, I’m not so happy with it.

Project I mostly work on has some sizeable amount of MVC controllers and views: 180K lines of code excluding code for views. On this codebase R# is choking badly.

Autocomplete

A lot of the times I get very random completion suggestions, even through I almost typed complete name for local variable that was defined a line above. Many times I get some random namespaces added to using block because R# thought I’m done with typing and concluded that I need some random namespace. I’ve disabled Resharper Intelisence and now using native Visual Studio functionality for that. VS does seem to do not a bad job there. Also it is not as automatic as R#, so I need to press Ctrl+Space to get the completion. Yes, extra 2 keystrokes, but that protects you from random crap that R# decides to add to your class.

Go Anywhere

Go Anywhere in Resharper 7 was useful. Most of the times it got me where I needed to. In v8 this is a VERY global search, and order of suggestions is nowhere near how it should be. When I type “web.cofnig” in Go Anywhere box, I expect to see web.config file in root of the project as first suggestion. Not some other auto-generated classes that have web and config in their name somewhere, like MyApp.Web.Infrastructure.AutomapperBootstrap.config. Most of the times the suggestion is bang on, but when it is not, it is so wrong – I don’t know where to start rant about it. Also, why does it offer me auto-generated classes as a first navigation option? (think T4MVC-generated controllers).

Turns out that Visual Studio has it’s own Navigate To option. Usually invoked by Ctrl+,, but probably R# have messed up the keyboard shortcuts for you, so you’ll need to re-assign the mapping again. And navigation in VS is not trying to be very smart, hence getting me to the places I’d like to go.

I’m dependant on Resharper so much, at the moment I can’t work without it. This is bad! I’ll keep adding here native replacements to R# functionality, as I discover them.

Here are the options I’d like to find replacements to:

  1. Renaming of classes and controller actions
  2. Creating of new classes from their name.
  3. Initialise fields from constructor parameters – for IoC injections
  4. … probably another infinite list of functions coming from R#

Why I’m not migrating to xUnit completely

After initial excitement about xUnit and how cool your tests become with AutoDataAttribute. My itch to convert all my tests into xUnit have died down. And I’m not excited as much. XUnit is certainly not the silver bullet.

I do agree with certain things that are in xUnit, like not providing [SetUp] and [TearDown], rather have constructor and destructor, but can’t agree with other things. And the authors of xUnit have not been listening to their community which is unfortunate. I’ll list the annoyances I discovered in the order I faced them.

Continue reading

MvcSitemaps Vs T4MVC and test for all controllers

One of the tasks have performed lately in our massive web-application is restructuring menu. And for the menu to work correctly we had to make sure that every page is somewhere on the menu.

For Menu generation we use MvcSitemapProvider. And for strongly-typed references to our controllers/actions we generate static classes via T4MVC. Task of making sure that every controller action (out of ~600) has a SiteMapAttribute is very tedious. And with development of new features, this can easily be forgotten, leading to bugs in our menu. So we decided to write a test. This turned out to be yet another massive reflection exercise and it took a while to get it correctly. So I’d like to share this with you.

Theory of the test are simple – find all controllers, on every controller find all the methods and check that every method has a custom attribute of type
MvcSiteMapNodeAttribute. But in practice this was more complex because we used T4MVC.

Continue reading