KnownTypeAttribute serialization error

It can happen that you get this exception while deserializing an object from xml:

Type ‘xxxx’ with data contract name ‘xxxxxxxxx’ is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types – for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.”

Do not despair, this is because the framework need to know what types are nested within the document and what to expect. To fix it, add the KnownType attribute above the unknown class :

[KnownType(typeof(selectionbox))]
public partial class selectionbox

SimpleMembership with an existing database.

I’ve been trying the SimpleMembership today and I just love it, the Asp.Net team came out with the simplest solution, great!

Managing users and their rights has always been a pain using the built in Membership feature pushing many developer to write their custom user/role tables, spending a lot of time in configuration and extending the various MembershipProvider and RoleProvider, as I did. SimpleMembership addresses that, but let’s start from the beginning, it will be quick don’t worry!

Authorization vs Authentication

The Asp.Net membership provides a  built in solution to manage authentication and authorization. While the Authentication defines the mechanism used to assign an identity (and eventually one or more roles) to a user, the authorization simply defines what an user or a role can access. The definition is obvious but necessary, because one of the main criticism is that in order to get even a basic authentication in place  there’s a lot of  setup code, including  functionality that will be hardly used. So basically in order to get to this:

if(User.Identity.IsAuthenticated && User.IsInRole("Administrator"))
{
 //do something
}

You need this (see picture below) and yes, it comes with a lot of lovely keys required in the web.config. It’s a bit too much for getting to the point to where I can safely assign a forms authentication ticket (ASPXAUTH cookie) to my user.Details on how to create the database can be found here.

membership schema

Universal Providers

Things improved with the recent introduction of the Universal Providers. Enabling support for all the SQL Server family, including azure, they can be easily integrated with the new DotNetOpenAuth providers and give back a cleaner database (picture below).  The main bits however remains the same: config keys needed for roles/profiles/membership, which is fine if you want to tune the default behaviour!

SimpleMembership

And what if instead you’re happy with that default behaviour and you want to get immediately productive, skipping all the configuration part ? SimpleMembership is the answer.

A new security provider actually hosted in the WebMatrix.WebData.dll and added by default within the Website template in Visual Studio, reducing to the essential both the SQL dependencies and the code to implement to get it working.  John Galloway gives a great overview of the SimpleMembership class in his post, describing how it inherit from ExtendedMembershipProvider, which extends the classic MembershipProvider.

All this goodness is accessed within webpages/controllers through the static WebSecurity class, which embeds all the authentication features usually needed, including the FormsAutentication SignIn/SignOut. For instance with a call to WebSecurity.Login a user get both validated and receive the authentication cookie I was talking about previously.All without one line of config. That’s awesome.
websecurityclass login

The database produced is really tiny and the required tables can be easily included within an existing one, using EFCode first for instance.

How does it works ? The SimpleMembership in order to work with your existing user table need a UserId and a UserName columns.  These values will then been used internally by the provider to hook up with the other membership tables containing the remaining bits that compose the full user profile. You can add the columns to any table as long it is decorated with the UserProfile attribute.

[Table("UserProfile")]
public class UserProfile
{
 [Key]
 [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
 public int UserId { get; set; }
 public string UserName { get; set; }
 public string Email { get; set; }
}

That’s it. UserProfile can be any of the tables of my current EFContext, just comment out the default connection string for the application services database on the web.config and use the DataContext one when initialiting the Membership. By default. with the MVC project, the membership get initialized within the AccountController with the [InitializeSimpleMembership] attribute, let’s comment it out and move the WebSecurity.InitializeDatabaseConnection  call in the global.asax.

protected void Application_Start()
{
 AreaRegistration.RegisterAllAreas();
 WebApiConfig.Register(GlobalConfiguration.Configuration);
 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
 RouteConfig.RegisterRoutes(RouteTable.Routes);
 BundleConfig.RegisterBundles(BundleTable.Bundles);
 AuthConfig.RegisterAuth();

//initialiting the database
 Database.SetInitializer(new DataContextInitializer());
 DataContext c = new DataContext();
 c.Database.Initialize(true);
 //DefaultConnection is used by the EF Context too.
 WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName",
 autoCreateTables: false);
}

Now that all is place, an example of why WebSecurity make it easy is the method CreateUserAndAccount. The result is the creation of a user record for our entity table plus its membership account. Note that the Email field is a custom column and it can be easily passed with an anonymous type to the method.

WebSecurity.CreateUserAndAccount("xyzUser", "xyzPassword", new { Email = "xyzUser@mail.com" }, false);

simplemembershiprecord

That’s basically all it takes to get started with the SimpleMembership. Despite a lack of documentation here are some useful links:

Most of the answers can also be found by simply investigating the WebMatrix.WebData assembly with ILSpy !

SQL Collation conflict

While attempting to copy  records from older database backup

update a
set latitude = b.latitude, longitude = b.Longitude
from newtable a
inner join [OldDb].[dbo].[LegacyTable] b on
b.name = a.name

I’ve encoutered the following :

Msg 468, Level 16, State 9, Line 5
Cannot resolve the collation conflict between “Latin1_General_CI_AS” and “SQL_Latin1_General_CP1_CI_AS” in the equal to operation.

Possibly caused because the file comes from SQL Server 2008 while now I’m on the 2012. 

Luckly easy to fix by adding COLLATE DATABASE_DEFAULT on the columns used by the equals operator:


update a
set latitude = b.latitude, longitude = b.Longitude
from newtable a
inner join [OldDb].[dbo].[LegacyTable] b on
b.name = a.name
b.name COLLATE DATABASE_DEFAULT = a.name COLLATE DATABASE_DEFAULT

Resize your images for Facebook

This an old utility I wrote a couple years ago in order to resize the images downloaded from my digital camera. After a recent trip to Spain where me and my friends took a lot of pictures, I tough it worthed to pick up again the solution and give it a refresh. Instead of uploading to Facebook several pictures weighting an average of 5mb each. Code is quite simple and old, don’t expect unit tests, funky interfaces, multithread and so on.. :) . You can download the full source code here or just download the client from here. If you’re getting the client, you only need to extract the archive on your pc and run it straight it by launching GM.ImageResizer.Win.exe, best to create a shortcut for the file on your desktop. I’m sure there’s plenty of similar tools around, here’s how this one works:

Unzip the archive and launch the file GM.ImageResizer.Win.exe

image

Launch the application and select the folder containing the images you want to resize:

image

Then select the ouput folder where you want the resized images to be dropped:

image

Finally select the output quality and resolution and then press GO!:

image

One completed, you can then find the resized images in the output folder, the size is much smaller then the original.

image

Happy upload!

Fluent interfaces introduction and sample.

Learning how to write a fluent interface can help when you want to write the next ORM or if you just wonder how to concatenate your methods in a LINQ style. I’m particularly interested in using this technique to write Html helpers. Anyway, let see a basic example.

A simple calculator class/interface , using a fluent interface:

Code Snippet
public interface IFluentCalcolator
{
    IFluentCalcolator Init(decimal number);
    IFluentCalcolator Add(decimal number);
    IFluentCalcolator Substract(decimal number);
    IFluentCalcolator Multiply(decimal number);
    IFluentCalcolator Divide(decimal number);
    decimal Result();
}

public class FluentCalculator : IFluentCalcolator
{
    private decimal _initialValue = 0;
    public IFluentCalcolator Init(decimal number)
    {
        _initialValue = number;
        return this;
    }

    public IFluentCalcolator Add(decimal number)
    {
        _initialValue += number;
        return this;
    }

    public IFluentCalcolator Substract(decimal number)
    {
        _initialValue -= number;
        return this;
    }

    public IFluentCalcolator Multiply(decimal number)
    {
        _initialValue *= number;
        return this;
    }

    public IFluentCalcolator Divide(decimal number)
    {
        _initialValue /= number;
        return this;
    }

    public decimal Result()
    {
        return _initialValue;
    }   
}

And here’s how to use it, the method concatenation looks coolWinking smile

Code Snippet
[Test]
public void FluentCalculator_Test()
{
    var fluentCalcolator = new FluentCalculator();
    var result = fluentCalcolator.Init(10).Add(10).Divide(4).Multiply(5).Result();
    Assert.True(result == 25);
}

Easy join tables with EF Code First.

Entity Framework Code First is getting even better, release after release. Here’s how to easily get a many to many relationship between two entities. Not to much to do really, once the relationship is specified within the two classes (an ICollection navigation property for each of the two ends in the relation), EF will take care of creating a join table.

Code Snippet
public class Character : BaseEntity
{
    public string Name { get; set; }
    public bool IsEvil { get; set; }
    public virtual ICollection<Videogame> Videogames { get; set; }
}

public class Videogame : BaseEntity
{
    public string Name { get; set; }
    public DateTime ReleasedDate { get; set; }
    public virtual ICollection<Character> Characters { get; set; }
    public Author Author { get; set; }
}

 

Code Snippet
[Test]
public void CreateJoinTable()
{
    var character = new Character() {Name = "Wario", IsEvil = true};
    var videogame = new Videogame() {Name = "Super Mario Bros 20", ReleasedDate = DateTime.Now , Characters = new Collection<Character>()};
    videogame.Characters.Add(character);
    var context = new NerdContext();
    context.Add(videogame);
    context.SaveAllChanges();
}

image