Category Archives: Uncategorized

Cache Util and ServiceBase for SubSonic RepositoryRecord items

I have started working on a project in my “free” time and want to share some of the things I’ve been playing with.  For the new project, I’m planning on using Mvc, SubSonic, Linq, and jQuery to name a few technologies.  I’ll release more info about the project as it shapes into something more tangible.

As I mentioned, I’m using SubSonic with this project and more specifically, I’ve been using what will be SubSonic 2.1.  I’ve been quite happy with the work Rob Conery and his team have done with SubSonic.  For this project, I chose to go with the RepositoryRecord base class rather than ActiveRecord for my objects.  My reasoning was that I end up using services to interact with the objects anyway, so I might as well reduce the “weight” of the objects.  The services that I use add basic object caching as well as hide SubSonic integration.

In order to facilitate caching RepositoryRecord items, I had to rewrite my CacheUtil class slightly:

public class CacheUtil
{
public static List<T> FetchAll<T>() where T : RepositoryRecord<T>, new()
{
string key = typeof(T).ToString();
object item = HttpContext.Current.Cache[key];

if (item == null)
{
List<T> collection = DB.Select()
.From<T>()
.ExecuteTypedList<T>();

HttpContext.Current.Cache.Insert(key, collection);
return collection;
}
return (List<T>)item;
}

public static List<T> FetchAllAsc<T>(params string[] columns) where T : RepositoryRecord<T>, new()
{
string key = typeof(T).ToString() + "__SortAsc";
foreach (string column in columns)
{
key += "_" + column;
}
object item = HttpContext.Current.Cache[key];

if (item == null)
{
List<T> collection = DB.Select()
.From<T>()
.OrderAsc(columns)
.ExecuteTypedList<T>();

HttpContext.Current.Cache.Insert(key, collection);
return collection;
}
return (List<T>)item;
}


public static List<T> FetchAllDesc<T>(params string[] columns) where T : RepositoryRecord<T>, new()
{
string key = typeof(T).ToString() + "__SortDesc";
foreach (string column in columns)
{
key += "_" + column;
}
object item = HttpContext.Current.Cache[key];

if (item == null)
{
List<T> collection = DB.Select()
.From<T>()
.OrderDesc(columns)
.ExecuteTypedList<T>();

HttpContext.Current.Cache.Insert(key, collection);
return collection;
}
return (List<T>)item;
}

public static void ClearCache<T>()
{
string baseCacheKey = typeof(T).ToString();
if (HttpContext.Current.Cache[baseCacheKey] != null)
{
HttpContext.Current.Cache.Remove(baseCacheKey);
}

RemoveWithWildcards(baseCacheKey + "__SortAsc*");
RemoveWithWildcards(baseCacheKey + "__SortDesc*");
}

/// <summary>
/// Removes items from the cache using wildcards * and ?
/// </summary>
/// <param name="pattern">Pattern to search cache keys</param>
public static void RemoveWithWildcards(string pattern)
{
pattern = pattern.Replace("*", @"w*").Replace("?", @"w");
// Only match whole words
pattern = string.Format("{0}{1}{0}", @"b", pattern);
RemoveByPattern(pattern);
}

/// <summary>
/// Removes items from the cache based on the specified regular expression pattern
/// </summary>
/// <param name="pattern">Regular expression pattern to search cache keys</param>
public static void RemoveByPattern(string pattern)
{
IDictionaryEnumerator enumerator = HttpContext.Current.Cache.GetEnumerator();
Regex regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
while (enumerator.MoveNext())
{
if (regex.IsMatch(enumerator.Key.ToString()))
{
HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
}
}
}
}

 

I’m using the following base class for my services.  While it’s likely to change, I think it’s a pretty good place to start.

public abstract class ServiceBase<T> where T : RepositoryRecord<T>, new()
{
public static void Save(T item)
{
Save(item, "");
}

public static void Save(T item, string username)
{
DB.Save(item, username);
ClearCache();
}

public static void Delete(T item)
{
DB.Delete(item);
ClearCache();
}

public static void Destroy(T item)
{
DB.Destroy(item);
ClearCache();
}

public static T FetchById(object id)
{
List<T> items = FetchAll();
return items.Find(delegate(T item) { return item.GetPrimaryKeyValue().Equals(id); });
}

public static List<T> FetchAll()
{
return CacheUtil.FetchAll<T>();
}

public static List<T> FetchAllAsc(params string[] columns)
{
return CacheUtil.FetchAllAsc<T>(columns);
}

public static List<T> FetchAllDesc(params string[] columns)
{
return CacheUtil.FetchAllDesc<T>(columns);
}

public static void ClearCache()
{
CacheUtil.ClearCache<T>();
}
}

 

Goodbye Vault, Hello Subversion

After a few years of using Vault, I have completed moving all of my internal projects to Subversion.  Since I regularly work from multiple computers/locations and will most likely be adding people in the future, i wanted a free, flexible solution for source control.  Subversion was a breeze to setup and I’m very happy with how it isn’t integrated with Visual Studio.  I much prefer using TortoiseSvn to manage my project.  No longer will I have to wait for visual studio to connect to a repository when Internet access isn’t available.  It just makes life a little easier…

I know that I could’ve used Vault with out the Visual Studio integration, but that’s how it set itself up and I generally take the path of least resistance.  Truth be told… I had numerous instances where Vault failed to overwrite files with the latest from the repository.  Also, I know that Subversion has a companion called VisualSvn that allows you to use it inside Visual Studio.  I’ve realized that I’m not a big fan of integrating the IDE with source control.  You may be different, but that’s how I feel…

Anyway, I welcome the change to Subversion and I hope that it serves me as well as Vault has.   

VS.Net 2008 “Command Prompt Here” registry key

To complement a previous post for Visual Studio 2003 and 2005, this registry key will add a context menu item to windows explorer.  The menu item opens a command prompt with the vsvars32.bat from Visual Studio 2008.

 

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOTDirectoryshellVisual Studio .NET 2008 Command Prompt]

[HKEY_CLASSES_ROOTDirectoryshellVisual Studio .NET 2008 Command Promptcommand]
@=”cmd.exe %1 /K “C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\vsvars32.bat””

New website design for Property Center

I updated the Property Center website this weekend.  I worked with the Action Finale guys and they did an awesome job.  The result is super clean xhtml markup and css.  Hell, even the print view looks good.  Take a look at the new design, and let me know what you think.

One minor change I made was to use MooTools instead of Prototype.  While I do like Prototype, I couldn’t justify the 70k+ download for the functionality that I wanted to use.  I was able to use a slightly modified slimbox for the tour previews.  Moo, slimbox, and one other script all come in at less than 40k, which is fine for the few pages that require them.  I am still using prototype for the software portion of Property Center.

Does Google make you less skilled at problem solving?

Over the last few years, I’ve used Google to help me solve various problems, resulting in me not figuring them out on my own.  I’m not saying that I can’t solve problems, but Google is usually the first place I turn to for a solution before taking the time to manually do it. 
I feel that my problem solving skills haven’t been practiced nearly as much as my ability to work the search engine to return relevant results.  Think about it… how many times do you turn to Google to answer a
question that is on your mind?  Rather than figure it out, Google
provides the answer with little thought on your part.  When it comes
time to think for yourself in a situation, you’re less prepared to
solve the problem than if you had been practicing problem solving
skills all along.  So while I don’t dismiss the immediate benefits of
using Google as an answer, I do think we grow more lazy as its index becomes richer. 

This correlates with how cellphones change us as well. 
It might date me to say this, but in high school (and part of college), I
had memorized every phone number of everyone I directly knew.  Although now, I
doubt that I could readily tell you the cell phone numbers of close family members, off the
top of my head.

While I realize that Google (and the cellphone phone book) are tools for solving problems, it feels like cheating to me.  This probably all boils down to evolution.  Lets
just hope the tools we use on a daily basis are factual.  If not,
hopefully we can discern which results are
accurate with our modern tools.
 

Getting familiar with .net 3.5

I started playing around with .net 3.5 today.  I wanted to take a look at the TimeZoneInfo class first, since that new class conflicted with a custom class I wrote for Property Center.  I’m happy to say that the new MS class does everything that mine does, so I can migrate my code to use the MS TimeZoneUtil class in the future.  They finally provide an easy way to iterate all timezones (listed in the current machine’s registry – which seems to be all current timezones in the world), not to mention easy ways to convert datetimes between each timezone.  It factors in all of the rules related to daylight savings as well.

After that, I looked into linq to sql so that I can start playing with actual data in my sql database.  I didn’t really feel like using the Object Relational Designer to generate the entity classes because truthfully… designers really don’t do it for me.  They ship a commandline tool called SqlMetal that does what I wanted.  If you have used subsonic’s generator, you’ll be a little disappointed with the options that SqlMetal provides.  For example, I prefix my tables with pc_, but i don’t want that showing up in my object model.  I couldn’t find a way to have sqlmetal ignore the table prefixes.  It also generates one large file containing all classes, which is a little annoying, imo. 

You can find more information on how to use SqlMetal at: http://msdn2.microsoft.com/en-us/library/bb386987(VS.90).aspx.  And as a side note, SqlMetal.exe exists in C:WindowsMicrosoft.NetFramework3.5.

Property Center running on .net 3.5

I got Property Center running on .net 3.5 tonight.  Honestly, it wasn’t a lot of work.  There were some minor conflicts with the internal timezone class that I use, and I had to enable asp.net 2.0 web server extension with the vs.net 2008 virtual pc image.  Other than that, things compile without any major problems and the site comes up as I expected.  It was interesting to note that as far as IIS is concerned, it still uses asp.net 2.0.

I’m really looking forward to doing some performance tweaking with linq and some of the 3.5 features.  I’m guessing that the site will begin a slow transition away from nHibernate as I get more comfortable with linq and linq for _____.  nHibernate has been great for me, but it has also made me lazy as far as performance tweaking.  It’s not nHibernate’s fault, since it does support performance tweaks quite nicely.  I’ll post my trials and tribulations as I work with the new version of the .net framework.

How to restore a db when the db is in use

I kept running into issues when I tried to restore a database from a backup file.  The error I kept getting was:

Restore failed for Server ‘localhostSQLExpress’.

Additional Information:
System.Data.SqlClient.SqlError: Exclusive access could not be
obtained because the database is in use.

For local sql instances, it’s not a huge deal since I can just restart the db server and clear the connections.  But in a managed/shared environment, that’s not possible.  I googled quite a bit for a solution, but didn’t really find anything that would work.  So I asked the newsgroups for some help and they came up with putting the db in single user mode before restoring the db.  That was cool and all but ended up locking me out of the db at my hoster.  So what I had to do was run the single user mode command and the restore command as one query.  Something like:

ALTER DATABASE  [your_db_name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE

RESTORE DATABASE [your_db_name] FROM  DISK = N’C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLBackupyour_db_name.bak’ WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 10
GO

The restore line can automatically be scripted for you by Sql Management Studio.  Just click the Script icon at the top of the restore dialog.  Maybe MS will add an option to clear connections on restore in a future version of the management studio… One other note is that the restore command will automatically set the restored database in multiuser mode.

Hope this helps someone…

Edit:

If you need to set the database back to multi user mode, you can use the following command:

ALTER DATABASE  [your_db_name] SET MULTI_USER WITH ROLLBACK IMMEDIATE

Parallel Fx

I read a little bit about the concurrency APIs that will ship with .Net 3.5.  It seems that they are FINALLY making it easy to integrate concurrency into an application without having to worry about locks, threads, etc.  I’m not saying that knowing those low level concurrency programming concepts is a bad thing, but it’s nice to see that there is a super easy way to place concurrency into your program.  I read this article about PFX (Parallel Fx) which shows exccellent examples like the following:

void ParMatrixMult(int size, double[,] m1, double[,] m2, double[,] result)
{
  Parallel.For( 0, size, delegate(int i) {
    for (int j = 0; j < size; j++) {
      result[i, j] = 0;
      for (int k = 0; k < size; k++) {
        result[i, j] += m1[i, k] * m2[k, j];
      }
    }
  });
}

 
Also, I found it very useful to listen to this episode of Hanselminutes where Scott interviews the Steven Toub.  They talk about how MS trying to make parallel computing easier on all levels for .net.  It was interesting to hear that Steven didn’t really think that pfx would help web apps much since they run on a webserver that is already pretty optimized for parallel processes.  I’d be interested in seeing a performance graph that shows site performance using pfx versus not using pfx, against a timeline of requests per second.

It’s safe to say that .net 3.5 is getting me excited about .net programming all over.  I think they’re coming out with some pretty cool things that are sure to make life easier (and probably complicated in new ways as well). 

Thoughts about this site

Now that things aren’t so hectic with Property Center development, I hope to get back into the swing of things and start posting more regularly.  I’ve also been thinking of what to do with this site… From the sounds of things, Graffiti cms might be more appropriate than Community Server as the engine for this site.  I’d like to get away from the separate blog per user concept and do something where there is only one entry point of the site while still allowing multiple contributers.  I also think that I’d like to get away from having the date embedded in the friendly urls.  I could go either way with the date thing, since I know I’ll have some posts that are useful for chronological organization, but I’ll have other posts that I don’t want an age associated with.

Community Server doesn’t really fit the role of where I want to take this site, but hopefully Graffiti will.  If not, I may look into writing the software by myself to get acquainted with some newer MS offerings (.net 3.5, linq, mvc, etc…).

The only bummer that I’ll have to work out is what to do with the pictures.  I don’t want to lose the pictures and really don’t feel like moving them all to Flickr.  I guess I could write an image gallery app, but that really doesn’t thrill me.