Italian Agile Day 2010


And tomorrow I’ll be in Genova (Italy) for the 7th Italian Agile Day 2010.

I’m really looking forward to it. See you there… Winking smile

Advertisements

New “Cube”: new post, new blog engine, new website version.


My new post on this new blog engine (after Microsoft decided to shutdown Live Spaces), is about a new version of my company website (also if we’re still in beta, that means we’re trying to do something in the spare time).

So, enjoy it!

Technorati Tags: ,,

Dynamically create a LINQ query


LINQ (Language INtegrated Query) is one of the most powerful new features coming with C# 3.0, that allow to compose queries and access data through your programming language. LINQ has different benefits, and one of these is, for sure, to write type-safe queries using C# or Visual Basic (also with the help of the Visual Studio Intellisense).

But, there is always a “but”, sometimes also the coolest feature cannot be what we’re actually looking for.

One drawback on working with Linq could be that you need to build your query dinamically… but you can’t.

I was searching a bit around the net and in the C# 4.0 documentation/samples, I found a nice set of extension methods that allow Linq to overtake this problem: the LINQ Dynamic Query Library (actually searching a little bit better I found that this library was included also in the VS2008 SP1 examples, but this is another story Winking smile).

By importing this library in our projects we’ll be able to write a code like this:

   1: NorthwindContext nwContext = new NorthwindContext();
   2: var prods = from p in nwContext.Products
   3:             .Where("CategoryID=2 And UnitPrice>3")
   4:             .OrderBy("SupplierId");
   5: ...

and this will work in the same way of the following snippet:

   1: NorthwindContext nwContext = new NorthwindContext();
   2: var prods = from p in nwContext.Products
   3:             where p.CategoryId == 2 && p.UnitPrice > 3
   4:             orderby p.SupplierId
   5:             select p;
   6:  
   7:         ...

So.. what is the point? Nerd smile

Quite simple… Let’s try to figure out if we need to filter a set of data but we don’t know yet how to do it, maybe cause we need some input from the user, like in most business analysts applications. Using this library we will be able to take advantage of all LINQ’s features and power without loosing flexibility and usability.

Ok, ok I know.. this looks too much general and also a “bit” marketing oriented.

An actual scenario where this library is really useful, it’s when you’re working with the jQuery Grid plugin and a Asp.Net MVC (or Asp.Net website).

In the following little javascript snippet you can see how to put a jQuery Grid in your website:

   1: <script type="text/javascript">
   2:     jQuery(document).ready(function(){ 
   3:       jQuery("#list").jqGrid({
   4:         url:'/MyData/GridExample/',
   5:         datatype: 'json',
   6:         mtype: 'GET',
   7:         colNames:['Id',... ... ],
   8:         colModel :[
   9:           {name:'Id', index:'Id', width:40, align:'left' },
  10:           ...
  11:           ...],
  12:         pager: jQuery('#pager'),
  13:         rowNum:10,
  14:         rowList:[5,10,20],
  15:         sortname: 'Id',
  16:         sortorder: "desc",
  17:         viewrecords: true,
  18:         imgpath: '/scripts/themes/custom/images',
  19:         caption: 'Grid Test'
  20:       }); 
  21:     }); 
  22: </script>

and here is the part of the GridExample method where the use of the Linq Dinamiyc Query Library is really useful:

   1: public ActionResult GridExample (string sidx, string sord, int page, int rows)
   2: {
   3:     MyTextContext context = new MyTextContext();
   4:     int pageIndex = Convert.ToInt32(page) - 1;
   5:     int pageSize = rows;
   6:     int totalRecords = context.Count();
   7:     int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
   8:     var testEnts = context.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
   9:  
  10:     List<string[]> lista = new List<string[]>();
  11:     foreach (TestEntity te in testEnts)
  12:     {
  13:         string[] lstr = new string[8];
  14:         lstr[0] = te.IdEntity.ToString();
  15:         ...
  16:         string str;
  17:         if(te.MyNullableDate.HasValue)
  18:             str = te.MyNullableDate.Value.ToShortDateString();
  19:         else 
  20:             str = String.Empty;
  21:         ...
  22:         lista.Add(lstr);
  23:     }
  24:  
  25:     var jsonData = new
  26:     {
  27:         total = totalPages,
  28:         page = page,
  29:         records = totalRecords,
  30:         rows =  (from l in lista
  31:             select new
  32:             {
  33:                 i = l[0],
  34:                 cell = l
  35:             }).ToArray()
  36:     };
  37:     return Json(jsonData);
  38: }

I’m testing now this library and I’m really looking forward to see it integrated in the next LINQ realease.

 


[Silverlight] Discoverable RIA Services


When they officially released the Silverlight RIA Services, I think they made also a smart move: they changed the name in WCF RIA Services. Why smart? ‘Cause I think this should help people to remember that after all, under the hood, we’ll always find our big friend: the Windows Communication Foundation (WCF for friends. 😉

So, keeping this in mind, there are no reasons why the services can be only reached by my Silverlight Client application (ok, I have all the proxy code generation and all the other stuff for free, but… I don’t care 😀 ). And with a little trick we can allow the RIA Services to expose data with OData, SOAP and JSON format, allowing to be reached from any kind of client (from WinPhone 7, to a java client).

To achieve this we need to add a reference to an assembly and add three rows in our config file.

In our RIA Services project we need to add a reference to the Microsoft.ServiceModel.DomainServices.Hosting assembly (from the WCF RIA Serivces Toolkit) and, in the web.config, the <system.serviceModel> section should look like this:

   1: <system.serviceModel>
   2:     <domainServices>
   3:       <endpoints>
   4:         <add name="OData" type="System.ServiceModel.DomainServices.Hosting.ODataEndpointFactory, System.ServiceModel.DomainServices.Hosting.OData, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
   5:         <add name="Soap"  type="Microsoft.ServiceModel.DomainServices.Hosting.SoapXmlEndpointFactory, Microsoft.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
   6:         <add name="JSON"  type="Microsoft.ServiceModel.DomainServices.Hosting.JsonEndpointFactory, Microsoft.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
   7:       </endpoints>
   8:     </domainServices>
   9:     <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  10:   </system.serviceModel>

Now to call our services we need only to navigate to the right address that we’ll compose in this way:

http://<host web address>/<services dir>/[namespace]-[typespace]-[classname].svc

eg:

http://localhost:52878/Services/BusinessApplication1-Web-DomainService1.svc

http://localhost:52878/Services/BusinessApplication1-Web-DomainService1.svc?wsdl

http://localhost:52878/Services/BusinessApplication1-Web-DomainService1.svc/OData/

where Services is the directory where I’m hosting all the RIA Services, and BusinessApplication1.Web.DomainService1 is the complete typename of our web service class, where we simply substituted the . (dot) with the –.

And.. that’s all, folks!!!


P & P Windows Phone 7 Developer Guide


A little post to help me to save this important link: the home page of the Developer Guide community site for the upcoming Windows Phone 7 from the Patterns & Practices guys.

Windows Phone guide on Codeplex

 


[Silverlight] A little work-around for the BusyIndicator control’s bug


I’m really starting to use Silverlight more and more and trying to propose to my customers every-time I can. With Silverlight 4 I also think that this platform becomes quite stable and power-full, ready to move the business application to a new level.

I was also enjoying a bit more of UI developing taking advantage of the Silverlight 4 Toolkit.. but here I found a little problem. I don’t why but after opened a page I saw my CPU indicator that became crazy (close to 100%). I started to debug a bit, I used Fiddler to see if I made some mistake in the communication between the client and the back-end server, but nothing.

After some tries, I found what was the problem: a little bug on the BusyIndicator control. I removed it and all the things went right. But I liked it and I found it useful inside my application so I decided to make a little workaround founding that the actual problem is not on the control itself but in the ProgressBar control animatiom: also after switching off the animation it looks like is not enough and the only way to let the animation leave the CPU is to disabled it.

My little work around is a simple child window with a progressbar inside like this XAML snippet:

<controls:ChildWindow x:Class="…"
            …    
<Grid x:Name="LayoutRoot" Margin="0">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <ProgressBar Grid.Row="0" Name="progressBar1" Height="30"/>
    </Grid>
</controls:ChildWindow>
and this is the C# code behind where I disabled the animation to avoid the CPU’s overload
    public partial class BusyChildWindow : ChildWindow
    {
        public BusyChildWindow()
        {
            InitializeComponent();
            this.progressBar1.IsIndeterminate = true;  // activate the animation...
            this.Close();
        }

        private void ChildWindow_Closed(object sender, EventArgs e)
        {
            this.progressBar1.IsIndeterminate = false;
            this.progressBar1.IsEnabled = false;
        }
    }
}

 

And that’s it…

Technorati Tags:


Just published my first presentation’s slides


I just uploaded to my public Skydrive space the slides that I used during the third meeting inside the Torino Technologies Group,  a (quite) brand new community about .Net and Microsoft technologies.

The presentation is about Agile Methodologies, Scrum and so on. I hope you like it.

http://cid-b706e2daf7520268.skydrive.live.com/embedicon.aspx/MyDoc/Teamwork0AgileMethodologies.pptx

Or if you prefer you can download if from slideshare:

Check it out.


Running Asp.Net MVC 1.0 with .Net Fx 2.0 (or, when Aruba.it SUCKS!)


Sometimes I really don’t understand how the providers manage their services. I recently bought an hosting service from Aruba.it, an italian provider, and I always thought that the only good thing about this provider was that it is quite cheap. But going through its web-site I found a lot of updates so I started to change my mind. Big mistake… Yes it’s true, they updated all and now they support .Net 3.5. The problem is that we’re now really close to the .Net 4.0 release and Microsoft released the 3.5 SP1 quite a time ago. They also released a big news (and a great improvement IMHO) in the web development using the technologies from Redmond: the MVC framework.

So I was a little bit too much hopeful, and as usual in these cases after all I’ll find a “nice” surprise, like this time: Aruba.it supports .Net 3.5 but it looks like it’s not the same for the SP1 and for sure there is no support for the MVC Framework (too much work guys?? so difficult to ADD, not to replace, a couple of f***ing officially released assemblies to the GAC, right???). I also tried to call the customer care, but… nothing changed: they answered me with a two rows e-mail (ok, now I’m quite sure: those guys are super busy or super lazy..) in which they wrote that they don’t support MVC (thanks, I just figured it out by myself).

In any case, all this long introduction to say what? Not more than a couple of things: one, IMHO, I think the world is full of some providers better than this, and the other one is that I tried to take advantage of the architecture of .Net and I was able to let Asp.Net MVC run on an Asp.Net 2.0 web-site! COOL!!!

Ok. So.. first let’s try to figure out how we can do it: all the new .Net releases are still compatible and based on the 2.0 Fx… something like a little onion. 😉 This little thought was also endorsed by my little search on the Internet (or if you prefer you can say that I Bing(ed) or Google(d) a bit around) and I found this good article on the MSDN library: How to: Deploy an ASP.NET MVC Application, in which they confirmed what I was thinking about and they also list, in a bit more official way smile_wink, the assemblies that we will need to accomplish our “porting” (not all actually, but this will see it better after).

Now we need to do something for real, so let’s open Visual Studio and go..
First of all we need to open the new project dialog box, select the Web project types and then the “ASP.Net MVC Web Application”. We follow all the instruction from the wizard, creating also the Test project, and then our new ASP.Net MVC web site will be ready to run, but not to deploy remotely.

Running the project all the things are working.. on our machine (“but it works on my machine!”). smile_teeth

The application now is running on .Net 3.5 and on the local web server, that means that it won’t work on our lazy internet provider structure.convertnet2[1]

The first step to do now is to convert all our stuff to the old .Net version: so we have to open the Properties of the project and we can simply do it double clicking the Properties section just under the project folder in the Solution Explorer, then we have to select the right version (2.0) in the Target Framework, just like in the picture.

This is something that Visual Studio won’t like it, but we have to not care so much about it, at least this time, so we answer Yes to both of the questions that it will show up, also to the last one that looks a little bit “dangerous” and now our project it’s ready to be deployed as a .Net 2.0 Web Application but it’s not yet a .Net 2.0 ASP.Net MVC Application. We need some other steps to do that.

Now there are a couple of steps to do to finally let our MVC Application run under .Net 2.0.

We have to manually add the MVC assemblies to our project and to do this we can actually choice between two ways: the easiest way is to locate the 3 MVC assemblies (System.Web.MVC, System.Web.Routing and System.Web.Abstraction) and set that we want to copy them locally (setting the Copy Local property to true in the assembly reference properties) so after when we’ll deploy the project Visual Studio will automatically add them to our deployed application “bin” folder, or the other way is to delete the reference of those 3 assemblies from the project then physically copy them to the bin folder from the GAC folder (that is in C:WindowsMicrosoft.NetassemblyGAC_MSIL… and we have to access this folder with a user with administrator level) and then from Visual Studio directly reference these assembly (Add Reference –> Browse). We didn’t finish yet our job with the assemblies: we’re still missing one that we need to add to our project, cause some parts of the MVC Fx actually refer to it, that is the System.Core.DLL (also this is to locate inside our GAC folder). So this is the list of all the assemblies that we need to manually reference inside our project:

  • System.Web.Mvc

  • System.Web.Routing

  • System.Web.Abstractions

  • System.Core

    Ok we almost finished. If we’ll try, our project should be able to compile but it won’t work properly. To completely accomplish our task we need also to make some code modification:

    • in the Global.asax file, in the root folder of our web application, we need to modify the routing rules simply adding an “.aspx” every time we refer to a particular Controller and make a particular rule for the Home page like in the following snippet
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
     
            routes.MapRoute(
                "Default",
                "{controller}.aspx/{action}/{id}",
                new { action = "Index", id = "" }
              );
            // specific route for the home page
            routes.MapRoute(
              "Root",
              "",
              new { controller = "Home", action = "Index", id = "" }
            );
        }
     
     
        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }        
    }
    • in all the .aspx files (and the Site,Master too) we have to change all the Html.ActionLink and Html.RenderPartial methods to something like this:
    <% System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(this.Html, "LogOnUserControl"); %>
    
    ...
    
    <li><%= System.Web.Mvc.Html.LinkExtensions.ActionLink(this.Html, "Home", "Index", "Home")%></li>
    
    <li><%= System.Web.Mvc.Html.LinkExtensions.ActionLink(this.Html, "About", "About", "Home")%></li>

    And after this last steps, rebuilding all the project we will be able to host our ASP.Net MVC application in our Asp.Net 2.0 web space, also if you made a so poor choice about the hosting provider like I did!

     

    Technorati Tags: ,


  • Uhmm.. Now it’s official


    I knew it very well, that was my former team, but now it’s official also for all the partner and not.

    Microsoft Dynamics Mobile has been discontinued

    So.. no comment, it’s  better!

    Technorati Tags: ,

    How to get the Public Key Token of a signed assembly inside Visual Studio


    Developing with the .Net Framework quite often we have to sign our assemblies and sometimes it could be nice also to know the Public Key Token from our own signed assembly.

    To do that we have to use the “sn.exe” utility, provided with the .Net Framework and located usually in “the C:Program FilesMicrosoft SDKsWindowsvX.XXBin" folder. The problem is that we have to use the command prompt (the one provided with Visual Studio not the normal one), add some parameters to the command line and this is, I know, something that a lot of people won’t really like it (me too actually). It’s not our fault, but Visual Studio really spoiled us so why don’t try to find another way to read the Public Key Token of a signed assembly from inside the IDE?

    Not so a big deal. A couple of step and we can do it. I think all the developers used at least once the “Tools” menu’ inside Visual Studio. Quite close to the bottom of this menu’ list, there is a link that allow us to customize the tools listed in our own menu’: the “External Tools…” one.

    http://cid-b706e2daf7520268.skydrive.live.com/embedphoto.aspx/Images/getTokenMenu.PNG

    Clicking on this Visual Studio will open a new window like the one showed in the following picture and it will allow us to enter our data to set up the new link that we want to add to menu:

    http://cid-b706e2daf7520268.skydrive.live.com/embedphoto.aspx/Images/getTokenTools.PNG

     

    As shown in the picture, the more important data are the arguments:

    • -T: ask the sn utility to actually display the token
    • $(TargetDir)$(TargetName)$(TargetExt): the Visual Studio variables that will point to our project output
    • enable the check “Use Output window” to enable Visual Studio to show the output result from the command in the output window

    And we done it!

    Now we can develop our own signed assemblies and we could expect a result like this after invoking our new link:

    http://cid-b706e2daf7520268.skydrive.live.com/embedphoto.aspx/Images/getTokenResult.PNG