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.
 
 

Tuesday, 2 July 2013

Designing to a common interface - Application loggers for SharePoint and ASP .NET

Last week I decided to start working on an application that I am planning to release as an open source initiative. My contribution will not be a framework but rather an application that will help schools to manage their information in a better way.

As I am slowly starting to work on the design of the application I started by tackling one of the Cross-cutting concern: Logging.

It is a good practice to centralized your logging code so if there are changes on the requirements, for the logging of your application, it will be easier to perform these changes.

Consider the case where an application was originally developed with logging to files, on the file system. If there is a change on the logging requirement, say the application needs to write its logs to a Oracle or MSSQL database tables, how easy is to change the code of the application to accommodate this new requirement?

If the logging functionality is scatter all over the different layer of the application then the changes will required a greater effort. On the other hand if the logging functionalities are centralized then the changes are isolated requiring less effort.

When building modules and applications it pays off to develop them having in mind 'Anticipation of Change'.

So I want to have my logging functionality centralized as much as possible and would love to have a common or related logging API for ASP .NET and SharePoint.

After some thinking I came up with the following design



 The logger to be used for SharePoint and ASP .NET implement a common interface. The interface ILogger and the classes that implement this interface , the SharePointLogger and WebLogger, can be built into the same assembly providing a common library that can be shipped for both platforms.

The SharePoint logger inherits from the SharePoint class SPDiagnostServcieBase. Inheriting from the SPDiagnosticsServiceBase allows us to have our own custom diagnostic categories and use the WriteTrace and WriteEvent methods to perform logging. You can read it up more about the SPDiagnosticServiceBase class here

The WebLogger on the other hand contain a logger property that can be an a type of a .NET logger library or framework such as Log4Net.

How the SharePointLogger and WebLogger implements the logging of errors and messages is abstracted from their clients, the classes our component using the logging API. 
In fact we could change the .NET library used by the WebLogger and that shouldn't affect other layers of the application such as the Database layer as long as the interface contract remain the same. The interface contract in this case being the methods Log(String category, String message) and LogError(String category, String message).

This design achieves the objective of centralizing the logging functionality for the application. It also makes it possible to ship the loggers to both platforms ASP .NET and SharePoint.
As an added bonus, we all like bonuses,  this design abstracts the logging logic away from other classes/components.

Many of the concepts that help us to write  re-usable code have its root on sound Software Engineering principles and programming paradigm such as OOP (Object Oriented Programming) help us to implement these principles.

On this note, I would like to recommend you  Fundamentals of Software Engineering (2nd Edition) by Carlo Ghezzi, Mehdi Jazayeri,Dino Mandrioli

This book is timeless and highlight the good principles of developing re-usable and robust software. A good companion book for any serious developer that views writing code as a Craft.

This link to a PDF lecture will give you a highlight of the third chapter of this book where it briefly mention the Software Engineering principles. Other chapters, of the book, dive-in deep into these principles and how to apply them.

We can be agile and write good code. ;-)