Tuesday, November 30, 2010

TryParse

We want result to be set to the value of someObject.SomeProperty, and in any other case to default to 99.


int result = 0;
int max = int.TryParse(someObject.SomeProperty, out result) ? result : 99;

equivalent to

int result = 0;
int max = 99;

if(int.TryParse(someObject.SomeProperty, out result) == true)
{
max = result;
}
else // ok, maybe this 'else' is redundant
{
max = 99;
}

Friday, November 12, 2010

Throw exception

When using throw after catching and handling an exception:


private void SaveRecord(Record record)
{
try
{
var db = new NorthwindDB();
db.SaveRecordInfo(null, record.ClientID, DateTime.Now).Execute(); // let's say this is the line 45
}
catch (Exception ex)
{
_logger.Error("Failed saving db record", ex);
throw;
}
}


We will get something like the following:


System.Transactions.TransactionManagerCommunicationException: blah blah blah ...
at SampleApp.DataAccess.Repository.SaveRecord(Record record) in C:\Projects\SampleApp.DataAccess\Repository.cs:line 45


Which is what we want, in this example we want to log the exception and then re-throw it without losing the stack trace info (and the exact line of code where the exception occurred)

Friday, November 5, 2010

Subsonic ActiveRecord CreatedBy, ModifiedBy, etc

On ActiveRecord.tt


public void Update(IDataProvider provider){
...
}


removed the following block codes:


if(tbl.Columns.Any(x=>x.Name=="ModifiedBy")){
if(String.IsNullOrEmpty(this.ModifiedBy))
this.ModifiedBy=Environment.UserName;
}



if(tbl.Columns.Any(x=>x.Name=="ModifiedOn")){
this.ModifiedOn=DateTime.Now;
}


after that the method should look like the one below:


public void Update(IDataProvider provider) {
if(this._dirtyColumns.Count>0)
_repo.Update(this,provider);
OnSaved();
}


Similarly remove the rest of the Update() methods. Do the same with the Add() methods.