By Ugo Lattanzi on June 8th , 2015 in various | comments

Today we announced (here) by the official channel some important news about the next Web European Conference

That will be a really AMAZING conference and we had several news for you and for all the attendees.

The previous conference was sold out in 40 minutes for 170 available seats, but now we have more seats so everything should go in the right way for all of you but, if you want to be the first to know about the conference, and to have the possibility to pre-register before the official registration opens, go to our website http://webnextconf.eu/ and subscribe to the mailing list. First July the registration will be free for all but, few hours early, we'll send the registration link to all people who subscribe our newsletter.

As for the previous edition, the conference will be free. That's really important and it's the difficult part of the organization. Is not easy to find the money for speakers, rooms, other stuff and keep the tickets free, for this reason your support is more important than ever.

During the registration you can choose if you wanna come for free, if you want the lunch (around 10€), the T-Shirt (€10) and if you want to make a donation (as you wish). We'll use the donation for the organization, speakers, stickers and other stuff like that.

The conference will be in Milan, University of Milano-Bicocca so, if you think you wanna come, it's time to book your hotel. That's important because there is the Expo fair in Milan, so lot of hotels are fully booked, don't wait!

All the information about the location is available on the conference web site here

Finally, I'm very happy to announce two important speakers that will be here in Milan The Great Scott Hanselman and the fabulous Dino Esposito who will talk about ASP.NET vNext and "Extending RWD with Lightweight Client-side Device Detection".

So far we received almost 50 proposals from 20+ different speakers, but to get even more speeches to choose from, we've decided to keep the call for presenters open till the end of June: if you haven't done it yet and you want have the chance to be in the "speakers room" with Scott, go on our Github account, fork the c4p repository, add your proposal and submit a pull request.

Is that cool enough? Yeah! But the surprices are not over, other cool speakers could come, so stay tuned.

By Ugo Lattanzi on April 23rd , 2015 in various | comments

In the previous post (you can read it here) I wrote about how cool is Redis as cache server and I showed the basic steps to run Redis on premise or on Microsoft Azure if you prefer.

In this post I wanna introduce an small package available on NuGet that complete one of the best library actually available for Redis in a .NET environement.

The package is StackExchange.Redis.Extensions and, as you can imagine from the name, it offers a set of useful helper.

What can we do easily with StackExchange.Redis.Extensions?

In the previous post I wrote that you have to serialize and deserialize a class if you wanna store it into Redis because the library stores a byte[] and the value could be sent via network. Using this library you don't have to worry about that, it does that for you. Right now it can use three different serialization libraries :

  • JSON.Net by NewtonSoft NuGet Status
  • Jil NuGet Status
  • Message Pack CLI NuGet Status

If you need to use another serializazion library you can easily do it by creating an implementation of ISerialize. Of course in this case a Pull Request is welcome

In the example below I'm going to use JSON.Net but the code is the same for the other librarys, just the Nuget Package changes.

First step is to install it on our project so:

PM> Install-Package StackExchange.Redis.Extensions.Newtonsoft

It contains all you need to use Redis, so you don't have to add StackExchange.Redis because it has the right dependency to it.

Now that we are ready, it's enough to create our ICacheHelper instance

var serializer = new NewtonsoftSerializer();
var cacheClient = new StackExchangeRedisCacheClient(serializer);

The constructor of StackExchangeRedisCacheClienthas different overloads offering you the opportunity to specify your custom serializer, database, connection string or, if you have it, your instance of ConnectionMultiplex.

If you use the code above is enough the add the following code to your configuration file replacing the right values (host, port, ssl and so on):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="redisCacheClient"
               type="StackExchange.Redis.Extensions.Core.Configuration.RedisCachingSectionHandler, StackExchange.Redis.Extensions.Core" />
    </configSections>

    <redisCacheClient allowAdmin="true" ssl="false" connectTimeout="5000" database="0">
        <hosts>
            <add host="127.0.0.1" cachePort="6379"/>
        </hosts>
    </redisCacheClient>
</configuration>

If you use a dependency injection framework, probably it's better to register it as singleton

From now we have a set of useful methods for the following scenarios:

How can I store a complex object into Redis?

var user = new User()
{
    Firstname = "Ugo",
    Lastname = "Lattanzi",
    Twitter = "@imperugo"
    Blog = "http://tostring.it"
}

bool added = myCacheClient.Add("my cache key", user, DateTimeOffset.Now.AddMinutes(10));

How can I retrieve an object into Redis?

var cachedUser = cacheClient.Get<User>("my cache key");

How can I retrieve multiple objects with single roundtrip?

That's one of my favorite features because It's very helpful in case you have to retrieve several objects in the same time.

var cachedUsers = myCacheClient.GetAll<User>(new {"key1","key2","key3"});

How can I add multiple objects with single roundtrip?

IList<User> values = new List<User>();

var user1 = new User()
{
    Firstname = "Ugo",
    Lastname = "Lattanzi",
    Twitter = "@imperugo"
    Blog = "http://tostring.it"
}

var user2 = new User()
{
    Firstname = "Simone",
    Lastname = "Chiaretta",
    Twitter = "@simonech"
    Blog = "http://codeclimber.net.nz/"
}

var user3 = new User()
{
    Firstname = "Matteo",
    Lastname = "Pagani",
    Twitter = "@qmatteoq"
    Blog = "http://qmatteoq.com/"
}

values.Add(user1);
values.Add(user2);
values.Add(user3);

bool added = sut.AddAll(values);

Can I search keys into Redis?

Yes that's possible using a specific pattern. If you want to search all keys that start with myCacheKey:

var keys = myCacheClient.SearchKeys("myCacheKey*");

If you want to search all keys that contain with myCacheKey:

var keys = myCacheClient.SearchKeys("*myCacheKey*");

If you want to search all keys that end with myCacheKey:

var keys = myCacheClient.SearchKeys("*myCacheKey");

Can I use a Redis method directly from ICacheClient without adding another dependency to my class?

Of course you can. ICacheClient exposes a readonly property named Database that is the implementation of IDatabase by StackExchange.Redis

How can I get server information?

ICacheClient has a method GetInfo and GetInfoAsync for that:

var info = myCacheClient.GetInfo();

That's what the library does right now and I've to say thanks to ziyasal, ppanyukov and rajasekarshanmugam for the contribution.

The project is available on Github here

By Ugo Lattanzi on Mar. 16th , 2015 in owin | comments

I'm very happy to announce that, from today, my first book is available here thanks to Syncfusion that is a popular company among developers for their great suites of controls. The ebook is focused on OWIN (Open Web Server Interface for .NET specification) and it's co-written with my friend Simone Chiaretta who is organizing with me the 2° Web European Conference.

It's a free ebook and, in 110 pages, it covers the most important things you need to know about OWIN from the basic stuff, like "What is OWIN" and "The Middleware", to more complex stuff like "Authentication using social networks" like Facebook, Twitter and Google with ASP.NET Identity and ASP.NET MVC.

Here is the TOC of the book:

  • OWIN
  • Katana
  • Using Katana with Other Web Frameworks
  • Building Custom Middleware
  • Authentication with Katana
  • Appendix

The book is distributed by Syncfusion for free, you just have to register and then you’ll be able to download it both in PDF and Kindle format. Of course if you have feedbacks or you find something that is not clear, that sounds strange or whatever, please don't hesistate to contact me

Owin Succinctly

By Ugo Lattanzi on Mar. 5th , 2015 in azure | comments

I know, the title is a bit provocative or presumptuous if you prefer, but I think this post could be useful if you wanna approach to Redis as cache server using .NET. For all the people who don't know what Redis is, let me quote that definition:

Redis is an open source, BSD licensed, advanced key-value cache and store.

And why is it so cool? This is probably the best answer you can find on internet (source here):

Redis running on an entry level laptop can scan a 1 million key database in 40 milliseconds.

Installation

Now that is clear why Redis is so cool and why lot of enterprise applications use it, we can see how to use it. First of all we have to download Redis from here, unzip the file and run it locally

> redis-server.exe redis.conf

and the console output should be something like this:

RedisConsole

if you want to use Redis on Microsoft Azure, you can do it by creating your instance here:

Azure1

Azure2

choose the best plan for you, the location, add your name in the proper field and create it.

creation could take a while and sometime you can get errors. The reason is that the portal is still in beta but don't worry, keep trying till you get the redis cache server up & running

Azure3

Azure4

Configuration

Here we go, Redis is up & running on your dev machine and/or on Azure if you choose it. Before to start writing code, it's important to choose the client library to use. The most used libraries are

The first one is free and opensource so, if you want to use it, you can do easily. The other one has a AGPL license (from 149$ to 249$).

if you prefer ServiceStack.Redis you can downgrade to version 3.9.71 which was the last truly free

In this article I'm going to use StackExchange.Redis so, let's start to install it using NuGet

PM> Install-Package StackExchange.Redis

There is also a StrongName (StackExchange.Redis.StrongName) package if you need to use it into a signed library.

Now, it's time to write some good code:

namespace imperugo.blog.redis
{
    class Program
    {
        private static ConnectionMultiplexer connectionMultiplexer;
        private static IDatabase database;

        static void Main(string[] args)
        {
            Configure();
        }

        private static void Configure()
        {
            //use locally redis installation
            var connectionString = string.Format("{0}:{1}", "127.0.0.1", 6379);

            //use azure redis installation
            var azureConnectionString = string.Format("{0}:{1},ssl=true,password={2}",
                                    "imperugo-test.redis.cache.windows.net",
                                    6380,
                                    "Azure Primary Key");

            connectionMultiplexer = ConnectionMultiplexer.Connect(connectionString);
            database = connectionMultiplexer.GetDatabase();
        }
    }
}

For some plans, Redis on azure uses SSL by default. If you prefer a no-secure connection you can enable it via Azure Portal, in this case use 6379 and remove ssl=true from the connection string

Add and Retrieve cache objects

StackExchange stores data into Redis sending/retrieving a byte[] or so, whatever you are storing into Redis must be converted into a byte[] (string is automatically converted by StackExchange.Redis implementation so we don't have to do it).

Let's start with simple object like a string

private static bool StoreData(string key, string value)
{
    return database.StringSet(key, value);
}

private static string GetData(string key)
{
    return database.StringGet(key);
}

private static void DeleteData(string key)
{
    database.KeyDelete(key);
}

and now we can use this methods

static void Main(string[] args)
{
    Configure();

    bool stored = StoreData("MyKey","my first cache string");

    if (stored)
    {
        var cachedData = GetData("MyKey");

        bool isIt = cachedData == "my first cache string";
    }
}

That's pretty simple but what about storing complex objects? As I wrote above, StackExchange.Redis stores only byte[] data so we have to serialize our complex object and convert it into a byte[] (there is an implicit conversion in case of string, for this reason we didn't convert the type string to byte[])

The easiest (and probably the best) way to store complex objects consists to serilize the object into a string before to store the data into Redis.

Choose your favorite serialized (NewtonSoft in my case ) and create some helpers like here

public bool Add<T>(string key, T value, DateTimeOffset expiresAt) where T : class
{
   var serializedObject = JsonConvert.SerializeObject(value);
    var expiration = expiresAt.Subtract(DateTimeOffset.Now);

    return database.StringSet(key, serializedObject, expiration);
}

public T Get<T>(string key) where T : class
{
    var serializedObject = database.StringGet(key);

    return JsonConvert.DeserializeObject<T>(serializedObject)
}

Now we are able to put and retrieve complex objects into Redis, next step is to remove it and check if the value exists

public bool Remove(string key)
{
    return database.KeyDelete(key);
}

public bool Exists(string key)
{
    return database.KeyExists(key);
}

if you need async methods, don't worry, StackExchange.Redis has an async overload for almost every method

Resources

Redis Commands absolutety the best reference to understand how Redis works and what StackExchage.Redis does under the table.

StackExchage.Redis documentation is absolutely helpful if you choose this library as your wrapper.

StackExchange.Redis.Extensions is a great library (and I suggest to you it) that wrap the common operation needed with StackExchange.Redis (basically you don't need to serialize objects or create helpers like I explained above):

  • Add complex objects to Redis;
  • Remove an object from Redis;
  • Search Keys into Redis;
  • Retrieve multiple objects with a single roundtrip;
  • Store multiple objects with a single roundtrip;
  • Async methods;
  • Retrieve Redis Server status;
  • Much more;

It uses Json.Net (NewtonSoft), Jil or Message Pack CLI to serialize objects into a byte[]. Anyway we'll see it with the next blog post.

Investigating Timeout Exceptions in StackExchange.Redis for Azure Redis Cache great article about possible timeout exception problem with Redis and Azure

Dashboard

Azure Dashboard

AzureRedis-Dashboard

It offers basic stats but it's free when you use Redis with Microsoft Azure

Redsmin

Redsmin-Dashboard

Probably the most complete dashboard for Redis, offers a set of stats about your Redis servers, supports Azure and has a good prompt allowing you to run Redis command directly on the server without using C# or any other programming language. Unfortunately it is not free, here plans and pricing.

Redis Desktop Manager

Redismin-Dashboard

Open Source tool for Windows, Mac and Linux hosted on Github here (right now it the version 0.7.6) offers to run Redis commands into Redis like Redismin, but unfortunately it doesn't support Azure yet (there is an issue about that opened here).

Redis Live

redis-live-Dashboard

It's a real time dashboard for Redis written using Python.

Conclusions

Redis is absolutely one of the best in memory database available right now. There is a wrapper for every language, it's got a good documentation and it's free. If I were you I'd give it a look!

staytuned!

By Ugo Lattanzi on Feb. 17th , 2015 in aspnet | comments

In the previous post, I wrote about HTTP security, particularly about "special" headers. This post is partially related to the previous one, it means I am writing about security in a common scenario for web applications.

How many times did you add a redirect from an HTTP request to an HTTPS? I think you did it more than one time and, looking on internet, there are several simple solutions.

If you are using OWIN it's enough to create a custom Middleware like this:

public class ForceHttpsMiddleware : OwinMiddleware
{
    private readonly int port;

    public ForceHttpsMiddleware(OwinMiddleware next, int port) : base(next)
    {
        this.port = port;
    }

    public override Task Invoke(IOwinContext context)
    {
        if (context.Request.Uri.Scheme == "http")
        {
            var httpsUrl = string.Format("https://{0}:{1}{2}", context.Request.Uri.Host,
                port,
                context.Request.Uri.PathAndQuery);

            context.Response.Redirect(httpsUrl);
        }

        return Next.Invoke(context);
    }
}

Nothing complex here, but the question is: "Is it correct to redirect a user from an unsecure connection to a secure connection?" Basically the answer should be yes, but you must be careful about a particular scenario.

An unsecure request (HTTP) that includes a cookie and/or SessionId is subject to hijacking attacks and we don't want that to happen on our website. The easiest way to prevent this is to release the cookies only in a secure mode, it means that the cookies are not available from an unsecure request, but only from an HTTPS preventig a MITM (Man in the middle) attack.

Using Aspnet and Owin you can do it easily

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = "Cookies",
    CookieSecure = CookieSecureOption.Always,
    CookieHttpOnly = true
});

Here the most important part is CookieSecure property. It defines that only HTTPS request can access to cookie. To complete the security scenario, you could add also HTTP Strict Transport Security (HSTS) explained here.

Enjoy.