Error: The certificate with thumbprint was not found. Http Status Code: BadRequest

leave a comment »

I’ve got this error today while publishing my azure cloud service project from visual studio.

The issue in my case was that the ssl certificate we used for https expired. We updated to a new one in the azure management web site but we didn’t update the visual studio project roles with the thumbprint of the new certificate.

To do this you first have to find the thumbprint of the new certificate: windows azure management web site -> cloud services -> yourservice -> configure -> scroll down to certificates and copy the thumbprint.

In visual studio, go to yourservice project -> roles file -> certificates -> now you should see your old thumbprint. Replace it with the new thumbprint and you are good to go.

Written by Liviu Trifoi

October 29, 2013 at 8:26 pm

Posted in azure, Visual Studio

AngularJS custom validation with business rules

with 8 comments

Long time, no posts :)
I’ve recently switched from silverlight to html5/javascript and we’re using angular – which is great! (and not so great sometimes).
My thoughts about angular validation is that it has been designed with very simple scenarios in mind.
If you just have a login form or one registration form, I would say that it provides enough.
If, however, you are building an app with dozens of screens and dozens of fields then you’ve come to the right place.

Let’s define some requirements first of what I want from my validation mechanism:
– When I first enter a screen and don’t do anything I want the fields to be pristine – not marked with any kind of error information
– If I modify a field and the value is invalid, I want the field marked with an error
– If I enter a screen, don’t modify any field and press submit, I want all my validation rules to be checked and mark the fields that have errors with error.
– I want localized and parameterized error messages (e.g. for a field with a minimum length rule I want to be able to show an error message like ‘value must have at least %s characters’)
– Some validation rules cannot be checked client side and the service I call will return the validation errors on a response. So I want to have the possibility to somehow mark the field with an error and set a custom error message.
– Some validation errors might not be related to an input field. E.g. you’re doing a student/courses app and you want to be able to select the courses for a student. There are some rules in what he can select (he cannot have certain courses as they are for year 2 and he is in year 1 for example). You’re also not using an input field to select the courses.

– Some validation errors are related to multiple input fields at the same time. E.g. you have a start date/end date/resolution date combo that have a rule that start date < end date < resolution date.

– I want to be able to validate at will all the rules of a domain model object (e.g student object) and see which fail. I want to do this in a service/controller. (e.g. validator.validate(student))

Let’s see what we can do with angular out of the box:
Suppose we have a simple form for entering data for a person name. Name is required and can have maximum length 512 characters.

We quickly write some code:

<form name=”personForm” novalidate=”" ng-app=”PersonApp” ng-controller=”PersonController” >
	<input name=”personName” type=”text” placeholder=”Person Name” ng-model=”viewModel.person.name” required ng-Maxlength=”3″/>
	<span ng-show=”personForm.personName.$invalid”>Person name is required and must be smaller than 3 characters</span>

What I don’t like about this code is that the length constant  “3” is defined in the UI. Then it is duplicated in two places and the error message is not localizable in its current form.

An easy fix would be to  define the constant ‘3’ in an angular module.constant, then refer to the constant in the controller and bind the UI to it instead of defining it in the UI. Also the error message should be defined in the controller using a localization mechanism.

Then we get to this requirement: “If I enter a screen, don’t modify any field and press submit, I want all my validation rules to be checked and mark the fields that have errors with error”

There’s no easy fix for this but Andy Norborg has written an excellent article on writing a directive that helps you accomplish that.

Initially I though about using that, but I would still have to figure a way on how to do these requirements:

– Some validation errors might not be related to an input field. E.g. you’re doing a student/courses app and you want to be able to select the courses for a student. There are some rules in what he can select (he cannot have certain courses as they are for year 2 and he is in year 1 for example). You’re also not using an input field to select the courses.

– Some validation errors are related to multiple input fields at the same time. E.g. you have a start date/end date/resolution date combo that have a rule that start date < end date < resolution date.

– I want to be able to validate at will all the rules of a domain model object (e.g student object) and see which fail. I want to do this in a service/controller. (e.g. validator.validate(student))”

Stop and think about it. How would you do that? I can see you struggling to break outside the form and out of ng-model. Ask yourself why should validation be strongly coupled to an ng-model and to a form? In the real world I don’t see any coupling between the two concepts. All I see are a set of validation rules which in many cases are used to to help validate form. That doesn’t mean it’s the only place you will ever need to use them. Well, sadly, the angular out of the box validation solution is saying to us that a form is the only place you will ever need to do any validation. Why it says that? I think because it fits >90% of validation usage patterns which are for fairly simple forms. Simplicity wins over flexibility which is not bad as long as you have an alternative for the more complex cases.

So back on how to solve this requirement. It can be done by writing a directive which would bind to a collection of validation rules defined in the controller and would execute those rules on input changes/submit. That’s what I did and by doing this, I bypassed the angular way of doing validation. (built in + custom validators). You know how it felt? Liberating! :) It feels good to be free! I want to give this freedom to you so here goes my suggested way of doing validation.

Validation should be based around business rules (validation rules). Those rules should be defined in a way they can be used/reused in any context (services/controller) (not just UI context).

Let’s write a validation rule that tells me if a a string has a length smaller then a maximum length.

(function (angular) {

        .factory('MaxLengthRule', function () {
            return function (maxLength, errorMessage) {
                this.errorCode = 'maxLength';
                this.validate = function (value) {
                    return {
                        result: (value !== undefined && value !== null) ? value.length <= maxLength : true,
                        errorMessage: _.str.sprintf(errorMessage, maxLength),


A validation rule is identified uniquely by an error code and it has a validate method that tells us if the rule is valid or not.
As you can see, we’re not returning a true/false value when validating the rule. The reason for this is that for a more complex validation rule the error message is not always the same. Imagine writing a validation rule to check if an arithmetical expression entered by the user is correct. So the user can enter: 1 + 1 * 2 (correct), 1 – – 1 (error: cannot have two minuses in a row), 1 * (2 – 1 * (3 + 5) (error: round bracket doesn’t close), etc.
If you just return a false message how will you know what error message to display? You could always display a generic: “calculation expression invalid” but it wouldn’t be too user friendly. That’s why I prefer to have a validation rule return a ValidationResult composed of a true/false result of validation and the error message of why the rule is invalid.

Next, one can group various validation rules in sets of validation rules. This proves useful when validating all the rules for a specific domain object field. For example we can define the set of rules that apply to the student name field. Let’s say they are [MaxLength(5), Required]. This represents a set of rules or RuleSet.

Now we just need a way to use those validation rules in the UI. What I mean by that is to mark fields with validation errors and show error messages. We need to do this whenever the value of a field changes or the user tries to submit (without changing any field) or some other custom scenarios.

To do this I wrote two directives. One is called validator.
It looks like this:

<input id="personName" ng-model="viewModel.person.name" validator="viewModel.validator" ruleSetName="personName" />

It can be placed on any field that supports ng-model and it will observe value changes and validation error changes. Whenever the value changes or a validation changed event is raised it will validate a RuleSet and mark the field with a has-error class if validation rules are failing. (basically makes the field red/borders red).
I didn’t want to couple the validation mechanism to the concept of “submitting” a form. That’s why there’s this concept of “validation changed” event which can be triggered manually by anything (e.g. a form submit) and it will cause the validator directive to re-validate the field on which it is placed.

Can you use this directive only on a field that has ng-model? If provided, ng-model controller will be used for detecting dirtiness, but it can easily be used without “ng-model” optional and then you just look at the validation changed event for more “exotic” types of input that don’t use ng-model. You can trigger the “validation changed” event manually yourself.

To show the validation error message I use another directive called validationMessageFor.
It looks like this:

<input id="personName" ng-model="viewModel.person.name" validator="viewModel.validator" ruleSetName="personName" />
<span validationMessageFor="personName" />

This directive can be placed on any element – a span for a example.
It will watch whenever the input it refers to changes or when a validation changed event is raised.
While I could’ve done some trick with the validator directive – make it inject a span next to the input field, I preferred to wrote another directive. This is because I wanted flexibility in showing an error messages in whatever way I want and anywhere on the page. E.g. I could do an errors area, if needed at the bottom of the page, some baloons with errors, etc.
Plus I can easily extend this directive to show errors for validation rules that are not specific to a single field or to any field if needed.

Now getting back to the validation solution you probably noticed that the validator directive is bound to a validator object.
This object keeps a collection of RuleSet. For example it can keep all the rule sets for a student object. As discussed, each RuleSet will contains the set of validation rules for a specific field (e.g. minlength, required).
In addition to this it has a few methods to validate all the rulesets and store the errors that resulted in an errors collection.
It also exposes a validation changed event that can be raised to notify observers (e.g. UI) that they need to re-validate the rules.

The code for the validator looks like this:

(function (angular) {

           .factory('Validator', function () {
               return function (validationRules) {

                   // this.validationRules example:
                   // {
                   //    contactTitleRules: [rules.isRequired(), rules.minLength(3)],
                   //    contactFirstNameRules: [rules.isRequired(), rules.minLength(3), rules.maxLength(7)],
                   // }
                   this.validationRules = validationRules;

                   // this.errors example:
                   //  {
                   //     ruleSetName1 : { errorCode1: true, errorCode2: false }
                   //     ruleSetName2 : { errorCode1: true, errorCode2: false }
                   //  }
                   this.errors = {};

                   this.validationChangedObservers = [];

                   this.triggerValidationChanged = function () {
                       for (var i = 0; i < this.validationChangedObservers.length; i++) {

                   this.watchValidationChanged = function(onValidationChanged) {

                   this.setHasError = function (ruleSetName, errorCode, isValid) {
                       if (!this.errors[ruleSetName]) {
                           this.errors[ruleSetName] = {};

                       this.errors[ruleSetName][errorCode] = !isValid;

                   this.validateRuleSet = function(ruleSetName, value) {
                       var rules = this.validationRules[ruleSetName];
                       for (var i = 0; i < rules.length; i++) {
                           var ruleIsValid = rules[i].validate(value).result;
                           this.setHasError(ruleSetName, rules[i].errorCode, ruleIsValid);

                   this.validateAllRules = function () {
                       for (var ruleSetName in this.validationRules) {

                   this.hasRuleSet = function(ruleSetName) {
                       return this.validationRules != undefined && this.validationRules[ruleSetName] != undefined;

                   this.ruleSetHasErrors = function(ruleSetName) {
                       var ruleSetErrors = this.errors[ruleSetName];
                       if (ruleSetErrors != undefined) {
                           for (var errorCode in ruleSetErrors) {
                               if (ruleSetErrors[errorCode] === true) {
                                   return true;

                       return false;

                   this.ruleSetHasError = function(ruleSetName, errorCode) {
                       var ruleSetErrors = this.errors[ruleSetName];
                       return ruleSetErrors != undefined ? this.errors[ruleSetName][errorCode] : false;

                   this.hasErrors = function () {
                       for (var ruleSetName in this.errors) {
                           if (this.ruleSetHasErrors(ruleSetName) === true) {
                               return true;

                       return false;

The only thing left is to construct the validator object in the controller.
For this I wrote a validation factory to help build the rule sets easier. (e.g. you don’t have to provide an error message every time you construct a MaxLength rule for example, as it can use a generic error message).

It looks like this:

    var rules = new ValidationRuleFactory(genericErrorMessages);
    $scope.viewModel.validationRules = {
      personFirstNameRules: [rules.isRequired(), rules.minLength(3)],
      personEmailRules: [rules.isRequired(), rules.minLength(3), rules.maxLength(7)],

You can see the entire solution in action in this Plnkr
While I really like this solution I must warn you that the code is probably not perfect. It’s probably not using the best practices of angular / javascript in some places as I’m fairly new to javascript/angular with just a few weeks of experience with them.

Feel free to comment with your thoughts or things that you see that need improvement.

Written by Liviu Trifoi

October 19, 2013 at 8:30 pm

Unknown build error, ‘An item with the same key has already been added.’

with one comment

I got this error today when trying to build a C# solution today.
In my case the error was caused by the fact that I had the same file added twice in the .csproj file. (This happened after a merge in the *.csproj file).
To find the exact file would have been very hard since there can be thousands of files in a *.csproj.
The first thing to do is to find the exact project which is causing the issue. Visual studio is using msbuild in the background to do the builds, but it’s outputing very little information from msbuild.
This can be controlled by going to Tools->Options->Projects and Solutions->Build and Run. Set MSBuild project output verbosity to Diagnostic.
Now do a build again. After it fails display the output window. Debug->Windows->Output. Select “Show output from” -> Build. Find the first “Build failed” text.
Now you know which project’s build failed.
Go to Build->Clean, then right click on the specific project that is causing the problem and select build. (Do not build entire solution).
If you do that instead of building the entire solution, you will sometimes get an error with the exact file which is causing the build problem.
If it still doesn’t show you the file, you will have to go through the csproj and find out which line is duplicate.
Now unload that project (right click -> unload). Right click the unloaded project -> edit. Now search for that file which is causing the build problem and ensure that it is only added once in the csproj.
E.g. if the file is called EquipmentDetailsTitleBarPopup.xaml, look for duplicates of

    <Page Include="Features\Equipments\EquipmentDetailsTitleBarPopup.xaml">

and remove one of them.
Now reload the project (right click -> reload) and build again.

This fixed it for me.

Written by Liviu Trifoi

January 18, 2013 at 1:35 pm

Posted in .NET, C#, Visual Studio 2010

Unable to determine the URL to the Xap file from web

leave a comment »

I encountered today this undocumented error: “Unable to determine the URL to the Xap file from web XXX”, after renaming one of my silverlight 4 projects, which was set to run Out of Browser.
Supposing you renamed your project from XXX to YYY.
To fix the error above, go to your YYY.csproj.user on the disk, and open it for editing with notepad.
Then change


Now save it, and you’re good to go.

Usually *.csproj.user files should not be under source control.
So if you rename a silverlight project which a colleague of yours has set it to be ran out of browser on his computer, then he will get this error unless you share the same *.csproj.user on the source control (which is not a good idea).

I think a visual studio 2010 improvement is needed here, that describes the situation better. Something like: “Unable to determine the URL to the Xap file from web XXX. If the project was renamed, please rename it inside your *.csproj.user” file settings as well”

Written by Liviu Trifoi

June 1, 2011 at 8:48 am

Visual Studio 2010 – No Source available: Browse To Find Source

leave a comment »

Seems there’s a lot of confusion about this “Browse to find source” feature of visual studio 2010.

I had a colleague which was convinced he didn’t need pdbs to debug an .net app, because of the “Browse to find source” :) Anyone else want to take a bet with me on that?
In this post I want to clarify when to use this “Browse to find source” feature since the mdsn doc is missing, and sometimes is grayed out for no (apparent) reason.

If you experiment a little with process monitor, you’ll see that every time visual studio displays the “Browse to find source” page, it looks inside the pdb file corresponding to the top stacktrace instruction your are trying to step into.

For example in the image below, it looks into the pdb of the DateTime.Now (which is mscorlib.pdb), since I’m trying to step into DateTime.Now:
pdb load info

But what is it looking for there?
Well, if the pdb file is for a private build, then it includes information on where to find the source file from which it was built.
And that’s what visual studio is searching for inside the pdb.

For example I built the following simple library consisting of just one class:

    public class Class1
        public static DateTime GetCurrentDateTime()
            return DateTime.Now;

Class1.cs was located at: d:\ClassLibrary\Class1.cs

If you build this program and then look inside the pdb file that was generated for the build, using dia2dump, you’ll see, among other things, the Files section:


Compiland = ClassLibrary.Class1


Suppose I reference the ClassLibrary1.dll which I built, in another simple console project called Console1 located at D:\Console1:

    class Program
        static void Main(string[] args)
            var currentDateTime = ClassLibrary1.Class1.GetCurrentDateTime();

If I build Console1I will have in D:\Console1\bin\debug a Console1.exe, Console1.pdb, and a ClassLibrary1.dll,
If I try to step into the ClassLibrary1.Class1.GetCurrentDateTime() above, the first thing visual studio will do, is look for the ClassLibrary1.pdb at: D:\Console1\bin\debug\ClassLibrary1.pdb, and then in a couple of other locations.

If it doesn’t find the pdb in any of those locations, then you’ll get a disabled (grayed out) “Browse to source”. Why? Because it’s impossible for the visual studio debugger to know which function goes into what class and at what line number having just an binary and the source code files from which it was built. You need to understand that if you just have an .net executable(or any other assembly) and its source code visual studio doesn’t magically know how to match the instructions from the exe with their corresponding functions/line numbers from source files. That’s what pdbs help do. They store this “mapping”.
You’ll would never be able to do do source code level stepping inside the debugger if you have the source files but don’t have the pdb.
So the first step you do if you get “No source code available” is right click on the top call-stack instruction, choose “Symbol Load Information” and be sure you have a “Symbols loaded” message somewhere there. If you don’t see any “Symbols loaded”, then you should try placing the pdb at one of the locations which is listed there.

Now if visual studio finds the pdb file it might still be possible, using our above example, that the file ” D:\ClassLibrary\Class1.cs” which it finds in the pdb, is no longer there.
You either moved it at a another location, say C:\ClassLibrary, or it was built by someone else on another machine at D:\ClassLibrary\Class1.cs and you don’t even have that directory on your computer.
In those cases you get a nice browse to source file dialog:

If you cancel this accidentally (or intentionally) you will get a “Browse to source” enabled:

Why? Well because the pdb is OK, and contains source line information, just that the source files path inside pdb, are not at the right location and since you canceled “browse to source file”, visual studio has no idea where to look for the source files.
One more thing to look out for is that not all pdbs have source line number information: see for example this. Those are pdb’s which you cannot use for stepping into source code, since they don’t contain the necessary information.
In those cases, you’ll also get a grayed out “Browse to source”.
In that case, we’re out of luck my friend and the only available solution is to use Reflector Pro’s ability to debug and step into those assemblies from visual studio at runtime :(

Written by Liviu Trifoi

May 19, 2011 at 8:14 pm

Silverlight IsolatedStorageFile.IncreaseQuotaTo

leave a comment »

I had a lot of troubles using IsolatedStorageFile.IncreaseQuotaTo

Msdn documentation for IsolatedStorageFile.IncreaseQuotaTo states that:
To increase the quota, you must call this method from a user-initiated event, such as in an event handler for a button-click event. When you call the IncreaseQuotaTo method, the common language runtime in Silverlight presents a dialog box for the user to approve the request. If the user declines the request, this method returns false and the quota remains the same size.

Now that seems like half-baked documentation to me since it doesn’t accurately describe what a user-initiated event is, it only gives one example.
After much digging, I did find out what a user initiated event is. Seems that the msdn documentation specifies what a user initiated event in the section related to “events overview“, but there’s no link between documentation of IsolatedStorageFile.IncreaseQuotaTo and Events Overview.
So here goes the definition:

Silverlight user-initiated events include the mouse events (such as MouseLeftButtonDown), and the keyboard events (such as KeyDown). Events of controls that are based on such events (such as Click) are also considered user-initiated.

API calls that require user initiation should be called as soon as possible in an event handler. This is because the Silverlight user initiation concept also requires that the calls occur within a certain time window after the event occurrence. In Silverlight 4, this time window is approximately one second.

User-initiated event restrictions also apply to usages of JavaScript API for Silverlight.

When Silverlight is in full-screen mode, some input events are deliberately limited for security reasons, although this can be mitigated for out-of-browser applications using elevated trust. For more information, see Full-Screen Support.

At first these limitations seemed draconian to me.
Thinking it more about it, I guess Microsoft didn’t want a user to have many tabs open in a browser and then poof: I call automatically IncreaseQuotaTo.
Since the IncreaseQuotaTo is a modal dialog, meaning you can’t navigate to other tabs from it, if the user is now on page google.com, and I show automatically IncreaseQuotaTo, the user might think that google.com is asking for more storage :)). This would be a security breach indeed.

Had they implemented this with a page level dialog, then that would have probably been more easily hacked (worked around). I can already start imagining drawing some evil forged “Silverlight needs to be updated” image over the IncreaseQuotaTo text, hence tricking the user in pressing Yes . Or maybe some other evil scenario.

I was curios though how exactly does silverlight know what a user initiated event is, but after digging through .net framework source code I’ve got to a dead end:

if ((browserService == null) || !browserService.InPrivateMode())
return false; //means that IncreaseQuota will fail
where browser.IsInPrivateMode is:

public bool InPrivateMode()
    bool privateMode = false;
    return (NativeMethods.SUCCEEDED(UnsafeNativeMethods.DOM_InPrivateMode(this._browserServiceHandle, out privateMode)) && privateMode);

where DOM_InPrivateMode is in a DllImport[“agcore”], which according to microsoft is confidential :(
So it looks like I won’t find out soon how they’re detecting user initiated events, although I’m guessing they have some centralized private method that detects clicks for example, and then probably sets a flag that this was indeed “a user initiated event”, and since you can’t forge clicks or keypresses using javascript and since you can’t call those private methods using reflection, it’s “safe”.

Written by Liviu Trifoi

May 18, 2011 at 6:33 pm

Posted in .NET, C#, Silverlight

Tagged with , , ,

Debugging .Net Framework source stepping problems using dia2dump

with 2 comments

So you are trying to step into .net framework source code.
You configured debugging options, triple-checked everything, consulted this comprehensive FAQ here: http://blogs.msdn.com/b/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx.
Still nothing seems to work.

You are not alone :(
The most likely cause is that Microsoft has released some patches to the .net framework, and didn’t publish pdbs that you could use for stepping into .net framework source code.
So supposing that you are trying to debug DateTime.Now.
First look on where the pdb-file downloaded from Microsoft Symbol Server is located on your computer, by right clicking in the Call-Stack -> Symbol Load Information:

Now we’ll look inside this pdb file using dia2dump which is a tool that comes with visual studio at: c:\Program Files (x86)\Microsoft Visual Studio 10.0\DIA SDK\Samples\DIA2Dump\

It’s not compiled by default, so you’ll have to open it’s sln and compile it. Fortunately it’s just a small C++ proj, and compiles easily. (Just press compile).
After compiling you should see it at c:\Program Files (x86)\Microsoft Visual Studio 10.0\DIA SDK\Samples\DIA2Dump\Debug\.
To look inside a pdb file you just open a command prompt and write: dia2dump.exe xxx.pdb >xxx.txt . This will write the contents of the pdb inside a xxx.txt.

So if we run dia2dump on the mscorlib.pdb file which was downloaded we can see that it doesn’t contain any source files information or start /end addresses like the mscorlib.pdb you get from: http://referencesource.microsoft.com/netframework.aspx and it’s ~300 KB vs 10 MB.
Now I’m no pdb file contents expert, since the format of the pdb keeps changing and there’s no public specification according to microsoft (you can read more about it here: http://msdn.microsoft.com/en-us/library/x93ctkx8%28v=VS.80%29.aspx)
But the fact that there’s no addresses and source code mappings does ring a bell to me that the pdb is not one that we could use for .net framework source code stepping purposes.

So how do we make it work?
My first idea was of using that “Browse to source” option in visual studio 2010, and browse to .net framework source code you have downloaded manually from referencesource.microsoft.com. But after looking at the information inside the pdb, or rather the lack of it, it’s now clear why it’s always grayed out.

So one solution is to use Reflector Pro, which is commercial, and use it’s runtime debugging feature to step into microsoft .net framework source code.
This is not an ideal solution (especially because of the optimized code), and I just don’t understand why Microsoft doesn’t publish automatically source code according to their latest hotfixes/patches of the .net framework :(
I mean, I need to step into .net framework because I’m having problems today, not in two months when they decide to actually publish it. What am I supposed to do? Disable windows update so I don’t install any hotfixes? :(
This might be a second solution: Just have a virtual machine with visual studio installed, and a .net framework version which has .net framework source stepping support. Then disable any updates on that virtual machine and do your debugging there. (Really painfull, I know)

Written by Liviu Trifoi

May 17, 2011 at 8:06 pm


Get every new post delivered to your Inbox.