The official Fatica Labs Blog! RSS 2.0
# Monday, 16 January 2012

Here below a list of tools and libraries I consider necessary to carry on my USB key in order to be operative everywhere in a very little time:

  1. SharpDevelop
  2. NHibernate
  3. Caliburn(Micro)
  4. NInject
  5. Kaxaml
  6. SQLite
  7. Rad Software Regular Expression Designer
  8. ILSpy
  9. FlyFetch
  10. log4net

SharpDevelop

Is probably the single OS replacement for MS Visual Studio. Install and start to using it in term of minutes thanks to xcopy deploy. It reads projects in the same format of the original one ( since it uses thestandard framework libraries for reading/writing projects ).

NHibernate

If you can see a way to model the DB you want to use, then NH is probably the best OR/M existing in the .NET environment. As soon you have some confidence with it, it is very easy to start modeling our objects, expecially with the 3.2.x version that does not require anymore to write hbms.

Caliburn Micro

If you write UI using some XAML dialect ( WPF/SILVERLIGHT/WP7/ the new coming Win8 ) and you like MVVM, you have to look at it. Very easy to boostrap, with coroutine support embedded, I would like to use it even for an Hello World application Smile

NInject

An easy to learn DI framework. Easy and very intuitive to configure, it has some function to allow multiple components to be injected as array, and to configure dependencies from external modules. I choose it not only, but also for the wonderful home page Smile

Kaxaml

A pad to learn and test XAML, with intellisense and preview as you type. Like xamlpad, but much better.

SQlite

An embedded file based database. It handles concurrent access consistently, easy to interface with NHibernate. Unfortunately it is a native solution, so it works only in fully trusted environments.

Rad Software Regular Expression Designer

there is a lot of regex testing tool, but this is the one I use, so…

ILSPy

The open source replacement for reflector, It comes from the same team who create SharpDevelop. It has all the features the standard reflector has, but not yet a real plugin environment.

FlyFetch

Is the tool I use when I need to display in UI a very long recordset, and I want to page it without rewrite every day the same code.

log4net

To use in all application, even the simplest: logManager.GetLogger(GetType()).Info(“Hello World”); Smile It is probably the .NET logger existing from the early days, with a lot of appenders already written and tested.

 

So this is my list, of course, another survival pre condition is having an internet access, and the StackOverflow help Smile. There is no NUnit nor a Mocking library ( as for example, Moq) since both can be replaced by custom test and mocks, but of course, if there is still place on the USB Winking smile

Monday, 16 January 2012 19:39:06 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
CodeProject | Programming

# Wednesday, 11 January 2012

In the WP7 library there is an interesting utility class: CivicAddressResolver. This class should help us in doing the so called Reverse GeoCoding: given a coordinate in term of latitude and longitude we want a readable address near to that place. Unfortunately there is a bad surprise: as we read in the documentation, “this method is not implemented in the current release”. So what if we need something like this, waiting for the fully fledged implementation? Since the class implements the interface ICivicAddressResolver, we can provide our own implementation, for example based on google maps geocoding api. So I created a little project and a demo application. The main class implementing the resolver is GMapCivicAddressResolver.AddressResolver. You can use it in an application awaiting for the definitive implementation, with the limitation that this implementation returns something meaningful just in the field CivicAddress.AddressLine1. Another limit is that you can’t call the blocking version of the resolve method,in any case this should not be a problem since the asynchronous call is the one to prefer.  Please check out the project here on Bitbucket. Here below a screenshot of the running app, showing a totally random address in Rome:

cv1

Wednesday, 11 January 2012 21:00:53 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
CodeProject | WindowsPhone

# Saturday, 17 December 2011

I would like to present here a little argument verification library that does not require you to type any string for specifying the name of the parameter you are checking. This lets the library faster to use, not intrusive in the actual method code, and refactor friendly. As a bonus you can use it by just embedding a single file. We can see below an example, just to get immediately to the point:

As we can see, there is no magic string at all. All the argument name are guessed thanks to the metadata contained in the linq Expression we use. For example the method at line 14 if called with a null value will report:

Value cannot be null.
Parameter name: arg1

The same happens to the more complex check we do at line 46, when we write:

Contract.Expect(() => array).Meet(a => a.Length > 0 && a.First() == 0);

We have a complex predicate do meet, described by a lambda, standing that the input array should have first element zero, and non zero length. Notice that the name of the parameter is array, but we need to use another name for the argument of the lambda ( in this case I used ‘a’ ), the library is smart enough to understand that ‘a’ actually refers to array, and the error message will report it correctly if the condition does not meet. Just to clarify, the message in case of failure would be:

Precondition not verified:((array.First() == 0) AndAlso (ArrayLength(array) > 1))
Parameter name: array

Well it is not supposed to be a message to an end real user, it is a programmer friendly message, but such validation error are supposed to be reported to a developer ( an end user should not see method validation errors at all, should he ? )

Well Meet is a cutting edge function we can use for complex validations. Out of the box, for simpler cases we have some functions too, as we can see on the IContract interface definition:

An interesting portion of the codebase proposed is the one renaming the parameter on the lambda expression, to achieve the reported message reflect the correct offending parameter. It is not so easy because plain string replacement would not work:we can have a parameter named ‘a’, seen in any place in the expression string representation and a plain replacement would resolve in a big mess, furthermore Expressions are immutable. So I found help on StackOverflow, and a reply to this question solved the problem, let see the “Renamer” at work ( Thanks to Phil ):

Basically is a reusable class that take the new name of the parameter and returns a copy of the input expression with the (single) argument changed.

To improve the library or just use it, please follow/check out the project on Bitbucket, suggestions and comments are always welcome.

Saturday, 17 December 2011 13:24:25 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
CodeProject | CSharp | Linq | Recipes

# Friday, 09 December 2011

It is easy to interface the Google data API by using the library Google  supply, for .NET too. Let’s have an example of acceding the contacts information:

 

This class requires the following references:

  • Google.GData.Client
  • Google.GData.Contacts
  • Google.GData.Extensions

All these are available in precompiled form after installing the Google Data API setup. Of course the complete API contains method to interact with a loot of good things in addition:

  • Blogger
  • Calendar
  • Calendar Resource
  • Code Search
  • Contacts
  • Content API for Shopping
  • Documents List
  • Email Audit
  • Email Settings
  • Google Analytics
  • Google Apps Provisioning
  • Google Health
  • Google Webmaster Tools
  • Notebook
  • Picasa Web Albums
  • Spreadsheets
  • YouTube

The only missing point: there is not (yet) a version for WP7, and the current codebase is not easy to port. Another missing point is that the API does not support OAuth2, that is indeed supported by the Google platform itself.

Friday, 09 December 2011 12:34:07 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
CodeProject | CSharp | google-api

# Saturday, 03 December 2011

Since I had an amazing number of views on my previous article about my chess engine rewriting and publishing it OS, I decided to extend a little bit more the discussion. Unfortunately this is not a brand new argument, since there is a lot of good articles on the web, but in order to me some missing point exists: if you start reading the code of a fully fledged engine, even in C#, you will probably get lost in a big mesh of heuristics and optimizations without really get what’s really happens. By contrary, if you read the literature you will find a lot of pseudo code but nothing really working, and something that is a detail for the pseudo code, can be really difficult to implement in real life just to see what’s happens. Here we will show how a plain algorithm from the literature behave in it’s essence, solving a real chess problem. Of course this will not works in a real playable engine but it has a big advantage: it is *understandable* and can be the starting point to optimize, so by gradually reaching the fully fledged engine we eventually get each single steps better.

Which algorithm use ? Chess engines uses some flavor of an algorithm called MiniMax, with an immediately ( even for a simply case ) necessary optimization called Alpha Beta Pruning. This is what we will show by example here below. So what exactly is MiniMax ? It is an algorithm that works by producing a tree of the possible games in which each node is a possible status and each arc that produce the transaction is the move ( the decision ) the player can do. At each node we can weight the result of the player Mini and the player Max, Mini win if that value is little, and Max win when the value is high, so Mini want to *minimize* a score function, and Max want to maximize it. Since chess is a symmetric game, we can say that a good result for Mini is a bad result for Max and vice-versa. This lead us to a single evaluating function, with sign changed depending on the player. This simplification is referred in literature as Negamax.  Lets see an example of a game tree, by starting from a specific chess position (2rr3k/pp3pp1/1nnqbN1p/3pN3/2pP4/2P3Q1/PPB4P/R4RK1 w - - 0 0):

     image

The position is our root node, and a portion of the resulting tree is:

image

Well it is a portion, its impossible to draw it all even for just a few play, it is even impossible computationally enumerate all nodes eve for a few ply, because of the high branching factor chess has. The branching factor is a measure on how many nodes are generated from a root, in other word, in chess is an average count of the possible moves a board has. For chess this number is about 35, and so we have, for each ply an exponentially increasing number of nodes like 35^n, where n is the number of ply. Let’s consider too why it is so important having a correct move generator: just a single wrong move somewhere will mess an enormous amount of nodes.

 

 

 

 

 

average number of nodes per ply in chess:

1 35
2 1225
3 42875
4 1500625
5 52521875
6 1838265625

Of course this is just average data, can be even worst in some situation. You can always know the exact count of nodes by using the perft test contained in the same project, but I suggest you to start with a 5/6 ply and see how long it takes befor tryng 8/9 ;)

So some optimization is necessary since such an exponential explosion can’t be managed with any kind of CPU. The only game I know in which generating all the tree is probably tic-tac-toe, but for chess is absolutely not the case. So we introduce alpha beta pruning in our algorithm, but how can we prune some nodes despites to other? let’s have an example with the same position shown above, and suppose we move the Knight in c6 ( Nxc6), the black can catch it with the rock, or with the pawn, Rxc6 and  bxc6 respectively. In an alpha beta pruning scenario as soon such a move refute the white move, ie the move give a gain better than the current opponent better score, the search stops at that level. This is an enormous gain in term of performance, the only draw back is that we have just a lower bound of the actual score of a position, so we don’t really know if we can do better, but we stay on the fact that we can do enough. How this is achieved by code? Let see what we need:

  1. A way of score the position: material balance is more than enough for this sample.
  2. An algo that traverse the algo keeping track of the best score for a player ( alpha ) and for the opponent ( beta )
  3. A way to sort the move ordered so the “strongest” are seen first, the weak later.

Point 1 is easy, just give some value to each piece type, and sum it considering positive the white if the white is the player or vice-versa. The algorithm we will see soon, but the tricky part is the 3). As you probably guess, having good move navigated first, increment the changes of stops the search ( the so called beta-cut off ) with a dramatic performance increment. So the first real heuristic that will give your engine strength and personality is that function. In the example we will use a very basic ordering strategy, that put all promotion and good capture in front, all the “other” moves in the center, and the bad captures at the end. ( a good capture is one in which the catcher has less value or equal to the captured ).

So let’s show the “Vanilla” algorithm. Why “vanilla” ? because a real chess engine extends a lot this concepts,and add lot of other functionality to make the engine responsive, but the one shown do the job and it is ( hopefully ) as clear as understand as the pseudo code, whit the difference that it is working code you can inspect and debug and use for learn:

The interesting portion are the Search function. I used delegates to extract the non algorithm related code so it appear simple as pseudo code, but it is working. Then I wrote a test case using this search function here:

 

[TestMethod]
       public void TestQg6()
       {
           using (var rc = new RunClock())
           {
               var engine = new SynchronEngineAdapter(new SimpleVanillaEngine(7),
                   "2rr3k/pp3pp1/1nnqbN1p/3pN3/2pP4/2P3Q1/PPB4P/R4RK1 w - - 1 1"
                   );
               Assert.AreEqual("g3g6", engine.Search());
               Console.WriteLine("Elapsed milliseconds:" 
                   + rc.GetElapsedMilliseconds());
           }
       }

 

 

The code of the search is called by the class SimpleVanillaEngine, this is just a wrapper that inject the proper move generation  calls and evaluation/ordering functions. That test works in about 40 sec on my laptop, that is unacceptable for a real engine, but satisfying because… even if the code is simple, it report the correct answer, why can I say so ? because the board I proposed is some sort of standard test  for chess engines. Please note that the correct move Qg6 is reported in the test as g3g6 since our engine does not yet supports the human algebraic notation, but the move as you can guess is equivalent. This case is important because it show how an apparently wrong move can lead in a win if we look deep enough.

Well if interest in the project continue as it started, I will blog again on how to move this in a real engine.

Saturday, 03 December 2011 13:03:44 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
Chess | CodeProject | CSharp | Games

# Sunday, 27 November 2011

In this post Ayende talk about when we should use NHibernate and he point that in almost read only scenario other approach can be preferred. I think he forget to mention the fact that even in such a scenario we can leverage a very reliable multi DB abstraction offered by NH that can help us if we think to target different data platforms. In order to me we should say that the point of decision to choose fro NH to another approach is the ability to create an entity model, and an entity model helpful to our objectives. This can also depends on how much we are confortable with the technology. Another interesting extension of the argument is, if we should not  use NH what can we use instead ? Well not for sure EF, since the reason of renounce to NH in a project should be the same to avoid EF. The NOSql solutions works only if we can completely avoid a relational database, and the pure crude ADO.NET is just ugly. An option could be Dapper,  a lightweight OR/M ( not exactly an OR/M, but almost ) that remove all the ugliness of ADO.NET and does not change the performance in comparison on using the manual data access approach. I did not tried it myself, but one of its users is stackoverlow, so this should be by itself a guarantee.

Sunday, 27 November 2011 08:56:37 (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback
CodeProject | NHibernate | ORM

My Stack Overflow
Contacts

Send mail to the author(s) E-mail

Tags
profile for Felice Pollano at Stack Overflow, Q&A for professional and enthusiast programmers
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2019
Felice Pollano
Sign In
Statistics
Total Posts: 157
This Year: 0
This Month: 0
This Week: 0
Comments: 127
This blog visits
All Content © 2019, Felice Pollano
DasBlog theme 'Business' created by Christoph De Baene (delarou) and modified by Felice Pollano
Nike Winkels Nederland Outlet Nike Nederland Store Outlet Nike Nederland 2015 Outlet Nike Outlet Online Nike Sneakers Outlet