Friday 10 October 2008

Business Logic in C# or T-Sql?

This has been a topic of debate for a long time. If you think this discussion is trivial, you need to evolve. Read on if you
think you got something to think. Practically developers, and designers prefer to use stored procedures simply because of one of the following reasons:

 - Code looks good! They get a feeling that at least they have done something right in their life. They keep ridiculing others for having used in-line queries. They once read somewhere that SPs are the way to go.

 - The above category is the follower - mindless follower. They are hard to convince and they will follow the same practice for years. Never mind. They also came to know in their college days that SPs are "precompiled", "fast", and "secure". They won't be able to tell you the whys and hows of things.

 - Some experienced and good developers attribute the usage of SPs over parametrized queries by saying that it saves you a lot of Network bandwidth, and gives you a single point of failure. You know where things can go wrong.

 - The flag bearers of business-logic-in-application-language-like-C# will tell you that the purpose of an RDBMS is to store data, and the act of manipulating it should be done on a higher level language. Languages like C# arm you with better weapons than T-Sql could ever do. T-Sql is Set based and Procedural thus monolithic. You are not living in caves anymore, are you?

 - What about Sql injection attacks? They are dreaded weapons of hackers. How does parametrized query work this out? Well, they are as safe as SPs. Both are parametrized, aren't they? Its different that in-line queries. In-line queries are prone to attacks. However, there are ways to break into SPs as well, so you are not safe anyways!

 - Are you talking about doing away with SPs altogether? Certainly not.
You need to decide whats best for the purpose. CRUD operations doesn't seem logical to me anymore. Imagine having a about 100 normalised tables in your database. Would you like to have 100*4 SPs doing the normal Insert, Update, Select and Delete for you? Doesn't seem so convincing. Moreover, the performance benefits of SPs and queries have been diminishing since Sql Server 7.0.
As per books online:
SQL Server 2000 and SQL Server version 7.0 incorporate a number of
changes to statement processing that extend many of the performance
benefits of stored procedures to all SQL statements. SQL Server 2000
and SQL Server 7.0 do not save a partially compiled plan for stored
procedures when they are created. A stored procedure is compiled at
execution time, like any other Transact-SQL statement. SQL Server 2000
and SQL Server 7.0 retain execution plans for all SQL statements in the
procedure cache, not just stored procedure execution plans.


 - If you are planning to be object based and enjoy the rich benefits of C# as a language you must consider LINQ, or any other efficient O/R mapper like NHibernate. You will start loving it. You will love the feeling of having used pragmatic best practices and approaches.

 - If you have Business Logic written in C# it implies that you can do Unit Testing with Code Coverage. If you need to traverse the rows its much easier, as it doesn't have to create #Temp tables in tempDB for Cursors. The DBA is no longer required to write complicated, hard to maintain thousands of lines of monolithic code. He can focus on database management, fine tuning, backup, replication and other important stuff! You don't need to explain the business to your DBAs. Let them be specialised in what they are doing.

 - I am not sure how successfully it isolates dependency on a platform(like Oracle or Sql Server), but it does relieve you of maintaining tons of unnecessary SPs.

 - Bad C# coding is certainly not a replacement of SPs. If you are writing business logic in a highly evolved language like it, you need to make sure that you are following best coding practices and patterns. If you end up writing monolithic procedural code in C#, you need to evolve before you can understand the true benefits of this discussion.

- What about debugging? I don't think that's a big deal. You can use Sql Profiler for the parameters. Agreed that you can't have IDE like debugging but Sql Server IDE is sufficient to trace a bug. You can also unit test the output generated from the database in your application with NUnit. So if you have good coverage of the SP side code, you will get to know what all you have broken as a result of the changes you made. Neat. So, this doesn't convince me to port my business logic to C#.

 - SPs can't be replaced in Data driven applications like report generators, but its advisable to code the business logic in C# for applications that do data manipulation like a Financial calculator!

You may consider reading the following articles for more details.
Dude, where's my business logic?
Stored procedures are bad, m'kay?

This one is interesting because it has people fighting for their favorite approach.
Who Needs Stored Procedures, Anyways?

My take on this: Be pragmatic. Be need driven. Be domain driven.

C#: Could be any programming language.

Friday 3 October 2008

Must Haves

Following is the list of must-haves; most of the Architects are aware of it. However, if you are an aspiring architect you should start from here.

Do remember that there are two ways of achieving a result: The easier way that always looks easy; and the not-so-easier-looking way which is actually fun and easy to walk on. If you are passionate about doing things in style, and quickly, and you want to be in complete control, always follow the industry best practices. Always look out for something new, keeping in mind the OO school of thought, you'll never go wrong. Frameworks will come, and go, but you need to know what triggered the need for that framework. How did they made it possible? What goes inside making such great stuff?

I am contributing in a small way a list that I have compiled today.

1. Frameworks
- Smart Client Software Factory for WinForms UI
- Web Client Software Factory for Web UI
- Spring.Net for AOP, DI and IoC, Logging, Data handling
- Unity Framework for DI and IoC
- Various Microsoft Software Factories; Enterprise Application Blocks
- Log4Net for logging

2. Tools
- Resharper for UnitTests and Code Analysis
- NCover
- NMock
- NHibernate for O/R Mapping
- Simian for Code duplication and Refactoring
- StyleCop for Code Styling
- CLR Profiler/ANTS profiler for application profiling

3. Architecture
- MVP/MVC
- Pragmatic Architecture
- SOA

4. Software Engineering
- Extreme Programming
- Agile Methodology

5. Books
- Head First Design Patterns
- Head First OOAD
- Code Complete 2
- Patterns of Enterprise Application Architecture
- Test Driven Development
- Domain Driven Develeopment

6. Practices
- TDD
- DDD
- MDD

7. Blogs
Top 100 Blogs ever!!!
Top 100 Software Engineering books ever!!!

Wednesday 24 September 2008

Using Code Generator to Create Sql Mapper Class



Good to see you again!!

This sample code used CodeDOM(System.CodeDOM) to create a code generator. The purpose is dual. It not only demonstrates how to use CodeDOM but also the way to automate a Sql input mapper generator.

Internally it uses SqlDMO COM dll to access a Sql Server database. It then fetches the required Stored Procedure, and exposes the input parameters.

The downloadable code contains the code fit for the purpose. Its as generalised as it should be. Feel free to use it.

The following is the class diagram for the CodeDOMDemo classes:


The following is class diagram for the SqlCodeDOM classes:


The following fixture gives you some of the usage scenarios.



using NUnit.Framework;
using Sanjeet.Demos.CodeDOMDemo;

namespace Sanjeet.Demos
{
[TestFixture]
public class GenerateStoredProcFixture
{
private const string serverName = "serverName";
private const string username = @"username";
private const string password = "password";
private const string databaseName = "databaseName";

[Test]
public void GenerateCounterParty()
{
const string spName = "GetCounterParties";
const string filename = @"c:\CounterParty.cs";
GenerateStoredProcedure sp =
new GenerateStoredProcedure(serverName, username, password, databaseName, spName, filename,
"Sanjeet.Data");
sp.Generate();
}

[Test]
public void GenerateDealsEnteredbyAllCounterParty()
{
const string spName = "GetDealsEntered";
const string filename = @"c:\DealsEnteredbyAllCounterParty.cs";
GenerateStoredProcedure sp =
new GenerateStoredProcedure(serverName, username, password, databaseName, spName, filename,
"Sanjeet.Data");
sp.Generate();
}

[Test]
public void GenerateDealsEnteredbyCounterParty()
{
const string spName = "DealsExport";
const string filename = @"c:\DealsEnteredbyCounterParty.cs";
GenerateStoredProcedure sp =
new GenerateStoredProcedure(serverName, username, password, databaseName, spName, filename,
"Sanjeet.Data");
sp.Generate();
}
}
}


Happy Coding!

Tuesday 23 September 2008

CSS Parser



Presenting to you a simple piece of code that parses CSS. It uses Regular Expressions to achieve the functionality.



The sample code below gives you an idea how to use it.



/*
*
* Date Created: 02-Sep-2008
* Author: SAHAY, Sanjeet, IDC
* Filename: CssParserFixture.cs
* Assembly: Sanjeet.Demos
* Project: Demos



* Purpose: Add purpose
*
*/
using System.Collections.Generic;
using NUnit.Framework;
using Sanjeet.Demos.CSSParser;

namespace Sanjeet.Demos
{
[TestFixture]
public class CssParserFixture
{
private IDictionary<string, string> properties;

private IContainer GetContainer()
{
const string cssFilepath = @"..\..\..\CssParser\StyleSheet.css";
return new DefaultContainer(cssFilepath);
}

[Test]
public void GetButtonsClip()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("Buttons");
Assert.IsTrue(this.properties["clip"].Equals("rect(auto auto auto auto)"));
}

[Test]
public void GetButtonsPropertiesCount()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("Buttons");
Assert.IsTrue(this.properties.Count == 16);
}

[Test]
public void GetH1Color()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("H1");
Assert.IsTrue(this.properties["color"].Equals("blue"));
}

[Test]
public void GetH1FontStyle()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("H1");
Assert.IsTrue(this.properties["font-style"].Equals("italic"));
}

[Test]
public void GetH1PropertiesCount()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("H1");
Assert.IsTrue(this.properties.Count == 2);
}

[Test]
public void GetMasterTablePropertiesCount()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("MasterTable");
Assert.IsTrue(this.properties.Count == 8);
}

[Test]
public void GetNameLabelPropertiesCount()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("NameLabel");
Assert.IsTrue(this.properties.Count == 4);
}

[Test]
public void GetUL()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("UL");
Assert.IsTrue(this.properties.Count == 4);
}

[Test]
public void GetULFontWeight()
{
IContainer container = this.GetContainer();
this.properties = container.GetProperties("UL");
Assert.IsTrue(this.properties["font-weight"].Equals("bold"));
}
}
}

Abstract Factory Pattern



Purpose:
The Abstract Factory Pattern involves the following OO priciple: Depend upon abstractions, do not depend upon concerete classes.

Abstraction doesn't necessarily mean an Interface. It points to a super type. It could easily be an Abstract class.

Encapsulating Object Creation. But Why?
We all have been "newing" for a long time without worries. Now we say that its better to encapsulate object creation. How is it going to help us? We are "newing" anyways!

The problem is certainly not with "new". Its the change that brings all the change. We need a way to encapsulate all the related "newing" at a single place so that its not spread across the code. In this example, a NuclearOrdananceFactory(Factory) is entrusted with creating Bullets, Guns, and Bombs(Products). Whenever Russia or China(Client) needs to create Nuclear bombs it goes to the Factory. It simply creates relevant weapons. No hassles, no worries, no code duplication, and no maintenance nightmares.

Abstract. Why Abstract?
The Factory classes like NuclearOrdnanceFactory, and BiologicalOrdnanaceFactory implement an Abstract interface. This allows the Client to create a set of related products.

I am presenting to you the most common design pattern that is also widely mis-understood! I am trying to simplify things by giving you a code sample and a test fixture that explains the usage.

It involves three distinct participants: The Factory, The Product, and The Client. The following class diagram will help ease down things.



The following fixture explains the usage of the factory.



/*
*
* Date Created: 16-Sep-2008
* Author: SAHAY, Sanjeet, IDC
* Filename: AbstractFactoryFixture.cs
* Assembly: Sanjeet.Demos
* Project: Demos
* Purpose: The Abstract Factory Pattern involves the following OO priciple:
* Depend upon abstractions, do not depend upon concerete classes
*
*/

using NUnit.Framework;
using Sanjeet.Demos.Patterns.AbstractFactory.Client;
using Sanjeet.Demos.Patterns.AbstractFactory.Factory;

namespace Sanjeet.Demos
{
[TestFixture]
public class AbstractFactoryFixture
{
[Test]
public void CreateABiologicalCountry()
{
IOrdnanceFactory factory = new BiologicalOrdnanceFactory();
ICountry country = new China();
country.MakeWeapon(factory);
}

[Test]
public void CreateAChemicalCountry()
{
IOrdnanceFactory factory = new ChemicalOrdnanceFactory();
ICountry country = new UnitedStates();
country.MakeWeapon(factory);
}

[Test]
public void CreateANuclearCountry()
{
IOrdnanceFactory factory = new NuclearOrdnanceFactory();
ICountry country = new India();
country.MakeWeapon(factory);
}

[Test]
public void CreateAStrongCountry()
{
ICountry country = new India();
country.MakeWeapon(new NuclearOrdnanceFactory());
country.MakeWeapon(new ChemicalOrdnanceFactory());
country.MakeWeapon(new BiologicalOrdnanceFactory());
}
}
}


Cheers!

Tuesday 16 September 2008

Welcome

Welcome to my new blog.

As the name suggests its going to be technical. I have been keeping a lot busy these days. But I hope to spare some time now, and share my technical findings with you all.

My area of expertise is .Net and you may call me a OO purist. All these years I have tried my best to convince people around me that there is nothing like R.A.D.(Rapid Application Development). Its a myth. It ends up being S.C.A.D.(Slow and Cumbersome Application Development). I will explain you as we go along.

My earlier technical outbursts can be seen here.