Tag Archives: c#

Projects

LocalStorage for .NET

It happened once too often. For the last time I wrote another helper class that serialized<>deserialized some stuff to the filesystem, just so it could be restored in a new debug session. “What a bless localStorage for Javascript is…”, I thought to myself. And with that thought, I started to work on LocalStorage for .NET.

LocalStorage is an extremely lightweight, dependency-less library with a simple concept: allow any .NET object to be stored in an in-memory store – and allow it to be persisted to filesystem. It serves the purpose of filling the gap where most in-memory caches, or key/value stores, are too complex or require either an install or some sort of tedious configuration before you can start coding.

LocalStorage for .NET is inspired by – but totally unrelated to – Javascript’s localStorage; a temporary caching lib for low-demanding data needs.

TL;DR

If you want to get started fast, simply install the library through NuGet:

$ Install-Package LocalStorage

I’ve made some effort to describe the how-and-what in detail in the README of the project, along with a bunch of examples, but let me oversimplify its use with the following sample:

// initialize a new instance
// (see the README for more configurable options)
using (var storage = new LocalStorage()) 
{
    // store any object
    var weapon = new Weapon("Lightsaber");
    storage.Save("weapon", weapon);

    // ... and retrieve the object back
    var target = storage.Get<Weapon>("weapon");

    // or store + get a collection
    var villains = new string[] { "Kylo Ren", "Saruman", "Draco Malfoy" };
    storage.Save("villains", villains);

    // ... and get it back as an IEnumerable
    var target = storage.Query<string>("villains");

    // finally, persist the stored objects to disk (.localstorage file)
    storage.Persist();
} 

Again, take a look at the GitHub repo for more in-depth information:
https://github.com/hanssens/localstorage-for-dotnet

LocalStorage for .NET: it’s dead simple. It has no dependencies. It’s lightweight. And it’s got a memorable name, so hopefully you’ll consider giving it a go yourself someday.

Recipes

Enabling gzip compression in a dotnet core webapi

A fine new addition to the ASP.NET Core 1.1, released medio November 2016, is the option to quickly configure and enable Gzip compression in your dotnet core application.

The recipe for enabling Gzip compression globally is quite easy, as the following two steps illustrate:

  1. Add the package Microsoft.AspNetCore.ResponseCompression
  2. Configure the middleware in your Startup.cs, as shown below:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseResponseCompression();
    }
    
    public void ConfigureServices(IServiceCollection services)
    {
        // Configure Compression level
        services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
    
        // Add Response compression services
        services.AddResponseCompression(options =>
        {
            options.Providers.Add<GzipCompressionProvider>();
        });
    }
    

There is also a video by the Visual Studio team that illustrates this as well. However, while this sounds like a solid deal at first sight you should be aware that it comes with a lot of dependencies.

For example, by installing the Microsoft.AspNetCore.ResponseCompression package through VisualStudio you are prompted with a long list of dependencies:

On itself having these dependencies does not really matter. Especially in a dotnet core application, where dependencies are nested and sort of isolated from other references. But awareness matters and this is definitely something to be aware about.

Code, Projects

ASP.NET MVC 5 Template for Xamarin Studio

Recently the latest version of Xamarin Studio has been released, along with Mono 3.4. And honestly, no one can deny that cross platform .NET development just keeps on getting better and better. I still see a great future for especially Mono if the open source community and the people at Xamarin manage to keep their current pace of improvements. #kudos++

Although with every update of both Xamarin and Mono the bar is set higher, some fields of interest seem to be lacking to get updated. Clearly the mobile platforms, like iOS, Android and Windows Phone seem to get all the attention. But the web platform seems to lose focus in the Xamarin/Mono tagteam, especially ASP.NET.

For example, the native template for ASP.NET is still set to version 3. Which was the non-MyGet version, if you remember. And that means b*tchy to update and cumbersome to update to recent versions. However, it is still possible to actually run and debug new ASP.NET MVC sites on Mono.

To this end, I’ve created a simple and clean setup for a Xamarin project that allows you to run an ASP.NET MVC 5.1 site on Mac OSX. In short:

Fork it on GitHub

Grab a fresh copy from the git repo and you’ll get:

  • A clean ASP.NET MVC 5 application with RAZOR support
  • Can be run entirely from Xamarin Studio on Mac OSX
  • Can be updated and extended through NuGet
  • It just works…

Known Issues

Do note that an Empty ASP.NET MVC 5 project created in Visual Studio won’t run by default in Xamarin. You have to plumb a bit here and there. If you’re curious on what you need to do to make things blend on Xamarin Studio on Mac, take a look at the changes I’ve made in the repo.

Tip: Want to reproduce it yourself? All required changes to run ASP.NET MVC 5 on Mac are neatly documented as seperate commits.

To summarize these changes, the current limitations for a clean setup seems to be:

  • App relative paths don’t work, e.g. using tildes like ~/assets/style.css
  • The view’s web.config has teh disabled
  • Mono currently supports .NET 4.5, not 4.5.1
  • routes.LowerCaseUrls isn’t supported (yet)
  • System.Web.Entity reference isn’t supported (yet)
Code

Create large files with a specific size

In order to test the latency on a specific server configuration, we simply wanted to test the throughput rate of downloading large files. The only question is: how can you efficiently create several (large) files with an exact size?

As easy as two lines, I can tell you. The snippet below basically writes a file with spaces, using a stream, until the designated size is reached. This to accomplish an exact file size.

    /// <summary>
    /// Creates a file with a specific size.
    /// </summary>
    /// <param name="outputFilePath">The full output path for the file. Overwrites if exists.</param>
    /// <param name="length">Filesize in bytes</param>
    static void CreateFileWithSpecificSize(string outputFilePath, long length)
    {
        using (var stream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            stream.SetLength(length);
        }
    }
Code

Drop an entire collection in RavenDB

Deleting a single document in RavenDB is easy. Deleting several documents is too. Deleting an entire collection of N-documents isn’t supported by default.

Here is a great extension that deletes an entire collection from your RavenDB document store:

    /// <summary>
    /// Deletes, or 'drops', an entire collection from the datastore, by the specified type.
    /// </summary>
    public void Drop<T>()
    {
        // Determine the concrete type of T
        Type g = typeof (T);

        // Delete the entire collection
        CurrentSession.Advanced.DocumentStore.DatabaseCommands.DeleteByIndex("Raven/DocumentsByEntityName",
            // ouch, be weary of the 's' suffix here (pluralization thingie)
            new IndexQuery { Query = "Tag:" + g.Name + "s" },
            allowStale: true
        );
    }
Code

Iterate through a hierarchical list of infinite child elements

Example that flattens a nested and, possibly infinite, hierarchical list of child elements.


    class Program
    {
        static void Main(string[] args)
        {
            // Create dummy categories - not especially pretty
            var categories = new List();
            categories.AddRange(new List()
                                    {
                                        new Category(){ Id = 1, Name = "Cat1", Children = new List()
                                                                                              {
                                                                                                  new Category(){ Id = 101, Name = "Subcat1"},
                                                                                                  new Category(){ Id = 102, Name = "Subcat2"},
                                                                                                  new Category(){ Id = 103, Name = "Subcat3WithChildren", Children = new List()
                                                                                                                                                                         {
                                                                                                                                                                             new Category() { Id = 10301, Name = "Subcat1-sub1" },
                                                                                                                                                                             new Category() { Id = 10302, Name = "Subcat1-sub2" }
                                                                                                                                                                        }
                                                                                                                }
                                                                                              }},
                                        new Category() { Id = 2, Name = "Cat2"}
                                    });

            // Flatten the nesteded list of *child* categories
            var flatCategories = new List();
            foreach (var rootCategory in categories)
                flatCategories.AddRange(IterateChildCategories(rootCategory));

            // Spit out the results
            foreach (var cat in flatCategories)
                Console.WriteLine(cat.Name);

            Console.ReadKey();

        }

        /// 
        /// Iterates through a list of child categories. 
        /// 
        /// 
        /// Note that this skips the parent categories, and focusses only on the children.
        /// 
        private static IEnumerable IterateChildCategories(Category parent)
        {
            if (parent.Children == null) yield break;

            foreach (var g in parent.Children)
            {
                yield return g;

                foreach (var sub in IterateChildCategories(g))
                    yield return sub;
            }
        }

        public class Category
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public List Children { get; set; }

            public Category()
            {
                this.Children = new List();
            }
        }
    }