Categoría: dotNet

Formas de ejecución de FxCop

Ejecución Manual

Si uno utiliza la versión standalone de FxCop, tiene en principio 2 alternativas: utilizar la interface de gráfica o la de línea de comandos.Pero hay que tomar en cuenta que mientras la interface de linea de comandos solo puede ejecutar análisis, la interface gráfica además de ejecutar análisis, permite crear proyectos de FxCop (.fxcop) con configuraciones específicas que incluyan conjuntos particulares de reglas y algunos otros parámetros específicos para la ejecución del análisis. Al mismo tiempo ocurre que la interface de línea de comando soporta  algunos opciones que la interface gráfica no, por ejemplo rulesets (.ruleset)

Otra forma de ejecutar análisis FxCop en forma manual es si uno cuenta con una version de Visual Studio que tenga la funcionalidad de Code Analysis incorporada. Es ese caso, pueden configurarse las reglas a aplicar desde las propiedades del proyecto y luego disparar el análisis desde el menú contextual del proyecto.

Ejecuación integrada a la compilación

Si uno cuenta con una versión de Visual Studio con la funcionalidad de Code Analysis incorporada, entonces también tiene opción de modificar los archivos de proyecto (.csproj) para que se dispare el análisis de código en cada compilación.

Ejecución con MSBuild

Esta opción es mi prefedida pues es independiente del Visual Studio lo cual la hace ideal a la hora de utilizar un build server. Básicamente consiste en generar un build script de MSBuild con una tarea de que se encargue de invocar a utilitario de linea de comando de MSBuild. Tiene un pequeño issue pues ni MSBuild ni FXCop proveen una tarea para ejecutar FxCop dentro de un script de MSBuild, por ello es necesario utilizar MSBuildExtensiónPack. Los interesado en esta opción pueden darle un vistazo a este build script que muestra un ejemplo (ver el target RunCodeAnalysis).

FxCop y Visual Studio

Continuando con la cuestión de análisis de código, quiero dedicar algunas líneas a estas dos herramientas. Como mencioné anteriormente,  Visual Studio ha incorporado nativamente a FxCop, pero he aquí algunos detalles curiosos:

  • No todas las ediciones de Visual Studio incorporaron FxCop, en particular las ediciones Professional no lo incorporaron hasta la version 2012 (nótese la diferencia entre version: 2008, 2010, 2012, etc  y edición: personal, professional, ultimate, etc).
  • Dentro de Visual Studio no hay ninguna mención a explícita a FxCop, sino que en los menús figura como Code Analysis, pero internamente es FxCop (pueden verse los assemblies dentro de la carpeta de Visual Studio).
  • Aún es posible descargar FxCop y utilizarlo de manera independiente al Visual Studio.
  • El FxCop independiente y el incluido en el Visual Studio no son exactamente lo mismo. Entre las diferencias hay algunos conjuntos de reglas adicionales que vienen con Visual Studio que no estan en el FxCop independiente.

Los puntos anteriores hacen que dependiendo de la versión específica de Visual Studio con la que uno cuente, la forma ejecutar el análisis de código sea diferente. en próximos post daré más detalles sobre esto.

Análisis de Código en .Net

Al hablar de análisis de código en .Net es necesario diferenciar entre Source Analysis y Code Analysis.

Con Source Analysis nos referimos al análisis del código fuente escrito por el programado (típicamente en C#) el cual se realiza con la herramienta StyleCop.

Con Code Analysis nos referimos al análisis del byte code (MSIL) generado como resultado del proceso de compilación. La herramienta para esto es FxCop.

Ambas herramientas funcionan en base a un conjunto de reglas que pueden personalizarse e incluso extenderse. Si bien estas herramientas trabajan sobre distintos artefactos y tienen distintos objetivos, hay ciertos puntos en los que se superponen. Para entender esto analicemos 3 situaciones “incorrectas”:

  • Una clase escrita en C# nombrada todo en minúsculas, es una situación que seria detectada por StyleCop pero no por FxCop
  • Una clase que oculta un método declarado en una clase base, es una situación que será detectada por FxCop, pero no por StlyeCop
  • Un método con 20 parámetros, es algo que puede ser detectado tanto por StyleCop como por FxCop

Inicialmente ninguna de estas dos herramientas venia integradas con Visual Studio y debian ser descargadas e instaladas por separado. En la actualidad StyleCop continua en esta situación, pero no FxCop, que fue incorporado nativamente a Visual Studio en la versión 2008 (o puede que sea 2010, no estoy seguro).

Continuará…

Visual Basic migration

One more time this morning I have been asked about VB6 to VB.Net migration. I have my opinion about this topic.

If you have a VB6 application that is working well and that maintainance is relativaly easy, then, why do you want to migrate? Just because .net is cool?, no that can’t be a reason. The reason that I have started hearing these days is: “Microsoft won’t give us support for VB6″. Ok, that is a good reason, but there is still another questions to be answer:

A) Do you want the same application (from user perspective and from technical perspective) running in a new platform?

or

b) Do you want to take advantage of the capabilities of the new platform?

If you answer is B, then I most of the cases you don’t need a migration, you need to build a new system, maybe you can reuse some assets like database schema, some stored procedures, etc.

But if your answer is A, then there are some useful resources you can count on. First of all lets hear the voice of Patterns & Practices Group at Microsoft: Guide for upgrading VB6 applications to VB.Net and VB6 to VB.net upgrade assessment tool. I think these resources are a good starting point to understand the implications of the epic.

There also some interesting materials provided by Artinsoft (a company specialized in software migrations) . They have developed a tool to automate the migration process and they have also written some articles about it: Design application migration strategy and some more specific ones.

Hope this help.

VS2008 extension for SharePoint 2007

Last week I started a development project based on SharePoint 2007 and for the first time for this kind of projects I am using Visual Studio 2008 and the corresponding extensions for SharePoint. Among other things, these extension add some projects templates. Yesterday I noticed that these project templates are class library projects, but with a particular behavior. When you right click on the project file there is a “Deploy” option, witch does not exist in the case of regular class library projects. At first I thought that it was because of some properties in the configuration of the project, but I checked it and there was…nothing. So I opened the project file with a text editor and I noticed that the SharePoint project file had the following additional line:

<ProjectTypeGuids>{593B0543-81F6-4436-BA1E-4747859CAAE2};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

It seems that this line is the magic item that adds the “Deploy” option in the VS project file menu. I will try to get some more information about this curiosity.

Error handling in Web Services (ws-part 4)

This post wasn’t part of the original series, but I have decided to add it because of a project I am working on these days.

Most of the times I have been involved in the server side of web services, developing web services, but in this opportunity I am consumer of web services.

When reviewing the technical specs of the web services I have to consume I found that each web service returned a complex type that contains the following fields:

  • Result: an integer that represents the result of the invocation, (1) successful invocation, (2) Invalid parameters, (3) Internal service error, and so on.
  • Errors: in case the result be (2) it details the name of the parameters that are not valid.
  • Data: the business information expected as the result of the invocation.

This approach is not bad, but I feel it like been reinventing the wheel. Maybe it is because of my object-oriented programming background. I am used to use exceptions to handle errors. Most of the technologies that give support to soap protocol provides a way to work  with exceptions to manage errors.

When you call a web service and an error raises during the process, a soap fault message should be used to communicate the error. This fault message contains:

  • Code: that allows the fault to be classified in one of the following categories: VersionMismatch, MustUnderstand, DataEncodingUnknown, Sender and Receiver.
  • Reason: provides a human-readable explanation of the fault
  • Node: provides information about which SOAP node on the SOAP message path caused the fault to happen
  • Role: identifies the role the node was operating in at the point the fault occurred.
  • Detail: is intended for carrying application specific error information

No matter what technology you used to work with SOAP, most of them provide a class to represent a Soap Fault, that is typically called Soap Exception. In the case of .NET there is a SoapException. This way if you are using .NET to consume a web service using Soap, .NET will generate a proxy object for you to call the web service, when you call this service you should do it inside a try-catch block adding 2 catch statements one catch for a SoapException and another catch statement for a System.Net.WebException, in case that no connectivity can’t be established.

Something is changing…

Over the last two years some interesting things have happened in the .net community, among these things I would like to highlight the followings:

  • Greater interest in Domain Driven Design in contrast to the traditional MSDN Data driven way. This has stimulated the adoption of certain design techniques like DI and AOP among other.
  • As a consequence of the previous point there has been a wider adoption and diffusion of open source tools (beyond the P&P application blocks). Tools like NHibernate, Castle and Spring.Net have proven to be high quality products providing efficient solutions for typical problems in enterprise development. Event Microsoft (in a certain way) has recognized these facts, I think ASP.NET MVC is an example of this.
  • Massive adoption of agile development practices like continous integration, unit testing, pair programming and iterative development among others.

I think that evidence of these facts are the creation of the ALT.NET community and the publication of the excellent book “Foundations of Programming” by Karl Seguin.
I see this as great progress for the maturity of the community and the quality of its developments.

Ping Pattern for Services

En los últimos meses he estado trabajando mucho con servicios WCF. Si bien en el ambiente de desarrollo no he encontrado mayores inconvenientes, si he encontrado algunos a la hora de desplegar los servicios en un ambiente de test/producción (win2003). Dichos inconvenientes se han debido principalmente a las diferencias existentes entre web server de Visual Studio y el IIS 6, existente en Windows 2003.

En más de una ocasión me encontré con servicios que en el ambiente de desarrollo se ejecutaban perfectamente y al desplegarlos en un ambiente de test no. En algunas ocasiones la diferencia estaba en cuestiones de configuración de WCF, mientras que en otras ocasiones en cuestiones relacionadas a la funcionalidad del servicio en sí.

Para poder distinguir rápidamente la causal del error, decidí agregar a cada servicio una operación "Ping" que simplemente, sin recibir parámetro alguno, devuelva la hora actual. De esta forma una vez desplegado el servicio, invocando a la operación Ping yo podía descartar cualquier problema relacionado a la configuración de WCF.

[OperationContract]
public string Ping()
{
    return DateTime.Now.ToString();
}

Después de haber aplicado esta receta en reiteradas ocasiones ya la he agregado a mi librito de prácticas útiles para el desarrollo de servicios.

 

Enjoy it!

Embedded Resources

Sometimes your assembly on runtime depends on a file, like a image or a simple text file. To manage this file, you could store its location in the application configuration file, and then load your file by reading its location from configuration. Another option is to embedded the file as a resource in your assembly and then use the following code snippet to load it.

System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream(“NameOfTheFile”);

Lets see an example. Suppose an assembly called Model.dll that requires a file called TextFile.txt that is part of the same visual studio project. First of all you should define that file as an embedded resource (properties->build action = embedded resource). Then in your code, when you need to access this file you can load it this way:

System.IO.Stream fileStream = this.GetType().Assembly.GetManifestResourceStream(“Model.TextFile.txt”);
System.IO.StreamReader sr = new System.IO.StreamReader(s);
string fileContent = sr.ReadToEnd();
fileStream.Close();

Note that the name of the assembly has been appended to the of the file. One you have read the contents of the file, remember to close the stream