schuirink.net
main destinations: home | the web & the world | out of here
Google

news headlines

News headlines collected from 498 newsfeeds.

weblogs.asp.net main feed

url: http://weblogs.asp.net

Novos artigos no MSDN


Olá pessoal, já estão publicados meus 3 novos artigos para ajudar a comunidade.

- Windows Phone 7 - dados de OData  - http://msdn.microsoft.com/pt-br/library/hh972465.aspx

- Bing Maps no Windows Phone 7.5 - http://msdn.microsoft.com/pt-br/library/hh972467.aspx

- A importância e o uso do Data Annotation - http://msdn.microsoft.com/pt-br/library/jj129537

Bons estudos e sucesso.



Recent SharePoint 2010 Books [CanCon]


Here in Canada, and particularly in south Ontario we're lucky to have an exceptionally strong SharePoint community. With the publication this month of Ruven Gotz's Practical SharePoint 2010 Information Architecture I count at least 6 books that were either written by, or contain contributions by our local SharePoint MVPs. Bookmark this post or watch my tweets for updates as I post reviews and add other local titles. Practical SharePoint 2010 Information Architecture by Ruven Gotz Not yet reviewed...(read more)

SharePoint Summit 2012 - Thank you!


Thanks to Danny, Reza, all the speakers and the rest of the team for hosting another great SharePoint conference in Toronto. Also a shout-out to the SharePoint Blues Band for putting on a great show Tuesday night, and for the privilege of joining them on-stage to play one of my originals. It was a lot of fun, and I hope we can do it again next year or sooner! Also a big thanks to everyone who attended my session on Large-scale SharePoint Architecture . I've attached the deck to this post and added...(read more)

Trends in HTML5 and mobile development - webinar recording


A couple of weeks ago I wrote a blog post inviting you all to our webinar we presented with Forrester Research. So thanks for everyone who attended and special thanks to Jefferey Hammond of Forrester who did an outstanding job in discussing the Open Web, Cloud computing and Mobility trends and presenting the new development challenges they bring and why organizations need to rethink their application development strategies. I wanted to bring to your attention the availability of the recorded video...(read more)

Code to Interfaces. Right. What?s an Interface?


The premise of coding to interfaces has been around for awhile now. The concept is simple. Given a definition of something you create things based on that definition. That might be a horrible description of an interface but I didn?t want to go all Computer Science on you.

Interface? What?s an Interface?

Here?s a simple interface:

   1: interface ICustomerService
   2: {
   3:     IEnumerable GetAllCustomers();
   4: }

Pretty basic. We have a Customer class somewhere and this interface describes a method called GetAllCustomers that will return you a list of Customer objects.

With an interface you don?t have an implementation. There?s no code here to say where we get the customers from, just that we expect this to return us a list of them.

Now in our code we can write something like this:

   1: public void DisplayAllCustomers(ICustomerService service)
   2: {
   3:     foreach (var customer in service.GetAllCustomers())
   4:     {
   5:         // Output whatever customer info here
   6:     }
   7: }

The method here expects an object that implements the ICustomerService interface. That?s how we can build and compile this but we have yet to build an implementation of this method. Of course the code won?t run because your application doesn?t know how to create an object that implements ICustomerService.

Like I said, the implementation is up to you but you?ll probably be driving it from requirements or what the user needs to see or whatever. Here?s a sample implementation:

   1: internal class CustomerRepository : ICustomerService
   2: {
   3:     public IEnumerable GetAllCustomers()
   4:     {
   5:         return new List
   6:                     {
   7:                         new Customer {Name = "Harold"}, 
   8:                         new Customer {Name = "Kumar"}
   9:                     };
  10:     }
  11: }

So if we created an object of this CustomerRepository class and passed it to the DisplayAllCustomers method above, we would output Harold and Kumar?s names (or whatever your display code was).

The $10,000 Question

People will stare at the code and say, why? Why create that ICustomerService and then have to go to the trouble of creating it and passing it along to the DisplayAllCustomers. More code to maintain they say. More work.

Let?s try to dispel some myths here.

Coding to Interfaces is Hard

Really? Do you understand the code above? That?s coding to an interface. Could you do that yourself? Sure you can. Let?s move on.

Coding to Interfaces Constrains Me

It?s true. If you added the method ?void AddCustomer(Customer customer)? to your inteface, you wouldn?t be able to compile your code. The CustomerRepostory class (and any other class that implemented the ICustomerService interface) would require it. Stop thinking about this as a constraint, it?s a design choice. It?s like the Architect giving you a window or door on the side of your house. You don?t go cutting open another hole because you want another window. You have to take into account load bearing walls, structural integrity, etc. which is what the Architect does (I know, I used to be one). Just because it looks good or you need it, doesn?t mean it should be done (at least in the way you might want it).

Coding to Interfaces makes you do extra work

Yes, you have to create those interfaces so yeah, that?s extra work. Some might argue that if your implementation is simple then you?re writing double the code. Again, all true. There are benefits that will outweigh this which we?ll look at in a moment.

Where are the Benefits?

Let?s talk some benefits here. First coding to an interface is giving you a layer of abstraction. Remember that ICustomerService above? The implementation is sort of silly but shows that we can write code that does what the system intends. We could also build an implementation that reads from a database. Or Active Directory. Or SAP. Or a Web Service. Each time we write a new implementation, we don?t have to change our DIsplayAllCustomers method.

That?s abstraction. You don?t have to worry in your DisplayAllCustomers method where the data came from or what infrastructure may or may not exist. All you care about is that you expect a list of customers to come back.

Now multiply that by 10 or 100 and you get the benefits of abstraction against a real codebase.

Some people will talk about future proofing and interfaces and while that may be a benefit down the road, and it can happen, consider it icing on the cake. Imagine if you had coded to an IEnumerable interface instead of ArrayList? Now you *might* not have to rewrite a lot of code (or any if you?re really lucky).

I do believe, and have rarely seen, entire implementations changed. For example one classic is the ?build a database interface so we can swap between SQL and Oracle?. You build an abstraction over a database to make it simpler to code to but not necessarily swap out technologies.

Just don?t use the future proofing claim as a crutch to not code to interfaces claiming YAGNI or something. There are different reasons for this.

The other big thing is testing. Going back to our CustomerRepository. It?s an in-memory representation to a list of customers. Imagine you had additional methods on your interface like this:

   1: internal interface ICustomerService
   2: {
   3:     IEnumerable GetAllCustomers();
   4:     void AddCustomer(Customer newCustomer);
   5:     void DeleteCustomer(Customer customerToDelete);
   6: }

And now with your in-memory representation you can write tests that ensure items are added and deleted in your repository and the counts all match and the list comes back with the right names. Now you?re starting to test against your interface, which is a good thing.

Testing

Testing frameworks will let  you do things like create stubs or fake implementations of the interface, without actually writing code to return actual values. Without interfaces if you tried to test the AddCustomer method in say a SQL based implementation, you would need a database, login information, test data, etc. That?s great for infrastructure tests but for unit tests it?s a lot of overhead you shouldn?t be getting into.

Another benefit is getting ahead of infrastructure. Imagine if your ICustomerService is going to talk to a web service, as web service that won?t be written for another month. You could go ahead and wait for the infrastructure to show up, code concrete classes against it, and then start your testing but now you?re in the crunch to get the system done and you?re just starting your unit testing.

Instead, based on requirements and perhaps UI discussions with users using paper, whiteboard, or digital wireframes, you come up with the interface. ?We?re going to need to display the customer fields and oh yeah, we want to search by first and last name?. Great. From that description you can come up with an interface something like this:

   1: interface ICustomerService
   2: {
   3:     IEnumerable FindBy(string firstName);
   4:     IEnumerable FindBy(string firstName, string lastName);
   5: }

Again we can write up some implementation (maybe going against a preset list of names you import from a spreadsheet) and actually build out a working UI. The user can put their hands on it, search by names, and see the results returned. All without that pesky infrastructure. Then come the say the database gets built, you create your implementation to read it and do searches and BAM, your system is online and working end-to-end.

On the testing front again, how would you test something that?s dependent on DateTime? For example you have a piece of code that ages some items in a system based on some business rules (or expires them).

It?s all well and fine to start tossing around DateTime objects like this:

   1: public void ExpireTest(ICustomerService service, DateTime date)
   2: {
   3:     foreach (var customer in service.GetAllCustomers())
   4:     {
   5:         if(customer.ContractDate > date)
   6:         {
   7:             ExpireContractFor(customer);
   8:         }
   9:     }
  10: }

However things get real ugly real fast. First I have to write this test and I?m sort of breaking both encapsulation and responsibility of the customer class. Maybe I should have a method on customer that takes in a DateTime object. Yuck. Now I?m passing that value into my business object which might be okay (it depends) but now consider the idea of something like this business rule:

   1: foreach (var customer in service.GetAllCustomers())
   2: {
   3:     if(customer.ContractDate.Day == date.Day && date.Hour > 12)
   4:     {
   5:         ExpireContractFor(customer);
   6:     }
   7: }

Now I?ll only expire the contract if the date passed in is the same day as my contract and it?s after noon. Silly logic yes, but would require another test method, another date object to be passed in, etc. A lot of setup to test something and then along comes this somewhere in my Customer class:

   1: class Customer
   2: {
   3:     public string Name { get; set; }
   4:  
   5:     public DateTime ContractDate { get; set; }
   6:  
   7:     public int AgeOfContract()
   8:     {
   9:         return (int) (DateTime.Now - ContractDate).TotalDays;
  10:     }
  11: }

Now I?m screwed, both in testing in code and testing on the site. I?m going to have to create test data with very specific dates, maybe mess around with the values (because I certainly can?t change the clock on the server) and frankly I?m going to cry.

Interfaces can save you here. What if we had an interface called:

   1: interface IDateTime
   2: {
   3:     DateTime Now { get; set; }
   4: }

And instead of the concrete implementation in our customer class we use the IDateTime interface. Here?s the Customer class refactored to use an interface:

   1: class Customer
   2: {
   3:     readonly IDateTime _dateTime;
   4:  
   5:     Customer(IDateTime dateTime)
   6:     {
   7:         _dateTime = dateTime;
   8:     }
   9:  
  10:     public string Name { get; set; }
  11:  
  12:     public IDateTime ContractDate { get; set; }
  13:  
  14:     public int AgeOfContract()
  15:     {
  16:         return (int) (_dateTime.Now - ContractDate).TotalDays;
  17:     }
  18: }

Yes, there?s more that needs to be here like how an IDateTime can subtract values from each other, return a TImeSpan object, etc. but this is just for concepts.

With the interface added, I?m now abstracted away from the concrete implementation of DateTime hard coded into my Customer class. I?ll pass in something that might implement DateTime to return some real time but for testing I can set it to anything I want.

Testing is easier now and I don?t have to change my domain logic to deal with responsibilities outside of my concerns.

Interfaces vs. Classes is the kind of thing to start holy flame wars. Some argue it adds extra code/work to the developer, others claim it unnecessarily future-proofs your app (aka YAGNI) and others think it makes for easier testing and abstraction away from things that have yet to come.

I like to live in the latter world where I build my systems loosely coupled but tightly integrated. Interfaces provide me that ability. I hope this article sheds some light on the subject for you, whatever you choose.

Enjoy.



CacheAdapter 2.5?Memcached revised


Note: For more information around the CacheAdapter, see my previous posts here, here, here and here

You may have noticed a number of updates to the CacheAdapter package on nuget as of late. These are all related to performance and stability improvements for the memcached component of the library.

However it became apparent that I needed more performance for the memcached support to make the library truly useful and perform as best as can be expected.

I started playing with optimising serialisation processes and really optimising the socket connections used to communicate with the memcached instance. As anybody who has worked with sockets before may tell you, you quickly start to look at pooling your connections to ensure you do not have to go about recreating a connection every time you want to communicate, especially if we are storing or retrieving items in a cache as this can be very frequent.

So I started implementing a pooling mechanism to increase the performance. I got to improving it to a reasonable extent, then found I would hit a hurdle where performance could be increased further but it was becoming harder and more complex to retain stability. I became lost in trying to fix the problem when a solution had already been in place for a long time.

It was about then I decided it best to simply take a dependency on the most excellent Enyim memcached client. It is fast. Really fast, and blew away everything I had done in terms of performance. So that is the essence of this update. The memcached support in the cache adapter comes courtesy of Enyim. Enjoy the extra speed that comes with it.

Note: There are no other updates to any of the other caching implementations.



Netduino at the Bay Area Maker Faire


If you are in the San Francisco Bay Area, or even feel like making a quick weekend tripI highly recommend checking out the Maker Faire this weekend in San Mateo, CA ( www.makerfaire.com ). I?ve posted a write up of some of my suggestions on what to bring to the Maker Faire over on my personal site, check that out if you are going to go. Netduino on site Chris Walker from Secret Labs , creators of the Netduino open source hardware project, will be at the Faire presenting two sessions on the Make:...(read more)

Google introduces the Knowledge Graph


Google is rolling out a HUGE new feature in the next few days.  They call it the ?Knowledge Graph? and it is supposed to be a much smarter system for gathering the search results that you want.  This will set SEO experts scrambling to see how to best optimize sites and content! [via Google ] Introducing the Knowledge Graph When you search, you?re not just looking for a webpage. You?re looking to get answers, understand concepts and explore. The next frontier in search is to understand real...(read more)

Keep Calm And PowerShell On


Another variation of the historic poster from WW2.

KCPOSH

SharePoint variations here?



Getting Started with ASP.NET MVC 3, Logging, and Depency Injection


I started a new ASP.NET MVC project recently and wanted to give you a little insight on kicking off new projects. There?s some setup time you want to spend setting up your solution and getting the plumbing in order before you dive into writing unit tests and building out your site.

For a full on, blow my mind, ultimate guide you *have* to go watch Rob Conery and his 90 minute walkthrough of setting up his MVC projects. I?ve watched this video a few times and Rob is awesome and knows his stuff. The tips he gives are gold. You can also check out the MVC 3 Starter Kit on CodePlex which is based on his MVC 2 Starter code but I found it was lacking a few features. In any case, go watch his video for the full meal deal either here on YouTube or here on TekPub. This post is just a mere shadow of his work but updates the use of Ninject with MVC 3.

Okay, so we?re going to be doing some simple plumbing to get this going. We?ll put together the Hello World MVC 3 app, add in a logging system, and plumb in dependency injection in just a few minutes.

You?ll need Visual Studio 2010 with MVC 3 and NuGet installed. You can get MVC 3 from the main site here. Next install NuGet from here. The MVC 3 framework is obviously needed (Visual Studio 2010 only comes with MVC 2 out of the box) and NuGet is used to install our additional libraries (trust me, if you haven?t used NuGet before it will blow your mind).

First steps is to build a new MVC 3 app. File > New Project. Then select Visual C# > Web > ASP.NET MVC 3 Application and give it a name.

image

Click OK and you?ll see the options dialog for a new MVC 3 Application.

image

Pick Internet application as it will work for most everyone (Windows authentication works fine too but for this post it?s just easier to go with Internet). Let?s choose Razor for the view engine (ASPX is so 2011) and use HTML 5 markup (hey, it?s just a demo). We won?t create a unit test project but in a real project you?ll create one (or create a class library separately so you can use other unit testing frameworks).

We?re creating a project based on the template to give us a controller as we?ll inject our dependency into it later, otherwise we would have to create those. In a real project we might start with an empty template and create our own controllers from scratch (again, demo land, remember?).

Once you do that you?ll be at the Hello World project of the MVC world.

image

Okay, now we?re going to install two NuGet packages, Ninject and NLog. Ninject is an open source dependency injection framework and makes working with external dependencies (like infrastructure and services) a breeze. NLog is a free logging solution for .NET and allows you to write anything to almost any target including files, event logs, web services, mail, forms. You name it, it can write to it. I was using log4net for all my projects but lately I?ve switched over to NLog. It?s super-simple to use and highly flexible. Did I mention it?s available as a NuGet package?

Right click on the References in your project and choose Manage NuGet Packages?

image

Make sure you?re looking at the Online packages (sometimes the dialog will open up to installed packages or updatable ones). Type in ?nlog? into the search box and you?ll see the filtered search results. Choose NLog Configuration from the options. If you already had a log configuration file you can just choose NLog to install the logger but since we?re starting from scratch we need a config file to start with. Selecting NLog Configuration and you?ll see it has a dependency on NLog so you can just install the one package which installs a starter config file and then drags along the library with it. Easy.

image

Once you?ve installed NLog you can enter ?ninject? in the search box. This will bring up a list of packages for the dependency injection library Ninject by Nate Kohari. You?ll want to install the Ninject.MVC3 package by Remo Gloor and Ian Davis. This package will install Ninject itself and the extensions for MVC 3 (along with the bootstrapper for web projects. Ninject requires you to review and accept the license agreement before it will install so go ahead and do that.

Two packages and all of their dependencies but you?re now only a few minutes (yes, minutes) away from dependency injection heaven and MVC 3.

The first thing we?re going to do is create an interface that will be our logging system. We have a logger (NLog) but that?s an implementation and while we could scatter NLog statements all over the place, we would be tied directly to that library. If we decided to phase out NLog and replace it with another library (such as how I?ve shifted from log4net to NLog) we would have to go through everywhere in our code and replace the NLog calls with the next best thing.

This the one of the principles of dependency injection, abstraction, and SOLID. Creating an abstraction of an implementation to code against without tying ourselves to any one system (so to speak). At the end of the day we?ll still be calling into NLog functions but we?ll be doing it through an implementation class via our interface.

The other key thing about this approach is that we we can mock or stub out the actual implementation of our logger for unit testing. You can really do that (very well) with concrete implementations. Imagine having to start up a database, file system logger, and the Windows Event log service just to unit test some business code.

In addition to being able to test our code, we can also code to interfaces meaning that we don?t need the actual implementation until it comes time to actually perform the work. For example the project I?m currently working on is going to require to call out to web services and databases. These components are not built yet and won?t be for another month or so. I don?t want to halt the development of my app so I create service interfaces and repositories that will abstract these away from my system, allowing me to build a fully working (and tested) system (which just happens to use hard coded values for now). Later when those services appear I just build an implementation to talk to them and voila, my system is still working exactly the way it does today.

Okay, enough talk. Here?s the interface for our logging system. I?m borrowing from Rob?s approach by creating a folder called Infrastructure with a subfolder called Logging. In it I?ll create an ILogger interface that will let me write an information message (most logging systems have various levels of logging like Information, Warning, Errors, etc.)

image

And here?s my ILogger interface:

   1: namespace MvcStarter.Infrastructure.Logging
   2: {
   3:     public interface ILogger
   4:     {
   5:         void Info(string message);
   6:     }
   7: }

Next we need an implementation. We?ll create one for NLog. This is a simple class that implements ILogger and provides the Info method (along with the setup needed for NLog to work). Here?s the NLogLogger class:

   1: using NLog;
   2:  
   3: namespace MvcStarter.Infrastructure.Logging
   4: {
   5:     public class NLogLogger : ILogger
   6:     {
   7:         private Logger _logger;
   8:  
   9:         public NLogLogger()
  10:         {
  11:             _logger = LogManager.GetCurrentClassLogger();
  12:         }
  13:  
  14:         public void Info(string message)
  15:         {
  16:             _logger.Info(message);
  17:         }
  18:     }
  19: }

We create a private variable of type NLog.Logger and create it in our constructor using the LogManager from NLog. Then to write using NLog we just call the Info method on the class, passing it our message.

There are a lot of other methods we can call and add to our interface so later maybe we?ll extend that but this is enough to get you started.

One more thing is that the default config file that was installed with the package is just that, blank. You need to tell it at least what target to use and what rules to apply to each target. The entire config file is documented online but you can just uncomment the sample implementation. Make sure to match up the logger rule (Trace in the config file) with your method you?re calling in the implementation. I just changed the minLevel of the NLog config file from Trace to Info to match our code.

That?s all you need to have logging working but how do we call it? And how does Ninject fit in?

Back when we installed Ninject it created a file for us. Go back to your project and check out the App_Start folder. Expand it and you?ll see a new file there called NinjectWebCommon.cs

image

This sucker is responsible for kickstarting Ninject for you. If you watched Rob?s video or saw some tutorials on the net they talk about changing the base HttpApplication to a Ninject one. That?s one approach but with MVC 3 and the NuGet package this way is much simpler. There?s nothing for you to do except tell Ninject what dependencies you want to deal with and how to resolve them.

Open up NinjectWebCommon.cs and scroll down to the RegisterServices method. This is where you?ll specify you own interfaces and concrete classes so Ninject can do it?s magic.

With a single line we?re going to tell Ninject this:

   1: /// 
   2: /// Load your modules or register your services here!
   3: /// 
   4: /// The kernel.
   5: private static void RegisterServices(IKernel kernel)
   6: {
   7:     kernel.Bind().To().InSingletonScope();
   8: }        

What are we saying here? Simple. We?re telling Ninject to:

  • Whenever you see the ILogger interface needed (e.g. passed into a constructor of a class)
  • Resolve to the NLogLogger class
  • Make it a singleton (i.e. only do it once and reuse it over and over again)

We?re making our logger a singleton because we don?t need to start NLog every time we want to log a message. You can also specify other scopes (like by thread or on demand) but for logging a singleton works.

Oh yeah, that?s it to hook up your dependency injection engine. And logging is ready to go.

Let?s give it a whirl. Crack open the HomeController class and add a constructor that takes in an ILogger interface then using that interface, write out a message when the Index method is called (i.e. our home page is visited). Here?s the modified HomeController class:

   1: using System.Web.Mvc;
   2: using MvcStarter.Infrastructure.Logging;
   3:  
   4: namespace MvcStarter.Controllers
   5: {
   6:     public class HomeController : Controller
   7:     {
   8:         private readonly ILogger _logger;
   9:  
  10:         public HomeController(ILogger logger)
  11:         {
  12:             _logger = logger;
  13:         }
  14:  
  15:         public ActionResult Index()
  16:         {
  17:             ViewBag.Message = "Welcome to ASP.NET MVC!";
  18:             _logger.Info("Home page visited");
  19:             return View();
  20:         }
  21:  
  22:         public ActionResult About()
  23:         {
  24:             return View();
  25:         }
  26:     }
  27: }

We add an ILogger interface to the constructor. This trigger Ninject to figure out what implementation to grab (our NLogLogger one) and create it for us (or reuse it since we told it we wanted a singleton). Then we use that implementation in our Index() method to log a message.

Compile and run the app to visit the home page of your app and you?ll see this in your log:

   1: 2012-05-15 19:18:38.8471 INFO Home page visited

That?s it. You have a logging system you can call anytime (just inject the interface into the class, Ninject will take care of the rest) and your project is setup with dependency injection and you?re ready to go. Now you can just add additional interfaces as you need them.

The awesome thing here is that a) you can now mock or stub out your logging implementation and test it and b) replace that implementation with some other logger any time and your code will still just work.

That?s the power of dependency injection.

As a bonus piece of information, now that you have the dependency injection setup you can use it any time in case you?re in a pinch and don?t need/want to inject the implementation into your class.

Here?s how you can call the logger from your Application_Start method (found in Global.asax.cs) before any controllers are fired up:

   1: protected void Application_Start()
   2: {
   3:     AreaRegistration.RegisterAllAreas();
   4:  
   5:     RegisterGlobalFilters(GlobalFilters.Filters);
   6:     RegisterRoutes(RouteTable.Routes);
   7:  
   8:     DependencyResolver.Current.GetService().Info("Application Started");
   9: }

See that last line? DependencyResolver.Current.GetService will use whatever IoC you have configured and return the implementation of that interface.

Okay, that?s enough to get started. Again, I encourage you to watch Rob?s *entire* video of setting up a new MVC project. Even though the video is for MVC 2, there are still a lot of idea that hold water in MVC 3 and it?s a great learning too (and free too).

Enjoy!