Friday, July 29, 2005

Installer class gawk

There are times when you installer class in your project the installation throws an error stating dependency not found. This error does not state anything more than could not find one or more dependency of the assembly.The best way to then resolve which dependency is missing is to write a small console application that through the exception with the inner information when you try to load the specific assembly dynamically using reflection.

Example:

Dim SampleAssembly As [Assembly]
' You must supply a valid fully qualified assembly name here.
Try
SampleAssembly = [Assembly].LoadFrom("C:\Program Files\MyAssembly.dll")
Dim Types As Type() = SampleAssembly.GetTypes()
Dim oType As Type
' Display all the types contained in the specified assembly.
For Each oType In Types
Console.WriteLine(oType.Name.ToString())
Next oType
Catch ex As Exception
Console.WriteLine(ex.InnerException)
End Try

Thursday, July 28, 2005

Rantings on Inheritance and Compositions.

There are two ways to vary behavior of a type. Either by inheritance or by composition each of this has a pattern associated. If you wish to vary by inheritance then use the template method else if you need to vary by composition then use strategy. Remember composition is better than inheritance because when it comes to maintenance of your application this is easier to change than too many inheritances in your application.
I am not stating Stratgey is better than Template. Both these patterns are usefull depending on the context.
Several projects are developed with no thoughts to maintenance in mind. This would be a problem to any new person doing the maintenance for the project and hence the project starts wobbling. In the lifecycle of a software product at least 60% of the time is spent on maintaining the application. Therefore this is a critical part of risk management.
When projects are planned and executed interestingly there are several methodologies and process suggested to improve the creation of the product but very limited to non existent for software maintenance.

Wednesday, July 27, 2005

Code Access Security (CAS)

Code Access security is the level of trust provided to the code to access the resources. The CLR implements the CAS based on evidence. Evidence location, strong named and whether it has a public key associated with it. This is in contrast to some developers believing it can restrict the access to the assembly itself. To know more about it click here.

Tuesday, July 26, 2005

Installer Gotcha .....

On building web application setup the following error is seen
"Unable to build folder named xyz" Now xyz is a sub folder within several folders.
These folders exist multiple times on the sub folders at different levels as well as same level but of different main folder.
The solution is to rename the folders differently and this helps the problem to disappear. Yet another effort would be to use filters on the content file. But his is helpful only if these folders contained C# or VB files because they are not part of the content instead get compiled as assemblies and are part of the primary output. If you have aspx files etc that needs to be deployed to the virtual directory then you cannot use filters but the former method of renaming the folders have to be done.

Monday, July 25, 2005

Ships and Software

Recently I was watching a program on Ship Building. The preciseness and the project timelines at every phase had to be on schedule. The ship was built as different components like software components and then put together which in our terms mean integration. It had to fit precisely with the room for error non existent to marginal if not they would have to be reworked which means time and money lost. This I thought needed incredible project planning. This made me wonder why cant software projects be built similarly. There is one major difference is that the ship is built where requirements never change except probably the interiors but the structure remains the same whereas in software projects we have creeping requirements. Could this be a reason to state software has more abstractions and therefore molding a software project with all the anticipated change is difficult? But structurally can we not keep the software project firm and let everything else vary. How about integration? Can this also be done with precise architectural definitions? I am sure this can be done. But another interesting note was all the senior engineers in ship building was people with decades of experience and have strong fundamentals. But in software development the opposite is true. If we were to build software like a ship with experience and quality at that level than our projects would increase in cost and would be difficult to get started.

This also means are we ready to reduce the errors or decrease the level of faults. If we do this then the cost of project increases, so it's very important to decide the extent to which this is acceptable else the cost would overrun and the feasibility of the project itself is questionable. With ships there is no room for error and therefore they are build with higher precisions even then nothing is perfect. Look at titanic!!!

Friday, July 22, 2005

Generics in .NET Framework 2.0

Generics are now part of .NET Framework 2.0. Those who have used C++ would be aware of templates. Generics are very similar to it.
Earlier in .NET 1.1 when you created collections the objects contained within these collections could be anything and supposing you intention was to have only integers but if you added a string it would not have been detected until runtime. But in using generics you can strong type the values in the collection hence any type mismatch would be detected at compile time.
The difference between templates and generics is that the compiled code with generics would still contain the generics as it is without it being expanded to its types and only later at runtime this is expanded. This is primarily to avoid code bloat.
You can use the generics provided with the .NET framework 2.0 or create your own generics. To create your own generics is simple.

1. Create the generic class.

public class MyOptions<T>
{
// Add any class processing information
}

2. Now use the class

MyOptions<int> values = new MyOptions<int>();
MyOptions<string> names = new MyOptions<string>();


The T within the angle bracket mentions the actual type that will be used when the class is instantiated as shown in step 2.
Remember every time when you do this
MyOptions<int> values = new MyOptions<int>(); it actually instantiates a new class that would accept only the type mentioned. Here it's integers only.

Thursday, July 21, 2005

Three things I like about SQL Server 2005

There are three things that I seemed to have liked with the new SQL Server 2005.

XML Support

It's at the level mapping XML documents with relational tables. It treats XML as a fundamental data type and hence can be indexed. There is also support of XQuery, that is another great feature. Well, it also uses XML as a means of notifications. Other than the TDS Tabular Data Stream support it now supports HTTP SOAP which would mean we can skip IIS and directly get data from the database by using HTTP.

CLR Support

The CLR support means that Store Procs can be now written in C# or VB.NET. Store procs can be written in both TSQL or in .NET. But data intensive task still TSQL is the best bet. .NET could be used for some complex processing say data access across remote servers that would need to manipulated before usage. Here a word of caution would effective use of TSQL or .NET since developers could end with a common refactoring problem of the "Golden Hammer"

Service broker

This is an interesting feature that I seemed to like. This like a messaging system within SQL Server. It has queues which are transactional and messages to be processed can be sent directly to it and the messages are processed appropriately. Because it's within the same system it does not need a two phase commits for the transaction and this itself is a performance gain. For example if you have some data that need to be transferred over to another database asynchronously then this a process to use. This is also extremely reliable and would tend to collect the messages even if the backend server were to fail. Developers would need to design and create a system that effectively uses it to gain fully from the benefits of service broker.

Wednesday, July 20, 2005

Open Source or not ??

I have been trying to get the msi task working in the NantContrib which is an extension to Nant. There are numerous bugs within the template itself. Moreover no matter how I change the template it has some fixed format and I cannot change it satisfy my needs. Well, I could put it in as a feature request to the open source community. But when will it be done and can I consider this added in future planning. I am sure the answer is no.
There are few grouses that I have with open source and they are issues such as bug fixes and documentation which is poor. But overall I see them bring out several new ideas like Nant as well as aspects of continuous integration. Microsoft’s MSBuild and Team system looks very similar to it. The only difference is even though the idea could be a rip-off the idea from the open source community they have a better finish to the product compared to the open source.
Sometime back a friend of mine in a startup had to make the decision to go with open source or with a specific product for example from Microsoft and he finally made the decision not to go with open source. His estimations proved to him that he will not be saving significant sum of money from going with open source. I hope there was some serious study in this direction. There is another organization that is at present converting all its Linux applications to Windows based application. But it needs to be mentioned that there are several successful organizations that are using open source. I believe organizations should encourage and support the open source community since several great ideas have evolved from the open source community and therefore they actually support improvement in the software development arena. Hence software organizations should not consider them as competitor but as supporters to improve quality of the product which is what we all strive to achieve.

Tuesday, July 19, 2005

XML Schema: Nillable, null and minoccurs

xsi:nil = true if used would mean that the element can be present but containing no values and hence is null. minoccurs=0 means the element is optional and need not be present. Therefore to make it truly optional minoccurs= 0 should be used in the schema whereas with nil attribute the element should be present but can have a null value.

Interestingly there is a bug in .NET Framework 1.1 XMLValidatingReader which ignores the nil attributes in the schema and hence any XML document validating against such a schema would throw an error.

Monday, July 18, 2005

Mock-ing objects for Unit Tests

Mock objects are being used extensively in Unit Testing. In-fact there is a Mock framework that can be downloaded and added as a reference which helps in some of the functionalities needed.
Why do we need these mock objects? Take the example where you would need to test your code against a database access. The database is not created. But for your test to run you would need to create the whole database immediately which is a waste of time and resources for the time being. Therefore it is better to use a Mock database which provides the necessary information without going real. This task is achieved by creating interfaces which are implemented by the real database class as well as by the mock database class. Thereby the pointer to the interface is used which is cast appropriately to the correct type and hence you get to use the mock database for the class.

Friday, July 15, 2005

Interrogative testing of Unit tests.

The following are interesting questions that can be asked when writing unit tests.

How: How to test the code?
Write test first before the actual code

What: What can go wrong?
Understanding the alternate routes to your code.

When: When would it fail?
The type of exceptions it would throw. Cross check results by other means.

Where: Where are the boundaries?
Limitations of the code or data. Performance characteristics within the bounds.

Why: Why perform the test?
The test should be significant and not frivolous.

Who: Who would know if it fails?
Run local tests with each compile. Run the test before checking in code.

Thursday, July 14, 2005

Food for thought.

When a bridge fails a civil engineer is asked the reason for the failure. When machine fails an electrical engineer is questioned for the failure. When an aircraft fails an aeronautical engineer is asked the reason for the failure. But when software fails it is the management that is questioned and not the software engineer why? Isn’t it odd?

Wednesday, July 13, 2005

Promotion in .NET Framework 2.0

The .NET Framework 2.0 there are two new types of Transaction Manager. They are Lightweight Transaction Manager (LTM) and the OleTx Transaction Manager.
LTM is used to manage transactions inside a single app domain using a single connection. OleTx Transaction Manager is used across app domain and also if transaction involves more than one resource within the same app domain.
A developer can code against the System.Transaction namespace without worrying about the transaction manger to use since there is something called promotion. Promotion involves assigning the correct Transaction Manager to your code without explicitly defining one.
When a transaction starts of it is LTM, but based on certain criteria it would automatically trigger a OleTx Transaction Manager. The criteria's are the following.
- Calls to SQL Server 2000 and other databases.
- When a second connection is open to SQL Server 2005
- When the Transaction is serialized

Tuesday, July 12, 2005

Avoiding DynamicCast via patterns

How to avoid DynamicCast ? Use visitor pattern. It lets you define new operations without changing the classes of the element on which it operates.
Therefore if for example based on performance rating each employee can be given a raise the raise can be a visitor hence when the employee is given a visit by the raise, automatically all the employees get a raise appropriately. Therefore this avoids the unnecessary extension to the employee class just to add another behavior where only the client is modified the moment the criteria are changed without affecting the employee concrete class. Visitor pattern can also be known as "Object laundering"

Monday, July 11, 2005

State and Strategy identical ? How about Bridge ??

Did you know that State and Strategy patterns are identical in their structure? Why are these patterns given different names? Its the intent that matters in design patterns than the structure of the pattern per se. Here the intent of both the pattern is different. The State pattern alters and objects behavior when its state changes whereas the Strategy pattern encapsulates varying algorithm which simply also means varying behavior of a type. State is dynamic whereas strategy is bind once static pattern.
Some architects / developers may go to the extent of classifying the State and Bridge also alike but I do not think so because Bridge pattern decouples the abstraction from the implementation. Here the decoupling of abstraction from implementation does not mean in terms of a class but as an objects behavior. Understanding this pattern in terms of an object makes it easier to understand and use it. In-fact this pattern is very easy to use in .NET since the Garbage collection is handled by the CLR and hence the implementation object can be destroyed when its abstraction is destroyed. This happens because when the Garbage Collector sees broken reference to an object it is automatically collected for garbage collection. Whereas languages like C++ have to keep a reference count and then destroy it based on the counts like in the COM world.

Friday, July 08, 2005

Abstract Factory And Factory Method

Many developers new to design patterns have this confusion with regard to Abstract Factory and Factory Method. The Factory Method is used in conjunction with Abstract Factory in most cases. The confusion is the term "factory" in the name. Abstract factory is grouping of a family of concrete classes by having a single Abstract class that represents the family. Hence type encapsulation occurs by using this pattern. Factory method really instantiates the appropriate concrete class at runtime and therefore a call to the method returns a concrete type at runtime. Therefore most concrete classes in an Abstract Factory can consists of factory methods which then return the appropriate type needed for the client.


Abstract Factory

The system shall be "platform-independent"
The system shall be independent of how its constituent pieces are created, composed, and represented.
The system shall be configured with one of multiple families of products.
A family of products designed to be used together shall have their relationship constraints enforced.
"case" statements are a maintenance nightmare - they shall be avoided


Factory Method

A subsystem shall not have the "type" of component it is responsible for creating hard-wired.
The system shall be "open for extension, but closed for modification".

Thursday, July 07, 2005

Chicken or Egg problem with XSD and XML

Should we create the XSD or XML first? This is similar to the Chicken or Egg problem. Its ok to create the XML file first if that is a place holder to create the XSD. But any subsequent creation of XML file should be validated against the schema. So, how can we validate the schema in .NET? Here is a code that is use to identify if the schema is valid as well as process the elements.

Private isValid As Boolean = True
Sub Main()
Dim reader As New XmlTextReader("C:\MyFolder\Example.xml")
Dim valid As New XmlValidatingReader(reader)
valid.ValidationType = ValidationType.Schema
AddHandler valid.ValidationEventHandler, AddressOf MyValidationEventHandler
Try

While valid.Read
' Do any processing here
End While

Catch ex As Exception
Console.WriteLine("There is an exception {0}", ex.InnerException)
End Try

valid.Close()

If isValid Then
Console.WriteLine(" The document is valid")
Else
Console.WriteLine(" The document is not valid ")
End If
' This is only to prevent the console window from closing.
Console.ReadLine()

End Sub

' Event handler
Public Sub MyValidationEventHandler(ByVal sender As Object, _
ByVal args As ValidationEventArgs)
isValid = False
Console.WriteLine("Validation event" & vbCrLf & args.Message)
End Sub

Make sure in the XML file you mention either of this attributes for the schema location in the root element.
xsi:noNamespaceSchemaLocation="example.xsd"
or
xsi:SchemaLocation="example.xsd"

The choice of the attribute is based on whether the XML file has namespace or not.

Wednesday, July 06, 2005

Six serving men in Software Architecture

I keep six honest serving-men
(They taught me all I knew);
Their names are What and Why and When
And How and Where and Who.
I send them over land and sea,
I send them east and west;
But after they have worked for me, I give them all a rest.

Extracted from Rudyard Kipling's Poem "I Keep Six Honest..."

I was reading the collected works of Rudyard Kipling recently in a bookstore and this struck me since I knew of an architectural framework very similar to the poem in software development. It’s called Zachman Framework for Enterprise Architecture.
It’s an interrogative framework consisting of six columns asking the What, How, Where, Who, When and Why which relate to Data, Function, Network, People, Time and Motivation in the same order. The rows are divided by the owners. They consist of Scope, Business Model, System Model, Technology Model and Detailed Representation. This forms cells which indicate a type of operation performed in that cell. The cells can be addressed in any order and need not be consecutive.
Software developers should be aware of this architecture since several organizations already use this very successfully. It’s an interesting architectural model and to achieve it completely is idealism but the goal is to strive to reach there. This process thereby improves architectural process. The question then is this applicable in Agile methodology ? Yes, very much and there are several successful real world examples of such utilization.

Tuesday, July 05, 2005

Intellisense for XML using VS.NET 2003

There is a neat trick to get XML intellisense in VS.NET for a given XSD. First place your XSD file at this location (C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\Packages\schemas\xml). Make sure you have a unique namespace for the XSD attribute targetNamespace. Here is an XSD fragment example

xs:schema xmlns:vs="urn:schemas-microsoft-com:HTML-Intellisense" targetNamespace="http://joetest/Example" xmlns:xs="http://www.w3.org/2001/XMLSchema"

Now open VS.NET create a new file and in the root element type the following xmlns="substitute your unique namespace here". Here is an XML fragment example

xmlns=" http://joetest/Example"

Now type any element and you would be guided by intellisense.I have noticed that if a change is done to the schema then its not immediately reflected unless you close and reopen VS.NET 2003.

Friday, July 01, 2005

Easy removal of unwanted software.

MyUnistaller is nice tool that shows you the list of installed application on your machine. This is better than the simple add/remove that is available on the machine. It’s quicker and very easy o remove. Moreover if you have several software that you are evaluating and would need to remove then this is much easier to use. More detailed information is also available of the installed software. The good aspect I like about it is that you can periodically check and keep your machine clean of software that you are not using.
Here is a link to download the software. http://www.nirsoft.net/utils/myuninst.html