Archive for the ‘C#’ Category

SELECT N +1 problem

Check Ayende post on the topic: Combating the Select N + 1 Problem In NHibernate

Basically, when using an ORM like NHibernate or EntityFramework, if you have a one-to-many (master-detail) relationship, and want to list all the details per each master record, you have to make N + 1 query calls to the database, “N” being the number of master records: 1 query to get all the master records, and N queries, one per master record, to get all the details per master record.

More database query calls –> more latency time –> decreased application/database performance.

However, ORM’s have options to avoid this problem, mainly using “joins”.

 

Topic on StackOverflow: http://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem

Publish ASP.Net web application using MSBuild and PowerShell

PowerShell script to build and publish ASP.Net web application, applying web.config tranformations, using MSBuild.

Considerations:

  • This works for a solution having  7 projects: 1 web application project and 6 related others (DataAccess, BussinessLogic,DomainEntities, Utils, etc).
  • All of these projects run under .Net Framework 3.5.
  • I’m using Visual Studio 2010.
  • Finally I got a MSBUILD error MSB1008 (Only one project can be specified.), but anyway, build and publish worked.

PowerShell script

$build = "$env:windir\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe"
$SolutionPath = "D:\SOLUTION_PATH"
$SolutionFile = "SEGU.sln"
$WebProjectFile = "SEGU\SEGU.csproj"
$WebConfigTransform = "Build-Web.Config.xml"
$OutputPath = "D:\SOLUTION_PATH\PrecompiledWeb\SEGU"
& $build "$SolutionPath\$SolutionFile" /t:rebuild
& $build "$SolutionPath\$WebProjectFile" "/t:ResolveReferences;_CopyWebApplication;publish" /p:OutDir="$OutputPath\bin\" /p:WebProjectOutputDir="$OutputPath"
& $build "$SolutionPath\$WebConfigTransform"

Build-Web.config.xml

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<UsingTask TaskName="TransformXml" AssemblyFile="C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.Dll"/>
<Target Name="GenerateConfigs">
<Message Text="Transfom Config." />
<TransformXml Source="SEGU/Web.config" Transform="Web.Release.Config" Destination="PrecompiledWeb/SEGU/Web.config" />
<Message Text="Done Transfom Config." />
</Target>
</Project>

Web.Release.config

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="UserName" value="myuser" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
<add key="Password" value="password" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
<add key="SERVERNAME" value="192.168.10.14" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
<add key="urlServerReporting" value="http://RELEASE_SERVER/ReportServer" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
</appSettings>
<connectionStrings>
<add name="ConSEG" connectionString="Data Source=RELEASE_SERVER;Initial Catalog=Seguros;User ID=username;pwd=password" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
  <system.web>
  <compilation xdt:Transform="RemoveAttributes(debug)" />
  </system.web>
</configuration>

References:

Replicate VS2008 “Publish Web Site” from command line
How do I publish a Asp.net web application using MSBuild?
How to Publish Web with msbuild?
MSBuild Error MSB1008
MSBUILD : error MSB1008: Only one project can be specified. Switch: Education

Web config transformations

Web.config Transformation Syntax for Web Application Project Deployment
How to: Transform Web.config When Deploying a Web Application Project
Transform app.config and web.config
Web.config Transformation Tester
_CopyWebApplication with web.config transformations
Using MSBuild 4.0 web.config Transformation to Generate Any Config File
Config transformations outside of web app builds
Deploying an ASP.NET Web Application to a Hosting Provider using Visual Studio or Visual Web Developer: Web.Config File Transformations – 3 of 12

Continuous Integration: some posts

Martin Fowler: Continuous Integration is a software development practice where members of a team integrate their work frequently, usually each person integrates at least daily – leading to multiple integrations per day. Each integration is verified by an automated build (including test) to detect integration errors as quickly as possible. Many teams find that this approach leads to significantly reduced integration problems and allows a team to develop cohesive software more rapidly.

Some posts about Continuous Integration for further reading:

Continuous Integration
How and why do I set up a C# build machine?
Best Continuous Integration Setup for a solo developer (.NET) [closed]
Continuous Integration for Everybody

NHibernate: ORM for .Net

NHibernate website states [1]: “NHibernate is a mature, open source object-relational mapper for the .NET framework. It’s actively developed , fully featured and used in thousands of successful projects.”

I found a demo project by Dario Quintana [4] and updated it, combining it with Getting Started  Guide – Your first NHibernate based application [2].

The demo app on the Getting Started  Guide – Your first NHibernate based application [2] is a little bit buggy, but combining it with Dario Quintana demo I got to understand this NHibernate stuff.

Sample project with full source code here:

https://docs.google.com/open?id=0B7gHrdOYQf9yNmRzeHNjU201eFk

Some code example:

public class Employee 
{ 
public virtual int Id { get; private set; } 
public virtual string FirstName { get; set; } 
public virtual string LastName { get; set; } 
public virtual Store Store { get; set; } 
}

You can notice the following:

  1. Firstly, the Id property has a private setter, this is because it’s only NHibernate that should be setting the value of that Id.
  2. Secondly, all the properties are marked virtual; this is because NHibernate creates “proxies” of your entities at run time to allow for lazy loading, and for it to do that it needs to be able to override the properties.

References:

NHibernate [1]
Your first NHibernate based application [2]
Tutorial de NHibernate – Primeros pasos [3] by Dario Quintana (source code here) [4]
Domain Driven Design by Eric Evans [5]
Lazy Load
Using NHibernate with Visual Studio .NET
Fluent NHibernate
Fluent NHibernate in a Nutshell
fluent-nhibernate / src / Examples.FirstProject / Program.cs
Auto mapping
RavenDB vs MSSQL
Convention over configuration
The Data Driven Conspiracy
An Irrational Love of the Relational
Codd’s 12 rules
Domain-driven design
db4objects
C# Domain-Driven Design sample application
Domain Driven Design: Learning
Domain Driven Design Quickly: free E-Book
NHibernate Best Practices with ASP.NET, 1.2nd Ed.
An Overview of Unit Testing using Visual Studio Team System
Using NUnit in Visual Studio 2010

Data Access Architecture

While I’ve been reading about software architecture, design patterns and stuff like that, I’ve found Udi Dahan – The Software Simplist page as a valuable resource for learning.

Began reading about Data Access layers, options, ORM’s, Domain Models.

Check these references:

Pragmatic Architecture: Data Access
nhibernate posts by Udi Dahan
datasets posts by Udi Dahan
business-rules posts by Udi Dahan
Object Relational Mapping Sucks!
Dataset – O/R mapping rumble at TechEd MVP Dinner
Domain Model Pattern
First time here – Using Domain Models
AnemicDomainModel

Using COM+ Services in .NET

Full Source Code: here (VS 2010, VB, .Net 4.0)

Mainly based on: Using COM+ Services in .NET by Tim McCarthy, InterKnowlogy // Paul D. Sheriff, PDSA, Inc.

Summary: Add new Microsoft .NET components to existing COM and COM+ applications and they will be able to work together; this will help you if you need to develop a .NET application that can do things like participate in transactions, take advantage of role-based security, or interact with a queue. (14 printed pages)

Class Library source code (VB):

 
Imports System.EnterpriseServices
Imports System.Reflection
Imports System.Runtime.InteropServices

'********************************************
'COM+ Registration details

'Supply the COM+ application name
<Assembly: ApplicationNameAttribute("ComPlusExample")>

'Supply a strong-name assembly
<Assembly: _
AssemblyKeyFileAttribute("bin/ComPlusExample.snk")>

'Role-based security attribute
<Assembly: SecurityRoleAttribute("Managers", False)>

<Assembly: ApplicationAccessControlAttribute(AccessChecksLevel:=AccessChecksLevelOption.ApplicationComponent)>

<Assembly: ApplicationActivationAttribute(ActivationOption.Server)>

<Assembly: ApplicationQueuingAttribute(Enabled:=True,QueueListenerEnabled:=True)>

'********************************************
<ComVisible(True)>
<TransactionAttribute(TransactionOption.Required)> _
Public Class COMPlusServices
Inherits ServicedComponent

Public Sub New()
MyBase.New()
End Sub

<AutoComplete()> Public Function DoTransaction() _
As String
Return "Success with COM+, Nathan"
End Function

Public Function IsManager() As Boolean

Dim objCallContext As SecurityCallContext = SecurityCallContext.CurrentCall
IsManager = objCallContext.IsCallerInRole("Managers")

End Function

Public Function EsPruebaComPlus() As Boolean

Dim objCallContext As SecurityCallContext = SecurityCallContext.CurrentCall
EsPruebaComPlus = objCallContext.IsCallerInRole("PruebaComPlus")

End Function

Public Sub QueueTest()
System.Diagnostics.EventLog.WriteEntry("COMPlusServces", "Queue Test", Diagnostics.EventLogEntryType.Error)
End Sub

End Class

Console Client source code (VB)

Imports COMPlusServicesVB

Module modMain
Sub Main()

Try
Dim objCOMPlus As New COMPlusServicesVB.COMPlusServices()
Console.WriteLine("DoTransacction :" & objCOMPlus.DoTransaction)
Console.WriteLine("IsManager: " & objCOMPlus.IsManager().ToString)
Console.WriteLine("EsPruebaComPlus: " & objCOMPlus.EsPruebaComPlus().ToString)
Cola()
Console.ReadLine()
Catch ex As Exception
Console.WriteLine("An error occurred. " & "Details:  " & ex.Message)
Console.ReadLine()
End Try

End Sub

Sub Cola()
Dim objTest As New COMPlusServicesVB.COMPlusServices()
Dim strMoniker As String
strMoniker = "queue:/new:COMPlusServicesVB.COMPlusServices"
objTest = GetObject(strMoniker)
objTest.QueueTest()

End Sub
End Module

More references:

Transacciones Automáticas: Cómo usar transacciones a través de los Enterprise Services (COM+)

Transacciones en Biztalk con .NET y COM+ (Terminado)

Parte I Introducción: Descripción del escenario, datos del ambiente y lo que deben saber sobre transacciones

Parte II .NET y COM+: Preparando nuestro componente transaccional y comprobando su funcionamiento

Parte III BTS, .NET y COM+: Realizando transacciones en una orquestación con el componente construido

NAnt: .Net automated builds

Official site

Fundamentals

Build files

Example build file for HelloWorld project:

    <?xml version="1.0"?>
    <project name="Hello World" default="build" basedir=".">
        <description>The Hello World of build files.</description>
        <property name="debug" value="true" overwrite="false" />
        <target name="clean" description="remove all generated files">
            <delete file="HelloWorld.exe" failonerror="false" />
            <delete file="HelloWorld.pdb" failonerror="false" />
        </target>
        <target name="build" description="compiles the source code">
            <csc target="exe" output="HelloWorld.exe" debug="${debug}">
                <sources>
                    <includes name="HelloWorld.cs" />
                </sources>
            </csc>
        </target>
    </project>

 

More references:

Installing NAnt to drive database continuous integration by David Atkinson

How to build a database from source control by David Atkinson