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);

Advertisements

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;
}

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());
}

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, ” “));
}