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




Sunday, 1 September 2013

OTB SharePoint forms and jQuery


SharePoint Forms and jQuery
Sunday, 1 September 2013
3:06 PM
For OTB forms SharePoint uses the hierarchy of UI controls to create the "id" and "name" attributes for their fields. This is a functionality that SharePoint inherits from ASP .NET

Sometimes you may want to get a 'hook' on one or several of these fields, without modifying the OTB form, to apply styles or modify the control behaviours  (i.e. make them read only). 
Since the developer doesn't have any control on the name and id attributes generated by SharePoint another attribute must be used to effectively get a reference to any of the fields.
First let see an illustration of the html mark-up generated by SharePoint and then we will see another attribute that can be used to get a reference to a field or fields in a SharePoint OTB Form.
If You go to an OTB document library such as the Document library and click on "new document". You will get a form, for adding a new document, consisting of a single input field with a browse button.
 









Using your favourite browse you can inspect the name and id that SharePoint (ASP .NET really) render/creates on the client side.
 






In this case we can observe that the name of the field is made of the Main Content control ID plus the name of the section where the field lies, which in this case happen to be a table row ( Html element),  plus the Input field own id. The main content control is the asp:content control that you see on the form should you open it with SharePoint designer:  <asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
 
There is another property that gets generated and it "title" As you can see from the screen shot below the title attribute of this field is "Choose a File"



Using the title attribute we can get a hook or reference to this field and perform operations on it like we would on any HTML Element using jQuery:

 //we hide the field by using the whole title property
("[Title='Choose a file']").hide();

//we hide any field starting with the term 'Choose'
["[Title^='Choose']").hide()

 //we hide any field ending with the term 'file'
["[Title$='file']").hide()
The cool thing about jQuery wildcard selectors is that if you have several fields that have a title attribute starting or ending with a common term such as 'employee' and you want to apply the same operation to all of them then you can do with a single line of code.

["[Title^='employee']").attr('disabled','disabled')

This would make any field with a title starting with 'employee' a read-only field.

Saturday, 27 July 2013

Property Sheets


If you find yourself working with MFC property sheets and run into a first-chance exception inside the  ::OnInitDialog method, check that all your dialogs resources have the right windows styles.


 
If you are using dialog resources , check that the dialog resources have the following properties:
 
Border: Thin
Disabled: True
Style: Child

In my case, one of the dialog resource had the 'Border' property set to 'Dialog Frame' and 'Sytle' to 'Pop up'

According to MSDN documentation , for the CPropertySheet::DoModal() method, all the windows styles should be disabled  with the exception of :

DS_3DLOOK
Obsolete. The system automatically applies the three-dimensional look to dialog boxes created by applications.
DS_CONTROL
Creates a dialog box that works well as a child window of another dialog box, much like a page in a property sheet. This style allows the user to tab among the control windows of a child dialog box, use its accelerator keys, and so on.
WS_CHILD
0x40000000L
The window is a child window. A window with this style cannot have a menu bar. This style cannot be used with the WS_POPUP style.
WS_TABSTOP
0x00010000L
The window is a control that can receive the keyboard focus when the user presses the TAB key. Pressing the TAB key changes the keyboard focus to the next control with the WS_TABSTOP style.
You can turn this style on and off to change dialog box navigation. To change this style after a window has been created, use the SetWindowLong function. For user-created windows and modeless dialogs to work with tab stops, alter the message loop to call the IsDialogMessage function.

 
And these are optional windows styles, that can be used with the guarantee that they won't cause First-chance exceptions.

DS_SHELLFONT
Indicates that the dialog box should use the system font. The typeface member of the extended dialog box template must be set to MS Shell Dlg. Otherwise, this style has no effect. It is also recommended that you use the DIALOGEX Resource, rather than theDIALOG Resource. For more information, see Dialog Box Fonts.
The system selects a font using the font data specified in the pointsizeweight, and italicmembers. The system passes a handle to the font to the dialog box and to each control by sending them the WM_SETFONT message. For descriptions of the format of this font data, see DLGTEMPLATEEX.
If neither DS_SHELLFONT nor DS_SETFONT is specified, the extended dialog box template does not include the font data.
DS_LOCALEDIT
Applies to 16-bit applications only. This style directs edit controls in the dialog box to allocate memory from the application's data segment. Otherwise, edit controls allocate storage from a global memory object
WS_CLIPCHILDREN
0x02000000L
Excludes the area occupied by child windows when drawing occurs within the parent window. This style is used when creating the parent window.
 

If you dialog resources are Kosha and you still get a First-change exception is very likely you are experience an exception that is expected (by design) when calling CPropertySheet::DoModal() or CPropertySheet::Create()

You can find out more about this expected exception 'that is safely handled by the operating system' following this link.

On that Microsoft page you will find three methods for resolving the issue.
 
Until next time, see ya.