Skip to content
/

I would like to introduce to you Winvision’s first open source project: Sandboxable.

Sandboxable enables your project to utilize functionality provided by other (Microsoft) libraries that normally are not available in a Partial Trust environment like the Microsoft Dynamics CRM sandbox process.
The project offers modified NuGet packages that will run with Partial Trust.

I would like to introduce to you Winvision’s first open-source project: Sandboxable.

Sandboxable enables your project to utilize functionality provided by other (Microsoft) libraries that normally are not able to use in a Partial Trust environment like the Microsoft Dynamics CRM sandbox process.
The project offers modified NuGet packages that will run with Partial Trust.

Sandboxing

Sandboxing is the practice of running code in a restricted security environment, which limits the access permissions granted to the code. For example, if you have a managed library from a source you do not trust, you should not run it as fully trusted. Instead, you should place the code in a sandbox that limits its permissions to those that you expect it to need.

You can read more on this in the article How to: Run Partially Trusted Code in a Sandbox
If you encounter a .NET sandbox today chances are it’s running with Security-Transparent Code, Level 2

A big example of software running in a sandbox are the Microsoft Dynamics CRM (Online) Plug-ins and custom workflow activities. (Plug-in Trusts)

The problem

As developers we use a lot of library code like NuGet packages as we are not trying to reinvent the wheel. The downside is that most of these libraries are not written with a Partial Trust environment in mind.
When we embed these libraries to our code in the sandbox, we encounter two common issues:

  1. The code contains security critical code and will fail to load with a TypeLoadException or will throw an SecurityException at runtime
  2. The package references another package that contains security critical code and even though the code might not even be used it will trigger one of the exceptions mentioned above

Problematic constructs

Calling native code
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CryptDestroyHash(IntPtr hashHandle);
Override SecurityCritical properties of an object like Exception
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
     ... 
}

Where Exception has the following attributes on this method

[System.Security.SecurityCritical]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
     ...
}
Serialize non-public classes, fields or properties
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, PropertyName = PropertyNotBefore, Required = Required.Default)]
private long? _notBeforeUnixTime { get; set; }

The solution

When we encounter a NuGet package that fails to load or execute in the sandbox and its source is available we make a Sandboxable copy of it.

This is done by eliminating the offending code in a way that is the least obtrusive and publish this version to NuGet.

The base rules are:

  • Keep the code changes as small as possible
  • Prefix all namespaces with Sandboxable
  • Eliminate offending NuGet dependencies
  • If a new dependency is needed, it will be on a sandbox friendly NuGet package

Source and contribution

The source is published at the Sandboxable project at GitHub.

Included in the solution is also a stand-alone project to test if code will break inside a sandbox. This makes testing libraries easier without the need to deploy it to a (remote) environment.

I like to invite everybody to use the Sandboxable NuGet packages and contribute to the project.

/

This week I’ll be attending the Microsoft Build 2016 conference in San Francisco.
Lots of news to be expected for developers covering the many technologies Microsoft is putting on the market.

This week I will be attending the Microsoft Build 2016 conference in San Francisco.

Lots of news to be expected for developers covering the many technologies Microsoft is putting on the market.

read more...
/

Recently I got certified by Microsoft as Solutions Developer for the Windows Universal Platform by taking two exams that are currently in beta. Because the exams are in beta there is not much guidance to be found online. I noticed during the exams I was being tested on skills not mentioned on the Microsoft Learning web site.

In this post I’ll cover these differences and how I prepared for the exams so it’ll be easier for you to get certified.

MCSD Universal Windows Platform

Recently I got certified by Microsoft as Solutions Developer for the Windows Universal Platform by taking two exams that are currently in beta. Because the exams are in beta there is not much guidance to be found online. I noticed during the exams I was being tested on skills not mentioned on the Microsoft Learning web site.

In this article I will cover these differences and how I prepared for the exams so it will be easier for you to get certified.

read more...
Filed under C#, Windows
Last update:
/

This is the second part in a series of posts about reducing the amount of data transferred between ASP.NET Web API or Azure Mobile App Service and the (mobile) client.
In this post we will squeeze a little bit more from our DTOs (Data Transfer Objects).

This is the second part in a series of posts about reducing the amount of data transferred between ASP.NET Web API or Azure Mobile App Service and the (mobile) client.

We will continue where we left off in Part 1: Default Value Handling.

In the first post we managed a reduction of 41%.

Of course, the reduction depends heavily on how often default values are part of your transferred data. But it’s an easy diet on transferred data that the other side can reconstruct on itself.
In this post we will squeeze a little bit more from our DTOs (Data Transfer Objects).

Part 2: Skip empty collections

First, we look at the response we got from the second controller:

[
    {
        "SomeUri": "http://reducejsontraffic.azurewebsites.net/api/",
        "TheDate": "2015-11-05T17:30:02.3206122+00:00",
        "AFixedDate": "2015-07-02T13:14:00+00:00",
        "SomeEmptyObjects": [],
        "SomeObjects": [
            { "ADouble": 0 },
            {},
            { "ADouble": 1.23456789 }
        ]
    },
    ...
]

(formatted for readability)

We see that the property SomeEmptyObjects is present in the message, despite being an empty collection. So, this is the next target for elimination.

Removing the empty collection

The reason the collection is present in the message is because a value of null is of course different than an empty array. But this post is about eliminating data on transport so we start with removing empty collections from our messages.

I was not the first one with this question, and at StackOverflow I found an answer by Discord. The post contains a custom contract resolver that deals with this situation.

public class SkipEmptyCollectionsContractResolver : DefaultContractResolver
{
  protected override JsonProperty CreateProperty(MemberInfo member,
                                            MemberSerialization memberSerialization)
  {
    var property = base.CreateProperty(member, memberSerialization);


    var isDefaultValueIgnored = ((property.DefaultValueHandling ??
                   DefaultValueHandling.Ignore) & DefaultValueHandling.Ignore) != 0;
    if (!isDefaultValueIgnored
                   || typeof (string).IsAssignableFrom(property.PropertyType)
                   || !typeof (IEnumerable).IsAssignableFrom(property.PropertyType))
    {
      return property;
    }

    Predicat<object> newShouldSerialize = obj =>
    {
      var collection = property.ValueProvider.GetValue(obj) as ICollection;
      return collection == null || collection.Count != 0;
    };

    var oldShouldSerialize = property.ShouldSerialize;
    property.ShouldSerialize = oldShouldSerialize != null
                               ? o => oldShouldSerialize(o) && newShouldSerialize(o)
                               : newShouldSerialize;

    return property;
  }
}

I created a third controller with the custom ContractResolver. This controller demonstrates this new behavior.

A GET request to http://reducejsontraffic.azurewebsites.net/api/skipemptycollection returns:

[
    {
        "SomeUri": "http://reducejsontraffic.azurewebsites.net/api/",
        "TheDate": "2015-11-10T16:35:32.3507203+00:00",
        "AFixedDate": "2015-07-02T13:14:00+00:00",
        "SomeObjects": [
            {
                "ADouble": 0
            },
            {},
            {
                "ADouble": 1.23456789
            }
        ]
    },
    ...
]

(formatted for readability)
Removing the empty collection removes another 6% from our transferred data. Bringing the total reduction of this example to 47%.

As I wrote before: there is a difference between a value of null and an empty array. The trade-off is that by removing the information from the DTO the client doesn’t know if there was an empty collection or nothing at all. If this is fine for your code you’re done for now.

Reviving empty collections on the receiving side

In the previous blog post I used the DefaultAttribute to declare these defaults on simple types:

[csharp][DefaultValue(14)]
public int Fourteen { get; set; }

When the client uses the Populate (or IgnoreAndPopulate) as DefaultValueHandling the property Fourteen will get the value of 14 then it’s not present in the data.

This also works for the AStringArray property which is an array of String.

[DefaultValue(new string[] {})]
public string[] AStringArray { get; set; }

However, for the arrays that contain objects you can’t declare this as a default. When you try:

[DefaultValue(new SomeObject[] { })]
public SomeObject[] SomeEmptyObjects { get; set; }

This will give the following error:

CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

We will have to find another way to declare the default value.

Initialize collections in the constructor

My own preferred way to initialize collections on a POCO is by setting the collection in the constructor.

public Message()
{
    SomeObjects = new SomeObject[0];
    SomeEmptyObjects = new SomeObject[0];
}

This will make sure we always have an empty collection. And if there is data in the message the Serializer will create a filled collection.
There is a caveat though. When there is no data in message and we have a set the DefaultValueHandling to Populate the empty collection is overwritten with a value of null. Therefore, we need to override the DefaultValueHandling for collection properties.

[JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)]
public SomeObject[] SomeEmptyObjects { get; set; }

To test this, we launch the demo client app again.
When we look at the watch in the debugger, we see again that all the properties that are not present in the transferred data are populated with either null or their correct default value.

Visual Studio Watch showing a deserialized object with default value handling

Conclusion

In this example we managed to get a total reduction of 47% and still have all the data available in the client.

Of course, the reduction still depends heavily on how often default values and empty collections are part of your transferred data. But the diet continues.

Source code

You can download the updated Reduce Json Traffic sample projecton GitHub.

You can also go to the specific commit to see the exact changes.

Filed under C#
Last update:
/

Not long ago I wrote a blog post about Responsive Pivot Headers in Universal Windows Platform apps. Paul responded to this post asking how to change the background of the selected item, just like the example I posted on top of the post.
It’s a great question and I’m sorry I didn’t cover this part so the pivot looks more like the example image.
An omission I want to correct with this blog post.

Not long ago I wrote a blog post about Responsive Pivot Headers in Universal Windows Platform apps. Paul responded asking how to change the background of the selected item, just like the example I posted on top of the article.

It is a great question and I am sorry I didn't cover this so the pivot looks more like the example.

An omission I want to correct with this article.

The example

So, to brush up on the first post, here is the example again:

Example design from pivot guidelines by Microsoft

The solution

There are only 3 small changes to make to get the pivot more like the example.

  1. Add a dark background to the pivot header
  2. Change the color of the pivot header content to light so we can read it
  3. Add a lighter background to the selected pivot header

Adding the background

There is not really an element to set the background of the whole pivot header, so we have to add one.
In the Pivot Template we have created in the first post we add a Border to the Grid of the PivotPanel.
It gets the darker color and has to span the 3 columns.

<PivotPanel x:Name="Panel" VerticalAlignment="Stretch">
<Grid x:Name="PivotLayoutElement">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
       ...
    </Grid.RowDefinitions>
    <Grid.RenderTransform>
        ...
    </Grid.RenderTransform>
    <Border Background="#FF34323F" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
    <ContentPresenter x:Name="LeftHeaderPresenter" ... />

Lighten up the foreground

Then we go the PivotHeaderItem style we also created before.
Here we add a setter so we can change the RequestedTheme to Dark.

<Pivot>
    <Pivot.Resources>
        <Style TargetType="PivotHeaderItem">
            ...
            <Setter Property="RequestedTheme" Value="Dark" />
                <Setter Property="Template">

Adding the highlighted background

Now we go to the Visual State named "Selected".
Here we change the Background color to the lighter color.

<VisualState x:Name="Selected">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground" >
            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAltBaseHighBrush}" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Grid" Storyboard.TargetProperty="Background" >
            <DiscreteObjectKeyFrame KeyTime="0" Value="#FF42424C" />
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>

And that is it!

It is not an exact replica, but you can change all the colors and sizes to accommodate your needs.

Styled Pivot Header with selected item

Source code

The source code of the sample project on GitHubhas been updated to reflect these changes.

You can also go to the specific commit to see the exact changes.

Filed under C#, Windows
Last update: