Tag: .NET
Using compile options for version compatibility

Using compile options for version compatibility

Here's the scenario; Your building a module and it needs to be compatible with different versions of a platform. e.g. Sitecore, and everything's great up until the day you need to call different methods in different versions of the platform. You'd rather not drop support for the old versions, and nor do you want to start maintaining two code bases. So what do you do?

C# Preprocessor Directives

Preprocessor directives provide a way to give the compiler instructions to follow while its compiling a project. By using this we can give the compiler conditions to compile different versions in different ways. Thereby allowing us to maintain one codebase, but produce compilations for different versions of the platform. e.g. One for Sitecore 8.0 and another for Sitecore 9.0.

#if, #else and #endif

When the compiler encounters an #if followed by an #endif, it will only compile the code between the two if the specified symbol had been defined.

1#if DEBUG
2 Console.WriteLine("Debug version");
3#else
4 Console.WriteLine("Non Debug version");
5#endif
6

Defining a preprocessor symbol

For the if statement to work, your going to need to define your symbol which is being evaluate.

This can be included in code as follows

1#define YOURSYMBOL

A more useful was of defining this however is to include it in your call to MSBuild (this is particularly useful when using a build server).

1-define:name[;name2]

If your compiling from Visual Studio an easier solution is to set up a new build configuration with a conditional compilation symbol.

  • Right click your solution item in Solution Explorer and select Properties
  • Click Configuration Properties on the left and then Configuration Manager on the right
  • In the pop up window click the Active solution configuration drop down and then click New
  • Enter the name of the build config. In my example above I have SC82 for Sitecore 8.2 and SC90 for Sitecore 9.0.
  • Click Ok and close all the windows you just opened
  • Right click the project that your going to build and select Properties
  • Select the Build tab
  • Select your build configuration from the configuration at the top
  • Enter the symbol your using for the #if directives

Reference different versions of an assembly

Adding conditions to our code is good, but for this to fully work we also need to reference different versions of the assemblies that are causing the issue in the first place.

There's no way of doing this through Visual Studio but by editing the .csproj file manually we can update the hint path on a reference to include the configuration name as a variable.

1..\libraries\$(Configuration)\Sitecore.Kernel.dll False

This example shows how different versions of the Sitecore Kernel can be referenced by keeping each version in a subfolder that corresponds with the build configuration name.

As well as different versions of assemblies, it may also be needed to target different versions of the .NET framework. This can be done in the .csproj file by including additional property groups that have a condition on the configuration name.

1bin\SC82\
2TRACE;SC82
3true
4v4.5.2
5
6bin\SC90\
7TRACE;SC90
8true
9v4.6.2

In this example I'm targeting .net 4.5.2 for my Sitecore 8.2 configuration and 4.6.2 for my Sitecore 9 configuration.

Useful Links

C# preprocessor directives
-define (C# Compiler Options)

How to create a new instance of a dependency inject object

How to create a new instance of a dependency inject object

I decided to write this post after seeing it done wrong on a number of occasions and also not finding many great examples of how it should be done. Most articles of DI or IOC tend to focus on objects such as a logger being injected and then calling functions on that object.

Take for instance, this example in the Simple Injector documentation:

1using System;
2using System.Web.Mvc;
3
4public class UserController : Controller {
5 private readonly IUserRepository repository;
6 private readonly ILogger logger;
7
8 public UserController(IUserRepository repository, ILogger logger) {
9 this.repository = repository;
10 this.logger = logger;
11 }
12
13 [HttpGet]
14 public ActionResult Index(Guid id) {
15 this.logger.Log("Index called.");
16 IUser user = this.repository.GetById(id);
17 return this.View(user);
18 }
19}

Here we can see the implementation of IUserRepository and ILogger get passed in the constructor and are then used in the Index method.

However what would the example be if we wanted to create a new user and call the user repository to save it? Creating a new instance of IUser from our controller becomes an issue as we don't know what the implementation of IUser is.

The incorrect implementation I usually see is someone adding a reference to the implementation and just creating a new instance of it. A bit like this:

1public class UserController : Controller {
2 [HttpPost]
3 public ActionResult SaveUser(UserDetails newUserInfo) {
4
5 IUser user = new User;
6 user.FirstName = newUserInfo.FirstName;
7 user.LastName = newUserInfo.LastName;
8 this.repository.SaveUser(user);
9 return this.View(user);
10 }
11}

This will work, but fundamentally defeats the point of using dependency injection as we now have a dependency on the user objects specific implementation.

The solution I use is to add a factory method to our User Repository which takes care of creating a User object.

1public class UserRepository : IUserRepository {
2 public User CreateUser() {
3 return new User();
4 }
5}

Responsibility of creating the object now remains with its implementation and our controller no longer needs to have a reference to anything other than the interface.

1public class UserController : Controller {
2 [HttpPost]
3 public ActionResult SaveUser(UserDetails newUserInfo) {
4
5 IUser user = this.repository.CreateUser();
6 user.FirstName = newUserInfo.FirstName;
7 user.LastName = newUserInfo.LastName;
8 this.repository.SaveUser(user);
9 return this.View(user);
10 }
11}
Redirect to https using URL Rewrite

Redirect to https using URL Rewrite

There's always been reasons for pages to be served using https rather than http, such as login pages, payment screens etc. Now more than ever it's become advisable to have entire sites running in https. Server speeds have increased to a level where the extra processing involved in encrypting page content is less of a concern, and Google now also gives a boost to a pages page ranking in Google (not necessarily significant, but every little helps).

If all your pages work in https and http you'll also need to make sure one does a redirect to the other, otherwise rather than getting the tiny page rank boost from Google, you'll be suffering from having duplicate pages on your site.

Redirecting to https with URL Rewrite

To set up a rule to redirect all pages from is relatively simple, just add the following to your IIS URL Rewrite rules.

1<rule name="Redirect to HTTPS" stopProcessing="true">
2 <conditions>
3 <add input="{HTTPS}" pattern="^OFF$" />
4 </conditions>
5 <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
6</rule>

The conditions will ensure any page not on https will be caught and the redirect will do a 301 to the same page but on https.

301 Moved Permanently or 303 See Other

I've seen some posts/examples and discussions surrounding if the redirect type should be a 301 or a 303 when you redirect to https.

Personally I would choose 301 Moved Permanently as you want search engines etc to all update and point to the new url. You've decided that your url from now on should be https, it's not a temporary redirection and you want any link ranking to be transfered to the new url.

Excluding some URL's

There's every chance you don't actually want every url to redirect to https. You may have a specific folder that can be accessed on either for compatibility with some other "thing". This can be accomplished by adding a match rule that is negated. e.g.

1<rule name="Redirect to HTTPS" stopProcessing="true">
2 <match url="images" negate="true" />
3 <conditions>
4 <add input="{HTTPS}" pattern="^OFF$" />
5 </conditions>
6 <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
7</rule>

In this example any url with the word images in would be excluded from the rewrite rule.

Sitecore: Extend profile matching over multiple visits

In Sitecore, to gain a better understanding of our visitors interests we have the ability to define Profile Keys and Cards to tag our content with. As our visitors navigate through the site, this data is used by Sitecore to build a profile of the visitor. A pre-defined Pattern Card that most resembles the visitors profile is then assigned to the visitor which can be used as the basis of selecting the content that should be displayed on a page for that visitor.

However what this doesn't do is carry the visitors profile over multiple sessions. Each time a visitor comes back to the site within a new session, the visitors profile key values are reset back to zero.

So what's Sitecore actually doing?

Before working out how to carry this information between visits, lets look at how a profile is actually being created.

If we look in the Profiles table within the Analytics database we can see the profile data that’s been recorded for a visitors visit.

The Pattern Values column contains the current profile key scores for each key the visitor has a score for. e.g.

background=40;scope=50

If the visitor was to visit a page which has scope score of 5 and background score of 10 these values would be added to the visitors current key scores. e.g.

background=50;scope=55

When a pattern card is assigned, the card with the closest shape of keys is chosen. e.g. If the visitor has a high value for background and low value for scope they will be assigned a pattern card with similar proportional key values.

How do we extend this over multiple visits?

So the easiest way to carry the visit information from one visit to the next would be to simply copy the profile key values from the last session to the next. The code for this would look similar to the following:

1var currentVisitIndex = Tracker.CurrentVisit.VisitorVisitIndex;
2
3if (currentVisitIndex &lt;= 1 || !Tracker.CurrentVisit.Profiles.Any())
4{
5 return;
6}
7
8var previousProfiles = Tracker.Visitor.GetVisit(currentVisitIndex - 1, VisitLoadOptions.All).Profiles;
9
10foreach (var profile in previousProfiles)
11{
12 var currentProfile = Tracker.CurrentVisit.GetOrCreateProfile(profile.ProfileName);
13
14 currentProfile.BeginEdit();
15
16 foreach (var ProfileKey in profile.Values)
17 {
18 currentProfile.Score(ProfileKey.Key, ProfileKey.Value);
19 }
20 currentProfile.UpdatePattern();
21
22 currentProfile.EndEdit();
23}

Now the visitors profile is how it was when they left and crucially we can use this data to personalize the sites homepage for the visitor.

So why shouldn't we do this?

As simple as this is, it comes with one potentially massive downside. If we go back to the way the profile values are built up they key values are essentially just being accumulated. Each time the visitor visits an item with a background score of 10, the visitors background profile key score in increased by 10.

Our visitors are humans going through different stages of there life, with constantly changing jobs and interests. There's nothing to ever reduce a profile keys score other than the fact everything is normally zeroed on each visit. By copying the data from the last visit on the start of the next this would never happen and the profile key's will continue to count up forever. The key value obtained from an item viewed 2 months ago would counted as just as important as the value from another key viewed on an item today.

So if you were running a travel site and a visitor looked at summer holidays for 3 weeks they will have a profile highly weighted towards summer holidays. If they then started to look at winter holidays we wouldn't want them to have to look at winter holidays for 3 weeks just to have an even likeness of summer and winter.

Overcoming this issue isn't so simple and largely depends on your business needs. If your visitors interests could change each week then you need something that will degrade the old visit data values quickly. Whereas if your trying to differentiate between people that are in a 2 week vs 6 month buying pattern, you need to retain that data a lot longer.

Some things we can do when copying the data from the visitors previous profile though could include:

  • Halving the profile scores, or reducing by a different factor. This would reduce the importance of values obtained on previous visits. So if a visitor received a 10 on the first visit, it would be worth 5 on the second, 2.5 on the third etc
  • Look at the date of the last visit. Is it to old to be relevant still or can we use the age to determine what factor we should reduce the scores by
  • Look at a combination of multiple last visits to establish what the recent scores were

All these ideas though need to be used on conjunction with what your trying to profile. If it's age then you know people are going to get older. If it's an interest that will change frequently then you know the data needs to degrade quickly, but if it's male/female then that doesn't necessarily need to degrade at all.

Bundling and Minification with Sitecore

There's various ways to add bundling and minification to a site, but one of the easiest is to use Microsoft's support from the Microsoft.AspNet.Web.Optimization package. This implementation has some great features including:

  • Automatically create the bundles and minify them as files are changed
  • Create unique urls to each version of a bundle to force browser refreshing of the file
  • Debug mode which outputs links to the raw files rather than the bundled minified version

The functionality is also fully compatible with Sitecore. To use it in your Sitecore solution follow these steps:

1. Add Microsoft.AspNet.Web.Optimization to your project from NuGet. This is the package from Microsoft that contains the functionality to do bundling and minification

 

2. Create your CSS and Javascript bundles. Where you put the logic for this is up to you but it will need to run when the application starts. Outside of Sitecore my main development is on bespoke ASP.NET MVC and Web API projects so I like to organise startup scripts into an App_Start folder and reference it from the Application_Start event in the global ascx file.

If you are running a Sitecore instance with multiple sites or if you do not have direct access to the production config files, it may be better to keep the logic separate and use a pipeline to create the bundles.

My bundle definitions would look something like this

1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Web;
5using System.Web.Optimization;
6
7public class BundleConfig
8{
9 public static void RegisterBundles(BundleCollection bundles)
10 {
11 bundles.Add(new ScriptBundle("~/bundles/scripts").Include(
12 "~/Scripts/jquery-{version}.js",
13 "~/Scripts/bootstrap.js"));
14
15 bundles.Add(new StyleBundle("~/bundles/css").Include(
16 "~/Content/bootstrap.css",
17 "~/css/site.css"));
18 }
19}

And in my Global.asax.cs file I would have some logic like this to call the other function

1protected void Application_Start(object sender, EventArgs e)
2{
3 BundleConfig.RegisterBundles(System.Web.Optimization.BundleTable.Bundles);
4}

3. Replace your Javascript/CSS references in your layout or rendering files with a call to render the bundle

Webforms

1<%: System.Web.Optimization.Scripts.Render("~/bundles/scripts") %>
2<%: System.Web.Optimization.Styles.Render("~/bundles/css") %>

MVC

1@Scripts.Render("~/bundles/scripts")
2@Styles.Render("~/bundles/css")

4. In your web.config file there are a couple of changes needed to get things to work.

First you need to set an ignore url prefix to stop Sitecore trying to resolve the URL to the bundle. In this example mine is called bundles (note: you should add the prefix the what is already in your config file. e.g. |/bundles)

1<!-- IGNORE URLS
2 Set IgnoreUrlPrefixes to a '|' separated list of url prefixes that should not be
3 regarded and processed as friendly urls (ie. forms etc.)
4-->
5<setting name="IgnoreUrlPrefixes" value="/sitecore/default.aspx|/trace.axd|/webresource.axd|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.DialogHandler.aspx|/sitecore/shell/applications/content manager/telerik.web.ui.dialoghandler.aspx|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.SpellCheckHandler.axd|/Telerik.Web.UI.WebResource.axd|/sitecore/admin/upgrade/|/layouts/testing|/bundles" />
6

Next a dependant assembly binding needs to be set up for Web Grease. Without it you will see an error about the Web Grease version number

1<dependentAssembly>
2 <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
3 <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
4</dependentAssembly>

If you have done this and are still getting a version number error check the assembly binding tag. Older versions of Sitecore have the applies to property set which may be only applying the bindings to .Net 2 and you may be using .Net 4.

1<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1" appliesTo="v2.0.50727">

5. If you are using IIS7 you will also need to make a change in your web.config file

1<system.webServer>
2 <modules runAllManagedModulesForAllRequests="true">
3 </modules>
4</system.webServer>

6. Publish your changes into your Sitecore site. Depending if you have compilation mode set to debug or not you will now either have a bundle reference for all your JavaScript and CSS or the individual file references.

Bundling and Minification error with IIS7

.NETs standard tools for bundling and minification are a great asset to the platform solving a lot of problems with only a few lines of code.

However if using IIS 7.0 you may run into a strange issue where the path to your bundles gets created but a 404 is returned whenever there accessed. The functionality is obviously installed and working otherwise the URL wouldn't be created, but a 404 clearly isn't what you want.

The solution lies in your web.config file by setting runAllManagedModulesForAllRequests to true

1<system.webServer>
2 <modules runAllManagedModulesForAllRequests="true">
3 </modules>
4</system.webServer>
Creating Training Buddy's Live Tile

Creating Training Buddy's Live Tile

Live tiles are probably the best known feature about Windows Phone. Unlike iOS's plain grid of app icons Microsoft designed their phones home screen to provide users with data without having to open the app. With Windows Phone 8 the feature was updated so that 3rd party apps like Training Buddy could offer full width tiles along with new layout templates.

Adding a live tile to your app is a great idea as it is one of the features users often look for when their choosing an app. The app store also handily points out if an app uses a live tile or not.

The Design

There are 3 tile templates to choose from when you add a live tile to your app. These are Flip, Iconic and Cycle.

Flip gives the illusion that the tile has a front and a back and will flip over after a few seconds.

Iconic has space for an image and a large number, a bit like the icon for messages and emails. When in its largest size there is also wide content zones that can contain text.

Cycle lets you choose 9 images that the app will Cycle through.

For Training Buddy I have used the Iconic template. You will probably find like myself that the type of app you are creating will more than likely determine what template you are going to use. As Training Buddy's live tile was ultimately going to show details of the users last activity, Iconic was the obvious choice. The smaller sizes don't really have enough space to give any activity stats and the large version gives you an additional space for a smaller image that was perfect for the activity type image (running, cycling, walking).

Another alternative is to make a completely custom design and write something in your app to render it as an image. You can then display the image using either the flip or cycle template.

The Code

The second reason you everyone should add live tiles to their app is because the code is so simple (this is the actual code from Training Buddy).

1// Application Tile is always the first Tile, even if it is not pinned to Start.
2 ShellTile TileToFind = ShellTile.ActiveTiles.First();
3
4 // Application should always be found
5 if (TileToFind != null)
6 {
7 string WideContent1 = "";
8 string WideContent2 = "";
9 string WideContent3 = "";
10 string activityLogo = "";
11 if (App.settings.LiveTile)
12 {
13 var lastActivity = (from a in AllActivities
14 orderby a.StartDateTime descending
15 select a).Take(1);
16
17 if (lastActivity.Count() &gt; 0)
18 {
19 if (App.settings.DistanceMeasurement == "Miles")
20 {
21 WideContent3 = "Distance: " + lastActivity.First().Distance.ToString("0.##") + " miles";
22 }
23 else
24 {
25 WideContent3 = "Distance: " + (lastActivity.First().Distance * 1.609344).ToString("0.##") + " km";
26 }
27 WideContent2 = "Date: " + lastActivity.First().StartDateTime.ToShortDateString();
28 switch (lastActivity.First().ActivityType.ToLower())
29 {
30 case "running":
31 WideContent1 = "Last Run";
32 break;
33 case "walking":
34 WideContent1 = "Last Walk";
35 break;
36 case "cycling":
37 WideContent1 = "Last Cycle";
38 break;
39 case "swimming":
40 WideContent1 = "Last Swim";
41 break;
42 }
43
44 activityLogo = "/Assets/" + lastActivity.First().ActivityType + "Black-70.png";
45
46 if (lastActivity.First().CaloriesBurned &gt; 0)
47 {
48 WideContent3 += " Calories: " + lastActivity.First().CaloriesBurned.ToString("0.#");
49 }
50
51 }
52
53 }
54
55 IconicTileData tileDate = new IconicTileData
56 {
57 Title = "Training Buddy",
58 WideContent1 = WideContent1,
59 WideContent2 = WideContent2,
60 WideContent3 = WideContent3,
61 IconImage = new Uri("/Assets/RunningBlack-150.png", UriKind.Relative),
62 SmallIconImage = new Uri(activityLogo, UriKind.Relative)
63 };
64
65 // Update the Application Tile
66 TileToFind.Update(tileDate);
67 }

First I'm finding the application tile. It is possible to create additional tiles for your app which is another great feature, but if you want to just update the main tile it will be the first one returned.

Next I'm checking to see if the user has turned on the live tile or not. If they haven't then I'm just setting the tile back to its default state.

The following lines are then getting the content to display on the tile and building up the strings on local variables.

Lastly and most importantly I'm creating a new instance of IconicTileData and setting each of its properties with the data to show. Then it's just a case of calling Update on the tile instance and providing it with the new IconicTileData object.

The Tile

And here's the result

Live tiles are really easy to create so if your developing an app you should definitely take the time to add one.

RestSharp with Async Await

RestSharp is an excellent open source project to use in a Windows Phone app if you want make http calls to a json api. However it doesn't have any inbuilt support for the async await syntax. Thankfully with C#'s extensions methods we can add this support in our app.

1namespace RestSharpEx
2{
3 public static class RestClientExtensions
4 {
5 public static Task&lt;IRestResponse&gt; ExecuteTaskAsync(this RestClient @this, RestRequest request)
6 {
7 if (@this == null)
8 throw new NullReferenceException();
9
10 var tcs = new TaskCompletionSource&lt;IRestResponse&gt;();
11
12 @this.ExecuteAsync(request, (response) =&gt;
13 {
14 if (response.ErrorException != null)
15 tcs.TrySetException(response.ErrorException);
16 else
17 tcs.TrySetResult(response);
18 });
19
20 return tcs.Task;
21 }
22 }
23}

This will add a new function to the RestSharp client type called ExecutreTaskAsync. Inside the method it will call the ExecuteAsync function as you normally would, but has also implemented returning a Task and setting it's results when its complete.

To use the function would be as follows

1var client = new RestClient("http://www.YOUR SITE.com/api/");
2var request = new RestRequest("Products", Method.GET);
3var response = await client.ExecuteTaskAsync(request);

Creating 301 redirects in web.config

For various reasons at times you may need to create a 301 redirect to another URL. This could be as a result of a page moving or you just need to create some friendly URLS.

As a developer you may be tempted to do something like this in code...

1private void Page_Load(object sender, System.EventArgs e)
2{
3 Response.Status = "301 Moved Permanently";
4 Response.AddHeader("Location","http://www.new-url.com");
5}

But do you really want your project cluttered up with files who's only purpose is to redirect to another page!

You may also be tempted to try doing something with .NET's RouteCollection. This would certainly solve an issue on creating a redirect for anything without a file extension, but there is a better way.

In your web.config file under the configuration node create something like this

1<location path="twitter">
2 <system.webServer>
3 <httpRedirect enabled="true" destination="http://twitter.com/TwitterName" httpResponseStatus="Permanent" />
4 </system.webServer>
5</location>

The location path specifies that path on your site that this redirect will apply to. The destination value in the httpRedirect is where the redirect will go to. As well as setting Permanent for the httpResponseStatus you can also specify Found or Temporary depending on your needs.

ASP.NET Session Timeout

A users session on an ASP.NET site by default will time-out after 20 minutes. This however can be changed through either the web.config file or IIS.

To edit through the web.config file you need to edit the sessionState tag under system.web

1<system.web>
2 <sessionState timeout="30"></sessionState>
3</system.web>

Or through IIS click on your site name and then click Session State under the ASP.NET heading. There will be a field labeled Time-out (in minutes).

The value you enter for time-out must be an integer.

Help it doesn't seem to work!

If your sessions still seem like there timing out after 20 minutes it could be because your site isn't very active.

The application pool for your site also has an idle time-out that is set by default to 20 minutes. When the idle time-out is reached it will cause your application pool to recycle and therefore loose any active sessions (that's assuming you have the session state mode set to In Proc). Therefore it is a good idea to increase this to whatever you have set the session time-out to.

To do this go to your sites application pool in IIS, click advanced settings on the right and then look for the Idle Time-out (minutes) setting and update this to be the same as your session time-out value.