Sessão Netponto: Entity Framework 7

A minha apresentação sobre Entity Framework 7 feita na 6ª reunião presencial da Netponto em Coimbra está disponível aqui.

Os tópicos cobertos foram:

  • Novidades do Entity Framework 7
  • Entity Framework 7 vs NHibernate

Brevemente o video e a apresentação estarão disponíveis no site da Netponto.

Obrigado a todos os que estiveram presentes! Winking smile

Entity Framework Pitfalls: Table Valued Functions

As of Entity Framework 6.x, Table Valued Functions are not supported, which is really a pity.

For example, the following does not work:

CREATE FUNCTION [dbo].[GetCustomers]()



    Id INT,

    Email NVARCHAR(50),

    Phone NVARCHAR(50),

    Name NVARCHAR(50)




    INSERT @ReturnTable

    SELECT Id, Email, Phone, Name

    FROM dbo.Customer




//throws an exception complaining about TVF

var customers1 = ctx.Database.SqlQuery(typeof(Customer), "[dbo].[GetCustomers]");


var customers2 = ctx.Database.Customers.SqlQuery("[dbo].[GetCustomers]");

However, you can do this:

var customers3 = ctx.Database.SqlQuery(typeof(Customer), "SELECT * FROM [dbo].[GetCustomers]()");

And it works!

Open Source @ Microsoft


This post is based on the presentation I did for Porto Tech Hub 2015, Microsoft ♥ Open Source, slightly revised and augmented.


I intent to demonstrate that Microsoft’s involvement with open source is not exactly new.

So, the big news is:

  • Microsoft is embracing/supporting/producing/using open source software: Microsoft
    Open Source
  • Lots of APIs are now open source, others will follow!
  • Applications are being considered for release as open source!

But, let’s think for a moment… is this actually new?

A Bit of History

So, let’s take a walk down the memory lane and remember some of Microsoft’s positions on this subject…


Hmmm… this doesn’t seem good for open source, does it?


First version!


Nice! At the time, AJAX Control Toolkit offered some cool features that would integrate nicely with ASP.NET!


Open Office XML formats!


Interesting! Who would have thought? Microsoft was then the 17th top contributor to the Linux kernel, even for “selfish” reasons – they wanted to be able to run Linux inside virtual machines, and also that Linux could run Windows VMs.


Oxite was an attempt at building an open source CMS, which was discontinued. Eventually, some of the people involved moved to Orchard. Nice to see that VS includes jQuery and Modernizr in their ASP.NET templates!


Wow, this this is getting interesting! All of MVC, Web API and related stuff is now open source! It seems they are getting serious about this!


Visual Studio now has Git support!


War is over! All peace! Winking smile



But Why?

But why the big shift? Well, in my view, there are a couple of reasons:

  • Trust the source: companies will respect more a package if they can see what’s inside and even change it
  • Gain from community: attract respected developers from the open source communities; have others fix bugs and contribute new features
  • Build bridges: join communities with similar concerns together; we don’t always have to be competitors
  • Reach other markets: sell software to other platforms; profit from support instead as from licenses
  • Everybody else is doing it!

What Exactly Are We Talking About?

So, what is exactly Microsoft’s commitment to open source today? I’d say it’s down to:


Microsoft has submitted for standardization (unlike others who are generally considered more open source friendly). Some examples include:

Not exactly open source, but they are also involved in the working groups that are specifying a number of technologies:


They have also build a couple of open source languages:

And also support others in IIS and in tools such as Code and WebMatrix:

Frameworks and Libraries

Microsoft has made available a number of frameworks and libraries, including:

A free implementation of Redis:

It also contributed a number of libraries to existing projects:

Visual Studio templates include popular open source JavaScript libraries:

And IntelliSense is offered for a number of others:

The next version of Visual Studio, 2015, will also support popular libraries for building JavaScript and managing dependencies, fully integrated with the IDE:

Finally, the Microsoft Ajax Content Delivery Network makes available all of these and more:


Also some great tools have been open sourced:

Others were made freely available:

Where Can I Find More Info?

There are a number of Microsoft-sponsored locations:

What’s Next?

Microsoft – or, rather, some of its employees – have given glues on what might come next:

  • Windows Live Writer: the popular blog editor is probably going to be released as open source. Scott Hanselman has been championing this cause
  • Internet Explorer: there have been talks about open sourcing it, especially now that it is going to be replaced by Edge in Windows 10
  • Windows Phone and Windows: also possible, there have been rumors about it, but not quite substantiated, I’d say

I would like to add a couple of suggestions myself:

  • SharePoint Designer: it is now freely available and has a number of notorious bugs; could profit from the community, because there is no other tool that does what it does
  • Expression Studio: the Expression suite has been discontinued and parts of it are present in Visual Studio 2013
  • Visual Studio Code: it is already based in an open source project (GitHubAtom)


So, as you can see, open source and Microsoft’s engagement is not exactly new. Microsoft has made important contributions to open source and appears to be willing to go even further. Not sure if Windows or Visual Studio themselves will ever be open source – I doubt it – but I think we will see an increasing push towards cross platform and open source solutions in the Microsoft ecosystem. These are interesting times indeed! Winking smile

NHibernate Pitfalls: Sharing a Session in Multiple Threads

The NHibernate ISession is not thread-safe, that is, it shouldn’t be shared by multiple threads. The ISessionFactory, however, is thread-safe, and thus it should be used to create ISession instances as needed. Do not worry, creating sessions does not mean that connections to the database are immediately open and kept alive, the ISession implementation only opens database connections when they are necessary and closes them when they cease to be.

Lesser-Known NHibernate Features: Statistics

NHibernate makes available a number of statistics about its work; this includes, among others:

  • All of the queries executed;
  • Number of entities loaded, inserted, updated and deleted;
  • Number of optimistic concurrency misses;
  • Number of second level cache hits and misses;
  • Number of transactions started and committed;
  • Number of connections opened and closed;
  • etc.

This is available per session factory:

var statistics = sessionFactory.Statistics;

And all of these settings can be filtered per entity:

var entityStatistics = sessionFactory.Statistics.GetEntityStatistics("MyEntity");

Statistics can help us diagnose, for example, second level or query cache issues.

If we have no need for them, we can disable them before building the session factory:

cfg.SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, Boolean.FalseString);

Or at runtime:

sessionFactory.Statistics.IsStatisticsEnabled = false;

An advice: do switch it off while on production, it does have an effect on performance.

SharePoint Reference Document Updated

Just updated my SharePoint reference document Excel (references: here and here) with the default content placeholders.

It now contains:

  • Fields: all the built-in SharePoint field types;
  • Content types;
  • List templates;
  • Site templates;
  • SPDataSource returned fields;
  • List fields;
  • Document library fields;
  • Search content classes;
  • Content placeholders in default master pages.

If you have any corrections or if I missed something, please let me know!

Lesser-Known NHibernate Features: Dynamic Components

NHibernate, unlike others, has lots of ways to map columns from the database to and from classes. Normally, there is a 1:1 relation between columns and properties, but it doesn’t have to be so: there are, for example, components and dynamic components.

This time we will be looking at dynamic components. Dynamic components allow the usage of a dictionary, where one or several columns from the database will be stored, each in its own entry. This is pretty cool, if we need to add more columns at some point, and we do not want, or can, change the class!

Show me the code, I hear you say:

public class DataStore


    public DataStore()


        this.Data = new Dictionary<String, Object>();



    public virtual int Id { get; set; }


    public virtual IDictionary Data { get; set; }


Yes, it will be possible to use generic dictionaries (IDictionary<TKey, TValue>), when pull request for NH-3670 is merged, which should happen soon (NHibernate 4.1).

Now, the mappings:

var mapper = new ConventionModelMapper();

mapper.Class<DataStore>(x =>


        x.Id(y => y.Id, y => { });

        x.Component(y => y.Data, new


            A = 0,

            B = ""

        }, y =>


            y.Property(z => z.A);

            y.Property(z => z.B);



I am setting the template for whatever will be stored in the Data dictionary, in this case, an integer column (A) and a string one (B) as an anonymous object. In NHibernate 4.1, it will be possible to use a dictionary instead (see NH-3704), which will help in making it more dynamic. In the third parameter to Component, we can change the mapping, for example, the physical properties of each column; we can even use ManyToOne instead of Property, so that a particular entry in the dictionary will point to another entity!

A sample usage:

session.Save(new DataStore { Data = new Dictionary<String, Object> { { "A", 1 }, { "B", "two" } } });

Windows Live Writer Tricks

As many others, I use Windows Live Writer (WLW) as my main tool for blogging. It has aged a bit over the years and sometimes crashes, but I think it is still the best tool around for this purpose. It will only get better if Scott Hanselman (@shanselman) succeeds in releasing it as open source! Winking smile

I would like to share with you some of my favorite tips for getting the best out of it.

  1. Change default style and template:
    Navigate to %ProgramFiles(x86)%\Windows Live\Writer\template and change the files defaultstyle.css and default.htm. New posts will inherit these.
  2. Change IE version used for rendering posts:

    Set the desired Internet Explorer version through the Registry: go to HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION and add key WindowsLiveWriter.exe with a value of (DWORD) 10000 (for IE10) or 11000 (IE11). Now you can preview HTML5 features right on WLW.
  3. Change posts location:
    This is useful if you use several machines and you want to keep all your posts (drafts, published) in the cloud (OneDrive, DropBox, Google Drive, etc). In Registry, go to HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows Live\Writer and add key Posts Directory. The value must be a full path!

  4. Export settings:
    Export all WLW settings by exporting this Registry key (and everything below): HKEY_CURRENT_USER\Software\Microsoft\Windows Live\Writer\Weblogs.
  5. Clearing cached themes:

    If you run into problems with a site’s theme, clear its local cache. Cached CSS and image files are stored at %AppData%\Windows Live Writer\blogtemplates.

  6. Disabling blog theme:
    If your theme misbehaves, and clearing the local cache doesn’t help, you can disable it in the ribbon:
  7. Use the Windows Live Writer SDK:
    Create plugins for WLW in .NET. Download the SDK here and reference it from %ProgramFiles(x86)%\Windows Live\Writer. There are several examples out there, just check out this one.
  8. Log file:
    The log file and a couple of others are located here: %LOCALAPPDATA%\Windows Live Writer.
  9. Open old posts:
    If you need to open a post that you created a long time ago and it no longer shows in the recent posts list, what to do? Get the WLV Post Download plugin from After you have it, open a blog post in your browser with the WLW protocol. For example, to use it with an Orchard or WordPress blog (MetaWeblog API), use this format: wlw://blog?postid=id, where you first need to find out the post id; with other blogs, use the format: wlw://blog/page.aspx. This will open up WLW with the desired post, and you can now change it and publish it.
  10. Use Blog This for blogging over a web page:
    In Internet Explorer, WLW adds an option for adding a link to the current page in a new blog post. It is called Blog This in Windows Live Writer and is available in the Tools menu:
  11. Use plugins:
    WLW has lots of plugins available on the Internet. My favorites are:
  12. Use the source:
    When you can’t easily format your text the way you want it using the designer (Edit) tab, you can switch to the Source tab and make your changes there. WLW will synchronize the designer.
  13. Post drafts to your blog:
    imageAfter you save the draft, it won’t be visible to the World, you need to use your blog’s management console to actually publish it.
  14. Get to know other WLW options:
    In FileOptions, explore what WLW offers (save auto recovery information, show word count in real time, disable emoticons, remember to add tags, check spelling, etc):