RSS

The located assembly’s manifest definition does not match the assembly reference


“System.IO.FileLoadException: Could not load file or assembly \”System.Windows.Interactivity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\” or one of its dependencies. The located assembly’s manifest definition does not match the assembly reference. (Exception from HRESULT: 0×80131040)”:”System.Windows.Interactivity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″

Looking in my solution explorer I can see I have referenced System.Windows.Interactivity, Version=4.5.0.0

Windows.Interactivity

But why does he complaint that version 4.0.0.0 is not found. The short answer for the problem is that another referenced library references itself System.Windows.Interactivity with version 4.0.0.0. Therefore, because version 4.5.0.0 is loaded by the version 4.0.0.0 is not found.

The solution is to configure a assemblyBinding in app.config.

This is done as follows:

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
        <assemblyIdentity name="System.Windows.Interactivity" 
                          publicKeyToken="31bf3856ad364e35" 
                          culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.5.0.0" 
                         newVersion="4.5.0.0" />
    </dependentAssembly>
</assemblyBinding>
 
Leave a comment

Posted by on February 20, 2014 in C-Sharp

 

sql71502 when using INSERTED keyword

Recently I had a strange exception when using the INSERTED keyword. It always mentioned that the Id property does not exists on table X.

SQL71502-Exception

The solution is rather simple. Just put the scheme name to your table then the exception is gone.

SQL71502-Solution

 
Leave a comment

Posted by on January 20, 2014 in SQL

 

Constant Enum: Circular definition

If you have declared an enum field as constant you may get following exception:

The evaluation of the constant value for … involves a circular definition.

The code where this exception appears looks like:

private const Parity Parity = Parity.None;

Well, thats strange. There is no error. I declare a constant field with the same name as the name of the type. This is allowed, because I can also write following line of code, and this would compile

private const String String = "HELLO"

The problem with enums is that the compiler interprets the third Parity not as the name of the enumeration but as the name of the field. Hence, we have a circular reference because the constant is defined by the constant itself. To solve the compile error you have two options: either you add the fully qualified name to the third Parity value or you change the name of the field.

private const Parity Parity = System.IO.Ports.Parity.None;
//or
private const Parity ParityValue = Parity.None;

If you use tools like ReSharper that cleans up the redundant qualifiers than I would suggest you to use the second option.

 
Leave a comment

Posted by on April 29, 2013 in C-Sharp

 

Tags: ,

Find primary keys from entities from DbContext

By using DbContext you can use the DbSet.Find method to find entities by the primary key(s). To find entities attached to a DbContext by using the DbSet.Find method you have to provide all entity key values, i.e. primary key columns, that identifies the entity. This is very easy if you have a primary key consisting of only one column and/or if this columns have always the same name (like Id).

context.Set().Find(myEntity.Id);

But in the case when you have different key names and sometime more than one column that defines the key this can be very tricky and error-prone. Not to mention if you change the key-name, or add column to the primary key. You should remember your keys, write and change them everywhere in the code as follows:

context.Set<EntityName>().Find(myEntity.Key1,myEntity.Key2,myEntity.Key3);

Well it works, but is is not beautiful. Another drawback is that you have to put the keys in the exact order as they are defined as foreign key. Therefore following snippet is not equivalent to the previous one.

context.Set<EntityName>().Find(myEntity.Key3,myEntity.Key2,myEntity.Key1);

Therefore, I thought that it might be useful to create a method that retrieves all the foreign key values for a specific entity automatically. In order to do that I have to use the old DatabaseContext from the Entity Framework because the DbContext does not offer such specific methods.

public string[] GetKeyNames(DbContext context) where T : class
{
    ObjectSet objectSet = ((IObjectContextAdapter) context).ObjectContext.CreateObjectSet();
    string[] keyNames = objectSet.EntitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray();
    return keyNames;
}

This method allows me to retrieve the name for every primary key. This keys can then be used for the following method that returns an object array with all the entities foreign key values.

public object[] GetKeys(T entity, DbContext context) where T : class
{
    var keyNames = GetKeyNames(context);
    Type type = typeof (T);

    object[] keys = new object[keyNames.Length];
    for (int i = 0; i < keyNames.Length; i++)
    {
        keys[i] = type.GetProperty(keyNames[i]).GetValue(entity, null);
    }
    return keys;
}

So we have a nice and compact way to retrieve the keys for an entity:

var keyValues = GetKeys(myEntity,context1);
var newEntity = context2.Set().Find(keyValues);

With the method GetKeyNames you get immediately the key names for an entity, but this will not work if you have an inheritance hierarchy between the entities.

abstract class A { }
class B : A { }
class C : A { }

If you are now trying following code snippet

B myEntity = [...]
var keyValues = GetKeys(myEntity,context1);

you will get an exception saying:

There are no EntitySets defined for the specified entity type ‘B’. If ‘B’ is a derived type, use the base type instead.

This is because you can create only an EntitySet for the base type of the entity hierarchy. In order to fix that I modified the listing above to following:

public string[] GetKeyNames<T>(DbContext context) where T : class
{
    Type t = typeof(T);
    
    //retrieve the base type
    while (t.BaseType != typeof(object))
        t = t.BaseType;

    ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;

    //create method CreateObjectSet with the generic parameter of the base-type
    MethodInfo method = typeof(ObjectContext).GetMethod("CreateObjectSet",Type.EmptyTypes)
                                             .MakeGenericMethod(t);
    dynamic objectSet = method.Invoke(objectContext, null);

    IEnumerable<dynamic> keyMembers = objectSet.EntitySet.ElementType.KeyMembers;

    string[] keyNames = keyMembers.Select(k => (string)k.Name).ToArray();
    return keyNames;
}

Because retreiving the primary key values from the ObjectContext is expensive I modified the code above and added caching for the primary key names:

public sealed class EntityKeyHelper
{
    private static readonly Lazy<EntitykeyHelper> LazyInstance = new Lazy(() => new EntityKeyHelper());
    private readonly Dictionary<Type, string[]> _dict = new Dictionary<Type,string[]>();
    private EntityKeyHelper() {}

    public static EntityKeyHelper Instance
    {
        get { return LazyInstance.Value; }
    }

    public string[] GetKeyNames<T>(DbContext context) where T : class
    {
        Type t = typeof(T);
    
        //retreive the base type
        while (t.BaseType != typeof(object))
            t = t.BaseType;

        string[] keys;

        _dict.TryGetValue(t, out keys);
        if (keys != null)
            return keys;

        ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;

        //create method CreateObjectSet with the generic parameter of the base-type
        MethodInfo method = typeof(ObjectContext).GetMethod("CreateObjectSet",Type.EmptyTypes)
                                                 .MakeGenericMethod(t);
        dynamic objectSet = method.Invoke(objectContext, null);

        IEnumerable<dynamic> keyMembers = objectSet.EntitySet.ElementType.KeyMembers;

        string[] keyNames = keyMembers.Select(k => (string)k.Name).ToArray();

        _dict.Add(t, keyNames);

        return keyNames;
    }

    public object[] GetKeys(T entity, DbContext context) where T : class
    {
        var keyNames = GetKeyNames(context);
        Type type = typeof (T);

        object[] keys = new object[keyNames.Length];
        for (int i = 0; i < keyNames.Length; i++)
        {
            keys[i] = type.GetProperty(keyNames[i]).GetValue(entity, null);
        }
        return keys;
    }
}
 
Leave a comment

Posted by on March 30, 2013 in C-Sharp, EF

 

Tags: ,

Create EDMX-file while applying Code First

Code first is a very nice feature, especially when you use the migration feature, but what if you are applying the MVVM pattern and want to generate view models from your code first model classes? This can be achieved with T4 templates. But a model generating T4 template, such as that one that generates POCO-classes from an edmx file, requires an edmx file. But when you are using code first this file is, by design, missing. So we need a way to generate an edmx file. This can be achieved with a single static method provided by the Entity Framework. The method of interest is EdmxWriter.WriteEdmx. You can use this method as follows:

var dbContext = new MyDbContext();
var xmlWriter = new XmlTextWriter("OUTPUT-PATH", new UTF8Encoding());
EdmxWriter.WriteEdmx(dbContext,xmlWriter);

After that an EDMX-file is generated to the specified output-location which can then be used as input file for T4 templates.

 
Leave a comment

Posted by on March 29, 2013 in EF

 

Tags: , ,

WPF Printing Library v2.0 (Article in preview state)

note: this article is a preview version and is subject to change

Structure, description, text-correction will change.
Internal library changes will not likely occur.

Introduction

Please refer to the first version of this library WPF Printing Library v1.0

What can be done until now using this library?

  1. Printing footer/header/recipient on every single page
    1. Decide whether the footer is print only on the last page
    2. Decide whether the header is print on every page, but not on the last page
  2. Printing the page count on every page
  3. Decide what has to be printed: e.g. header and no footer, no page count
  4. Print a new item on a new page if there is not enough page available
  5. Printing a customizable summary of all items at the end of the report

Resolved drawbacks from v1.0

  1. If an item is longer than the available space for printing items you will get an infinite loop.
  2. According standards of WPF, that a control is created only in the main thread, you cannot print in background(I will check that and try to fix it) Not possible
  3. Impossible to print to OneNote and XPS.
  4. Until now not possible to decide whether the footer is printed only on the last page according to that you also cannot decide whether a header is printed only on the first page.
  5. Only compatible with WPF (I will not change that).

Class Library

PrintAppendixes


The PrintAppendixes is a flag-enum that defines the parts that have to be printed. Here you can set up if you want to print only the page footer, page header, footer and header or all other possible combinations of all values. As you certainly know, flag enums can be combined. That means you can select only one value but also more of them by applying it with the binary operator |.

PrintAppendixes pa = PrintAppendixes.Header | PrintAppendixes.Footer;

This enum is used for the PrintOnPage attribute that has to be added on the PrintProcessor class.

IPrintPartDefinition


I have decided to remove the definition of the print parts that have to be printed from the PrintDimension constructor. The reason for that was, because there you could set the PrintAppendixes only once and this will hold for the whole document. I thought that it would be useful to define for every page whether the PrintAppendix should be print or not. Therefore I created an Attribute hierarchy that enables this. It is pretty cool and simple. Just set an attribute of your choice on your implementation of the PrintProcessor class. You have four types of attributes available:

  • PrintOnPage
  • PrintOnAllPages
  • ExcludeFromPage
  • ExcludeFromAllPages

I think the names are self-explanatory.

Example: You want to print the footer only on the last page, but the header on every page except the last one. You achieve this by defining such a PrintProcessor class:

[PrintOnAllPages(PrintAppendixes.Header)]
[ExcludeFromPage(PrintAppendixes. Header, PrintPartDefinition.LastPage)]
[PrintOnPage(PrintAppendixes.Footer, PrintPartDefinition.LastPage)]
public abstract class TestPrintProcessor : PrintProcessor {}

That is all you need to do. Cool isn’t it? But what is happening if I define following attributes:

PrintOnAllPages(PrintAppendixes.Footer)]
[ExcludeFromPage(PrintAppendixes.Footer,1,4,5)]

If you write such a print part definition, that the footer gets only printed on page 2, 3, 6… If for a single page the ExcludeFrom and PrintOn is defined, than this print part will not be printed on this page.

Now you might think that this is pretty cool, but it is very static and needs to be defined during coding. That’s right for the attribute aspect. But I have created an additional property PrintDefinition in the PrintProcessor class on which you can call the SetPrintAttribute(IPrintPartDefinition definition) method. Now you can change when to print which print part at any time.

PrintProcessor


The PrintProcessor class is the class of mayor interest. It is an abstract class based on the interface IPrintProcessor and provides all necessary methods and properties for creating a cool print with custom headers, footers etc. In order to do that you should override the corresponding methods (GetFooter, GetHeader,…).

Note: If you define a header on page 2 and you do not provide a value for GetHeader() an exception gets raised. Not providing a header means that you do either return null or that you have not overwritten the method GetHeader().

Alternating the rows

An additional feature is to color the rows as you desire. To do that you can set a list of Brushes to the AlternatingRowColors property. But this is not enough: you have to enable the alternating coloring through the property IsAlternatingRowColor. If you just set IsAlternatingRowColor to true but do not set a value to AlternatingRowColors the default values, transparent and light gray, were used.

Break last item on new page

As you continue in printing it might be sometimes the case that you want to print the footer only on the last page. So it can be that all elements have been printed, but the footer does not fit on the last page. So we need a page break only to fit the footer on the last page. So we have the situation that on the last page the footer (and other PrintAppendixes) is printed. In order to avoid such an awkward situation you can set the property BreakLastItemIfLastPageWouldBeEmpty to.

Print result is not what you wanted

A very cool feature, for debugging reasons only is that you can enable coloring the print parts by setting ColorPrintPartsForDebug to true. This will color all the PrintAppendixes in such a way that you can see where space for a too large element is wasted.
Demo ColorPrintPartsForDebug

Bulk print

Beginning from version 2.0 you can bulk print. This method takes a list of PrintProcessors that gets printed all at once.

Print direct to printer

Also a new feature for this version is that you can start printing and choose the printer from the print dialog, but also by direct printing to the printer. This is achieved by calling one overload of the Print method. You have two overloads available:

  • PrintDocument(printQueueName)
printer.PrintDocument("PDF-XChange Printer 2012");
  • PrintDocument(printQueueName, PrintServer)

This overload is used to print to a LocalPrintServer and set some settings to it.

PrintDimension


The next class that is of interest is the PrintDimension class. It provides all necessary information to paginate the document.

Here you can control the height that is reserved for each print part if it gets printed on the page. In addition I suggest to add some properties for the column width for the IPrintContent.Content panel. This is very useful because in many times this content panel is in tabular form.

Change from v1.0: You cannot set the PrintAppendix in this class anymore. Instead you set it as attribute on the PrintProcessor class.

The default contstructor initializes the Margin to {0,0,0,0}

Relative column position

Facts that your page size may vary from print to print you want stretch or shrink the print. In version 1.0 you set for every column in the IPrintContent.Content panel the width for each column. By setting UseRelativeColumnPosition to true you enable that the columns gets shrink a stretched as they have space. To define the width for a column you simply derive from PrintDimension and create some properties with a ColumnDimensionAttribute on it. The constructor takes a double representing the percentage that a column may fill up. As second parameter you can passeither ColumnDimensionType.Absolute or ColumnDimensionType.Relative relative. These two values are for defining whether the double value is an absolute width value for the column or like in the exaple below 50% of the page width.

Example:

ColumnWidthAttribute

If you want to achieve columns that has exactly that width, than you write:

public class CustomPrintDimension: PrintDimension
{
    public CustomPrintDimension()
    {
        UseRelativeColumnPosition = true;
    }

    [ColumnDimension(.50,ColumnDimensionType.Relative)]
    public double WidthColumn1 { get; set; }

    [ColumnDimension(.15,ColumnDimensionType.Relative)]
    public double WidthColumn2 { get; set; }

    [ColumnDimension(.35,ColumnDimensionType.Relative)]
    public double WidthColumn3 { get; set; }
}

//usage

public override UIElement GetTable(out double tableHeaderHeight, out Brush borderBrush)
{
    Grid g = new Grid();
    borderBrush = Brushes.Gray;
   //for _printDimension.WidthColumn1 you will a value that repesents 50%
    //of the width of the page according the page orientation an page size.
    g.ColumnDefinitions.Add(new ColumnDefinition
        {Width = new GridLength(_printDimensions.WidthColumn1)});
    g.ColumnDefinitions.Add(new ColumnDefinition
       { Width = new GridLength(_printDimensions.WidthColumn2) });
    g.ColumnDefinitions.Add(new ColumnDefinition
        { Width = new GridLength(_printDimensions.WidthColumn3) });

Note: If you change the PageOrientation in your PrintProcessor class from Portrait, which is the default value, to Landscape you will get bigger values for WidthColumn1,WidthColumn2 and WidthColumn3 because the width of the printable area changed.

IPrintContent


This interface was refactored from ILineItem. It provides a single property only. With that property you can provide the content of the line. Unlike in the previous version you do not have to provide the height of the line. This gets computed automatically.

NOTE: If the content is bigger than the remaining space of a page the element gets positioned automatically on a new page no matter if it has space or not.

public class TestPrintContent : IPrintContent
{
    private readonly int _item;
    public TestPrintContent(int item)
    {
        _item = item;
    }
    public Panel Content
    {
        get
        {
            var sp = new Grid();
            var textBlock = new TextBlock
                {Text = _item.ToString(),};
            sp.Children.Add(textBlock);
            return sp;
        }
    }
}

If you want to specify exactly the height of the content you can do this as follows:

public Panel Content
{
    get
    {
        var sp = new Grid();
        sp.Backgroud = Brushes.Red; //only to make the grid visible.
        sp.Height = 150;
        return sp;
    }
}

PrintProcessorBackground


As you might have seen in the PrintProcessor class there is a GetBackgroud() method that provides the background of the document. The class provides only methods for positioning the background on the document and the background element, of that the opacity can be set.

Sample C# project

You can download a complete working “Visual Studio 2012 project” that demonstrates my printing library by using this link: (Click here to download the sample project.).

NOTE: please change the file format of the downloading document from *.docx to* .zip

 
31 Comments

Posted by on March 6, 2013 in Printing, WPF

 

Tags: ,

Update NuGet.exe

NuGet allows you to update third party packages, which you have referenced in your projects, but how do you update NuGet itself? After updating NuGet from the Package Manager, the old NuGet version will remain in the .nuget folder of your solution. In order to update the executable you have two options:

  • Delete the .nuget folder from both, the solution folder and from disk. Then you should restart Visual Studio. After restarting and opening the solution, you have to right-click on the solution node and select Enable NuGet package restore. This command will copy a new version of NuGet into your solution folder and reference it. The drawback is that if you did not backup the nuget.targets you will lose every modification that you did on this file.
  • open the command line, navigate to the .nuget folder and execute the following command:
    nuget.exe update -self

After completing one of both steps you should have that, the new version of NuGet got copied into the solution.

 
 

Tags: ,

 
Follow

Get every new post delivered to your Inbox.