Lessons learned from WebAPI and MVC Implementations

My Notes on a painful journey to learn, make and publish a Azure hosted MVC, Sinlge-Page application, Android client app and a WebAPI working with-one another. Software technology can be real pain in the ass!!!

JSON and Self referencing loop

If you get the following error:

Self referencing loop detected for property ‘your model’ with type ‘System.Data.Entity.DynamicProxies

Solution:

Loop Reference handling in Web API

My Solution:

I used [JsonIgnore] attribute to tell the proper inheritance to JSON serialization.

using Newtonsoft.Json;

public partial class Set
{
public Set()
{
this.Exercises = new HashSet<Exercise>();
}

public long Id { get; set; }
public string Name { get; set; }
public string UserId { get; set; }

public virtual ICollection<Exercise> Exercises { get; set; }
}

public partial class ExerciseRecord
{
public long Id { get; set; }
public double Record { get; set; }
public System.DateTime Date { get; set; }
public System.DateTime StartDate { get; set; }
public System.DateTime EndDate { get; set; }
public long ExerciseId { get; set; }

[JsonIgnore]
public virtual Exercise Exercise { get; set; }
}

public partial class Exercise
{
public Exercise()
{
this.ExerciseAttributes = new HashSet<ExerciseAttribute>();
this.ExerciseRecords = new HashSet<ExerciseRecord>();
}

public long Id { get; set; }
public string Name { get; set; }
public double Target { get; set; }
public long SetId { get; set; }
[JsonIgnore]
public virtual Set Set { get; set; }
public virtual ICollection<ExerciseAttribute> ExerciseAttributes { get; set; }
public virtual ICollection<ExerciseRecord> ExerciseRecords { get; set; }
}

 

MVC loads older script files

This is due to browser script caching. The easiest solution for this is to set the browser which you are using to debug to retrieve the newest versions of web page content on each time you visit a webpage.

Missing Key definition from Model when creating a controller

You might get an error like this: EntityType ‘your type’ has no key defined. Define the key for this EntityType.

To fix such problems simply add this namespace definitions:

using System.ComponentModel.DataAnnotations;

And then define in your data model a key like this:

public class ColumnDataHighChart
{
[Key]
public int ID { get; set; }
public String Title { get; set; }
public String SubTitle { get; set; }
public IList<String> xAxisCategories { get; set; }
public String yAxisTitle { get; set; }
public IList<SeriesDataHighChart> Series { get; set; }

}

 

Intercepting web requests

 

I have two ways of doing this:

  1. A delegation handler
  2. Or an action filter for a controller.

Delegation handler

DelegatingHandler Class

Sample code:

public class AuthHandler : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
// Call the inner handler.
var response = await base.SendAsync(request, cancellationToken);
return response;
}
}

Action filter for a controlle

Notice that for MVC and Web API there are two different sets of action filter definitions:

http://msdn.microsoft.com/en-us/library/system.web.http.filters.actionfilterattribute(v=vs.118).aspx

http://msdn.microsoft.com/en-us/library/system.web.mvc.actionfilterattribute(v=vs.118).aspx

MVC Sample:

public class AuthenticationActionFilterHelper : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
if (SessionHelper.LoggedInUser<AspNetUser>(HttpContext.Current.User.Identity.Name) == null)
{
//SessionHelper.UserSessionID = user.Id;
AspNetUsersController aspUserCon = new AspNetUsersController();
var sessionUser = aspUserCon.GetUser(HttpContext.Current.User.Identity.Name);
//SessionHelper.UserSessionID = user.UserName;
SessionHelper.LoggedInUser<AspNetUser>(sessionUser, sessionUser.UserName);
}
}
}

}

WebAPI Sample:

public class AuthenticationActionFilterHelper : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
}

public override System.Threading.Tasks.Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, System.Threading.CancellationToken cancellationToken)
{
return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
}

public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
if (SessionHelper.LoggedInUser<AspNetUser>(HttpContext.Current.User.Identity.Name) == null)
{
//SessionHelper.UserSessionID = user.Id;
AspNetUsersController aspUserCon = new AspNetUsersController();
var sessionUser = aspUserCon.GetUser(HttpContext.Current.User.Identity.Name);
//SessionHelper.UserSessionID = user.UserName;
SessionHelper.LoggedInUser<AspNetUser>(sessionUser, sessionUser.UserName);
}
}
}

public override System.Threading.Tasks.Task OnActionExecutingAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
{
return base.OnActionExecutingAsync(actionContext, cancellationToken);
}
}

 

Lambda Expression “Magic” 🙂

Retrieve distinct parent from child elements

As the title suggests I needed to retrieve the parent from a multilevel data set:

 

First I needed to get the child elements and in this exmaple it is assumed that you have the child elements retrieved.

Once you have the child elements it is time to get the distinct parent elements. for this I needed a way to group the distinct parent from the child elements. Here are my steps:

  • Get child elements:

ExerciseRecordsController exerciseRecordsController = new ExerciseRecordsController();
var exerciseRecordsData = exerciseRecordsController.GetExerciseRecords().Where(er => er.Date > startDate && er.Date < endDate && er.Exercise.Set.UserId.ToLower().CompareTo(this.user.Id.ToLower()) == 0);

  • Define a custom extension named “DistinctBy”

public static class LambdaExtensions
{
public static IEnumerable<t> DistinctBy<t>(this IEnumerable<t> list, Func<t, object> propertySelector)
{
return list.GroupBy(propertySelector).Select(x => x.First());
}
} Original code from: http://www.elevenwinds.com/linq-distinctby-with-lambda-expression-parameter

  • Apply the new extension on the data set

var setsData = exerciseRecordsData.DistinctBy(o => o.Exercise.SetId).Select( o => o.Exercise.Set);

How to create/populate a collection with data with an unknown data type

You may ask yourself why would anyone needs this? Well I do not why would others needs this but I came into a situation where I needed this.

I had a solution where I needed to be able to create data from a back-end server WebAPI to a JS HighCharts JS library without knowing what kind of data I would be processing, also I wanted to have the possibility to extend the back-end code so that it can return any kind of data to the client and let the client figure out what to do with the data.

So how to do this?

In a human language it goes something like this: Use LINQ in your code to go through the data set, select your data and return it as and array of objects, then create a new collection by passing to the constructor your processed data as an array of objects. Ofcourse your collection must store objects as well. The data type information is going to be stored because every class in C# is a descendant of the Object class.

public class SeriesDataHighChart
{
[Key]
public long ID { get; set; }
public String Name { get; set; }
public IList<object> Data { get; set; }
}

 

// One series corresponds to one set and data for each month
SeriesDataHighChart seriesData = new SeriesDataHighChart();

seriesData.ID = chartSet.Id;
seriesData.Name = chartSet.Name;
var seriesMonthsActivityCountData = (from monthActivityCount in chartSet.ChartSetMonthsData
select new object[] { monthActivityCount.ActivityCount as object });
seriesData.Data = new List<object>(seriesMonthsActivityCountData.ToArray());

hsData.Series.Add(seriesData);

 

You could also return an array of more complex object such as a key value pairs:

var sd = from d in unparsedData
select new object[] { d.Key as object, d.Value as object };

newSeries.Data = new Data(sd.ToArray());

Avoiding “Sequence contains no elements” exception in object initializers

If you have something like this in your code:

chartExercise.ChatMonthsData.Add(new ChartExerciseMonthData
{
ActivityCount = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate).Count(),
StartDate = DateTime.Now.StartOfMonth(month),
EndDate = DateTime.Now.EndOfMonth(month),
MonthRecordAverage = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate).Average(a => a.Record)

});

 

The Average lambda expression will throw the above exception error message because the Where clause may return Zero elements back(Notice that for example the Count expression will not throw a similar exception).

To fix(go around the problem, yes there might be other solutions but this was mine at the moment 🙂 ) I created an anonymous function that checks if there are elements returned by the clause and only then perform the Average operation on the elements. The solution is highlighted with the green color.

chartExercise.ChatMonthsData.Add(new ChartExerciseMonthData
{
ActivityCount = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate).Count(),
StartDate = DateTime.Now.StartOfMonth(month),
EndDate = DateTime.Now.EndOfMonth(month),
MonthRecordAverage = new Func<double>(() => {
double averageRecord = 0;
var exerciseRecordByDateRange = exercise.ExerciseRecords.Where(m => m.Date.Month == month && m.Date >= startDate && m.Date <= endDate);
if (exerciseRecordByDateRange.Count() > 0)
averageRecord = exerciseRecordByDateRange.Average(a => a.Record);

return (averageRecord);
})()
});

 Get the count for a complex data structure/hierarchy, tree like

A rather simple implementation, choose to retrieve any records inside your main records set with a where:

set.Exercises.Where(o => o.ExerciseRecords.Any(m => m.Date.Month == month)).Count()

Update Azure SQL Database via SQL Server management studio and Generated scripts

  1. Mouse second button on database > Taskas > Generate Scripts > Choose your objects (Chose objects view) > Select “Advanced” button, then in the “Script for the database engine type” select option Windows Azure SQL Database
  2. Next open the database connection with management studio to your Azure SQL Database.
  3. Create a new empty database
  4. Open a new query windows and simply add the generated script to this window and run the script against the new empty database. This will create the structure and data if you selected so.

After deploying your WebAPI you get a following error when accessing your database data “There is already an open DataReader associated with this Command which must be closed first.”

To fix this error simply add the following to your connection strings used in your web api in Azure MultipleActiveResultSets=true.

Enable WebAPI Cross-Origin Resource Sharing (CORS)

You might run into problems after deploying your WebAPI to Azure and trying to access your api from different origins. Here is a solution:

http://www.codeproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En

Summary of the article above: Install the following nuget package in your WebAPI project: Microsoft.AspNet.WebApi.Cors

In your webapiconfig add the following(in green):

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

var cors = new EnableCorsAttribute(“*”, “*”, “*”);
config.EnableCors(cors);

// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: “DefaultApi”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = RouteParameter.Optional }
);

config.MessageHandlers.Add(new Handler.AuthHandler());
}
}

Next add the following to your ApplicationOAuthProvider.GrantResourceOwnerCredentials function:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add(“Access-Control-Allow-Origin”, new[] { “*” });
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
//SessionHelper.UserSessionID = user.Id;
AspNetUsersController aspUserCon = new AspNetUsersController();
var sessionUser = aspUserCon.GetUser(user.Id);
//SessionHelper.UserSessionID = user.UserName;
SessionHelper.LoggedInUser<AspNetUser>(sessionUser, user.UserName);
if (user == null)
{
context.SetError(“invalid_grant”, “The user name or password is incorrect.”);
return;
}

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);

AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);

}

Notice that these changes may have undesired effects. Find out if these are suitable to your needs.

Advertisements

SharePoint Language specific CSS loading

Today I worked on a annoying problem where I had to figure out how to do a language specific CSS file loading during header load from a Master Page.

The solution is as following in our case:

Our code deploys under the LAYOUTS folder our project style sheets, js files etc. We created for each language ID it’s own folder and under each language folder the css file that we wanted to use for a each language.

Next we addedthe following line inside the <HEAD> element and the right CSS file based on the language ID was loaded:

<SharePoint:CssRegistration name=”<% $SPUrl:/_layouts/projectname/styles/~language/master.css %>” runat=”server”/>

In the definition above what is in bold and in blue is what you MUST add for the reference to work. What is in green and not in bold is your path where your CSS file is located. Change it to fit your needs.

What is the most interesting part is the “~language” definition in the URL. This will retrieve the proper language ID(example for English-US: en-US). The final URL reference will look something like this:

/_layouts/projectname/styles/en-US/master.css

How to deal with a single long continuous word in CSS and HTML

If you have a very long piece of text that has no white spaces or anything that would make the word into smaller bits or information this will likely cause problem when rendered by the browser. Might cause your content to explode width wise.

In one on my problem cases I was creating a custom XSLT to display email related data. One of the data was the To information of emails which holds the recipients of an email. If the email had lots of recipient they where one after another in a single continuous string. This caused a problem when the data was retrieved from the CMS system and displayed to the user. Width wise everything exploded.

What we did in our case the had a table into which the data was inserted. The TD element was modified so that the content would be scroll able and forced to a certain width. This may help someone if you have a similar problem.

<td style=”WIDTH: OVERFLOW: hidden” class=”ms-vb”>
<span style=”DISPLAY: block;WIDTH: 257px; OVERFLOW: auto”>
<xsl:value-of select=”fieldname”/>
</span>
</td>