Damn, I love Add-ins !

Hey y’all,


I can’t seem to stop, those add-ins bastards are too addictive !
Oh well, here are more great VS.NET add-ins you should all check them out:



  1. GhostDoc – This great utility will able you to “auto” document your methods\properties with a single mouse click.
  2. WhidbeyCommands 2 – Just read the man’s post :) TIP: if you give presentations while using the VS.NET, you MUST download this baby (check out “Demo font” option) !
  3. HandleWhiteSpace – Clean your files from unnecessary white spaces.

peace.

 

Viewing your “TODO”s in VS.NET “Task list”

It’s possible to use built in keywords in order to mark some lines in you code for later reference. For example, I use the “TODO” keyword as a remark over a set of lines I know I’ll have to change later on –


todos.gif


As you can see, my TODO task is now appearing at my Visual Studio .Net “Task list” which is great for a constant reminder.
As default, the Task list shows only the “Build Errors” so in order to support other keywords you’ll have to (mouse)right-click over one of the table headers (“Description” for example) -> Show Tasks -> All (or any other suitable option). In addition, you can select how to sort the results by (I use “Priority”).


* If you want to change the custom tasks priority or names – go into Tools-> Options… -> Environment -> Task List.

 

Great Videos with Brad Abrams and other .NET experts.

Read this post by the legendary Brad Abrams and watch the videos you’re interested at. I’ve seen “Designing Inheritance Hierarchies” and Enabling Development Tools” videos (for the moment) and I promise that you can learn a thing or two as well ;-).


Happy learning…


update:
I thought it will be interesting to write my notes from the Designing Inheritance Hierarchies video, so here it is:



  1. Interfaces don’t allow backward compatibility ! Let’s assume we have to following interface

          public interface IMyInterface
          {
               void MyMethod();
          }


    Now let’s assume that I have MyClass which inherits from IMyInterface. If I’ll decide to add a new 
    signature to the interface, MyClass will be broken (TypeLoadException will be thrown in compile time).


  2. Base Classes version better than interfaces – if MyClass was inherited from MyBaseClass instead of IMyInterface I wouldn’t have a problem to add new signatures to the class without causing the inherited classes to break.
  3. If you must inherit from 2 “root” classes, the recommended pattern is:

          public class A {}
          public class B {}
        
          public class C : A // Let’s assume that A is “more” root to C than B
          {
             public B BInstance
             {
                get
                {
                    // return B class instance.
                }
             }
          }


  4. You can use Interfaces in “private” way via Explicit declaration:


      public interface IMyInterface
      {
         string ReturnSomething();
      }

      public class MyClass : IMyInterface
      {
          string IMyInterface.ReturnSomething()
          {
            return “oren”;
          }
      }


      Now, when you create a new instance of MyClass, you won’t see 
          ReturnSomething method on the public view:


      MyClass.gif


      Though, you can always call this method simply by casting c to IMyInterface:


      MyClassViaCasting.gif


      This can be useful if you want to “hide” some of the interfaces’ abilities in your 
          class. This is recommendable if you don’t want the “clients” to use a 
          certain behavior directly
through the class. 
         .NET framework use this ability in Int32 structure:


      int i = 5;
      i.ToString() // work
      i.ToInt32(); // don’t work.
      ((IConvertible)i).ToInt32(); // work !


      “ This member supports the .NET Framework infrastructure and 
        is not intended to be used directly from your code. ” 
      (from MSDN, Int32.IConvertible.ToInt32 method)


 


I hope I’ve managed to give you some insights, just enough to convince you to start viewing these videos.

 

Introducing String Resource Generator

I’m currently using a .resx file at my projects to contain my friendly client’s messages. I’m reading from this file via ResourceManager class which allows me to supply consistent messages at my GUI layer, e.g for every successful delete in my application you’ll get the same message format “The {0} was deleted successfully” – in my “Workers” form you’ll see The worker was deleted successfully and in my “Cars” form you’ll see The car was deleted successfully;


I’ve encounter the SR (String Resource) Generator a week ago and I thought to give it a try. So, what is SR generator ?


” This custom tool allows the generation of a resource class (and optionally .resx file) from either a .resx file, or the Microsoft SR.strings file.


I think that a simple example will show the tool’s capabilities.



  1. I’ve downloaded the source which also includes the .msi file and installed it.
  2. I’ve added a file named SR.strings to my web application:

             SRGSolutionOnAdd.gif


  3. I’ve used the “Custom Tool” option and call SRCodeGen – this is an EXE which will parse your .strings file.
             SRGFileProperties.gif

     

  4. Next I’ve edit the SR.strings file –       

      [strings]
      Worker = Worker
      ItemDeleted(string itemName) = The {0} was deleted successfully.
      ItemAdded(int itemId, string itemName) = The {1} was added successfully, it’s new ID is: {0}.


      [strings.he]
      Worker = עובד
      ItemDeleted(string itemName) = ה{0} נמחק בהצלחה.
      ItemAdded(int itemId, string itemName) = ה{1} נוסף בהצלחה, מספרו החדש {0}.


  5. I’ve saved the file in UTF-8 format, for Hebrew support.
             SRGFileEncoding.gif

     

  6. Rebuild the web project, this will cause the SRCodeGen to generate required files:

  7.                   SRGGeneratedFiles.gif

  8. Now lets use the SR class which was generated for us, here is my usage of it 

  9.          PageMessage.Text = SR.ItemDeleted(SR.Worker); // In my Worker.Delete()

     

             OR

             

             PageMessage.Text = SR.ItemAdded(newId, SR.Worker); // In my Worker.Add()

     

  10. Finally we can select the SR.Culture we want to use, so the messages will be formated in the correct language. This can be done easily be calling:

                  SR.Culture = new System.Globalization.CultureInfo(“he”);

   

                  OR

 

                  SR.Culture = new System.Globalization.CultureInfo(“en”);

         You can put this code in your Global.asax.cs in Application_Start method or 
         change it at any time, according to your needs.


 


This tool is a MUST in my opinion for two main reasons:



  1. IntelliSense, IntelliSense, IntelliSense ! (don’t you love it ?!?!).

  2. Changing the messages Culture requires only one line of code, simple as that.

 

Another tip from Ellenbogen’s Kitchen – .NET Postback in modal dialog.

If you’re trying to postback from a modal dialog window, you’ll see that a new window will open up with the results. In order to stay at the same window, use <base> element inside the document’s <head> element –


<html>
   <head>
      ….
      <base target=“_self”/>
   </head>
   ….
</html>

 

Another two great tools to work with.

As you aware by now, I’m kind of programming-gadgets freak. After sharing with you the magic of SlickRun I thought it will be nice (of you to listen, I’m gonna write it anyway) to recommend about another two tools.



  • Visual XPath – After reading Justin’s recommendation about it I thought to give it a try. In my every day work I’m handling a lot of xml, mostly via XmlHttp or sophisticated client side-work (like dependable DropDownLists, custom validations, building dynamic html) and this tool just give you great ability to test XPath phrases with no effort and nice GUI (always important). 

 


  • VSTabs – My second recommended tool is actually an add-in for Visual Studio .NET; The greatest value of this add-in IMHO is the file wrapping tab. It “smart” enough to wrap your .aspx file with it’s .cs file and put them all in one tab. Well, one image is better than 1000 words so –

 

          vstabs.gif

   

        As you can see, it’s wrapping all the linked files in one tab which is great if like to be organized,

        or you’re one of those fellows, like me, that sometimes getting lost if I have

        MyFile.aspx at the beginning of the tabs scrollbar and MyFile.aspx.cs at the end if it.

 

If you have some add-ins to share with me – bring it on !

 

“Hello World” to a mini enterprise application… sounds familiar ?

Hey happy coders,

 

I’m currently developing a “2-weeks-max” application for an Israeli bank (If you see “Israeli bank” instead of the name of the bank, you don’t have sufficient privileges ;-)). The characterization was written and approved on the fly, without a deep understanding of the client’s domain, i.e what are the other applications that the users use in his every day work ? are they look the same ? does he “MUST” have some features that his already used to in his other applications ?

Now I’m facing the harsh results.

 

I’ll give you an example of “little-MUST-feature-that-can-come-back-and-bite-you”. The user requested a screen which will have to following fields in it (and some others, but they’re irrelevant now):


  1. Requester drop down list: show all the users from a specific group in the AD (active directory).
  2. A->B->C linked drop down list: 3  DDL (drop down list) which are connected meaning that when you select a different value in A DDL all the values in B&C DDLs must show all the children of A (changing B will change C values of course).

This looks like a trivial requests right? Well, you’re right, if you look at this skeleton request it may appear trivial, but the key is to understand how to user expect to choose a value from those DDLs. In my case, the user likes to work with auto-complete drop down lists. Combining his auto-complete mechanism in this screen was NOT a trivial task at all. The client gave me his code, so it seems that I just have to integrate it in my code and Voila; BUT The code was written for ASP, so I had to wrap it in a custom web control, handle the viewstate of the control, and worst – his code didn’t worked so well (client-side behavior) so I was required to adjust and fix it as well(black box component in my a$$).

 

The 2 weeks application is now estimated in 3 weeks, 50% more than the first estimation !

I’m expecting a good night 24:00-06:00 sleep at the office for the next 2 weeks, wish me luck !

 

Some lessons I’ve learned:


  1. Don’t give a fast reply for hours estimation just to move along and get the development process running, it WILL hurt you later on.
  2. Always try to understand the solution domain as well as the client’s domain. Ask him to show you other applications that he uses for his every day work, ask him if he wants the same GUI in his new application that you’re going to develop for him. If he does, think about the amount of time you’ll be needed in order to do that, do you need to use a specific “template” so the new application will look the same as his old ones (how are you going to integrate it with ease?), do you need to allow him some special features that his already used to (auto-complete drop down list)? do you need to support key combination (Ctrl+S will save his document) ? In a “clean”(without technical considerations) characterization it probably will not be shown, but you must consider it in the technical characterization(if you have one) and in your total hours estimation ! Don’t forget that the user thinks that adding a new feature to the application is an easy task because he already saw those features in other applications he uses every day (“can’t you simply copy it from here???”) – you must remind him that it’s not a trivial task, and allow him to choose if he wants to spend time on these features.
  3. “Milk” the client for information, write all the possible scenarios that the client expect the system to handle. What screen X will show when I login as Administrator, what it will show when I login as Technician, as Supervisor ? Don’t start programming unless you have the answers for those client “trivial” scenarios, refactoring will be a bitch !
  4. update: just to clarify, I didn’t write the characterization and neither was my PM (project manager), it was written by another co-worker a long time ago. This is a huge mistake IMHO, you must ask the implementors, if you’re not one of them, for their opinion on the development process before you can give your hours estimation.

Any tips you can share with me ?

 

 

 

Using a transaction doesn’t mean you save roundtrips to the database.

I saw a post in one of the forums I’m active at about “how to insert multiple rows to a table in the database”.

The main goal in this scenario, and that’s a rule of thumb in almost any database-operation, is to send a bulk of requests so they’ll be send for execution in ONE roundtrip to the database.

 

I immediately thought to concatenate the insert requests via “;”(or using the “Bulk Insert” command) for Sql Server or using “BEGIN” + “END” for Oracle.

 

[SqlServer]

SqlConnection conn = new SqlConnection(“your-connection-string”);
string query = “insert into t1 (‘value’); insert into t1 (‘value2’);”;
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();

 

[Oracle]

OracleConnection conn = new SqlConnection(“your-connection-string”);
string query = “BEGIN insert into t1 (‘value’); insert into t1 (‘value2’); END;”;
OracleCommand cmd = new OracleCommand(query, conn);
cmd.ExecuteNonQuery();

 

Someone from the forum suggested that all we need to do is to create the required commands object (with the query inside) and wrap them with a transaction. His code looked like this:


using (SqlConnection oCon = new SqlConnection(“ConnectionString”))
{
   oCon.Open();
   IDbTransaction transaction = oCon.BeginTransaction();

   try
   {
         string Commands[] = new string[] {“insert…”, “insert…”};
         foreach (string sqlCommand in Commands)
         {
            SqlCommand oCom = new SqlCommand(sqlCommand, oCon, transaction);
            oCom.ExecuteNonQuery();
         }

         transaction.Commit();
   }
   catch
   {
      transaction.Rollback();
   }
}


He claimed that the transaction object will simply collect the commands and only in transaction.Commit(); the request will be sent to the DB so only one roundtrip was performed.

Well, it didn’t sound right to me, I knew that the transaction wraps the commands but I thought that every call to ExecuteNonQuery() will cause a roundtrip to the DB. But I wasn’t absolutely sure so I’ve decided to check it out and I’ve built a simple tester:


// I’ve created Cities table (Sql Server) with the fields –
// 1. ID – int – PK & identity
// 2. Name – varchar(50) – Unique !
using (SqlConnection oCon = new SqlConnection(“connString”))
{
   oCon.Open();
   SqlTransaction transaction = oCon.BeginTransaction();

   SqlCommand c1 = new SqlCommand(“Insert into cities(name)values(‘oren_test1’)”, oCon, transaction);
   SqlCommand c2 = new SqlCommand(“Insert into cities(name)values(‘oren_test1’)”, oCon, transaction); // this will throw an exception for duplicated row (Cities.Name is unique)
   SqlCommand[] commands = new SqlCommand[] {c1, c2};

   try
   {
      foreach (SqlCommand command in commands)
      {
         command.ExecuteNonQuery();
      }

      transaction.Commit();
   }
   catch(Exception err)
   {
      Console.WriteLine(“error: {0}, rollback.”, err.Message);

      transaction.Rollback(); 
   }
}//using will close the connection even in case of exception.


As you can see for yourself(try it), the second ExecuteNonQuery (for the second insert) throw me an exception about the duplicated row (unique exception) so now I’m sure that the roundtrips are NOT “saved” by wrapping the command with a transaction. It’s making a lot of sense, the DB opens a transaction while calling the BeginTransaction() method and keeping it open until we call the Commit() or Rollback() methods. In between, while calling the ExecuteNonQuery() method, the database saves the row in a temporary table just until the the transaction ends (again, via Commit() or Rollback()) and only then the rows are inserted to the “real” table (i.e Cities table).


Conclusion


One of your main concerns while developing a web application is to prevent redundant roundtrips from your application server to the database server.


While the transaction object is vital for data integrity while inserting\updating\deleting many(more than 1) rows and it can boost your request(Trying to insert 1000 rows to the table, each insert with it’s own private transaction, will be much slower than calling the same insert with one transaction for the all 1000 rows), it doesn’t mean that it’s wrapping your calls to the DB and saves those redundant roundtrips.


And if I wasn’t clear so far – You should use the first approach showed in this post.


p.s –
General tip: (need I to say?) Always check your theories before you running along and using them in your applications.

 

Generate your way to the solution via CodeSmith.

Why do we(my bad, I) need code generator ?
I really don’t want to get into this philosophical argument, whether code generation is good or not, but just think of your Code Generator as a silent programmer which REALLY loves to do your dirty repetitive work. Please read the following with an open mind to the subject, you’ve got nothing to lose.

 

Background

Way back, When I was still serving my country, I was “introduced” to the world of Code Generation. The concept was well familiar to me, but I didn’t saw a tangible implementation until my team leader at the time, Pavel Bitz, showed us his(great) implementation which later on became the first code generator (aka “CG”) I ever used. This CG was written in PL/SQL and ran, obviously, on our Oracle (9i) database. I wasn’t so happy about the extendability of this code, but we were in a tremendous stress to develop & deploy our projects so there was no time to develop something “cleaner”(in my opinion anyway). After few weeks, at my final days in the army, I was starting to build my own code generator just to understand more of the .NET framework power – i.e usage of templates, custom config files, Database reverse-engineering, reflection, practicing my OOD\OOP etc. After all, nothing teaches you better to “exploit” the framework than writing an application which will test its capabilities. After 2 weeks I had a nice CG which ran quite well and did everything the PL/SQL CG did and then some.
My time at the army was done and I was back in the free market.

2 days after I was employed for SQLink company, I talked with Amir Engel about the idea of code generation. He told me that he managed to write some templates with CodeSmith and he showed them to me. It looked great but I was hoping to use my CG for that purpose, still, I wanted to protect my “baby”. But this desire was gone when I read about CodeSmith’s SchemaExplorer. My god, I was shocked about how easy it is to write a template which will connect to my database with zero (0 !) effort. In addition, it has its own Studio which allows me to write,test and debug my templates with ease.

BUT the biggest advantage was that there were many open source templates out there – just for me to use !

 

Code Generation – safety first

Before you start to generate code, you must think about how to integrate the code generation usage in your every day work without the need to overwrite your “custom” writing. I’ll give you an example – Let’s say that we generate the Data Access Object for Users table in our database. This object does the CRUD (Create\Insert, Read, Update, Delete) operations for that table. Now I need to add a “specific” method named “GetUsersFromCity” which will return all the users from a given city id. So I’ll add the method to my UsersDAL class and I’m an happy programmer no ?   (think here…)  NO!

Why not ? because the next time I’ll want to generate this class again, because one of the fields in the table was changed or a new field was added to the table (whatever), I don’t want to overwrite the class and lose my custom changes !

The “Base” principle:
This is where the “Base” principle kicks in and help us to protect our custom changes. My correct “DAL” object class structure will be:


// File: UsersDALBase.cs
public class UsersDALBase
{
    // our “generated” code here – all the CRUD operations for example.
}

// in another file!
// File: UsersDAL.cs
public class UsersDAL : UsersDALBase
{
    // My custom behivors here.
}


Every time I’ll regenerate the code, I’ll overwrite the “Base” file and no harm done – my custom changes are safe !
In my “upper” layers, I always use UsersDAL(or [table]DAL for that manner) and not UsersDALBase.


Now that we’ve got the background, it’s time to introduce to you my amigo –


CodeSmith – harness its power for your own need


I’m not going to write here about how to use CodeSmith, there is too much information about this issue all over the web – just google a little and I’m sure you’ll do just fine. What I’m going to talked about is what’s the greatness of CodeSmith and my tips about easy development and debugging while using this tool.

 


  • SchemaExplorer – Stop doing all the reverse engineering for Oracle\SqlServer (via “system tables”), it’s already written for you. The only thing you need is to specify is the connection string and… thats it ! You want to see how easy it is? OK OK, relax:

      <%@ CodeTemplate Language=“C#” TargetLanguage=“C#”
        Src=“../OeCodeTemplate.cs” Inherits=“OrenEllenbogen.Templates.OeCodeTemplate”
        Debug=“False” Description=“Generate an entity class for a given table.” %>

      <%@ Property Name=“SourceTable” Type=“SchemaExplorer.TableSchema” 
         Category=“Connection” Description=“Table Object should be based on.” %>

      <%@ Assembly Name=“SchemaExplorer” %>
      <%@ Import Namespace=“SchemaExplorer” %>


      <%
      // Collection of all columns in the table.
      ColumnSchemaCollection Columns = new ColumnSchemaCollection(SourceTable.Columns); 
      %>


      <% 
      // Variables by table columns.
      for (int i=0; i < Columns.Count; i++) { %>
      /// <summary>
      /// <%=Columns[i].Name%><%=(Columns[i].Description.Length>0) ? ” : ” + Columns[i].Description : “”%>
      /// </summary>
      protected <%= GetCSType(Columns[i]) %> <%=VariableStyle(Columns[i].Name)%> = <%= GetCSDefaultByType(Columns[i]) %>;
      <% 
      } //end for 
      %>


         Some Explaining:



    • you can use “code behind” file (*.cs) which holds the common methods for all your templates files (mine is OeCodeTemplate.cs)
    • I use the methods GetCSType, VariableStyle and GetCSDefaultByType methods which are in my “code behind” file, but this are simple methods which you can copy\write by yourself.

         As you can see, it’s so easy to start dealing with the template itself instead of trying to remember 
         how to get all the indexes\columns\primary keys\(etc)  from a given table.


  • Templates GUI – You’ve seen that I’m using SourceTable property on the previous section, the great thing about it is when I’ll open this template with CodeSmith explorer I’ll be able to pick the table directly from my DataSource. So easy and comfortable.

   CodeSmithExplorer.JPG   

 

 


  • Huge community – you can find a lot of examples in CodeSmith forums. Don’t try to write something which was already written before you; You can always find a template and get some of its code for your specific need.
  • Its easy – believe me, my 4 years old cousin can write a template with CodeSmith, its that easy !
  • Its(was) free ! – version 2.6 is free for use, but the new one (3.0) costs (nothing you can’t afford though).

Developing with CodeSmith


  • Using Lut’z reflector with CodeSmith 2.6 – The main problem with this version (and former) is the lack of IntelliSense. This is a problem due to the simple fact that you can’t remember every method\member  in SchemaExplorer object for example which makes it harder for you to develop. The simple solution is to use the reflector over the SchemaExplorer.dll, which “sits” in CodeSmith directory, and explore your way to the required member\method.
  • Debugging – Debugging with CodeSmith 2.6 (and former)  isn’t so comfortable, but it doable – that’s enough for me. In order to do it, all you need to do is to put Debug=”True” in the page header directive and call Debugger.Break(); before the lines you want to debug.

NOTE: in the new version (3.0), Eric .J. Smith, the creator of this great tool, spoiled us with brand new features like built-in IntelliSense and easier debugging options and much more.



Summarize:
Code generation, in my humble opinion, is MONEY SAVER, simple as that, you can cut down the development time by half !

I’ve built full-spectrum templates for my N-Tier applications – Entities (object which represent table), Data Access objects, Business Object, Web forms, Utilities layer, Cache layer and stored procedures script generator. I’m now able to build 50%-60% of the project “foundation” before I need to write my first code line ! In addition,  I’m using my CodeSmith templates for my every day work – I did some helper templates like generating new “SqlParameter” with the parameter type\size\scale according to the column type, This is great for adding a new SqlParameter to SqlCommand with “full information” about the parameter in single click.
And finally, I’m not afraid to change the database because I know what I need to change and now – it’s even EASY to do.

 

 

Automated build for my ASP.NET project using NAnt

As I’ve promised – I share with you my experience with NAnt while attempting to automate my build process for my ASP.NET project. After reading a lot on the subject, I must admit that the documentation is quite poor and the “open source” examples are not exactly what I’m looking for. Before I’ll start, if you don’t know what is NAnt or NAnt contrib, now will be a good time to do some reading, I’ll wait…


Requirements (What do you need to install before you can start):



  1. Download and install NAnt.
  2. Add the nant\bin directory path to your PATH variable (“System Variables”).
  3. Download and install NAnt contrib.
  4. Integrate between NAnt and NAnt contrib using these steps:

    1. Copy nant-contrib\bin\*.dll to nant\bin\ directory.
    2. Create the folder nant\bin\tasks\net (manually).
    3. Copy nant-contrib\bin\*.dll to nant\bin\taks\net directory.

  5. Download NAnt.UtilityTasks.dll and put it in nant\bin directory.

Let’s Start:

OK, now we’re ready to start the build process; So here is my solution structure:


MySolution
   – WebProject (ASP.NET project)
      – *AssemblyInfo.cs
      – Other files and directories (& porno, of course)
   – BusinessLayer (Class Library)
   – DataAccessLayer (Class Library)
   – EntitiesLayer (Class Library)
   – *SolutionInfo.cs
  – etc..


* Before I continue about the process itself, I must mention that I’m using “Link File” option in order to share my AssemblyVersion attribute in my ClassLibraries projects. In a perfect world, ASP.NET projects would be able to “Link File” as well, but (surprisingly) it’s not; So I have 2 places which hold the AssemblyVersion:
1. MySolution\SolutionInfo.cs (This file is being linked in all of my class libraries).
2. MySolution\WebProject\AssemblyInfo.cs.


Great, we can carry on –
I’ve discussed about the proper build process with my friends A&A (The Amir’s aka “The markowitz” and “The Engel”) and we’ve agreed that we require 2 processes – “Build”(complete new version) and “Rebuild”(rebuild the current version, it’s required after the Build process failed for some reason).

The desired processes work flow
:
Note: you don’t need to copycat my process, you’re a free human being, consider me as your Build mentor :-o

1. “Build” process –
   1.1 Increment my build version (SolutionInfo.cs & AssemblyInfo.cs)
         In order to do that, I’m using a great code snippet I found during my last weekend searches to 
         create a new version number. Afterwards, I’m checking-out the SolutionInfo.cs file and imprint the 
         new AssemblyVersion using <asminfo> task.
         Eventually I’m checking-in the SolutionInfo.cs file.

         * I’m using some properties – ${property_name} – for easy maintenance, you can see it in the 
            file I’ve upload (way over down).


   <vsscheckout username=“${vss.username}” password=“${vss.password}” 
      localpath=“${slndir}” recursive=“false” writable=“true” dbpath=“${vss.dbpath}” 
      path=“${vss.slnpath}/SolutionInfo.cs” failonerror=“true” />

   <asminfo output=“${slndir}\SolutionInfo.cs” language=“CSharp”>
      <imports>
         <import namespace=“System” />
         <import namespace=“System.Reflection”/>
         <import namespace=“System.Runtime.CompilerServices”/>
      </imports>
      <attributes>
         <attribute type=“AssemblyVersionAttribute” value=“${build.version}” />
         <attribute type=“AssemblyCompanyAttribute” value=“${company}” />
         <attribute type=“AssemblyProductAttribute” value=“${product}” />
         <attribute type=“AssemblyCopyrightAttribute” value=“Copyright (c) 2005, ${company}.” />
         <attribute type=“AssemblyTrademarkAttribute” value=“Trademark by ${company}” />
         <attribute type=“AssemblyDelaySignAttribute” value=“false” />
         <attribute type=“AssemblyKeyFileAttribute” value=“..//..//..//key.snk” />
         <attribute type=“AssemblyKeyNameAttribute” value=“” />
      </attributes>
   </asminfo>

   <vsscheckin username=“${vss.username}” password=“${vss.password}” 
      localpath=“${slndir}\SolutionInfo.cs” recursive=“false” writable=“true” 
      dbpath=“${vss.dbpath}” path=“${vss.slnpath}/SolutionInfo.cs”
      comment=“change build version: ${build.version}” />


         I use the same code (with minor changes) to update my AssemblyInfo.cs file as well.

   1.2 Put a label on the VSS with the current new version.
         This is even easier, I just use <vsslabel>(NAnt contrib) task:


      <vsslabel
           username=“${vss.username}”
           password=“${vss.password}”
           dbpath=“${vss.dbpath}”
           path=“${vss.slnpath}”
           comment=“New build version: ${build.version}”
           label=“${build.version}”
      />


   1.3 Get the files from the VSS to my local directory recursively using <vssget>(NAnt contrib) task.
      <vssget
           username=“${vss.username}”
           password=“${vss.password}”
           localpath=“${vss.outdir}”
           recursive=“true”
           replace=“true”
           writable=“false”
           dbpath=“${vss.dbpath}”
           path=“${vss.slnpath}”
      />


   1.4 If I’m required to (by property) – generate the projects pdb’s.
        This is great for release mode, I can pull the pdb’s for the version at the Production environment 
        and make some extreme production debugging using the pdb’s as symbols – 
        I must give the credit to “The markowitz” for the idea !
      


        The code is quite simple – build the solution in Debug mode and copy the *.pdb files
        to my “version_directory”\pdb\WebProject.
        You can see the code in the attached file.


   1.5 Build the solution.
         I’m using <solution> task and <webmap> for easy build.
         Again, nothing fancy, look in the attached file.

   1.6 Copy the web project output to my MySolution\Builds\[version_number] directory for 
        an easy XCOPY deployment. I’m using <copywebproject> task in order to do 
        this magic, it’s working like a charm.  
   <copywebproject project=“${slndir}\WebApp\WebApp.csproj” 
      todir=“${outdir}\WebApp” configuration=“${config}” />


   
2. “Rebuild” process – 
      Call steps 1.3 to 1.6.


TIPS:
I recommend that you’ll download VSTweak and let the VS.NET treat your .build file as .xml file.


TODO:
I’m going to add a NAnt task which will get all the *.js\*.htc files from the web project (.csproj) and format them
via Jazmin – this will cut down the size of the files(by removing comments and other not-required characters) for performance improvement (the smaller the file is, the faster the client will download it).


CREDIT:
If you’re using my file as your “template”, I would appreciate if you’ll add a comment and let me know about it, including new features you’ve added or planning to add. I’ve dedicated my time to share with you, please do the same grace with me. Thanks !


My (template) build file:
default.zip (3 KB)

How to run the build file ?
You’ll need to configure the default.build file I’ve attached (5 minutes max).
Go to your solution directory and copy the “default.build” file into it.
Now, activate “cmd” and navigate to that directory.
Type “nant build” and Voila !