Friday, 9 December 2016

Entity Framework 7 - Dependencies issue

Couple of weeks ago I was having issues with some of the Entity Framework packages. The packages with the red squiggle were failing to load



These are the steps I followed to fix the dependencies issues:

  • Installed the latest version of Remotion.Linq 2.1.1
  • Installed "System.Interactive.Async 3.1 1

Ix-Async has been deprecated. Go to this link

 After I applied these changes the restoring of the packages was still failing:

Package Ix-Async 1.2.5 is not compatible with netcoreapp1.0 (.NETCoreApp,Version=v1.0). Package Ix-Async 1.2.5 supports:
      - net40 (.NETFramework,Version=v4.0)
      - net45 (.NETFramework,Version=v4.5)
      - portable-net45+win8+wp8 (.NETPortable,Version=v0.0,Profile=Profile78)
    One or more packages are incompatible with .NETCoreApp,Version=v1.0

  • I changed the 'import' section of the 'frameworks' json
    from
    "imports": "dnxcore50"

     to
    :"imports": [
    "dnxcore50",
    "dnx4.5.1"
     ]

After adding dnx4.5.1 to the imports section the package restore process was completed successfully

Tuesday, 2 August 2016

Automatic properties



Back on 2010 I worked on two projects for couple of months. For one project I used Eclipse/Java and for the other I used VS 2008/C#.

I remembered the day that one of our Java colleagues commented on Automatic properties, back then it was a new feature of C# (C# 3.0)

He said: "The way that you can implement properties in C# you might as well declared them public".
He was referring to this:
public decimal ExchangeRate {get;set;}; //automatic property
being the equivalent of this:
public decimal ExchangeRate. //public variable

I understand, that for automatic properties, the compiler would automatically create the required private fields.  Still that property can be assigned a value from any part of your code.

The issue that I see, and other people do, with automatic properties is that a class with automatic properties doesn't protect  its invariants. "A class invariant expresses properties of an object which are stable in between operations initiated via the public client interface".


I want to illustrate this with a small example

public class CurrencyInfo
    
{
        
public int CurrencyId { get; set; }
        
public string CurrencyCode { get; set; }
        
public decimal ExchangeRate { get; set; }
        
public string Name { get; set; }
    
}

We were tasked on creating a functionality that allows our software to perform a Currency conversion between other currencies and the Australian dollars, also known on the Australian market as the Little Battler. The CurrencyInfo class, above, is one of the classes that makes the Currency Conversion API.

Let's say that we also have a service that Update the currency using the class CurrencyInfo.

public bool UpdateCurrency(CurrencyInfo currencyInfo, string userName)
        
{
       _logger.log(
currencyInfo.ExchangeRate ,userName, currencyInfo.CurrencyCode
..............
...............//code that does the updating goes here
...............//and here
        }

What would happen if a developer, using our API, forget to set the CurrencyCode property?
We might think that We are safe because some validation can be applied on the UI level so not null or empty values would make their way into the CurrencyInfo class.

However, we write code for reuse and it is not uncommon that many API get used by Cron jobs or Windows services. Think about a poller, polling salaries in Singaporean currency that needs to be converted to Australian currency. Can we guarantee that a property such as CurrencyCode is set to a correct value?

I like the idea of checking for properties values in the class where they are declared. Another approach would be to do this kind of check on the Application Service Layer.  I think that with this approach we would need to check that the CurrencyInfo class has valid values on every Service class or Servcie's method that uses it.

By having check in our properties the class invariant are protected and the  class or instance of the class don't go into an invalid state.

Remember that what is a 'valid' value  varies depending on the business requirements.  In one application a Salary of 0 might be a valid value whereas on another might not.

public int CurrencyId
  
{
      
get
      
{
          
return currencyId;
      
}

      
set
      
{
          
//we don't have currency id negative or zero
          
if (value <= 0)
              
throw new ArgumentOutOfRangeException(nameof(value));

          
currencyId = value;
      
}
  
}
  
public string CurrencyCode
  
{
      
get
      
{
          
return currencyCode;
      
}

      
set
      
{
          
if (value == null)
              
throw new ArgumentNullException(nameof(value));

          
currencyCode = value;
      
}
  
}
  
public decimal ExchangeRate
  
{
      
get
      
{
          
return exchangeRate;
      
}

      
set
      
{
          
if (value < 0)
              
throw new ArgumentOutOfRangeException(nameof(value));

          
exchangeRate = value;
      
}
  
}

So now with the safe guard checks in place, We could go one step further and make sure that users of the CurrencyInfo are obligated to provide the property values when they create an instance of the CurrencyInfo.

We could do this by making the setters private and creating a constructor that take the properties' values.

public CurrencyInfo(int currencyId, string currencyCode,
                            
decimal exchangeRate, string name)
        
{
            
CurrencyId = currencyId;
            
CurrencyCode = currencyCode;
            
ExchangeRate = exchangeRate;
            
Name = name;
        
}
        
public int CurrencyId
        
{
            
get
            
{
                
return _currencyId;
            
}

            
private set
            
{
                
//we don't have currency id negative or zero
                
if (value <= 0)
                    
throw new ArgumentOutOfRangeException(nameof(value));

                
_currencyId = value;
            
}
        
}
        
public string CurrencyCode
        
{
            
get
            
{
                
return _currencyCode;
            
}

            
private set
            
{
                
if (value == null)
                    
throw new ArgumentNullException(nameof(value));

                
_currencyCode = value;
            
}
        
}
        
public decimal ExchangeRate
        
{
            
get
            
{
                
return _exchangeRate;
            
}

            
private set
            
{
                
if (value < 0)
                    
throw new ArgumentOutOfRangeException(nameof(value));

                
_exchangeRate = value;
            
}
        
}

        
public string Name
        
{
            
get
            
{
                
return _name;
            
}
            
private set
            
{
                
if (value == null)
                    
throw new ArgumentNullException(nameof(value));

                
_name = value;
            
}
        
}
    
}

Now the users/developers of this class must supplied the properties values when they created an instance of it . Otherwise, it won't compile. If they make a mistake and pass invalid parameters in the constructor then the class has safe guard checks which will provide a feedback , in the form of exception, before the class get used by other part of code.

A while ago I used to think that this approach tends to create a lot of code. However, this code  gets re-used every time that someone uses the CurrencyInfo. This approach takes the load off the the application's Services as they have a guarantee that any CurrencyInfo instance has the appropriate values.

 The application's Services don't have to check if a flag or a property is not null;  or if a value stored in an instance of the CurrencyInfo is valid within the context of the business requirements.

The Application's Services are left to do what they do best, the orchestration of other classes and repositories, to achieve a given outcome.

Perhaps there is a tool out there that can help with the protecting of class invariants using a  Aspect-oriented programming approach.

The key point is that automatic properties don't protect the class invariants. I can see the usage of automatic properties in DTO's as the DTO properties get populated with values before they are serialize and because our CurrencyInfo is guarantee to have valid values these values could be mapped to a DTO.

Technical References:




  

Thursday, 7 July 2016

EF Core - Invalid JSON File

I have been doing some development, on a pet project, using .NET, ASP .NET and EF Core.
Just few days ago I installed the Update 3 for VS 2015 . As you know this update contain the latest .NET Core versions.

Once I upgraded to the Update 3 I made some small changes to my EF model and wanted to create a migration. I went to the package manager console and run the following command:

Add-Migration AddForeignKeyPropertiesToGig

Running this command caused the following error:
Invalid JSON File in "……project.json".








The reason of this error was that the version of the  Microsoft.EntityFrameworkCore.Tools , in the tool section of the project.json, was different than the Microsoft.EntityFrameworkCore.Tools version located in the dependencies:







Making the version of the Microsoft.EntityFrameworkCore.Tools the same, in both section of the project.json file, should fix this error.

In mine case i made both of them "1.0.0-preview2-final"

Saturday, 28 February 2015

MembershipGroupId=0

 The other day, I was having issues with a SharePoint 2013 workflow. The workflow would break when sending notifications to a SharePoint group which I was member of. As a matter of fact the only member of it. The workflow would go into a "Canceled" state, with an error "System.ApplicationException: HTTP 400"

Taking out my user account, from the SharePoint group, and using some one else would make the workflow ‘happy’.

I removed my user account from the 'User Profile' service and added it back, and it didn't yield any joy.

After discussing the issue with one of my colleague, he suggested to go inside a SharePoint group and replace the SharePoint group id with 0, as in "MembershipGroupId=0".

After doing this, I saw a complete list of the users in the Site Collection and noticed that there were two accounts for me. I removed the duplicated account and kicked off the workflow again. Problem solved!

So, if you ever are having issues around workflow notifications and you think that the culprit may be a specific account, this trick may help you out.

Friday, 19 September 2014

Using a WEB API Controller in an MVC Web Application project

Sometimes you may have a valid reason of hosting a Web API controller inside your MVC Web application. Usually when exposing REST services you are better of having your WEB API controllers encapsulated into a project of its own so you options of hosting them are broader.

However, if you must host a Web API controller inside your MVC application you can follow the steps below.

Environment wise, these instructions have been implemented and tested using MVC 5, Web Api 5.2 and VS 2013 (aka 'Tool for Men')

1.  Add a Web API controller to your existent MVC project.




2.  Set up the route configuration for WEB API controller.

When you create a MVC web application using the MVC template, Visual Studio will create
the RouteConfig class for you and implement the default MVC routing, as below:

public class RouteConfig
    {
        
public static void RegisterRoutes(RouteCollection routes)
        {
            
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            
routes.MapRoute(
                
name"Default",
                
url"{controller}/{action}/{id}",
                
defaultsnew { controller = "Home"action = "Index"id = UrlParameter.Optional }
            );
        

In this class you can add new routes to your MVC application.

However, for matching REST requests to  a WEB API controller actions another routing is needed.

To implement the Web API routing just:

  1. Create a class on the App_Start folder of your MVC Web Application.
    If you create the class using the Visual Studio Wizard (i.e. CTR + Shift , A), remove the
    "App_Start" from the namespace of the class. By default Visual Studio will append the
    name of the folder "App_Start" to the namespace.
  2. Create a public static method named Register. This method is akin to the
    RegisterRouter method of the RouteConfig.cs

    public static void Register(HttpConfiguration config)
            {
                
    // Web API configuration and services
                
    // Web API routes
                config
    .MapHttpAttributeRoutes();
     
                config
    .Routes.MapHttpRoute(
                    name: 
    "DefaultApi",
                    routeTemplate: 
    "api/{controller}/{id}",
                    defaults: 
    new { id = RouteParameter.Optional }
                );

    You can add more routes to match the REST requests to the desired URI format.

    3. Add a references to the System.Web.Http.WebHost dll in your MVC Web Application.

    4. Add a  reference to the System.Web.Http namespace on the MVCApplication class
    (Global.asax.cs source file)

    5. On the Application_Start() method of the MVC Application class add this statement
    that will invoke the WebApiConfig.Register method

    GlobalConfiguration.Configure(WebApiConfig.Register); 
    

Now you should be able to invoke the methods in your Web API controller through REST verbs such as:
  /api/Students -> (get all students)
  /api/students/5 (get student with an id of 5)

Saturday, 1 March 2014

Nice Entity Framework trick


There is a cool trick for deleting a item from a database table using the Entity Framework.

Usually you would delete an item like this:

public bool DeleteOrder(int id)
{
 Order order = contextDb.find(id);
contextDb.Remove(order);
contextDb.SaveChanges();
}

However if you want some improvement, on performance, You could re-write the above code
like this:

public bool DeleteOrder(int id)
{
 Order orderToNuke = new Order {ID:id};
contextDb.Entry(orderToNuke).State.Deleted;
contextDb.SaveChanges();
}

Entity Framework is smart to know that that order marked with the  Stated.Deleted it needs to be removed from the database.


Thursday, 14 November 2013

Entity Framework Template not available on VS 2013

Few weeks ago I installed VS 2013 in my laptop. After installing it , without any issue, I ended up having three version of Visual Studio: Visual Studio 2010, Visual Studio 2012 and Visual Studio 2013.

Over the following weeks I opened and built VS 2010 projects with VS 2013 without any problem. This week I started developing the data model of an ASP NET MVC 5 Web Application. My plan was to used the latest and greatest version of Entity Framework, EF 6.0.

To my surprise I couldn't find the template for Entity Framework on my Visual Studio 2013:





  As I didn't perform a custom installation of VS 2013 I knew that there wasn't nothing wrong with the installation process.

After fiddling around a bit with VS 2012 and VS 2013 I noticed that my installation of VS 2012 didn't have  Entity Framework 6.0 installed. So I installed Entity Framework 6.0 for Visual Studio 2012 which you can find by following this link.

Once Entity Framework 6.0 was installed on VS 2012 I run the 'repair' installation option of VS 2013 and voilĂ  the Entity Framework template was back on VS 2013