Category Archives: .Net

Logging CSP violations to Exceptionless with NWebsec

Logging CSP violations to Exceptionless with NWebsec

Anyone that creates web applications should use Content-Security-Policy (CSP) to protect their applications against injection attacks by specifying where content in the web pages can be loaded from.

If you’re unfamiliar with CSP you should read An Introduction to Content Security Policy by Mike West, one of the Chrome developers. You’ll also find information about CSP on the Mozilla Developer Network.

In this article we will look into how simple it is to log CSP Violations in order to find the correct settings for your application using NWebsec and Exceptionless.

NWebsec is a very nice security library by Andre Klingsheim that allows you to handle configuration of CSP in web.config or in code. Exceptionless is a real-time error, feature and log reporting for all kinds of applications and can either be hosted on-site og use the SAAS provisioning by Exceptionless.

Source code is available at

I start out by creating a new ASP.NET MVC project and add the following NuGet packages:

– NWebsec.Mvc
– Exceptionless.Mvc

Assuming you may already have your own webapplication already running, we will use the Content-Security-Policy-Report-Only to report CSP violiatins without actually making the browser enforce the CSP. When your baseline is set it is just a matter og changing the name in config to Content-Security-Policy and the browsers will now starte to
enforce the policies.

You may use both Content-Security-Policy and Content-Security-Police-Report-Only in parallel but only Content-Security-Policy will make the browsers enforce policies.

Note: Each violation in the users browser will be logged as a separate call back to your website (report-url).

Configure NWebsec

by adding this configuration section in web.config to confiure Content-Security-Policy-Report-Only.
Note that the configuration also sets the report-uri option to enable the builtin handler.

<securityHttpHeaders><content-Security-Policy-Report-Only enabled="true">
<default-src self="true"/>
<script-src self="true">
<add source="" />
<add source="" />
<style-src unsafeInline="false" self="true" />
<img-src self="true">
<add source=""/>
<object-src none="true" />
<media-src none="true" />
<frame-src none="true" />
<font-src none="true" />
<connect-src none="true" />
<frame-ancestors none="true" />
<report-uri enableBuiltinHandler="true"/>

Configure Exceptionless

If you do not have an account on Exceptionless already head on to Exceptionless and create a free account and add a “Project”.

Follow the instructions and select your project type (ASP.NET MVC) and make sure to update the
the exceptionless apiKey=”API_KEY_HERE” section located in the project’s web.config with your Exceptionless API key.

Add logging to Exceptionless

So we now have the CSP configred along with Exceptionless and a corresponding “project” in Exceptionless.
To round up the logging part in code we need to add this in Global.asax.cs:

protected void NWebsecHttpHeaderSecurityModule_CspViolationReported(object sender, CspViolationReportEventArgs e)
var report = e.ViolationReport;
var directive = report.Details.ViolatedDirective.Split(' ').FirstOrDefault();

$"Violation:{report.Details.BlockedUri}", Exceptionless.Logging.LogLevel.Warn)

Run you application and open Exceptinless in a new tab , login and view the “Log messages” folder.
Exceptionless Log Messages

and when you use the detailed view you get the entire post details:
Exceptionless log detail view

Now we can start working on adding the necessary configurations in the config, rerun the application and then verify that the violations are gone. This is a great learning experience into what is beeing used in your application as well as a very efficient security practice to avoid f.ex spyware/adware in the users browser from injection content into your application on the client side.

For this sample MVC app the required configuration is:

<content-Security-Policy-Report-Only enabled="true">
<default-src none="true"/>
<script-src self="true">
<add source=""/>
<add source=""/>
<add source=""/>
<style-src unsafeInline="true" self="true" />
<img-src self="true"/>
<object-src none="true" />
<media-src none="true" />
<frame-src none="true" />
<font-src self="true" />
<form-action self="true"/>
<connect-src self="true" />
<frame-ancestors none="true" />
<report-uri enableBuiltinHandler="true"/>

This post has a good intro to CSP and MVC:
An introduction to Content Security Policy – Mike West

You may still see a violation from the Visual Studio Browser Link as this uses an arbitrary port number in development.

I hope this inspired you to start using Exceptionless for logging purposes. We use it when introducing CSP and setting the baseline for our web application and found it very useful. After the baseline was set we also get to see how much adware/spyware there is out there.

There is a lot more that you can use Nwebsec to strengthen the security of your website so if you are not using this already I recommend to take a deeper look into this library.

Reference links:

– Exceptionless
– NWebsec docs – Configuring CSP
NWebsec Demo
An introduction to Content Security Policy – Mike West
CSP – Mozilla Developer Network
– Content Security Policy (CSP) for ASP.NET MVC – Muhammad Rehan Saeed

Unit Test CSLA 4 BusinessRules

Unit tests in CSLA 4 is now classes and most developers want to create unit tests to verify the correct behavior and result.
In this article I will show you a suggested way to create these tests.

Basic rule knowledge

Let’s start with how rules is registered in CSLA:

  1. <bo>.AddBusinessRules is only called once and register ALL rules for that object type.
  2. A rule instance should be viewed as a Singelton or Shared object. You cannot store any value elated to the execution (data values) in member variables.

The execution of the rule follow these steps:

  1. The RuleEngine will create an instance of a RuleContext with the actual rule
  2. and if InputProperties have entries copy values from BO to <context>.InputPropertyValues
  3. set <context>.Target property to the <bo> instance (with exception if IsAsync = true and ProvideTargetWhenAsync = false).
  4. call the <rule>.Execute method with <context> as parameter.
  5. When rule has completed call a CompleteHandler for both synchronous and async rules.

The rule engine will call the completed handler automatically for syncronous rules but for async rules your code is responsible for calling <context>.Complete in ALL execution paths.
The <rule>.Execute method is always called inline and when IsAsync = true the assumption is that your code in Execute will do an asyncronous call an in order to notify the rule engine when the rule is completed your code must call <rule>.Complete.

Then take a look at the <rule>.Execute method.

A: Your rule does NOT use <context>.Target and has no relationship to the actual BO.
These rules only interact with the RuleContext and use <context>.InputPropertyValues for input values and may call <context>.AddOutValue or context.AddXYZResult.

The output from these rules is in

  • <context>.Results
  • <context>.OuputPropertyValues

B: Your uses uses <context>.Target and the support methods in BusinessRule base class for ReadProperty or LoadProperty.
These rules interact with the BO and uses methods in BusinessRule base class that expects an actual CSLA BO to be present (implements Csla.Core.IManageProperties).

The output of a rule can be

The output from these rules is in

  • <context>.Results
  • <context>.OuputPropertyValues
  • directly updated properties in the context.Target or child object from calling <rule>.LoadProperty

RuleContext support for result

context.Results is a list of RuleResult that yon can add test for. <context>.AddXYZResult will all add a RuleResult to context.Results.
context.OutputPropertyValues is a dictionary of IPropertyInfo and values to be set in the bo.

So we should be able to create unit tests for both

  • synchreonous rules and async rules
  • rules that only interacts with the rule context.
  • rules that interacts with the context.Target

Support methods in CSLA

RuleContext has a constructor specifically designed for use in unit tests:

public RuleContext(Action<RuleContext> completeHandler, IBusinessRule rule, object target, Dictionary<Csla.Core.IPropertyInfo, object> inputPropertyValues)

that allows the test code to specify the

  • completeHandler for callback when rule has completed.
  • the actual business ruleyou want to test
  • the target object (may be null if your rule does not use the context.Target)
  • a dictionary of input property values

Support class BusinessRuleTest.cs in RuleTutorial samples download

adds more support for tests and will allow you to write the exact same test code whether the rule is syncronous or not.
This is done by adding a CompleteEeventHandler that will wait for up to 3 seconds on an async rule before calling <context>.Complete.

public void InitializeTest(IBusinessRule rule, object target)
public void ExecuteRule()
public void ExecuteRule(Dictionary<IPropertyInfo, object> inputPropertyValues)
public T GetOutputPropertyValue<T>(PropertyInfo<T> propertyInfo)

The ExeuteRule method will copy values from target object to input property values and then call rule.Execute
The ExecuteRule with InputPropertyValues dictionary will just set thes into the context and call rule.Execute.

Then to the unit tests

My proposed solution for creating unit tests uses the constructor in RuleContext, the BusinessRuleTest base class and creating fake business objects for the tests.

I like the testing approach from Phil Haack and Brad Wilson so these sample tests use a separate class for each method.
Read more here:

Testing a ToUpper transformation rule that makes sure a property is always uppercase.

This rule only interacts with the <context>.InputPropertyValues and <context>.OuputPropertyValues

My fake root object:

  public class RootFake : BusinessBase<RootFake>
    public static readonly PropertyInfo<int> CustomerIdProperty = RegisterProperty<int>(c => c.CustomerId);
    public int CustomerId
      get { return GetProperty(CustomerIdProperty); }
      set { SetProperty(CustomerIdProperty, value); }

    public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(c => c.Name);
    public string Name
      get { return GetProperty(NameProperty); }
      set { SetProperty(NameProperty, value); }

The the test class for constructor:

    public class TheCtor
      private IBusinessRule Rule;
      public void InitTests()
        Rule = new ToUpper(RootFake.NameProperty);

      public void IsSync()

      public void HasPrimaryProperty()
        Assert.AreEqual(RootFake.NameProperty, Rule.PrimaryProperty);

      public void HasInputProperties()

      public void HasAffectedProperties()

Then testing the Execute method with supplied InputPropertyValues:

    public class TheExecuteMethod : BusinessRuleTest
      public void InitTests()
        var rule = new ToUpper(RootFake.NameProperty);
        InitializeTest(rule, null);

      public void MustSetOutputPropertyToUpper()
        var expected = "CSLA ROCKS";
        ExecuteRule(new Dictionary<IPropertyInfo, object>() {{RootFake.NameProperty, "csla rocks"}});
        Assert.IsTrue(GetOutputPropertyValue(RootFake.NameProperty) == expected);

Then testing the Execute method with a fake object to supply the property value:

    public class TheExecuteMethodAlt : BusinessRuleTest
      public void InitTests()
        var rule = new ToUpper(RootFake.NameProperty);
        var root = new RootFake();
        root.Name = "csla rocks";
        InitializeTest(rule, root);

      public void MustSetOutputPropertyToUpper()
        var expected = "CSLA ROCKS";
        Assert.IsTrue(GetOutputPropertyValue(RootFake.NameProperty) == expected);


I hope this gave you a better understanding of how Business Rules work and what to test.

You will find more unit test samples in the Net\cs\RuleTutorial sample available at and if you have questions please post on the CSLA,NET Forum at

CSLA 4.2 Rules update

The CSLA rule engine had a major change when moving from 3.8.x to 4.0. The major change being that rules is now classes and inheritable whereas the earlier rules were static methods.

For the upcoming CSLA 4.2 release we have made a number of bug fixes plus added some new features that you should be aware of.

1. InputProperties is now also considered Dependencies just as AffectedProperties.

Take for example the validation of StartDate and EndDate where StartDate must be before EndDate.

In CSLA 4.0/4.1 you would have to add:

 1: BusinessRules.AddRule(new LessThan(StartDateProperty, EndDateProperty));
 2: BusinessRules.AddRule(new Dependency(EndDateProperty, StartDateProperty));
 4: BusinessRules.AddRule(new GreaterThan(EndDateProperty, StartDateProperty));
 5: BusinessRules.AddRule(new Dependency(StartDateProperty, EndDateProperty));

In order to make the validation rules execute as expected, ie,  StartDateProperty must be validated when StartDate is changed or EndDate is changed (Dependency) and EndDate vice versa.
It’s very easy to miss the dependencies so in CSLA 4.2 you will only need:

 1:  BusinessRules.AddRule(new LessThan(StartDateProperty, EndDateProperty));
 2:  BusinessRules.AddRule(new GreaterThan(EndDateProperty, StartDateProperty));

And both rules will be executed when either of the property values is changed.

Having Dependency rules will NOT break your code so the code sample with Dependency rules will run exactly the same way as the last sample.

2. Provide overloads to set your own message text

When you register a rule you may now also specify either a constant message string (MessageText) or a lambda expression (MessageDelegate) to fetch a string from a resource file.
Using the lambda version you can support translation/localization of the message.

NOTE: The formatting function is supported in just the same way as the default messages.

Using a constant string:

 1:       BusinessRules.AddRule(new Required(NameProperty){MessageText = "Customer must have name"});
 2:       BusinessRules.AddRule(new MaxLength(NameProperty, 50){Priority = 1, MessageText = "{0} cannot be longer than {1} chars"});
 3:       BusinessRules.AddRule(new MinValue<int>(Num1Property, 5) { MessageText = "Num1 must be larger than or equal to {1}" });

Using a lambda to support localization:

 1:       BusinessRules.AddRule(new Required(NameProperty){MessageDelegate = () => Resources.NameRequired});
 2:       BusinessRules.AddRule(new MaxLength(NameProperty, 50){Priority = 1, MessageDelegate = () => Resources.NameMaxLength});
 3:       BusinessRules.AddRule(new MinValue<int>(Num1Property, 5) { MessageDelegate = () => Resources.Num1MinValue });

This properties/delegate is implemented in the base classes, your own rules must make sure to override the GetMessage method to provide the default (and preferably) localizable message text.

 1:     protected override string GetMessage()
 2:     {
 3:       return HasMessageDelegate ? base.GetMessage() : Resources.AnyRequiredRule;
 4:     }

3. Rules for affected properties on an Async rule is automatically rerun and UI notified when context.Complete is called.

This was missing pre 4.2 so when an async rule would lookup information in a database and set a number of
properties in the <bo> the rules for those properties were not rechecked. This would cause the field content
and error/warn/info messages to get out of sync.

4. Rules can now specify conditions for when the rule is not allowed to run.

Typical usage is for any rule that you will only allow to run when the user edits a value and f.ex do an async lookup to a database.
By default and to not brake any existing code, rules will run without restrictions.

Flag Property rule Object rule
CanRunInCheckRules         Yes           Yes
CanRunAsAffectedProperty         Yes           No
CanRunOnServer         Yes           No

Object level rules is executed when either <bo>.CheckObjectRules() or <bo>.CheckRules() is called.

PropertyRules is executed when either <bo>.PropertyHasChanged(property) or <bo>.CheckRules() is called.
And PropertyHasChanged is implicitly called when SetProperty changes a value so most developers will never call PropertyHasChanged.

CanRunInCheckRules when false means that the rule will not be executed when <bo>.CheckRules() is called.

CanRunAsAffectedProperty when false means that this property rule will not run when this property is an affected property on another property rule.

CanRunOnServer when false means that this property rule will not run on the “logical” server side, by all practical means in Data Access Layer.
So when CheckRules is called from Data Access do not execute this rule when set to false.

5. New rule base classes

Two new base classes is introduced:

Class name Description
ObjectRule For an object level rule. Will always have PrimaryProperty = null.
PropertyRule For a property level rule. Must always have a PrimaryProperty.


All Property validation rules shipped in CommonRules have this inheritance hierarchy:

– PropertyRule
– CommonBusinessRule
– Actual Rule

So if your own rules inherit from CommonBusinessRule then you will automatically inherit from PropertyRule.

To make this easier for your developers consider adding your own base classes like:

 1:   public abstract class SyncLookupRule : CommonBusinessRule
 2:   {
 3:     protected SyncLookupRule(IPropertyInfo primaryProperty) : base(primaryProperty)
 4:     {
 5:       IsAsync = false;
 6:       CanRunAsAffectedProperty = false;
 7:       CanRunInCheckRules = false;
 8:       CanRunOnServer = false;
 9:     }
 10:   }


 1:   public abstract class AsyncLookupRule : CommonBusinessRule
 2:   {
 3:     protected AsyncLookupRule(IPropertyInfo primaryProperty) : base(primaryProperty)
 4:     {
 5:       IsAsync = true;
 6:       CanRunAsAffectedProperty = false;
 7:       CanRunInCheckRules = false;
 8:       CanRunOnServer = false;
 9:     }

for Sync and Async lookup rules that will only run when a property is changed by user or code.

Identify patterns and stereotypes of rules in your app and create more base classes. You can share them with us on the CslaContrib site

6. Both Object and Property rules can set Error/Warning/Info on other properties, and even co-exist.

This feature would seem possible with Csla 4.0/4.1 but never worked properly. These issues are now fixed and will even allow a
property level rule to set error/warning/info message on other properties than the Primary property.

This AnyRequired rule will make sure that at least one of the fields must have a value and if broken sets ErrorMessage on all fields:

 1:   public class AnyRequired : CommonBusinessRule
 2:   {
 3:     public AnyRequired(IPropertyInfo primaryProperty, params IPropertyInfo[] additionalProperties)
 4:       : base(primaryProperty)
 5:     {
 6:       InputProperties = new List<IPropertyInfo>() {primaryProperty};
 7:       InputProperties.AddRange(additionalProperties);
 8:     }
 10:     protected override string GetMessage()
 11:     {
 12:       return HasMessageDelegate ? base.GetMessage() : Resources.AnyRequiredRule;
 13:     }
 15:     protected override void Execute(RuleContext context)
 16:     {
 17:       // if all values are Null or Empty
 18:       if (context.InputPropertyValues.Select(keyvalue => keyvalue.Value.ToString().Trim()).All(string.IsNullOrEmpty))
 19:       {
 20:         var fieldNames = string.Join(", ", context.InputPropertyValues.Select(p =>p.Key.FriendlyName));
 22:         foreach (var field in context.InputPropertyValues)
 23:         {
 24:           context.Results.Add(new RuleResult(this.RuleName, field.Key, string.Format(GetMessage(), fieldNames)) { Severity = this.Severity });
 25:         }
 26:       }
 27:     }
 28:   }

 1:     BusinessRules.AddRule(new AnyRequired(NameProperty, Name2Property, Name3Property));


This post gives a brief introduction to the enhancements that is made in the Rule engine for Csla 4.2.

Stay tuned for more updates. My next posts will dive into different types of rules and how to implement these.
All code I use here can be found the RuleTutorial sample that will be in the Samples download.
At time of publishing this sample is not included in the Csla 4.2 Alfa release so you must get latest version from trunk to get the code.