Friday 10 October 2014

Differences in Sitecore Image Data Type From 6.x to 7.x

Sitecore's raw data difference

When selecting an image, Sitecore generates some xml which is saved and used when getting the image from the field on your template. There is a difference from 6.x and 7.x. In 7.x the attributes src and mediapath have been removed.

6.x
<image mediaid="{5B2DA590-21FF-409D-9E03-4759D5CB65BE}" mediapath="/Images/TestImage" src="~/media/Images/TestImage.ashx" height="" width="" hspace="" vspace="" />

7.x
<image mediaid="{5B2DA590-21FF-409D-9E03-4759D5CB65BE}" height="" width="" hspace="" vspace="" />

The problem with retrieving data

A normal thing to do with images is to get the url of the image. For instance we need it for the open graph meta-tag og:image. As documented in the Presentation Component
XSL Reference for Sitecore 6.2 or later you can use the 'src' to get the source of the image. Like the following, but the problem is that this stopped working in Sitecore 7.x since the src attribute was removed.

<meta name="og:image" content="{sc:fld('FieldName', $sc_currentitem, 'src')}" />

The problem after updating from 6.x to 7.x

When selecting a new image, you rarely would press 'clear' and then select a new image. When selecting the new image sitecore will change the mediaid and the height/width. The mediapath/src will remain. If your code hasn't been updated it will seem like you can't change the image or the old image is still being loaded.

So how do we fix this?

We have the mediaid from the field and thats all. We can output an image with sc:image but that doesn't work if we only need the images url. We also have sc:GetMediaUrl that takes an Item or XPathNodeIterator as an argument and we have the sc:Item which takes an item ID as argument. Putting that together 

7.x
<xsl:variable name="imageId" select="sc:fld('FieldName', $sc_currentitem, 'mediaid')"/>
<xsl:variable name="imageItem" select="sc:item($imageId, $sc_currentitem)"/>
<xsl:variable name="imageUrl" select="sc:GetMediaUrl($imageItem)"/>

or all in one statement <xsl:variable name="imageUrl" select="sc:GetMediaUrl(sc:item(sc:fld('FieldName', $sc_currentitem, 'mediaid'), $sc_currentitem))"/>

<meta name="og:image" content="{$imageUrl}" />

Not as easy as it used to be, but again using Razor would be alot easier.

Tuesday 22 April 2014

New features for c# 6 part 2

This is part 2 of the new features for c# 6, see part 1 here. All these features are already done for c# 6, where the part 1 is planned features.

Primary constructors

Primary constructors a shorter way to write a constructor that automatically assigns to private instance variables. The constructor is defined with the class itself as class Point(int x, int y) { … }


Auto-property initializers / Getter-only auto-properties

Another shorthand for properties that only retrieve/assign the value to a private member. Now you can do this public int X { get; set; } = x; You can also use an getter-only auto-property, which is perfect for immutable classes! public int Y { get; } = y; 


Using static members

In your using statements you can have static members to have all methods easily accessable in that class. As so using System.Console; … Write(4);


Dictionary initializer

Dictionary initializer is another short hand. new JObject { ["x"] = 3, ["y"] = 7 } would be the same as jsobj = new JSObject(); jsobj["x"] = 3; jsobj["y"] = 7;


Indexed member initializer / indexed member access

This is quite basic but really awesome. Lets take the example from before new JObject { ["x"] = 3, ["y"] = 7 }. Doing this with indexed member initializer would be new JObject { $x = 3, $y = 7 }. So object["x"] is the same as object.$x which can be used in the initializer or when accessing normally.


Declaration expressions

With declaration expressions you can declare a variable when calling a method with the out parameter. For example when parsing an int using the TryParse method you can declare the variable to out, when calling the method as such int.TryParse(s, out var x);


Await in catch/finally / Exception filters

You can now use await in catch/finally try … catch { await … } finally { await … } and as a new thing you can filter your exceptions with an if clause so it will only be caught if the terms are matched catch(E e) if (e.Count > 5) { … }

Wednesday 9 April 2014

New features for c# 6 part 1

This is a list of planned features for c# 6 and what they do. Its exciting to see what is coming in c# 6. This is the first part of two posts. Part 2 will cover other features coming in c# 6 which are already done at the moment.

Binary literals and digit separators

Working with long numbers, hex or binary in c# can be hard. With binary literals and digit separators it could get a lot easier. Binary literals are used to write values of types int, uint, long, and ulong. Binary literals have two possible forms: decimal and hexadecimal.

Binary literals would look like this 0b00000100, which is equal to 4 and digit separators would look like this 0xEF_FF_00_A0, which is equal to 4026466464.

I see these features as a small change for easier readable code when working with large numbers.

Expression-bodied members

Expression-bodied members are members that have a dynamic value without getting the value from a method. For instance public double Dist => Sqrt(X * X + Y * Y) normally doing this would require a method or having a property. This would be a nicer and cleaner way of doing so.

Event initializers

You can now initialize objects with events. As of now you would have to create you object and then assign events to that object. Now you can do it directly in the initialization of that object. 

new Customer { Notify += NotifyEventHandler };

Null propagation

Null propagation is also known as safe navigation operator. 

Lets say you're going to access an descendant of a given class. Our call would be Class.ChildClass.Property. Lets say for instance that ChildClass is null. We would have to check for a null reference of the Class type and ChildClass to be safe.

With the Null propagation/Safe Navigation Operator we would be able to write Class?.ChildClass?.Property without having to check for null references all the time.

I've written about the Safe Navigation Operator before

Semicolon operator

Semicolon operator is the sequential composition operator on expressions. Just as semicolon is sequential composition on statements. Thats means you can string expressions together and the "value" of the expression is the last one.

(var x = Foo(); Write(x); x * x)

Private protected

Not much to explain, you can now have a private protected method, property or member.

private protected string GetId() { … }


Params IEnumerable

You can now use IEnumerable as a params parameter on the method, for instance int Avg(params IEnumerable<int> numbers) { … } instead of an Array of ints.


Constructor Inference

When working with generics, it can be annoying that you have to define the generic type each time. Having Tuple you need to define each type when creating a new object. It would be like new Tuple<int, string, bool>(3, "three", true);. With constructor inference we will be able to do the following new Tuple(3, "three", true);

NameOf operator

The nameof will give you the name of an call and will be nice to use with diagnostics. Log("MyMethod called"); will be replaced with Log(nameof(MyMethod) + " called"); so when the method is renamed be rerfactoring or manually changed, the log message will change automatically. If you don't change it manually the solution won't compile. No more changing static names in logging messages :)

Friday 4 April 2014

Roslyn .NET Compiler is now available as open-source

Yes, the new .NET compiler "Roslyn" is now available as open source. Exciting! Microsoft is also accepting contributions to the compiler. I can't even imagine where that could take it.

C# compiler source code available here.

Monday 3 March 2014

Safe Navigation Operator being considered for c#

One of the highest suggested features on UserVoice is the safe navigation operator. Now Mads Torgersen, PM of the C# Language, has expressed that they are considering implementing the feature. The next couple of months they will do some prototyping.

Why is this good and what is the Safe Navigation Operator?


Well, having a short hand null reference check would lighten up your code. Every time you're checking for null references in your code would get a lot easier and shorter. Lets have a look at it.

Lets say you're going to access an descendant of a given class. Our call would be Class.ChildClass.Property. Lets say for instance that ChildClass is null. We would have to check for a null reference of the Class type and ChildClass to be safe.


With the Safe Navigation Operator we would be able to write Class?.ChildClass?.Property without having to check for null references all the time.


Quite neat! If this is ever going to come to c# let's hope it's the next release. You can read more about the suggestion here.

/JJ


Sunday 2 March 2014

Chocolatey, apt-get for windows!

Chocolatey is simply a Machine Package Manager for Windows. When installing Windows applications, Chocolatey can do it for you in a single line. It will download and install that application with one line only! At the time speaking there are 1644 packages, so a lot of applications are available.

Installing Chocolatey is also a single line:
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin

From there you can just type cinst PackageName like cinst GoogleChrome. Look at Chocolatey's website to find the packages you need.

Enjoy an apt-get like tool for Windows!

/JJ

Saturday 22 February 2014

Using NArrange to structure and arrange C#/VB source code

NArrange is an open source tool to arrange source code. It beautifies the source code by grouping members, properties, events and more, into configurable regions. You can set it up to run as a command or a pre-build event. Lets take a look at it.

We have this code to start with, not dealing with whitespace or anything - it's a mess but for illustration purposes still quite simple.


By running NArrange we then expect to get 3 regions, constructors, methods and fields. A cleanup of the file(s), indenting correctly and removing whitespaces should also happen. Lets take a look at the code afterwards.


The tool is great for consistency in the source code to a project which is under version control, by enforcing NArrange to be run before or as an event during check-in, the formatting will be consistent.

On the down side running as a pre-build event can have some annoying moments. For instance building during a debug session could move your newly typed code around which can be annoying.

Setting it up in Visual Studio

Download NArrange from the website or as a chocolatey package. All the examples takes the solution file as input and arranges all projects in the solution. The parameter can, if needed, be a single project or just a single file.

As an external tool

We will create two external tools, one for arranging / taking a backup, and one for restoring the backup if needed. In Visual Studio select Tools -> External Tools -> Add and you will have to fill in the command, arguments and initial directory fields.



Command: C:\Program Files (x86)\NArrange 0.2.9\narrange-console.exe
Arguments: "$(SolutionFileName)" /b
Initial Directory: $(SolutionDir)
Note that the /b is for taking the backup


Command: C:\Program Files (x86)\NArrange 0.2.9\narrange-console.exe
Arguments: "$(SolutionFileName)" /r
Initial Directory: $(SolutionDir)
Note that the /r is for restoring the backup - it requires a backup is present.

Pre-build event

In properties of your project under build events add the following to the pre-build event.


cd C:\Program Files (x86)\NArrange 0.2.9
narrange-console.exe "$(SolutionPath)"

/JJ