Why diff tools aren’t the fix to the CL/RF git issues

Scott Hanselman had a great post today on the problem with line endings in git.

Hanselman Blog

People in the comments seem to think that this is a problem solved by a diff tool. This has very little to do with the diff view, and more to do with the fact that this is a systemic problem in git. The fact that you even have to decide what type of line endings to set is slightly ridiculous in this day and age. Especially for languages where this has absolutely zero affect on the code.

However as Scott points out there are fixes, but the real thing is that we shouldn't have to be dealing with these fixes in the first place. A point that many missed.

KnockoutJS The Power of if

To If or IfNot That is the Question

Knockoutjs is a fantastic library for building single page applications and for making use of the MVVM in your javascript heavy web pages. Something that is over looked a lot when talking about knockout is the if and ifnot bindings.

What Does if Do?

From the docs

The if binding causes a section of markup to appear in your document (and to have its data-bind attributes applied), only if a specified expression evaluates to true (or a true-ish value such as a non-null object or nonempty string).

This is an extremely powerful feature of knockout, some reasons:

  • It allows you to have conditional DOM elements without caring if the property is defined

  • It allows you to have large collections and only render the current active one

  • It allows you to speed up your page rendering time

Let's discuss:

Say you have the following ViewModel that has 1 Million child items

  1. var data = function() {
  2. var self = this;
  3.  
  4. self.items = ko.observableArray();
  5. self.selectedItem = ko.observable();
  6.  
  7. //get old value
  8. self.selectedItem.subscribe(function(value) {
  9. if(value) {
  10. value.Toggle();
  11. }
  12. }, self, "beforeChange");
  13.  
  14. //get the new value
  15. self.selectedItem.subscribe(function(value) {
  16. if(value) {
  17. value.Toggle();
  18. }
  19. });
  20.  
  21. //populate some items
  22. for(var i = 0; i < 1000; i++)
  23. {
  24. self.items.push(new nested(i));
  25. }
  26. };
  27.  
  28. var nested = function(name) {
  29. var self = this;
  30.  
  31. self.Name = name;
  32.  
  33. self.IsActive = ko.observable(false);
  34.  
  35. self.Toggle = function() {
  36. self.IsActive(!self.IsActive());
  37. }
  38.  
  39. self.nestedItems = ko.observableArray();
  40.  
  41. //populate some propeties on the items
  42. self.msg = var msg = 'This is a really big collection ' + self.Name;
  43. for(var i = 0; i < 1000; i++)
  44. {
  45. self.nestedItems.push(self.msg);
  46. }
  47. }
  48.  

Then you render this as follows

  1. <select data-bind="options: items, optionsText: 'Name', value: selectedItem"></select>
  2.  
  3. <ul data-bind="foreach: items">
  4. <li data-bind="if: IsActive">
  5. <ul data-bind="foreach: nestedItems">
  6. <li>
  7. <span data-bind="text: $data"></span>
  8. </li>
  9. </ul>
  10. </li>
  11. </ul>
  12.  

JsFiddle This uses a slightly smaller amount of items as 1 Million is really not the best idea to generate in JS.

What's difference between if and ifnot

Again from the docs

The ifnot binding is exactly the same as the if binding, except that it inverts the result of whatever expression you pass to it. For more details, see documentation for the if binding.

It also says that ifnot is the same as an inverted if or

  1. data-bind="if: IsActive">

is the same as

  1. data-bind="if: !IsActive()"

One thing to note is that if you directly access an observable in a binding you don't need to evaluate it; however, if you need to invert it you must first access the value (e.g. IsActive()). ifnot avoids this requirement.

SignalR – HAL To Use It

SignalR - HAL to use it

You probably shouldn't be using it without a good reason, but if you have anything that you need to update in "real time" in your application you should use it.

SignalR for those who don't know is

ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is "real-time web" functionality? It's the ability to have your server-side code push content to the connected clients as it happens, in real-time. - SignalR

SignalR is an official Microsoft project.

Installation

You can install it with

Install-Package Microsoft.AspNet.SignalR -pre
  • Warning it's still in RC but it's stable

Hello, Dave

The fastest way to use SignalR is to

  1. Add New File -> Class
  2. public class MyHub : Hub
  3. {
  4. public string Hello()
  5. {
  6. return "Hello, Dave.";
  7. }
  8. }
  9.  

Then in your Global.ascx add this line

  1. RouteTable.Routes.MapHubs();

(For people familiar with previously using SignalR, it no longer generates a javascript proxy for you more on this later)

Then in a view add the appropriate scripts

  1. <script type="text/javascript" src="~/Scripts/jquery-1.9.0.js"></script>
  2. <script type="text/javascript" src="~/Scripts/jquery.signalR-1.0.0-rc2.min.js"></script>
  3.  
  4. <script>
  5. $(function() {
  6. var connection = $.hubConnection(); //this is a connection specifically for a hub
  7. var proxy = connection.createHubProxy('myHub'); //note the capitalization
  8.  
  9. //We must start the connection before we do anything with it
  10. connection.start();
  11.  
  12. //again note capitalization
  13. proxy.invoke('hello').done(function(result) {
  14. alert(result);
  15. });
  16. }):
  17. </script>
  18.  

This should prompt an alert with "Hello, Dave."

Interact

Now adding the method

  1. public void OpenThePodBayDoors()
  2. {
  3. Clients.Caller.response('I'm sorry Dave I can't do that');
  4. }
  5.  

Add the following to your view

  1. <button id="clicker">Please</button>

Add to your script section

  1. $('#clicker').bind('click', function() {
  2. proxy.invoke('openThePodBayDoors');
  3. });
  4.  
  5. proxy.on('response', function(message) {
  6. alert(message);
  7. });
  8.  

So in the above examples what we have done is created a proxy to our hub, via the createHubProxy(hubName) call.
Bound to specific server raised events with proxy.on(event, callback) and invoked events from the client with `proxy.invoke('event', data);

Using A Generated Proxy

If we change the MapHubs call to contain the options to generate the Javascript Proxy for us we can change our code to look like this

  1.  
  2. RouteTable.Routes.MapHubs(new HubConfiguration() { EnableJavaScriptProxies = true });
  3.  
  1. <script>
  2. $(function() {
  3. var connection = $.connection.hub();
  4. var hub = $.connection.myHub;
  5.  
  6. //Again we must start the connection before we do anything with it
  7. connection.start();
  8.  
  9.  
  10. hub.server.hello().done(function(result) {
  11. alert(result);
  12. });
  13.  
  14. $('#clicker').bind('click', function() {
  15. hub.server.openThePodBayDoors();
  16. });
  17.  
  18. hub.client.response = function(message) {
  19. alert(message);
  20. };
  21.  
  22. }):
  23. </script>
  24.  

In this scenario we have two properties on our hub proxy which is created under $.connection.hubName (in this case hubName is myHub), client and server, which seperate the client and server methods from each other. We then can invoke server side methods, or set client side methods to a callback.

Notice - other than the change to the MapHubs call there is no change to our Hub.

Groups

SignalR contains the ability to assign a connection to a Group. The best thing to know about groups is that they are effectively channels that messages are only sent to clients that are in that channel.

The api for groups is as follows

Groups.Add(string ConnectionId, string GroupName)

Groups.Remove(string ConnectionId, string GroupName)

A thing to remember is that SignalR doesn't persist anything, so it's up to you if you want to be able to access who is in a group.

A good way to use groups is for something like a chat room.

  1. public void JoinRoom(string room)
  2. {
  3. //Context.ConnectionId is the ConnectionId of the person who called the method
  4. Groups.Add(Context.ConnectionId, room);
  5. }
  6.  
  7. public void LeaveRoom(string room)
  8. {
  9. Groups.Remove(Context.ConnectionId, room);
  10. }
  11.  
  12. public void SendMessage(string room, string message)
  13. {
  14. Clients.Groups(room).newMessage(message);
  15. }
  16.  

There is nothing to be done to specifically handle groups on the client end but the code would look similar to

  1. function joinRoom(roomName) {
  2. proxy.invoke('joinRoom', roomName);
  3. }
  4.  
  5. function leaveRoom(roomName) {
  6. proxy.invoke('leaveRoom', roomName);
  7. }
  8.  
  9. proxy.on('newMessage', function(message) {
  10. alert(message);
  11. });
  12.  

Closing the Doors

Hopefully this has provided you with a brief glance of what is capable in SignalR via the javascript client (at least for this post). I plan to cover more advanced use of SignalR and using it with other Clients in the near future.

Favorites for the Week – January 18th

Learning how to use block level elements properly in CSS. Big thanks to Jesse Harlin for this.

Redis Live, a python based tool for monitoring Redis Instances https://github.com/kumarnitin/RedisLive.

SignalR went to RC2 - This is one of my favorite things recently. http://signalr.net

Aylele Coffee from Elemental Coffee in Oklahoma City. Really good micro-lot of coffee that I've been drinking at work all week, and brewing via my Chemex. http://elementalcoffeeroasters.com/default.aspx

Sword And Sorcery EP by Jim Guthrie a great electronic style album give it a listen here http://jimguthrie.bandcamp.com/album/sword-sworcery-lp-the-ballad-of-the-space-babies

I'm working on a post about SignalR right now and some of the lessons that I've learned while using it to build an interactive tutoring system at work.

Using ServiceStack.Redis Part 2 Sets and Hashes

ServiceStack.Redis Sets and Hashses

In my last post about redis I talked about getting set up with Redis and using the ServiceStack.Redis IRedisList to empower yourself as a developer.

This post is a quick overview of the IRedisSet<T> and IRedisHash<TKey, T> that are available in ServiceStack.Redis. I'm not going to spend much time talking about the non-generic implementation of both of these interfaces since for the most part the function like calling them with T as string

Set and Hash are much more powerful data models for manipulating your data in Redis directly

Sets

If you take a quick glance at redis sets they don't look that different from lists. In fact when you get data back from ServiceStack.Redis you get it as an IList which is fantastic, but there are a few important things to know.

If you're using the redis set operations, (sort, intersect, etc) you will find that you will have problems with types that have over loaded equaility. This is because these operations are actually being done in redis, and you are comparing them byte to byte (in most cases).So Sets are great if you are using a primative type that exists in redis.

PROTIP: Set's are great but by nature they are going to take up more memory than just a list, this is something to think about if you don't really need the power in the set.

How do you make a set and manipulate it:

  1. //set up the connection
  2. //cast it into the Generic type we wish to use
  3. using(var redis = new RedisClient())
  4. using(var client = redis.As<string>)
  5. {
  6. //Let's first get a reference to a set that we want to manipulate
  7.  
  8. //As most ServiceStack.Redis actions this requires some kind of key
  9. var set = client.Sets["Set"];
  10.  
  11. set.Add("bill");
  12. set.Add("bob");
  13. set.Add("jeremey");
  14.  
  15. var otherSet = client.Sets["OtherSet"];
  16.  
  17. otherSet.Add("bill");
  18. otherSet.Add("jeb");
  19. otherSet.Add("kermin");
  20.  
  21. //HERE ARE SOME THINGS WE CAN DO
  22.  
  23. //Returns the intersect of the sets
  24. //bill
  25. var intersect = set.GetIntersectFromSets(otherSet);
  26.  
  27. //Returns a HashSet<T> containing unique items from both sets
  28. //bill
  29. //bob
  30. //jeremy
  31. //jeb
  32. //kermin
  33. var union = set.GetUnionFromSets(otherSet);
  34.  
  35. //Returns a HashSet<T> containing the differences between the sets
  36. //bob
  37. //jeremey
  38. //jeb
  39. //kermin
  40. var differences = set.GetDifferencesFromSets(otherSet);
  41.  
  42. }
  43.  

Hashes

What's so great about Hashes? Well a lot of things but one of the best things to know is that a hash is basically a Dictionary (in the case of the non-generic hash it's just a Dictionary). This makes the hash very useful for storing objects if you need to manipulate individual properties on the object directly and you don't want to manipulate the entire object.

  1. ///boilerplateAction you've seen this before
  2. using(var redis = new RedisClient())
  3. using(var client = redis.As<string>())
  4. {
  5. //so with hashes you have to get a hash first before you can manipulate it
  6. var hash = client.GetHash<string>("hashID");
  7.  
  8. hash.SetValue("key", "value");
  9.  
  10. //get an individual value from a hash
  11. var individualValue = hash.GetVlauesFromHash("key");
  12.  
  13. hash.SetValue("otherKey", "value");
  14.  
  15. //get all the values from a hash
  16. var allValues = hash.GetAllEntriesFromHash();
  17.  
  18.  
  19. }
  20.  

The main thing to remember with hashes is that you first have to get the hash before you can manipulate values in the hash. This is because all of the hash methods are extensions of IRedisHash<TKey, T> for the generic hash.

This should provide you with an idea of where to get started when using ServiceStack.Redis to manipulate Sets and Hashes. These are powerful tools that can really allow you to quickly manipulate your data and make it available across your application.

Using the ServiceStack.Redis Client

Using the ServiceStack Redis Client to Work with Redis Lists (ServiceStack.Redis)

I'm not going to focus on using Redis as a Cache, this is pretty straight foward and a lot of what I am going to talk about can be
applied to using the Redis as a Cache.

First: Familarize yourself with Redis.

I would suggest checking out redis.io (the main redis site) and giving The Little Redis Book (http://openmymind.net/2012/1/23/The-Little-Redis-Book) a read.

Redis is 'just' a key-value store, but it allows the values to be actual data structures instead of just strings. ServiceStack has taken this farther for us and provided serialization interfaces to allow us to use a Typed client to interact with redis without worrying about this ourselves.

Second: Get Redis running locally

The fastest way to do this is to download the latest version from https://github.com/dmajkic/redis/downloads and start the redis-server.exe on your machine.

Third: All hail NuGet.

Install-Package ServiceStack.Redis into your project.

Fourth: Connecting to Redis

ServiceStack has made this simple. The easiest way to do this is like this

  1. using(var client = new RedisClient())
  2. {
  3. //code goes here
  4. }

This works great but it creates a new client everytime we connect to redis. You can however do the following into your IoC container

  1. Container.Register<IRedisClientsManager>(new BasicClientManager("http://localhost:6378"))

or

  1. Container.Register<IRedisClientsManager>(new PooledClientManager("http://localhost:6378"))

then instead of calling new RedisClient() you can call Container.Resolve<IManagedRedisClients>().GetClient()!

Which one should I use?
Both of these implementations will pool your clients. BasicClientManager, is best when your redis server is on localhost PooledClientManger, is best when your reids service is on a remote machine.
So now that you've got your application hooked up to redis what can you do?

The simplest thing to do with Redis is just store and read some values.

  1. using(var redis = new RedisClient())
  2. {
  3. redis.SetEntry("name", "Michael Sarchet");
  4. console.log(redis.GetEntry("name"));
  5. }

What if we want to store a value that is a type

  1. public class DataType
  2. {
  3. public string Name { get; set; }
  4. }
  5.  
  6. using(var redis = new RedisClient())
  7. {
  8. var client = redis.As<DataType>();
  9. client.SetEntry("Data1", new DataType() { Name = "Michael" });
  10. console.log(client.GetEntry("Data1").Name);
  11. }

//Remember in a production environment you are going to want to use the IRedisClientsManager.GetClient() method, since this is the thread safe way to get a client. For now we can just use new RedisClient().

Now we've just stored a value with a type into Redis. This is done via the Asmethod on the client. This tells the client to serialize and deserialize the values as that type.

If you open up the redis-cli and run
get Data1
you should see something that looks like

  1. {\"Name\" : \"Michael\"}

This is becuase ServiceStack.Redis is serializing these values, and handling the deserialization on the read. This covers the basic use case for Redis, storing some data and reading it back from Redis. The client exposes most (if not all) of the redis command line actions directly. Play around with it and get a feel for how this will work in your application.

Now that you are more familiar with how the RedisClient works directly we will look at using the List structure that redis provides. This is one of the more directly useful things that you can do via redis without getting into a lot of the specific redis functionality.

So let's look at persisting a larger more complex object and what we would need to do to access a list of these objects:

  1. public class Customer
  2. {
  3. public string Name { get; set; }
  4. public string Phone { get; set; }
  5. public string Address { get; set; }
  6. }
  7.  
  8. public class CustomerAccess
  9. {
  10. public static IList<Customer> Customers
  11. {
  12. get
  13. {
  14. using(var client = new RedisClient())
  15. {
  16.  
  17. TClient = client.As<Cusomter>(); //woah I'll get to this don't worry
  18. return TClient.Lists["cusomters"].ToList();
  19. }
  20. }
  21. }
  22.  
  23. public static void AddCustomer(Customer customer)
  24. {
  25. using(var client = new RedisClient())
  26. {
  27. TClient = client.As<Cusomter>();
  28. TClient.Lists["customers"].Add(customer);
  29. }
  30.  
  31. }
  32.  
  33. public static bool RemoveCustomer(Customer customer)
  34. {
  35. using(var client = new RedisClient())
  36. {
  37. TClient = client.As<Customer>();
  38. return TClient.Lists["cusomters"].Remove(customer);
  39. }
  40. }
  41. }

What just happened?

client.As<T> returns a IRedisTypedClient which just handles the serialization for us.

TClient.Lists[key] gives us access to an IRedisList (which is the wrapper for the internal Redis List data structure). IRedisList<T> implements IList<T> which lets us access it like a normal list.

Internally ServiceStack is handling all actions to call these methods (proTip! most of these are native to redis :D so it's super fast)

If you notice in the Customers Property I called Tclient.Lists["customer"].ToList(), this is because if you just return the IRedisList any time you act on it it will reopen a connection to redis, which can be kind of bad. Instead we are just getting a snapshot of the data at that time. However if you wanted and you ignored the "ToList()" you could add data and then get it and it will all come directly from redis, which can be useful in the right circumstances.

My next post will cover the Set and Hash Implementations and some of the more powerful things you can do with those.

Improve Your ASP .NET Website Performance

5 minutes to better performance on your ASP .NET Web Site

Step 1:

Turn on Gzip.

How do you turn on gzip

For most sites you want to put this into your web.config

  1.  
  2. <system.webserver>
  3. <httpCompression directory="%TEMP%\iisexpress\IIS Temporary Compressed Files">
  4. <scheme name="gzip" dll="%IIS_BIN%\gzip.dll" />
  5. <dynamicTypes>
  6. <add mimeType="text/*" enabled="true" />
  7. <add mimeType="message/*" enabled="true" />
  8. <add mimeType="application/x-javascript" enabled="true" />
  9. <add mimeType="*/*" enabled="false" />
  10. </dynamicTypes>
  11. <staticTypes>
  12. <add mimeType="text/*" enabled="true" />
  13. <add mimeType="message/*" enabled="true" />
  14. <add mimeType="application/x-javascript" enabled="true" />
  15. <add mimeType="application/atom+xml" enabled="true" />
  16. <add mimeType="application/xaml+xml" enabled="true" />
  17. <add mimeType="*/*" enabled="false" />
  18. </staticTypes>
  19. </httpCompression>
  20. <urlCompression doStaticCompression="true" doDynamicCompression="true"/>
  21. </system.webserver>
  22.  

You may need to enable Compression in IIS if you are running an older version.

Step 2:

Set the correct cache headers on your javascript and css

  1.  
  2. <system.webserver>
  3. <staticContent>
  4. <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="350.00:00:00" />
  5. </staticContent>
  6. </system.webserver>
  7.  

This says cache all my static content for 350 days

**Warning** You may not want to do this if you aren't doing some kind of cache invalidation with your file names.

Step 3:

Minify and Combine all of your javascript and css into as few requests as possible per page

Minify - Strip all white space and comments from your javascript and css
Combine - Put as many files into one file as you can

Easiest way to do this:

Install Request Reduce in each project you want to combine and minify in

www.requestreduce.org

Nuget Action:

Install-Package RequestReduce

You shouldn't have to config anything and it should work out of the box

Slightly more complicated ways of doing this

Use a bundler

the ASP .NET bundler is great

Cassette is also awesome

BAM!

You've now just probably sped your page up!