Entity Framework Pitfalls: TransactionScope

Most people using Entity Framework use the TransactionScope API to manage database transactions. This is a powerful API, that can be used to enlist .NET APIs and even WS-*-compatible web services in transactions, that may well be distributed. Microsoft used to recommend it for working with EF, but isn’t doing it anymore, or, at least, developers need to understand a thing or two.

Most modern APIs offer asynchronous methods in addition, or instead, of blocking ones, and Entity Framework is a good example – just think of SaveChangesAsync, FindAsync and ToListAsync. The problem with TransactionScope prior to version 4.5.1 was that it didn’t handle well transaction-enabled methods running in other threads – which is what EF’s asynchronous methods do. In this version, Microsoft introduced the

TransactionScopeAsyncFlowOption flag, which can be used to tell TransactionScope to flow transactions across async threads.

Also, if we open two database connections inside a TransactionScope, the transaction gets automatically promoted to a distributed one. The problem is, distributed transactions require Microsoft Distributed Transaction Coordinator service running, and it is not available in Azure, for example (Web Apps).

So, the key here is: if we cannot be certain of the environment where EF will run, which may include pre-.NET 4.5.1 or Azure, we should use explicit transactions instead. It’s not that difficult, it’s just a matter of calling Database.BeginTransaction() and either committing or rolling back/disposing of the returned object when we are done with it.

Inline Images in ASP.NET MVC Core

I have blogged extensively about Data URIs in the past. It allows us to render external contents inside of the page’s HTML, avoiding additional HTTP requests, but enlarging the HTML to serve. Sometimes, it does make sense, especially because the whole page can be made cacheable.

MVC does not offer any mechanism for serving images as inline Data URIs, and that is the reason for this post! Winking smile

For this example, I added an extension method to the IHtmlHelper class, InlineImage:

public static class HtmlHelperExtensions

{

    private static string GetFileContentType(string path)

    {

        if (path.EndsWith(".JPG", StringComparison.OrdinalIgnoreCase) == true)

        {

            return "image/jpeg";

        }

        else if (path.EndsWith(".GIF", StringComparison.OrdinalIgnoreCase) == true)

        {

            return "image/gif";

        }

        else if (path.EndsWith(".PNG", StringComparison.OrdinalIgnoreCase) == true)

        {

            return "image/png";

        }

 

        throw new ArgumentException("Unknown file type");

    }

 

    public static HtmlString InlineImage(this IHtmlHelper html, string path, object attributes = null)

    {

        var contentType = GetFileContentType(path);

        var env = html.ViewContext.HttpContext.ApplicationServices.GetService(typeof (IHostingEnvironment)) as IHostingEnvironment;

 

        using (var stream = env.WebRootFileProvider.GetFileInfo(path).CreateReadStream())

        {

            var array = new byte[stream.Length];

            stream.Read(array, 0, array.Length);

 

            var base64 = Convert.ToBase64String(array);

 

            var props = (attributes != null) ? attributes.GetType().GetProperties().ToDictionary(x => x.Name, x => x.GetValue(attributes)) : null;

 

            var attrs = (props == null)

                ? string.Empty

                : string.Join(" ", props.Select(x => string.Format("{0}=\"{1}\"", x.Key, x.Value)));

 

            var img = $"<img src=\"data:{contentType};base64,{base64}\" {attrs}/>";

 

            return new HtmlString(img);

        }

    }

}

You can see that I only support three image formats: JPEG, GIF and PNG. These are the safe formats that can be rendered by all browsers. The format is inferred from the file name’s extension.

The InlineImage method takes a local file name that will be considered from the site’s root, and an optional collection of attributes. If present, these attributes are added to the generated IMG tag as-is.

To use this extension, all we need is to add this code in a Razor view:

@Html.InlineImage("image.jpg", new { width = "200", height = "200" });

And the output should look like this (trimmed):

<img src="data:image/jpeg;base64,SGVsbG8sIFdvcmxkIQ%3D%3D...=" width="200" height="200" />

This code works as is in ASP.NET MVC Core, but can be easily changed to work in MVC 5 or prior: just use Server.MapPath to get the physical address of the file to load.

MVC Controller Resolver Cache

I recently faced a curious problem: I was using a third party IoC container in an MVC 5 (ASP.NET 4.*) app. In it, I had registered a service with a lifetime of transient, meaning, each resolution would return a different instance.

As you may know, in an MVC controller, there are two ways by which we can resolve a service using the MVC infrastructure:

 

I was using Controller.Resolver to resolve a service, but, after the first resolution, I would alwas get the same instance! It turns out that, by default, Controller.Resolver does not resolve to the same as DependencyResolver.Current, but instead uses an internal implementation that caches resolved services(DependencyResolver.CurrentCache, an internal property)! This means that it is virtually unusable with any lifetime other than singleton!

There are at least three workarounds:

 

If you were to ask me, I’d go for option #3.

Machine Learning Week – Packt Publishing

MLW2016-banner

The good guys at Packt Publishing are at it again!

Packt Publishing is celebrating the Machine Learning Week. Machine Learning Week runs from Monday 18th January until 23:59 GMT on Monday 25th – throughout one will be able to save 50% on some of the most popular titles – such as Python, Java .NET and many more. Also, with a 50% discount on top titles, one can also pick up a 5-eBook bundle for just $50. Checkout link http://bit.ly/209h0lv!

Sites Portugueses Sobre Desenvolvimento de Software

Actualizado a 11/05/2017

(Portuguese only, sorry!)

Os seguintes sites sobre desenvolvimento de software, nas suas várias vertentes, são escritos por portugueses, seja em português, seja em inglês. Não se trata de descriminação, mas apenas de divulgar o que é feito por portugueses, onde quer que se encontrem.

Pretende-se que seja uma lista de sites vivos, ou seja, que tenham tido alguma actividade no ano transacto ou no actual. Irei periodicamente verificá-los.

Eventualmente, irei incluir outra informação, por exemplo, principais tecnologias abordadas (ex: Java, .NET, SharePoint, SQL Server, Dynamics, etc).

Se conhecerem outros, se pretenderem corrigir ou complementar alguma informação, ou se não quiserem que o vosso site apareça listado, contactem-me!

Nome URL Autor(es)

Língua

Development With A Dot https://weblogs.asp.net/ricardoperes Ricardo Peres (@rjperes75) Inglês
Broculos http://www.broculos.net Dércia Silva e Nuno Freitas Inglês
My Time Break For SharePoint http://aaclage.blogspot.pt André Lage (@aaclage) Inglês
XptCRM http://www.xptcrm.com Pedro Azevedo (@azevedo_pedro) Português
Mónica’s Blog http://mrodriguesblog.azurewebsites.net Mónica Rodrigues (@monica85rodrig) Português
Adão Feliz http://adaofeliz.com Adão Feliz (@adaofeliz) Inglês
typeof(saramgsilva) http://www.saramgsilva.com/ Sara Silva (@saramgsilva) Inglês
Niko Neugebauer http://www.nikoport.com Niko Neugebauer (@nikoneugebauer) Inglês
André Vala https://andrevala.com André Vala (@atomicvee) Inglês
Bruno Lopes’ Lack of imagination http://blog.brunomlopes.com Bruno Lopes (@brunomlopes) Inglês
Rui Quintino Blog https://rquintino.wordpress.com Rui Quintino (@rquintino) Inglês
Tiago Duarte http://ftduarte.blogspot.pt Tiago Duarte Inglês
Ponto de Partilha http://pontodepartilha.blogspot.pt Pedro Mateus Inglês
Sandro Pereira https://sandroaspbiztalkblog.wordpress.com Sandro Pereira (@sandro_asp) Inglês
Rui Romano Blog https://ruiromanoblog.wordpress.com Rui Romano (@ruiromano) Inglês
UmProgramador.NET http://umprogramador.net Ricardo Santos (@kamoleano) Inglês
Tech Talk PT https://techtalkpt.wordpress.com Ricardo Magalhães Inglês
Stepping stones for crossing technological ponds https://mystepstones.wordpress.com Rui Melo (@ruimelo) Inglês
Demétrio Silva – Especialista SharePoint e SQL Server https://demetriosilva.wordpress.com Demétrio Silva (@demetriosqldba) Português
Rui Machado Blog https://rpmachado.wordpress.com Rui Machado (@ruimachado89) Inglês
Exceptional Code https://exceptionalcode.wordpress.com/ João Angelo (@jmpangelo) Inglês
André de Carvalho http://acarvalho.tiddlyspace.com André Carvalho Inglês
Murilo Miranda http://www.sqlshack.com/author/murilo-miranda Murilo Miranda (@murilocmiranda) Inglês
Pedro’s Tech Mumblings http://build-failed.blogspot.pt Pedro Sousa Inglês
Jorge Moura https://ojmoura.wordpress.com Jorge Moura (@jorge_moura) Inglês
Roberto Cortez http://www.radcortez.com Roberto Cortez (@radcortez) Inglês
Nuno Árias Silva Website http://www.nuno-silva.net Nuno Árias Silva (@nunoariassilva) Inglês
Digital Mind Ignition http://digitalmindignition.com Alexandre Marreiros (@alexmarreiros) Inglês
Visual Basic em Português http://www.jorgepaulino.com Jorge Paulino (@vbtuga) Português
Let’s Exchange http://letsexchange.blogspot.com Nuno Mota (@nfmota) Inglês
João Sousa Blog https://joaoeduardosousa.wordpress.com João Sousa (@joaoedusousa) Inglês
Sérgio Agostinho Dev http://sergioagostinho-dev.blogspot.pt Sérgio Agostinho Inglês
Guilherme Ferreira http://gsferreira.com Guilherme Ferreira (@gsferreira) Inglês
WHERE BLOG = ‘PDRSNTSFRRR’ http://pdrsntsfrrr.com Pedro Ferreira (@pdrsntsfrrr) Português
vsloureiroblog https://vsloureiro.wordpress.com Vitor Loureiro Inglês
pedrolamas.com – Windows Development https://www.pedrolamas.com Pedro Lamas (@pedrolamas) Inglês
ruimarinho.NET http://ruimarinho.net Rui Marinho (@ruiespinho) Inglês
André Varandas http://andrevarandas.com André Varandas (@iamvarandas) Inglês
Rambling about .NET https://nunofilipecosta.wordpress.com Nuno Filipe Costa (@nunofcosta) Inglês
The Blinking Caret http://www.blinkingcaret.com Rui Figueiredo (@ruidfigueiredo) Inglês
Ricardo Fiel https://ricardofiel.com Ricardo Fiel (@theplastictoy) Inglês
Adão, the developer http://adaodeveloper.blogspot.com Pedro Gomes Adão Inglês
Fábio Carvalho https://fcsharepoint.com Fábio Carvalho (@fcsharepoint) Inglês
Nuno Cancelo https://nunocancelo.wordpress.com Nuno Cancelo (@masterzdran) Inglês
Miguel Alho – Ramblings on developing applications http://www.miguelalho.pt Miguel Alho (@mytymyky) Inglês
The Privilege of Making the Wrong Choice http://www.eduardopiairo.com Eduardo Piairo (@edpiairo) Inglês
Tiny Bits https://medium.com/bitmaker-software BitMaker Software (@bitstiny) Inglês
Pedro Félix’s shared memory https://pfelix.wordpress.com Pedro Félix (@pmhsfelix) Inglês
HANDS ON SharePoint http://sharepoint.handsontek.net João Ferreira (@joao12ferreira) Inglês
André’s ramblings on the web https://andreduarte.info André Duarte (@onemanclapping) Inglês
Agile Management Walkthrough https://pedrogustavotorres.wordpress.com Pedro Gustavo Torres (@_pedro_torres) Português
Mr Fields https://vetras.github.io Carlos Campos (@vetraspt) Inglês
My ramblings on Azure http://007fff.blogspot.pt Fernando Madruga (@FMBMadruga) Inglês
Tiago Costa blog http://www.tiagocosta.eu Tiago Costa (@tiagocostapt) Inglês
Lusocoder https://lusocoder.com João Cardoso (@joaocardoso) Inglês
Luís Gonçalves | Sharing interests https://luisfsgoncalves.wordpress.com Luís Gonçalves Inglês
Rui Jarimba https://ruijarimba.wordpress.com Rui Jarimba (@ruijarimba) Inglês
António Lourenço http://antoniolourenco.com António Lourenço (@ciistado) Português

 

2015 in Retrospective

Well, 2016 has arrived, time to look at 2015!

This was the year I was first awarded as Microsoft MVP – by the way, I got renewed! – and the year I left CRITICAL Software for Simplifydigital and started coming to London every month. A very exciting and challenging year indeed. Made lots of new friends and started using loads of new technologies. A lot was unsaid, but something got registered!

Here is my personal list of my favorite blog posts of the year, in no particular order (well, from recent to older):

 

I can see some trends, not just in this list, but in all of the published posts:

  • Moving to ASP.NET 5;
  • Gradually dropping Web Forms in favor of MVC;
  • More Entity Framework than NHibernate;
  • Posts on plain .NET/C# instead of a particular API;
  • Some contents on SharePoint too, which will probably continue;
  • I wrote my first (and probably the last) posts on WPF/Silverlight, although I didn’t pick any for this list.

 

I also continued some of my “classic” topics:

 

And started new ones, which will continue throughout the year:

 

Did a couple of book reviews for Packt Publishing and was even one of the technical reviewers of Learning NHibernate 4.

Also, I started to gather a list of portuguese (meaning, authored by portuguese people or written in portuguese) on development, but it has proven difficult. I will get back to this soon.

I had the chance to speak at a number of events:

 

And my first article for Programar magazine was out, on ASP.NET 5, and even made the cover of the June edition!

Last but not least, I released another ebook on the Syncfusion Succinctly series: ASP.NET Multitenant Applications Succinctly Released. There will be some news on this later this year, stay tuned! Winking smile

I have to thank all of my friends and colleagues (current and former) and all the great people at CRITICAL Software, Simplifydigital, Microsoft, Packt Publishing, Syncfusion, my MVP colleagues and all my friends in the Portuguese development communities that provided inspiration, friendship and support and who had the patience to put up with me!

Now, coming back to 2016, I can imagine I will be talking more about:

  • ASP.NET 5 and MVC 6;
  • Azure;
  • SharePoint 2016;
  • Entity Framework 7.x;
  • MongoDB;
  • ElasticSearch;
  • SQL Server 2016;
  • Docker;
  • JavaScript frameworks;
  • Node.js.

 

Well, that’s it. Have a great 2016 and keep dropping by! Winking smile As always, I’d love to hear from you!