For the love of problems :)

A Developers Blog


Leave a comment

Modern C++ 11/14 – C# alike events

For a project of mine I needed a functionality like that found in C# events. Since my C++ is a bit rusty :) I looked up some options and found this example which I edited to support variadic templates.

The original implementation(now modified with variadic templates) from: http://geekswithblogs.net/raccoon_tim/archive/2011/09/28/lambdas-and-events-in-c.aspx

template<typename… T1>
class Event
{
public:
typedef std::function<void(T1…)> Func;

public:
void Call(T1 …arg)
{
for (auto i = m_handlers.begin(); i != m_handlers.end(); i++)
{
(*i)(arg…);
}
}

void operator ()(T1 …arg)
{
Call(arg…);
}

Event& operator += (Func f)
{
if (typeid(f) != typeid(Func))
throw std::bad_function_call(“Error in type”);

m_handlers.push_back(f);
return *this;
}

Event& operator -= (Func f)
{
for (auto i = m_handlers.begin(); i != m_handlers.end(); i++)
{
if ((*i).target<void(T1)>() == f.target<void(T1)>())
{
m_handlers.erase(i);
break;
}
}

return *this;
}

private:
std::vector<Func> m_handlers;
};

 

To use the event class in you code:

Example 1 – Single parameter:

int stackValue = 200; Event<int> e; e += [=](int i) { printf( “%d\n”, i + stackValue ); }; e += [&](int i) { printf( “%d\n”, i + stackValue ); stackValue += 100; }; e += [&stackValue](int i) { printf( “%d\n”, i + stackValue ); }; e += [stackValue](int i) { printf( “%d\n”, i + stackValue ); }; e( 100 );

Example 2 – Multiple Parameters:
int stackValue = 200;
float stackValue2 = 12;
double stackValue3 = 200;
Event<int, float, double> e;
e += [=](int i, float j, double k) { printf(“%d\n”, i + stackValue + (int)j + (int)k); };
e += [&](int i, float j, double k) { printf(“%d\n”, i + stackValue + (int)j + (int)k); stackValue += 100; };
e += [&stackValue](int i, float j, double k) { printf(“%d\n”, i + stackValue + (int)j + (int)k); };
e += [stackValue](int i, float j, double k) { printf(“%d\n”, i + stackValue + (int)j + (int)k); };

e(100, stackValue2, 53);


Leave a comment

SharePoint – Enabling Enterprise Keywords field for libraries

This is a sample how you can enable the enterprise keywords field for a library. The funny part is that in SharePoint2013 just adding the field did not work properly. What I had to do was to use ILSpy to get an idea what the SharePoint code is doing. I found out that for some reason(in this case atleast) the exterprise keyword field need to exist so that the list content type is altered to use the enterprise keyword field. Only then I could use the field in the library properly. Don’t know why :), didn’t find out :).

public static string FeatureProperty_ListsToApplyLogic = “ListsToApplyLogic”;
private System.Guid guidKeywords = new System.Guid(“{23F27201-BEE3-471e-B2E7-B64FD8B7CA38}”);

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb web = properties.Feature.Parent as SPWeb;
if (web == null)
return;
String listsToApplyLogic = null;
if(properties.Feature.Properties[FeatureProperty_ListsToApplyLogic] != null)
listsToApplyLogic = properties.Feature.Properties[FeatureProperty_ListsToApplyLogic].Value as String;

if (String.IsNullOrEmpty(listsToApplyLogic))
return;

String[] listNames = listsToApplyLogic.Split(‘;’);

foreach (var listName in listNames)
{
SPList metadataList = web.Lists.TryGetList(listName);
if (metadataList != null)
{
if (!metadataList.Fields.Contains(this.guidKeywords))
{
SPWeb parentWeb = metadataList.ParentWeb;
SPField field = parentWeb.AvailableFields[this.guidKeywords];
metadataList.Fields.Add(field);
}
else
{
this.KeywordsFieldExistsInContentTypes(true, metadataList);
}
metadataList.Update();
}
}

}

bool KeywordsFieldExistsInContentTypes(bool bAdd, SPList metadataList)
{
SPField sPField = null;
bool result = true;
if (!metadataList.AllowContentTypes)
{
return result;
}
foreach (SPContentType sPContentType in metadataList.ContentTypes)
{
if ((sPContentType.Id.IsChildOf(SPBuiltInContentTypeId.Document) || sPContentType.Id.IsChildOf(SPBuiltInContentTypeId.DocumentSet)) && sPContentType.FieldLinks[this.guidKeywords] == null)
{
if (bAdd)
{
bool @sealed = sPContentType.Sealed;
bool readOnly = sPContentType.ReadOnly;
try
{
if (@sealed || readOnly)
{
sPContentType.Sealed = false;
sPContentType.ReadOnly = false;
}
if (sPField == null)
{
SPWeb parentWeb = metadataList.ParentWeb;
sPField = parentWeb.AvailableFields[this.guidKeywords];
}
SPFieldLink fieldLink = new SPFieldLink(sPField);
sPContentType.FieldLinks.Add(fieldLink);
sPContentType.Update(false, false);
continue;
}
finally
{
if (@sealed || readOnly)
{
sPContentType.Sealed = @sealed;
sPContentType.ReadOnly = readOnly;
sPContentType.Update(false, false);
}
}
}
result = false;
if (!bAdd)
{
break;
}
}
}
return result;
}


Leave a comment

SharePoint and Google Maps – How to use them together

Here is an example how to use Google Maps and how to integrate it with SharePoint.

To start with you need to include the following files somewhere in your project

<SharePoint:ScriptLink ID=”JQueryJSFunctionality” runat=”server” Name=”/_layouts/myfolder/scripts/jquery-1.11.2.min.js”></SharePoint:ScriptLink>
<script src=”http://maps.google.com/maps/api/js?sensor=false&#8221; type=”text/javascript”>
</script>

<script type=”text/javascript”>
var listName = ‘<%=ListName %>'; // This can be used to pass a list name from web part properties to the JavaScript/JQuery logic, this is a propert defined in the code behind of a user control
</script>

<!–<SharePoint:ScriptLink Name=”SP.js” runat=”server” OnDemand=”true” Localizable=”false” />–>
<SharePoint:ScriptLink ID=”ScriptLink1″ Name=”sp.debug.js” LoadAfterUI=”true” Localizable=”false” runat=”server” />
<SharePoint:ScriptLink ID=”userWorldMapJSFunctionality” runat=”server” Name=”/_layouts/myfolder/scripts/yourGoogleMapsLogicFileName.js”></SharePoint:ScriptLink>

 

Next is the JavaScript/JQuery code

Create instances of needed Google Maps functionalities

var gmGeocoder = new google.maps.Geocoder();
var gmBounds = new google.maps.LatLngBounds();

var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.HYBRID
};

var gmMap = new google.maps.Map($(“#map_canvas”)[0], mapOptions);

// You can use this to listen when the Google Maps has finnished its operations
google.maps.event.addListenerOnce(gmMap, ‘idle’, function () {

});

 

// You can use this function class to pass on information to the Google Maps geo location finder

var street = “”;
var zip = “”;
var city = users[iter].city;
var country = users[iter].country;
address = street + “,” + zip + “,” + city + “,” + country;

gmGeocoder.geocode({ ‘address': address }, function (user, allUsers) {
return (function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results.length == 0) {
//console.log(“Geocoding: There are no results for address ‘” + results[0].formatted_address + “‘! Expected exactly one result. > Do not show any marker on map for this address.”);
}
else {

// Here is where you get a results back for the specified address and start to construct data for a Google Maps marker
var externalCount = 0;
var internalCount = 0;
gmLatLng = results[0].geometry.location;
//markerBounds.extend(gmLatLng);
var msgForInfoWindow = “<div id=’slider1′ >”;
var colorValue = “red”;
if (user.isexternal == true) {
colorValue = “blue”;
externalCount++;
} else {
internalCount++;
}
var orderID = 0;

// The actual content that goes into the marker starts here
msgForInfoWindow += “<div class=’viewport’>”;
msgForInfoWindow += “<ul class=’overview’>”;

 

orderID++;
msgForInfoWindow += “<li>”;
msgForInfoWindow += “Add your data here”;
msgForInfoWindow += “</li>”;
msgForInfoWindow += “</ul>”;
msgForInfoWindow += “</div>”;
msgForInfoWindow += “<a class=’buttons prev’ href=’#’><</a>”;
msgForInfoWindow += “<a class=’buttons next’ href=’#’>></a>”;

msgForInfoWindow += “</div>”;
var isExternalMarker = false;
if (externalCount > internalCount)
isExternalMarker = true;

// Calling this function will create a maker based on the given parameters
SetMarkerForGoogleMapForSharePointList(gmLatLng, gmMap, gmBounds, user.city + “, ” + user.country, msgForInfoWindow, isExternalMarker);
}
}
else {
//console.log(“Geocode for address ‘” + address + “‘ was not successful for the following reason: ” + status);
}
});
} (users[iter], users));

//getting coordinates
gmGeocoder.geocode({ ‘address': address }, function (results, status) {

});

 

function NullVerification(stringValue) {
var returnValue = ” “;
if (stringValue != null)
returnValue = stringValue;

return (returnValue);
}

function NullVerificationBool(stringValue) {
var returnValue = false;
if (stringValue != null)
returnValue = true;

return (returnValue);
}

 

function SetMarkerForGoogleMapForSharePointList(gmLatLng, gmMap, gmBounds, title, contentForInfoWindow, isExternalMarker) {

// This is just a logic on how to control the marker styling, you can use your own

var icon = “”;

if (isExternalMarker)
icon = “yellow”;
else
icon = “red”;
icon = “http://maps.google.com/mapfiles/ms/icons/&#8221; + icon + “.png”;

// Create the marker for the Goole Map
var gmMarker = new google.maps.Marker({
position: gmLatLng,
map: gmMap,
title: title,
zIndex: 0,
icon: new google.maps.MarkerImage(icon)
});

// This will center the map based on given marker positions
gmBounds.extend(gmLatLng);
gmMap.setCenter(gmBounds.getCenter());
gmMap.fitBounds(gmBounds);

// Define properties for the info window that is opened when the marker is pressed

if (contentForInfoWindow != null && contentForInfoWindow != “”) {
var gmInfowindow = new google.maps.InfoWindow({
content: contentForInfoWindow,
maxWidth: 500,
maxHeight: 600
});

// This will attach a listener to the marker to that we can apply logic when it is opened.

google.maps.event.addListener(gmMarker, ‘click’, function () {
gmInfowindow.open(gmMap, gmMarker);
$(‘#slider1′).tinycarousel({ bullets: true });
var t = 0;
});
}
}

// This is an example how to retrieve data from a SharePoint list using JavaScript 

function retrieveListItems() {

var clientContext = SP.ClientContext.get_current();
if (IsEmpty(listName))
listName = ‘UsersMapData';
var oList = clientContext.get_web().get_lists().getByTitle(listName);

var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(‘<View><Query><Where><And><IsNotNull><FieldRef Name=”Country” /></IsNotNull><And><IsNotNull><FieldRef Name=”City” /></IsNotNull><IsNotNull><FieldRef Name=”PersonName” /></IsNotNull></And></And></Where><OrderBy><FieldRef Name=”ID” Ascending=”True” /></OrderBy></Query></View>’);
this.collListItem = oList.getItems(camlQuery);

clientContext.load(collListItem);

clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

}

 // When the data retrieval from the list succeeds this function is called. Here the needed data is then retrieved and parsed. Then passed on to be used later

function onQuerySucceeded(sender, args) {

var listItemInfo = [];

var listItemEnumerator = collListItem.getEnumerator();

// Here the data from SharePoint is went through and items are retrieved to container objects to be used later

while (listItemEnumerator.moveNext()) {

var oListItem = listItemEnumerator.get_current();
var newUserData = { id: oListItem.get_id(),
name: oListItem.get_item(‘PersonName’),
country: oListItem.get_item(‘Country’),
city: oListItem.get_item(‘City’),
imageLocation: oListItem.get_item(‘UserImageLocation’)
};
listItemInfo.push(newUserData);
}

return (listItemInfo);
}

function onQueryFailed(sender, args) {

alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}


Leave a comment

SharePoint 2013 Blog – Change the author of the post with a custom selected user

This is a sample JS to use with the posts webpart in the SharePoint blog(JSLink webpart property). Originally I wanted to the blog.xsl but I simply could not get it to world desirably in SharePoint 2013. Well it worked in a different manner that what it used to be in SharePoint 2010.

Here is the code with comments:

var userID = 0;
var globalListItemIDs = [];
var spjsLoaded = false;
var listName = “Viestit”;
var customUserFieldInternalName = “PostOwner”;

// Main function – Start point
(function () {

var overrideCtx = {};

overrideCtx.Templates = {};

// Register a template override for the author field
overrideCtx.Templates.Fields = {‘Author':{‘View':CBody}};

SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();

function CBody(ctx) {

// Load SP client context, ote async event
SP.SOD.executeFunc(‘sp.js’, ‘SP.ClientContext’, sharePointReady);

// create a point of focus where to add the loaded information from the post item user field, Notice taht we are using the list item ID as an identifier where to put our user data
var ret = “<b><span class=’Blog_userTemplateContextData’ id=’userTemplateContextData” + ctx.CurrentItem.ID +”‘></span></b>”
var newListItemData = { id: ctx.CurrentItem.ID };

globalListItemIDs.push(newListItemData);

//var ret = ctx.CurrentItem.Body;

return ret;

}

function sharePointReady() {
if(spjsLoaded == true)
return;
spjsLoaded = true;

clientContext = SP.ClientContext.get_current();
website = clientContext.get_web();

var oList = clientContext.get_web().get_lists().getByTitle(listName);

// Check if a specific post list item is specified, this would mean that the user is viewing a sigle post
var listItemID = getParameterByName(‘ID’);

// If no single post id is found then load all available posts and their custom users to be used instead of the author(TODO: Optimize for displayed posts only)
if(listItemID === null || listItemID === “”)
{
/*for (var iter = 0; iter < globalListItemIDs.length; iter++)
{
listItemID = globalListItemIDs[iter].id;
MakeNewDataCall(oList, clientContext, listItemID);
}*/
var camlQuery = new SP.CamlQuery();

camlQuery.set_viewXml(‘<Query><OrderBy><FieldRef Name=”Created” Ascending=”False” /></OrderBy></Query>’);
this.collListItem = oList.getItems(camlQuery);

clientContext.load(collListItem);

clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
} else
{
// Only a single post is needed
MakeNewDataCall(oList, clientContext, listItemID);
var newListItemData = { id: listItemID };

globalListItemIDs.push(newListItemData);
}

}

function MakeNewDataCall(oList, clientContext, listItemID)
{
var camlQuery = new SP.CamlQuery();

camlQuery.set_viewXml(‘<Query><Where><Eq><FieldRef Name=”ID” /><Value Type=”Counter”>’ + listItemID + ‘</Value></Eq></Where><OrderBy><FieldRef Name=”Created” Ascending=”False” /></OrderBy></Query>’);
this.collListItem = oList.getItems(camlQuery);

clientContext.load(collListItem);

clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {

var listItemInfo = [];

var listItemEnumerator = collListItem.getEnumerator();

// Get the post data(single or many) and process it
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
var listItemID = oListItem.get_id();

// Seek the SharePoint generated posts and seek if the current item is something we want to process
var userDataDiv = document.getElementById(“userTemplateContextData” + listItemID);
if(!(userDataDiv === null))
{
var author = oListItem.get_item(‘Author’);
// IF so then get the custom user information
var personOwner = oListItem.get_item(customUserFieldInternalName);
if(!(personOwner === null))
{
var name = personOwner.get_lookupValue();

// Put default data that is going to be used if a user image is not found, Notice that we define a user image location
userDataDiv.innerHTML = “<span class=’Blog_postUserData’ id=’postUserData” + personOwner.get_lookupId() +”‘>” + name + “</span>”;
var context = SP.ClientContext.get_current();
var web = context.get_web();
var userInfoList = web.get_siteUserInfoList();

// Make a call to the user profile information for this user to see if there is a user image available
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(‘<View><Query><Where><Eq><FieldRef Name=”ID”/><Value Type=”Number”>’ +personOwner.get_lookupId()+ ‘</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>’);
this.listItems = userInfoList.getItems(camlQuery);
context.load(listItems);
context.executeQueryAsync(Function.createDelegate(this, this.onProfileSuccessMethod), Function.createDelegate(this, this.onQueryFailed));
}
}
}
}

function onProfileSuccessMethod(sender, args) {
var item = listItems.itemAt(0);
var firstName = item.get_item(‘FirstName’);
var lastName = item.get_item(‘LastName’);
var userId = item.get_id();
// Get the location where the user image is to be inserted
var userDataDiv = document.getElementById(“postUserData” + userId);
if(!(userDataDiv === null))
{
// If there is an image then use it, if no image is provided do nothing and display the user full name instead.
var picture = item.get_item(‘Picture’);
if (picture!=null) {
userDataDiv.innerHTML = “<img class=’Blog_userDataImgClassStyle’ src='” + picture.get_url() +”‘ height=’42’><span class=’Blog_postUserDataName’ id =’postUserDataName’>” + firstName + ” ” + lastName + “</span>”;
}
}
}

function onQueryFailed(sender, args) {

alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}

function getParameterByName(name) {
name = name.replace(/[\[]/, “\\[“).replace(/[\]]/, “\\]”);
var regex = new RegExp(“[\\?&]” + name + “=([^&#]*)”),
results = regex.exec(location.search);
return results === null ? “” : decodeURIComponent(results[1].replace(/\+/g, ” “));
}


Leave a comment

Modern C++ Visual Assist Script for Encapsulating object with fail safe mechanism

This is a small snippet for Visual Assist to encapsulate member objects and making sure that you can not use those objects unless they are instantiated or assigned. Also making sure that assignment operation is type safe.:

$end$$SymbolType$ $GeneratedPropertyName$() const {
if (this->$SymbolName$ == nullptr)
throw std::bad_function_call(“The object you are trying to use is empty. This functionality is not avaible. Please pass an object before usage.”);

return $SymbolName$;
}
template<typename T>
void $GeneratedPropertyName$(T &&value) {

static_assert(!is_same<objectPhysics, T>::value, Aurora::Errors::ErrorMessages::TypeMismatch.c_str());

$SymbolName$ = std::forward<T>(value); }

 

Or with assertion on both operations(for minimal overhead for release version):

$end$$SymbolType$ $GeneratedPropertyName$() const {
assert($SymbolName$ == nullptr && “The object you are trying to use is empty. This functionality is not available. Please pass an object before usage.”);

return $SymbolName$;
}
template<typename T>
void $GeneratedPropertyName$(T &&value) {
static_assert(!is_same<objectPhysics, T>::value, Aurora::Errors::ErrorMessages::TypeMismatch.c_str());

$SymbolName$ = std::forward<T>(value);
}


Leave a comment

Android Studio Gradle problems

 

If you get these kinds of errors:

Error occurred during initialization of VM
Could not reserve enough space for object heap
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

Then the solution for me was this:

Control Panel
System
Advanced(tab)
Environment Variables
System Variables
New
Variable name: _JAVA_OPTIONS
Variable value: -Xmx512M

The above is thx to this post: http://www.savinoordine.com/android-studio-gradle-windows-7/. Works for Windows 8.1 + Android Studio 1.0.2


Leave a comment

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.

Follow

Get every new post delivered to your Inbox.

Join 165 other followers