Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

2020-01-31

Building strong named assemblies in Azure Pipelines (or solving the MSB3325 error)

If you, like me, are using a certificate to sign your assemblies, making them strong named, you will get in trouble when trying to build the project on another machine (or as in this case, using an azure pipeline). MSBuild will throw an error (MSB3325) that looks like below.

Error MSB3325: Cannot import the following key file: mycertificate.pfx. 
The key file may be password protected. 
To correct this, try to import the certificate again 
or manually install the certificate to the Strong Name CSP 
with the following key container name: VS_KEY_F287A1878DD02205

Problem background

Certificates (in pfx containers) are password protected and for MSBuild to be able to use them, they must be installed in a key container. (MSBuild uses the "Microsoft Strong Cryptographic Provider", MSC)

Normally, when selecting a certificate in Visual Studio, you are prompted for the password and Visual studio creates the container for you. When the container is created, you do not need the password as long as the container exists. If you would like to build the project on another machine you will get the error above since the container is not present.

Manual solutions

If you go to another machine, one simple way to create the container is to deselect and select the certificate again (in visual studio, in the properties/signing window) which will prompt you for the password.
Another way is to use sn.exe and pass the certificate and key container name as parameters

Sn.exe -i mycertificate.pfx VS_KEY_F287A1878DD02205

This command will then prompt you for the password and create the container
https://docs.microsoft.com/en-us/dotnet/framework/tools/sn-exe-strong-name-tool

Running on Azure pipelines

To be able to build this on Azure Pipelines you need to create the container beforehand.
One way is to create a self-hosted agent that you install the container on.
https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/v2-windows?view=azure-devops

If you would like to use a Microsoft-hosted agent, then you must include the creation of the container in the pipeline itself. Using sn.exe seems like a promising way.

Automated solutions

If we would like to automate the process we have two problems that need solving
1. We need to calculate the name of the container
2. We need to pass the password to the sn.exe tool somehow.

The container name is determined by a class in Microsoft.Build.Tasks.v4.0.dll named ResolveKeySource. It will base the name upon the contents of the certificate, plus the user's domain and username that are running the MSBuild command. kdrapel posted an answer regarding this on StackOverflow

The other issue, passing the password to the sn.exe tool seemed a bit harder. There were some examples where piping it to the exe or writing a wrapper around stdin but none of them worked for me.

SnInstallPfx

Thanks to honzajscz, who also had this issue, the GitHub project SnInstallPfx solved both issues in a nice way. Both calculating the container name and allowing us to enter the password ended us up with a simple command line

SnInstallPfx.exe mycertificate.pfx mypassword

Final solution in Azure Pipelines

To include it in the pipeline I used the library function
https://docs.microsoft.com/en-us/azure/devops/pipelines/library/?view=azure-devops

In the library, I uploaded both the certificate and the sninstallpfx.exe tool.
The password I added in a variable group.

In the YML I first added the variable group

variables:
- group: 'My password'

Then the files needed to be copied to the target host using DownloadSecureFile task

- task: DownloadSecureFile@1
  displayName: Download Pfx
  name: myCertificatePfx
  inputs:
    secureFile: MyCertificate.pfx

- task: DownloadSecureFile@1
  displayName: Download sni
  name: snInstallPfx
  inputs:
    secureFile: SnInstallPfx.exe

Then added a PowerShell task where I imported the file paths and password as an environment variable and just invoked the exe

- task: PowerShell@2
  env:
    SN_INSTALL_PFX: $(snInstallPfx.secureFilePath)
    MYCERTIFICATE_PFX: $(myCertificatePfx.secureFilePath)
    MYCERTIFICATE_PFX_PASSWORD: $(myCertificatePfxPassword)
  inputs:
    targetType: 'inline'
    script: '&"$($ENV:SN_INSTALL_PFX)" "$($ENV:MYCERTIFICATE_PFX)" "$($ENV:MYCERTIFICATE_PFX_PASSWORD)"'

After a long research, I was finally able to build the project on a Microsoft hosted pipeline.

2019-12-02

Uri.ToString() automatically decodes url encoded characters

Uri.ToString() has been discussed quite a lot and its output has not always been consequent.
It can decode URL encoded characters in the URL, especially in the query part where it will be troublesome.

See the article from Anders Abel that discusses the differences between framework 4.0 and framework 4.5 https://coding.abel.nu/2014/10/beware-of-uri-tostring/

As shown in this article, more changes have been introduced int the newer frameworks.

I have done some testing by setting different targetFramework in the httpRuntime element of web.config.

Tests have been performed by creating a URI with a parameter and iterating all ASCII characters (256) and then calling ToString().

for(var i=0;i<16*16;i++) {
  var enc = $"%{i:x2}".ToUpper();
  var uri = new Uri($"https://some.site/?key={enc}");
  uri.ToString();
}

Tests show that different encodings are being decoded when other encodings are kept and the following table shows the differences between each framework where x marks the characters being decoded and a blank space shows that the encoding is kept even after ToString().



targetFramework decodedControl
00-1F

20
!
21
"
22
#
23
$
24
%
25
&
26
'()*+,
27-2C
-
2D
.
2E
/
2F
0-9
30-39
:
3A
;
3B
<
3C
=
3D
>
3E
?
3F
@
40
A-Z
41-5A
[
5B
\
5C
]
5D
^_`a-z{\|}~
5E-7E
DEL
7F
extended
80-FF
4.0 126 x x x x x x x x x x x x x x x x x x x x x x x
4.5 - 4.7.1 83 x x x x x x x x x x x x x x x
4.7.2 - 4.8 75 x x x x x x x x x x
The decoded column lists the number of characters that is decoded (of the 256 possible ASCII characters available).

Summary

ToString always decodes
%20,%22,%2D,%2E,%2F,%30-%39,%3C,%3E,%41-%5A,%5E-%7E 
 "-./0-9<>A-Z^_`a-z{\|}~

I'm not sure that I would like the %20 (whitespace) to be decoded but that's perhaps a personal preference. Of course, it's readability is improving but for programming use, I'm not a fan.

4.5-4.7.1 also decodes
%21,%27-%2C,%3A,%5B,%5D 
!'()*+,:[]

4.0 also decodes
-%1F,%24,%26,%3B,%3D,%3F,%40,%5C 
Control characters $&;=?@\

4.0 is not good since an embedded query string will be decoded since an encoded & and = (%26,%3D) in a value will be decoded.

Example

https://some.site/?key=key%3Dvalue
will be decoded to
https://some.site/?key=key=value
which will mess up the whole meaning

Workaround

If you would like to avoid decoding any URL:s you can use the following extension method.
This will use the AbsoluteUri when we are dealing with an absolute URI and the OriginalString for relative

public static string ToUrl(this Uri uri)
{
    if (uri == null) return null;
    if (uri.IsAbsoluteUri) return uri.AbsoluteUri;
    return uri.OriginalString;
}

Conclusion


  1. Don't use target framework 4.0, at least switch to 4.5.
  2. If you want to avoid encoding, don't use Uri.ToString(). It will always decode some encoded characters (even if newer frameworks are better att avoiding characters that might get you in trouble).

2018-05-02

Maintaining config files in your project

Have a problem with config files (web.config, app.config) and individual settings in a team or for your building server? Look no further. Check the video below and see if ConfigBuilder can be the solution to your problems. Available as a NuGet package (Meriworks.PowerShell.ConfigBuilder) to install in your project.

2011-06-24

Supporting Cross Origin Resource Sharing (CORS) requests in a WCF Rest service - Part 4

For background information, see part 1
For message inspection code, see part 2
For operation dispatcher code, see part 3

To include the message inspection in our wcf service for our service we need to bind it to our service. This is done using behaviors. To bind the IDispatchMessageInspector that works on the ServiceEndpoint level we need to implement an IEndpointBehavior and assign it to our endpoint.

To bind the IOperationInvoker and IDispatchMessageFormatter we need to implement the IOperationBehavior that works on the operation level.

This class also works as an attribute so you can decorate your contract and operations with it if need be. It also contains some properties if you want to control the header values.

https://github.com/dhvik/Wcf-cors-behavior/blob/master/CorsBehaviorAttribute.cs

Assigning can be done in many ways. By declarations on the contract (attribute), configuration in the applications configuration file or direct using code. I'm using code since I host the services in a windows service.
var host = new WebServiceHost2(serviceType, false,
new Uri(serviceBaseUrl + serviceName));
var endpoint = host.AddServiceEndpoint(contractType,
new WebHttpBinding(WebHttpSecurityMode.None), "");
//add support for cors (both for the endpoint to detect and create reply)
endpoint.Behaviors.Add(new CorsBehaviorAttribute());

foreach (var operation in endpoint.Contract.Operations) {
//add support for cors (and for operation to be able to not
//invoke the operation if we have a preflight cors request)
operation.Behaviors.Add(new CorsBehaviorAttribute());
}
When we now have all pieces in place we don't need to bother about cross domain requests. Our endpoint and operation behaviors handles this and we don't need to litter our service code with things that don't belong there anyway.

Supporting Cross Origin Resource Sharing (CORS) requests in a WCF Rest service - Part 3

For background information, see part 1
For message inspection code, see part 2

When a cors request is identified we now have the CorsState object available on our operation level and can act upon this. To be able to skip calling the service method in case of a preflight request we need to implement two extension points in the operation level. Message formatting and operation invocation. Since the preflight request won't have the correct requests message format, we skip the deserializing process and the message using the normal deserializator can results in errors. So in that case we skip both serialization and deserialization.

https://github.com/dhvik/Wcf-cors-behavior/blob/master/CorsFormatter.cs

When it comes to the IOperationInvoker we just skip invoking the operation if we have a preflight request. All other requests uses the original invoker.

https://github.com/dhvik/Wcf-cors-behavior/blob/master/CorsInvoker.cs


In the part 4 we will see how we bind all these extension points together for our service.

2011-06-23

Supporting Cross Origin Resource Sharing (CORS) requests in a WCF Rest service - Part 2

For a background in the subject please see part 1.

To handle Cors requests we can take advantage of the extensibility mechanism that is embedded in WCF. There are many extension points that we can use and the cors problem can be issued in more than one way.
There is a great article, written by Aaron Skonnard, published in the Dec 2007 issue of MSDN magazine, that covers many parts of this mechanism that I can recommend for further reading.

Our main problem is that we need to analyse the incoming request and determine if it is a cors preflight request, cors normal request or a normal request. Preflight request should not reach the service method at all since we don't want to invoke the service method. The other requests should invoke the method but for all cors responses we should add extra headers.

I found a reply by Carlos Figueira in a msdn thread that solves the "analyse message and skip invoking the service method"-part that I used as a start. (as a side note Richard Blewett stated (in the same thread) that we could intercept the message before it reaches the dispatcher by writing a protocol channel. I will leave that excercise to the reader or for another day.)



So to analyse the incoming message we use the first avaliable extension point in the dispatcher (server) that would be the Message inspection stage.
To use this extension point we implement an IDispatchMessageInspector. In this stage we are at the service endpoint and haven't decided wich method of the service that we should call. What we do here is that we look for a cors request (checking if the Origin header is present). If so we create a Cors state object and adds a property to the message so we can use this later on in other extension points.
If it is a preflight request we also create a response message that we should use.
When the message inspector receives the reply we add the headers (and if it was a preflight request, we replace the whole response.

In part 3 we will continue to the operation level where we check the property and omits the call to the service method in case of a preflight request.

View code on github https://github.com/dhvik/Wcf-cors-behavior/blob/master/CorsDispatchMessageInspector.cs

In part 3 we will see how we handle things on the operation level.

Supporting Cross Origin Resource Sharing (CORS) requests in a WCF Rest service - Part I

If you use try to consume a rest service using JavaScript (jquery) and are using chrome or Firefox (newer versions) you might run into cross domain issues that involves the w3c standard for accessing resources on other domains (or ports).

In short, if you try to request a resource on a page using javascript(call a rest service) that is located on another domain/port then the XMLHttpRequest object that is implemented in the browser will first try to discover if the cross-origin resource is prepared/allows to accept requests from the origin. If this preflight request succeeds then the real request will be fired.
All this is handled by the browsers XMLHttpRequest object so from the JavaScript side this don't affect the code.

The server side code must support cors though.

An example: we take a simple service method that only returns a string.

public string Hello() {
return "Hello!";
}

If we want to allow cors requests, then we must detect the preflight request and reply accordingly and if it is the real request we should perform the actual method.

public string Hello(){
//for all cors requests
WebOperationContext.Current.OutgoingResponse.Headers
.Add("Access-Control-Allow-Origin","*");
//identify preflight request and add extra headers
if (WebOperationContext.Current.IncomingRequest.Method == "OPTIONS") {
WebOperationContext.Current.OutgoingResponse.Headers
.Add("Access-Control-Allow-Methods", "POST, OPTIONS, GET");
WebOperationContext.Current.OutgoingResponse.Headers
.Add("Access-Control-Allow-Headers",
"Content-Type, Accept, Authorization, x-requested-with");
return null;
}
return "Hello!";
}

Basically we first add the Access-Control-Allow-Origin header telling that we allow any origins (we can also specify an origin that matches the origin that the request comes from). Then we check if the request is a preflight request (method is OPTIONS). If it is we add extra headers to declare which methods and headers that we allow the real request to contain. There are a few more access-control headers that we can add if we need and these are described in the w3c spec.

To add this code in every method is not a great solution but in part 2 we will see how we can use WCF extensibility to do this in a more elegant way.

2010-05-21

Writing a custom trigger for CruiseControl.Net

I’ve had some problems regarding the triggering of our nightly builds and has not been able to solve this with the standard triggers that comes with ccnet (using v1.4.4). So finally I took some time (night time, kids are sleeping and there is peace and quiet in the house :) and wrote a trigger that fixed the issue at hand. I will come to the trigger in just a moment but I’ll take some time to explain our ccnet setup.

Interval builds

All our projects are built using CruiseControl.Net and for each project we setup two builds. One interval build that triggers when the source has been changed. This build uses the intervalTrigger that checks the source repository at regular intervals. The interval build compiles the project and performs unit testing and provides feedback to the programmer. This is quite standard setup I guess so there’s no rocket science here…

Nightly builds

The other build is a nightly build that (in addition to the tasks for the interval build) performs analysis, generates documentation and installation packages ready to deploy to a target system. It also creates deliverable folder in a specific ”drop zone” for the project. This folder is named using the label of the nightly build.

Labels

All projects uses the project name and build no as label (like MyProject – 234). We reuse the build number of the interval build for the nightly build so if the last interval build was ”MyProject – 234”, the next time the nightly build is triggered the label for the nightly build is ”MyProject-Nightly – 234”. This creates a side effect that if the nightly build is triggered twice and the interval build hasn’t been triggered, the label is the same. If you remember the drop zone folder it uses the label of the nightly build as a name so if it is triggered twice using the same label, it tries to overwrite the drop zone folder.

This is a big no-no and to solve this I added a nant task that fires in the beginning of the nightly build that fails if the drop zone folder exists.

Triggering the nightly build

So to avoid failing the nightly build, it should only be triggered if an interval build has successfully been completed and the nightly build for that interval build hasn’t been performed.

Normally nightly triggers are defined to run at a specific time every night using a ScheduleTrigger that fires at that time if any changes to the source has been made during the day. In combination with a projectTrigger that only fires if the interval build has been successful we can accomplish the trigger to fire only if the interval is successful.

Problem with projectTrigger

There is a limitation to the projectTrigger that affects our setup severely. It doesn’t remember the project status after the ccnet server has restarted. This causes the nightly projects to be rebuilt after a server restart. Since we have lots of projects on the server, we need to restart it atleast once a week and this causes the nightly builds to fail.

New trigger?

To solve this we need another way to trigger the build. The first solution that comes to mind is if there was a trigger that could check if a specific folder (the drop zone folder in this case) was missing, we could replace the projectTrigger with a ”Missing folder trigger”.

Perhaps could look like this.

<missingFolderTrigger path="Z:\PublishedBuilds\MyProject-Nightly\1.0.0.234"/>
Problem here is that we don’t know the last folder name. The ”1.0.0.234”comes from the file version for our compiled assemblies.
The first part of the version number can be any numbers and the 234 refers to the build number of the project. This changes for each build so we need a way to look this up.

Final design

I speak highly of the KISS principle, but I’m also great at creating generic things and sometimes this ”generic gene” gets some overhand (and sometimes also get way out of hand, but I think I found a good level this time :)
So the final design was a trigger syntax like below:
<fileExistsTrigger
triggerOnMissing="true"
seconds="30"
path="Z:\PublishedBuilds\MyProject-Nightly\"
match="\d+\.\d+\.\d+\.[Regex.Match([Projects(MyProject).LastSuccessfulBuildLabel],\d+$)]"/>
  • This trigger is now a more ”generic” one allowing us to trigger on both files and directories.
  • The ”triggerOnMissing” allows us to trigger on both exists and not exists.
  • It’s based on an interval trigger and the ”seconds” parameter allows us to set on how often a file/directory should be checked.
  • The ”path” allows us to set the path that should be checked. If we only need to check a file/directory that we know the name of, this is enough. End with a \ to check a directory.

The match attribute

The ”match” allows us to perform a regular expression search that searches for a match for a directory/file in the supplied path.
  • The \d+ will match one or more digits
  • The \. will match a dot.
  • Repeating this match three times \d+\.\d+\.\d+\. will match the ”1.0.0.” part of the file (or any other valid version major.minor.build. combo)
Now the fun part begins :). I added some syntax to perform string operations and replacements. Any valid command is surrounded by [] and are replaced before the file/directory regex matching begins.
In this example we have two commands, one property and one method call. Properties are evaluated first so [Projects(MyProject).LastSuccessfulBuildLabel] allows us to instruct the trigger to lookup the project named ”MyProject” and return the LastSuccessfulBuildLabel. In this case this would be ”MyProject – 234”.
The method call would look like this after the property replacement. [Regex.Match(MyProject - 234,\d+$)]. This will call the Regex.Match method and return the matched pattern. In this case \d+$ will match the last digits in the ”MyProject – 234” and would return ”234”.
So the final match attribute will be \d+\.\d+\.\d+\.234 and would in this case find a folder named 1.0.0.234. If the folder is missing, the build will be triggered, but if it is there, no trigger is fired. If the interval build fires and is successful, the LastSuccessfulBuildLabel increases and is 235. When the nightly build is triggered again, the folder is missing and the trigger will fire.

Writing the trigger

The first part to think about when writing extensions/plugins to ccnet is that the assembly must be named ccnet.*.plugins.dll otherwise ccnet wont find it. Secondly, the trigger class needs to be decorated with the ReflectionTypeAttribute to tell the class what the xml element name for the class looks like (like [ReflectorType("fileExistsTrigger")]). Every field/property that should be read into the trigger should also be decorated with the ReflectorPropertyAttribute (like [ReflectorProperty("path", Required = true)]). I mainly looked at the ProjectTrigger that comes with ccnet and added stuff along the way.
Beware that the code don't fix all special cases, like if your project name contains , ) or other characters that messes up the expressions, but this is what I needed (remember TDD).
You can use the code below as it is or modify it to your needs. If you want the whole solution (including unit tests), just drop me a mail.
Good luck :)
using System;
using System.Collections.Generic;
using System.Linq;
using ThoughtWorks.CruiseControl.Remote;
using ThoughtWorks.CruiseControl.Core.Triggers;
using ThoughtWorks.CruiseControl.Core.Util;
using Exortech.NetReflector;
using System.Text.RegularExpressions;
using System.IO;

namespace Meridium.CruiseControl.Net.Triggers {
[ReflectorType("fileExistsTrigger")]
public class FileExistsTrigger : IntervalTrigger {
/// <summary>
/// If the trigger should be active if the file is missing, default is false
/// </summary>
[ReflectorProperty("triggerOnMissing", Required = false)]
public bool TriggerOnMissing;
/// <summary>
/// The url to the ccnet server, defaults to a local ccnet installation tcp://localhost:21234/CruiseManager.rem
/// </summary>
[ReflectorProperty("serverUri", Required = false)]
public string ServerUri;
/// <summary>
/// The file/directory path to see if it exists or not
/// </summary>
[ReflectorProperty("path", Required = true)]
public string Path;
/// <summary>
/// Optional parameter to use if a regular expression should be used to match a file or directory in the path. Default is an empty string.
/// </summary>
[ReflectorProperty("match", Required = false)]
public string Match;

private readonly ICruiseManagerFactory _managerFactory;

public IDictionary<string, ProjectStatus> ProjectStatus {
get {
lock (ProjectStatusLock) {
//if cache has timed out, clear cache.
if (_projectStatus != null && DateTime.Now > _cacheValidUntil) {
_projectStatus = null;
Log.Debug("Cache was deleted, was valid until " + _cacheValidUntil.ToString("yyyy-MM-dd HH:mm:ss,fff"));
}
if (_projectStatus == null) {
Log.Debug("Updating ProjectStatus cache from server: " + ServerUri);
_projectStatus = new Dictionary<string, ProjectStatus>();
foreach (ProjectStatus status in _managerFactory.GetCruiseManager(ServerUri).GetProjectStatus()) {
_projectStatus.Add(status.Name, status);
}
_cacheValidUntil = DateTime.Now + CacheTime;
Log.Debug("Cache valid until " + _cacheValidUntil.ToString("yyyy-MM-dd HH:mm:ss,fff"));
}
return _projectStatus;
}
}
}
private static DateTime _cacheValidUntil = DateTime.MinValue;
private static readonly TimeSpan CacheTime = new TimeSpan(0, 10, 0);
private static Dictionary<string, ProjectStatus> _projectStatus;
private static readonly object ProjectStatusLock = new object();

public FileExistsTrigger()
: this(new DateTimeProvider(), new RemoteCruiseManagerFactory()) {
}

public FileExistsTrigger(DateTimeProvider dtp, ICruiseManagerFactory managerFactory)
: base(dtp) {
ServerUri = "tcp://localhost:21234/CruiseManager.rem";
_managerFactory = managerFactory;
}
public override IntegrationRequest Fire() {
//only check on intervals
if (base.Fire() != null) {
try {
Log.Debug(string.Format("More than {0} seconds since last integration, checking url.", IntervalSeconds));
if (FileExists() != TriggerOnMissing) {
Log.Debug("Trigger matched, fire IntegrationRequest");
return new IntegrationRequest(BuildCondition, Name);
}
} catch (Exception ex) {
Log.Error(ex);
} finally {
IncrementNextBuildTime();
}
}
return null;
}
private string HandleProjectPropertyMatches(Match m) {
string projectName = m.Groups["projectName"].Value;
string property = m.Groups["property"].Value;
var ps = GetCurrentProjectStatus(projectName);
switch (property.ToLower()) {
case "lastsuccessfulbuildlabel":
return ps.LastSuccessfulBuildLabel;
case "name":
return ps.Name;
case "buildstatus":
return ps.BuildStatus.ToString();
default:
throw new NotImplementedException(string.Format("Support for property {0} is not implemented yet!", property));
}
}
private static string HandleRegexMatchMatches(Match m) {
string input = m.Groups["input"].Value;
string pattern = m.Groups["pattern"].Value;
Match match = Regex.Match(input, pattern);
return match.Success ? match.Value : string.Empty;
}
private bool FileExists() {
string fp = TranslateValue(Path);
string match = TranslateValue(Match);
if (!string.IsNullOrEmpty(match)) {
if (!fp.EndsWith(@"\"))//"
fp += @"\";//"
var dir = new DirectoryInfo(fp);
if (!dir.Exists) {
Log.Debug(string.Format("Matching path {0} failed. Directory does not exist.", fp));
return false;
}
foreach (var fs in dir.GetFileSystemInfos().Where(fs => Regex.IsMatch(fs.Name, match))) {
Log.Debug(string.Format("Match successful with fileSystemInfo {0}", fs.FullName));
return true;
}
Log.Debug(string.Format("No match for {0}", match));
return false;

}
bool isDirectory = fp.EndsWith(@"\");//"
bool exists = isDirectory ? Directory.Exists(fp) : File.Exists(fp);
Log.Debug(string.Format("Checking if {0} {1} exists: {2}", (isDirectory ? "directory" : "file"), fp, exists));
return exists;
}
/// <summary>
/// Translates the supplied value and expands all methods and variables
/// </summary>
/// <param name="val">The value to translate</param>
/// <returns>The translated value</returns>
private string TranslateValue(string val) {
//handle replacements...
//like [Projects(MyProject).LastSuccessfulBuildLabel]
val = Regex.Replace(val, @"\[Projects\((?<projectName>[^\)]+)\)\.(?<property>[^\]]+)\]", HandleProjectPropertyMatches, RegexOptions.IgnoreCase);
//handle Regexp
//like [Regex.Match(string,pattern)]
val = Regex.Replace(val, @"\[Regex\.Match\((?<input>[^,]+),(?<pattern>[^\)]+)\)\]", HandleRegexMatchMatches, RegexOptions.IgnoreCase);

return val;
}
private ProjectStatus GetCurrentProjectStatus(string project) {
if (!ProjectStatus.ContainsKey(project)) {
throw new NoSuchProjectException(project);
}
return ProjectStatus[project];
}
}
}

2010-04-13

Adding buttons to the TinyMce editor in EPiServer 6 programmatically

While developing ImageVault we needed to add buttons to insert images in the TinyMce editor that ships with EPiServer CMS 6. The buttons are decorated with a TinyMCEPluginButtonAttribute and they can be added manually by entering admin mode and modifying the settings for the XHTML property (see Oskars post "Add functionality to the rich text editor in EPiServer cms 6").
To do this by code this was rather simple since EPiServer has a great Api (even that it could contain more examples)...

The settings are stored in the EPiServer database and is accessed using the PropertySettingsRepository class.
To get the current settings for the TinyMce editor, just create a repository and use the GetDefault method

PropertySettingsRepository p = new PropertySettingsRepository();
PropertySettingsWrapper defaultSettings = p.GetDefault(typeof(TinyMCESettings));

The PropertySettingsWrapper contains metadata for the settings, like DisplayName, Id etc.
It also contains the specific setting for the TinyMce editor in the property PropertySettings.

To create a new settings for the TinyMce editor with some buttons added we can use the code below.

PropertySettingsRepository p = new PropertySettingsRepository();
PropertySettingsWrapper defaultSettings = p.GetDefault(typeof(TinyMCESettings));

//create a copy of the default settings
PropertySettingsWrapper copy = defaultSettings.Copy();
copy.DisplayName+="(My copy)";
TinyMCESettings settings = copy.PropertySettings as TinyMCESettings;

//create a new toolbar row for my buttons
ToolbarRow row = new ToolbarRow();
settings.Toolbars.Add(row);

//the buttons are added using the name defined in the
//ButtonName property of the TinyMCEPluginButtonAttribute.
row.Buttons.Add("mybutton1");
row.Buttons.Add("separator");
row.Buttons.Add("mybutton2");

//Save the copy as a global setting
p.SaveGlobal(copy);

//Set it as default
p.SetDefault(copy.Id);

Quite easy. The separator button is included in EPiServer 6 the others need to be added using classes decorated with the TinyMCEPluginButtonAttribute.

Note!
To actually use this code in EPiServer you need to insert it somewhere :) The easiest way is to create a InitializationModule class (implement IInitializaionModule and mark it with the InitializationModuleAttribute). Then in the Initialize method, add your code to the InitializationEngine.InitComplete event.

public void Initialize(InitializationEngine context) {
context.InitComplete+=(sender,args)=> MyInstallButtonsMethod();
}

More about EPiServer Initialization on episerver world.

2009-07-27

Mvc for Winforms - Mapping the View event to the Controller action Part III

Long time since part I and II were posted, but I've been quite busy lately so I haven't found time (or prioritized) to write the last part, but here we are :)

To recap, in part I I explained about the background of the issue, that I was writing a small winforms MVC framework. The goal of the framework was to be able to instruct the controller to listen to a component in the view and when the component called an event, a specific method would be called.
For example, the call below would register the click event from the saveButton
Controller.RegisterAction(saveButton,"Save");
(in later editions I have also added support for lamda expressions instead of method names, and thus almost abandoned the previous)
Controller.RegisterAction(rotateRightButton,() => Controller.Rotate(90));
Controller.RegisterAction(rotateLeftButton,() => Controller.Rotate(-90));
In part II I wrote about how find and listen to the event of the component.
In this section I will explain how I call the method.

What we ended with in the last post was that we had registered the controllers event to call the ExecuteAction method of the Controller class.
public void ExecuteAction(object source, object eventArgs, ActionData actionData)
or in the latter case using lambda expressions (or action)
public void ExecuteAction(object source, object eventArgs, Action action)
In this case the Action is the easiest to implement. Just call the Invoke method of the Action instance and you are done.
public void ExecuteAction(object source, object eventArgs, Action action) {
action.Invoke();
}
The no Action ExecuteAction method (almost abandoned way )
The ActionData variant is somewhat more tedious but this is how ASP.NET MVC does it.
First we need to find the method to call. The ActionData contains the name of the method. We now needs to find the method of the controller that matches that name. MVC for ASP.NET uses the ActionSelectorClass. The ActionSelectorClass is responsible for retrieving the MethodInfo for an action by passing in the name of the action. It support action aliases and other things so look it up for a great example.
In short it uses reflection to get all methods, filters out irrelevant methods and returns the one that matches the name.
Example (really shortened example, lookup ActionSelectorClass in the ASP.NET MVC framework for a complete example.)
//get all methods
MethodInfo[] array = ControllerType.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance);
//convert to a dictionary
ILookup<string,MethodInfo> methodLookup = array.ToLookup(method => method.Name, StringComparer.OrdinalIgnoreCase);
//return the matching MethodInfo
MethodInfo action = methodLookup[actionName];
Now we have the MethodInfo to invoke, only to calculate the parameters to pass to the method is left.

The action is invoked using the Invoke method of the MethodInfo class and we need to pass the instance to invoke it on (the controller instance) and the object array containing the parameters to pass to the method/action.
Example
action.Invoke(controller,parameterValues);
If the action don't have any parameters we just pass null, but if we do have parameters we need to assign values for them.
Remember: we wanted to be able to register the call
Controller.RegisterAction(createBoldTextButton, "CreateText", new {name="Bold", type=4}); 
To call the action method
public void CreateText(string name, int type) {...}  
using the "Bold" as value for the name parameter and 4 as value for the type parameter.

To succeed with this we need to do some parsing.
  1. Iterate all parameters of the method info.
  2. Handle special cases (like if the parameter is named source and is of type object, then the source value from the event handler method should be passed).
  3. Find a property with a matching name from the value object passed in the RegisterAction.
Iterate all parameters of the method info
Using reflection it's easy to find the parameters.

List<object> objects = new List<object>();
foreach (ParameterInfo info in method.GetParameters()) {
objects.Add(GetParameterValue(info));
}
return objects.ToArray();
Handle special cases
The GetParameterValue method will return the value to pass to the supplied ParameterInfo. In some cases the value to be passed as parameter is not any of the values passed to the values parameter (in the RegisterAction method), like for example, if one would need to get the EventArgs or source parameter passed from the event component, then we would need to handle them. (other customizations can be done here, this is an example)
Type parameterType = parameterInfo.ParameterType;
string parameterName = parameterInfo.Name;

//handle eventArgs and source parameters
if (string.Equals(parameterName, "e", StringComparison.OrdinalIgnoreCase) && _eventArgs != null && parameterType.IsAssignableFrom(_eventArgs.GetType()))
return _eventArgs;
if (string.Equals(parameterName, "source", StringComparison.OrdinalIgnoreCase)&& parameterType.Equals(typeof(object)))
return _source;

//parse the values object
return GetValuesValue(parameterType, parameterName);
Find a matching property of the value object
At last we would try to find a matching property of the value object that matches the parameter type and name. (First we check that the parameter don't matches the whole value object)
//if we don't have a value, return null
if (ValueType == null)
return null;
//if the value is matching, use it as value
if (type.Equals(ValueType))
return _actionData.Values;
PropertyInfo[] valueProperties= ValueType.GetProperties();
//if the value don't have any properties, return null
if (valueProperties.Length == 0)
return null;
//find matching property
PropertyInfo[] possibleMatches = valueProperties
.Where(p => string.Equals(name, p.Name, StringComparison.OrdinalIgnoreCase)
&& type.IsAssignableFrom(p.PropertyType))
.ToArray();
if (possibleMatches == null || possibleMatches.Length == 0)
return null;
if (possibleMatches.Length > 1)
throw new AmbiguousMatchException(string.Format("The value collection contains ambigous match values for the parameter {0} {1}", type, name));
return possibleMatches[0].GetValue(_actionData.Values, null);
Ok, so now we can invoke the method with our array of parameters. (as I said, a bit tedious).
If we compare the two variants,
Controller.RegisterAction(createBoldTextButton, "CreateText", new {name="Bold", type=4});
Controller.RegisterAction(createBoldTextButton, ()=> Controller.CreateText("Bold", 4);
you understand why I have abandoned this last variant and only uses Actions/lambda functions.
The tedious method can still be used if you want to lift the connection between view and controller to a configuration layer. Then the Action method will be hard to implement.

That sums up this last part of my WinForms MVC framework lessons and experiences. Hope that you learned something.

2009-05-04

AssemblyName.GetPublicKeyToken() ToString using lambda

I was searching for a convenient way to get the public key token from a signed assembly and present it in an ordinary string style that is found in all FQ assembly names. The problem is that the GetPublicKeyToken() method from the Assembly type returns a byte array and using ToString() isn’t that great.

I searched the net a bit and all I found was examples on how to do it with a loop and using ToString(”x2”) on every byte, or even more horrible, indexing the 8 bytes by hand...
But if I use a linq/lambda expression, this could be a nice one-liner? ’aye?!

Ok, first convert the byte array to a string array
GetPublicKeyToken().Select(x=>x.ToString(”x2”))
Then aggregate (i was trying the concat first, but that didn’t make any sense) to a single string.
.Aggregate((x, y) => x + y)
With some error handling this boils down to the following method.

#region public static string GetAssemblyPublickKeyToken(Assembly assembly)
/// <summary>
/// Gets the public key token of the supplied argument
/// </summary>
/// <param name="assembly">The <see cref="Assembly">to get the public key token for</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">If <paramref name="assembly">is null.</exception>
public static string GetAssemblyPublickKeyToken(Assembly assembly) {
if (assembly == null) {
throw new ArgumentNullException("assembly");
}
byte[] token = assembly.GetName().GetPublicKeyToken();
if(token == null token.Length==0)
return null;
return token.Select(x => x.ToString("x2")).Aggregate((x, y) => x + y);
}
#endregion