Register here to learn how to use Silverlight to build next-generation applications in half the time it would take with traditional web development technologies. SoftSource provides you with a competitive advantage in application development, delivering the highest quality of software on time and within your budget. Now learn the secrets from our trainers about how to leverage this cutting edge technology to deliver the same results yourself. “Until now, the standard for user experience for browser-hosted applications has been defined by AJAX and JavaScript. However, the powerful and rich user experience provided by these applications has come at a significant cost in development. Silverlight allows us to deliver an even more compelling user experience while simultaneously simplifying the programming model and leveraging our existing .NET skills. During this session we will cover the foundational concepts and technologies you will need to know to jumpstart your transition to Silverlight development. Several highlights include: * Silverlight Architecture * Dependency and Attached properties * XAML resources * How to access your code in XAML.” Registration for the Portland event can be found here: https://registration.sftsrc.com/Register.aspx?EventId=1 There is also a Bellevue event you can attend here: https://registration.sftsrc.com/Register.aspx?EventId=382 Spots are limited, so sign up early to ensure that you get yours.
Practical Silverlight: More than just Flash
Posted by stuartthompson on January 23, 2009
Posted in Silverlight | Tagged: Flash, Portland, Silverlight, SoftSource, Training | Leave a Comment »
The Secret to Organizational Agility
Posted by stuartthompson on December 8, 2008
Mike Cottmeyer wrote an excellent article about the importance of eliminating dependencies in agile projects:
http://www.leadingagile.com/2008/12/secret-to-organizational-agility.html
How many times have the following been true:
- “Many teams are trying to sprint through product development using a traditional MRD or PRD.”
- “Many teams are working with traditional project managers who are doing their best to be agile, but have been trained to manage dependencies and tell people what to do.”
- “Teams are trying to be agile with tightly coupled software architectures, insufficient test coverage, legacy code bases, and unable to do a daily build.”
Removing dependencies is a key step that can be taken towards a truly agile development environment.
Posted in Agile | Leave a Comment »
Be careful with your online brand…
Posted by stuartthompson on December 8, 2008
As the popularity of Web 2.0 is growing, so is the ability for others to observe and evaluate your story and your personal online brand. This article from JASE marketing reports that a “survey of 500 top colleges found that 10 percent of admissions officers said they look at MySpace and Facebook to evaluate applicants.”
I’ve always lived by two golden rules with regards to blogging:
1) Blog only something you would wish to see printed and cited at any time in the future.
2) Do not edit or update a blog assuming that a printed/archived/cached copy of the original does not exist.
It’s a general faux pas to update a blog post for any reason. The web is alive with caches and indexes so the chances are that the original is still out there for people to compare. Spelling errors are generally ok, but if the content of an article is to be updated it is good form to list at Updated: [description of update] at the top or bottom of the post. If an opinion is being revised, be clear about why there is a change in stance. Comments are a great way to revise an opinion after learning new information as it allows readers to see the thought processes and perhaps benefit from the same line of thinking that provoked your own turn around.
Web 2.0 means we are all ultra-connected. This can be great not only for staying in touch with friends but also for business networking and establishing a reputation and a brand in the online world. However, remember that this “permanent record” can go both ways: and this one is for the world to see.
Posted in Uncategorized | Leave a Comment »
Ruby on Rails Setup with DreamHost
Posted by stuartthompson on October 28, 2008
As step 1 of my latest experiment, I’ve started by configuring a Ruby on Rails site with DreamHost. This actually involved quite a bit of setup work, which is not unusual when remotely hosting a new website. I have documented the steps as fully as I can for anyone else curious about trying development in Rails.
Step 1 – Signup with DreamHost
You can sign up using this link or use the promo code LETMETRYRAILS and receive $50 off (i.e. no setup fee).
Step 2 – Configure your domain
The next step is to configure your domain. We’ll start at the DreamHost configuration panel. Select Domains and then Manage Domains from the left-hand sidebar. This will bring up the list of domains in your account. Click the Edit button in the Web Hosting column.
This will open the settings page for that domain. Check the FastCGI and Passenger (mod_rails) checkboxes. Finally click the Change fully hosted settings now! button (note that this button is not at the bottom of the page, rather at the end of the first section).
FastCGI support allows your Rails project to run much faster. The Passenger (mod_rails) option allows your Rails application to be configured much more easily and is the preferred DreamHost method for hosting Ruby on Rails applications.
Step 3 – Configure your FTP/SSH user
We will be performing much of the setup and configuration of the website via SSH. We will need to setup a user account for this purpose. During your initial setup you should have created an ftp account for your domain, probably with the same name as that domain (if you accepted the defaults). Select the Users and then Manage Users options from the left side-bar. Click the Edit button next to your user in the Actions column.
This will open the following page where you can edit your user. Change the User Account Type to Shell account and select the /bin/bash shell type. Finally, hit the Save Changes button at the bottom of the page.
This enables the user to connect using a Telnet/SSH client, which is exactly what we are going to do next.
Step 4 – Download some tools
Next we’re going to download the tools we’ll need to create and configure our rails website. We’ll need the latest release of Ruby, MySQL, HeidiSql, and PuTTY. HeidiSql is a free gui for maintaining MySQL databases. PuTTY is a free Telnet/SSH client that we’ll use for remote configuration of our site. Note that you do not need to signup on the MySQL site to get the download. Click the No thanks, just let me download link.
- Ruby 1.8.6-27 RC1 can be downloaded here.
- MySQL 5.0 Community Server can be downloaded here (select the Windows ZIP/Setup.EXE (x86) option)
- HeidiSQL 3.2 can be downloaded here.
- PuTTY can be downloaded here.
Step 5 – Installing Rails
Now that we have the necessary tools installed it is time to setup Rails locally. Fortunately, Ruby comes with everything we need to get setup and running, including the WEBrick web server that we can use to run and test our site before deployment. When installing Ruby, be sure to check the Enable RubyGems option on the first page of the installer.
Once the installer completes, open up a command window and execute the following commands:
cd ruby/bin
gem update –system
gem install rails –version 2.1.2
This will use the gem system to install rails locally. If everything is successful, your command window should look something like this:
You may need to restart your system at this point. Ughh. This is because Windows Vista and XP sometimes struggle to detect that new environment variables were added to the $PATH. Unless you relish fully qualifying the C:/Ruby/bin directory on the next few commands, I’d advise you restart now. It’s also not a bad idea since we did just install four new programs. I’ve found Windows seems to run more smoothly if you reboot after installing new things.
Step 6 – Create your Rails site locally
Now that we have Rails setup, let’s create a simple site locally. I created a new directory on C:\ called projects in which to develop the site. Open a command prompt and type the following:
cd \
md projects
cd projects
rails MyRailsSite
This will create your rails site in C:\projects\MyRailsSite. Before we add our first view and controller, let’s quickly check that everything wired up properly. To do this we need to start the WEBrick server:
cd C:\projects\MyRailsSite
ruby script/server
Vista may ask if you wish to unblock Ruby, which you do. Your command prompt should look something like the following:
You can now navigate to http://127.0.0.1:3000 to see your site. If everything is configured correctly you should see the Ruby on Rails welcome page:
We can shutdown the WEBrick server by pressing Ctrl-C in the command prompt window.
Now let’s create our first controller and view. We’re going to keep it simple and put up a page that displays the message “Hello World!”. At the command prompt type the following:
cd projects\MyRailsSite
ruby script/generate controller HelloWorld
This will generate a new controller for you as well as a new view. If you aren’t familiar with MVC development, just follow along for now until the sample becomes clear. The rest will come in time and with additional reading and practice. For now it is suffice to say that a controller will perform the work for a web page request where the view will display the results of that work.
Let’s edit the controller that was generated. To do this, open up an explorer window, navigate to C:\projects\MyRailsSite\app\controllers, right-click over the hello_world_controller.rb file and select Edit from the context menu. This should open the controller file in the SciTE editor. We need to add lines to the class to respond to the index action. The index action is the default action that will be performed for a controller. To do this, edit the file to look like the following:
This controller will now set the variable @message to the literal “Hello World”; when the index action is requested. Controllers perform actions.
Save the file and close it. Now we will create a view to display the message. Navigate to the C:\projects\MyRailsSite\app\views\hello_world directory in explorer (notice how Rails created the view directory for us). Right-click in the directory and create a new file called index.html.erb. Now right-click this file and open it in your favorite editor (Notepad will suffice). Add the following to the file:
Save the file and close the editor. We’re almost ready to test out our new controller and view. First, however, we need to configure a route for our site. A route is a mapping from an end-point (url) in our site to an actual controller and view that will fulfil the request. In explorer, navigate to C:\projects\MyRailsSite\config, right-click the file routes.rb and select Edit from the context-menu. This will open your routes file in the SciTE editor. Almost the entire file is commented out. Most of this file contains instructions for configuring custom routes. We’re going to comment out the last two lines of the file and insert a single mapped route of our own. Edit the end of the file to look like the following:
This line connects the helloworld route to the hello_world controller for the index action. The action specification isn’t actually necessary as the index action is assumed by default if none is specified, but I prefer to be explicit.
There is one final thing we’ll need to do before we can browse to our page locally. We need to install and configure MySQL.
Step 7 – Install and configure MySQL
This is a very short step. Run the MySQL setup package you downloaded earlier and select the Typical installation option. Then hit Next->Next->Finish all the way to the end. When the configuration wizard runs, choose Detailed Configuration, then Developer Machine, then Multifunctional Database. When asked for a location for the Inno files, I used C:\projects\MySQL. Choose Decision Support (DSS)/OLAP then leave both boxes checked on the next dialog with 3306 as the port number. Choose Standard Character Set, then check Install As Windows Service and leave Include Bin Directory in Windows PATH unchecked. Enter a new root password, leave Create An Anonymous Account unchecked. Finally, hit Execute to finish the configuration wizard. MySQL is now installed and configured.
Step 8 – Create a database for our project
We’ll need to create a database for our project. To do this we’ll need to install HeidiSql. Let’s run that installer now. I use the defaults from the installer except on the Select Additional Tasks dialog where I uncheck Associate .SQL Files with HeidiSQL. When the installer completes it will launch the HeidiSQL gui. Click the New button at the top of the first dialog. Name the connection MyRailsSite, click OK, and then enter the password you selected during your MySQL installation into the password box provided. The first thing we’re going to do is create a new database. Right-click over root@127.0.0.1 in the left side-bar and select Create database from the context menu. Enter MyRailsSite as the database name and click ok. Now select Tools->User-Manager from the top menu. We’re going to create a new user to avoid using the root user in our application. For the Username type myrailsdbuser, set From Host to localhost, and type a password for your new user. Don’t use the same password you used for root. In the Allow access to list, left-click over the myrailssite database (it will turn yellow). Now click Add User. Then click Close to close the user manager dialog. Now we’ve created a database and a specific user for our Rails application to use.
Step 9 – Configure Rails to use the database
Finally we need to configure our Rails site to use our new database. In an Explorer window, navigate to C:\projects\MyRailsSite\config, right-click the database.yml file and edit it in your favorite editor (I use TextPad but NotePad will suffice). Edit your file to look like the following:
Step 10 – Testing the site locally
We’re finally ready to test the site locally! Open up a command window are run the following to start the WEBrick server:
cd c:\projects\myrailssite
ruby script/server
Then open a browser and navigate to http://127.0.0.1:3000/. You’ll notice that the Rails welcome page still displays. However, change the url in the browser to point to http://127.0.0.1:3000/helloworld. You should now see your view displaying the message “Hello World!”. Let’s remove the default index page now and then make your default route point to your helloworld view. To do this, open up Explorer and navigate to c:\projects\myrailssite\public. This is your site’s public directory. From here, delete the index.html file. That’s the welcome page gone; we don’t need it anymore. Now navigate to c:\projects\myrailssite\config and open the routes.rb file again. Add the following line just before the map.connect line we added earlier:
map.root :controller=>”hello_world”
This configures the root route to point to our hello world controller. As we stated earlier, there is no need to specify the index action as it is assumed by default. Save and close the file, then browse to http://127.0.0.1:3000 once more. Your site should now be displaying your “Hello World!” message. Note how the url is just http://127.0.0.1:3000 and doesn’t have helloworld at the end. This is an important point about routes. You aren’t navigating a particular directory structure on the site, you are simply navigating routes and actions. The controller could be named anything you like as long as the route for a particular end-point correctly routed requests for that end-point to your controller. For now, let’s stop the WEBrick server and close the command window. The final task is to get your Rails site up to DreamHost and serve your “Hello World!” request remotely.
Step 11 – Configuring DreamHost for your site
This final configuration step may seem a little confusing at first, but only if you aren’t familiar with Linux and BASH. It doesn’t take very long and it isn’t important to understand how it works because you’ll only need to do it once. We’re going to install version 2.1.2 of rails to your remote host because that’s the version that Passenger (mod_rails) needs in order to run your site. This is where we’ll need PuTTY. Fortunately there is no installation step with PuTTY. It is simply an executable that you download and run.
When you run PuTTY, you will need to supply the username and password of the user we configured in step 3. This will connect you to the server that will host your site. The following instructions are commands to enter into the BASH shell as well as instructions on editing your ~/.bash_profile file (which is similar to environment settings for the command shell in Windows). The first part of these instructions is about editing your ~/.bash_profile file to ensure that some paths and other required settings are configured before beginning installation. These instructions have been adapted from the DreamHost wiki article on this topic.
Before we update rails, let’s first create our Rails site remotely. To do this, first run PuTTY. For the Host Name you will supply your domain name in the form www.MyDomainName.com. Then click Open. I choose No from the next dialog as I don’t want to store anything in the registry. You will now enter the username and password for the user we created in step 3. When you connect, type ls and hit enter. This is the BASH command to list the contents of the current directory. You should see MyDomainName.com listed in the output. We are going to navigate to that folder and then create a rails site inside that folder.
cd MyDomainName.com
rails MyRailsSite
This will create a Rails site on the DreamHost server, the same way we did it locally earlier. We’re going to create the site like this and then upload our site files from our local machine to the remote site. To upload our files, we’ll use an Explorer window and ftp. First, however, we need to create a copy of our database.yml and environment.rb files. This is because those files will be different on our remote host than they are locally. Create a copy of each of those files called database.yml.live and environment.rb.live now. Now edit the database.yml.live file to look like the following:
Edit your environment.rb.live file and uncomment the following line (its on line 5):
ENV['RAILS_ENV'] ||= ‘production’
This is important because running in development mode under FastCGI will cause memory leaks on the DreamHost server. They will catch them and clean them up but it’s better to run in full production mode and not cause problems.
One final change we need to make locally is to update the c:\projects\myrailssite\config\environments\production.rb file. Comment out the config.action_view.cache_template_loading = true line as it causes problems with the Passenger product that will host our site.
Now we’re ready to install Rails 2.1.2 remotely. Switch back to your PuTTY session (or log in again if you exited). Let’s first edit the ~/.bash_profile file. To do this we will be using the nano text editor. To open the ~/.bash_profile file in nano, type the following:
nano ~/.bash_profile
Now you can use the cursor keys to navigate the file. We need to add the following lines to the end of the file:
# Path settings
export GEM_HOME=”$HOME/.gems”
export GEM_PATH=”$GEM_HOME:/usr/lib/ruby/gems/1.8″
export PATH=”$HOME/bin:$HOME/.gems/bin:$PATH”
export RUBYLIB=”$HOME/lib:$RUBYLIB”
# Stops the DreamHost processes from killing the gem install process
alias gem=”nice -n19 ~/bin/gem”
To save your changes press Ctrl-O then hit enter. Press Ctrl-X to exit the editor and return to the shell. You can now type cat ~/.bash_profile and the contents of the file should be printed out. This is a good way to check that your changes were saved and that you typed everything correctly.
Now we need to perform the installation. The following commands will achieve this:
cd ~
mkdir .gems
mkdir bin lib src
cd ~/src
wget http://rubyforge.org/frs/download.php/43985/rubygems-1.3.0.tgz
tar xzvf rubygems-1.3.0.tgz
cd rubygems-1.3.0
ruby setup.rb –prefix=$HOME
cd ~/bin
ln -s gem1.8 gem
For more information on what each of these steps is doing check the DreamHost wiki article. We can check that the path and gem versions are correct by typing the following:
which gem
gem -v
These commands should return /home/USERNAME/bin/gem and 1.3.0 respectively. Now we can execute the command to install Rails 2.1.2, which is:
gem install rails –version 2.1.2
What we’ve accomplished here is to install RubyGems and Rails 2.1.2 to our hosted server. The last thing we need to do to make everything work is to use rake to freeze our version of Rails to 2.1.2 so that Passenger will use our Rails installation when running our site. The commands to do this are as follows. Please note that you need to supply your domain name in the format MyDomainName.com and the name of your Rails site in place of MyRailsSite in the first command. This simply changes the current directory so that we’re running rake in the right place.
cd ~/MyDomainName.com/MyRailsSite/
rake rails:freeze:edge TAG=rel_2-1-2
That’s it! Phew. That felt like a lot of work, but at least you only have to do it once.
Step 12 – Deploying and testing your site remotely
Now that we’ve set up the environment with DreamHost, the only task left is to deploy the site remotely and test it out. Before we do that though, we are going to check one last configuration setting in the DreamHost control panel, just to be sure that everything is setup correctly. If you navigate to Domains->Manage Domains in the left side-bar and then click the Edit button again (see step 2), then check out the Specify your web directory setting. This is where DreamHost will send requests to MyDomainName.com. It should be set to:
/home/username/MyDomainName.com/MyRailsSite/public
By setting the directory to the public directory of your Rails site, it means that users cannot navigate outside of that directory and browse places that they aren’t supposed to be.
Let’s finish up and deploy our Rails site from the local machine to the remote server. We’ll use Explorer and ftp to do this. Open up Explorer and type ftp://ftp.MyDomainName.com into the address bar. Now open up the MyDomainName.com and then MyRailsSite folders. You will need to copy your app directory from your local machine at c:\projects\myrrailssite\app up to the remote server. When you have copied these files, navigate to the pubilc directory on the remote server and delete the index.html file. We don’t need the Rails welcome page on live anymore either! Then navigate to the config directory and copy the routes.rb, environment.rb.live and database.yml.live files up to the corresponding folder on the server. Don’t forget to rename these to environment.rb and database.yml on the remote server. We only renamed them so that we could have two different files locally. Finally, navigate to the config/environments folder and copy the production.rb file that we edited up to the corresponding location on the remote server. From now on, when you deploy your site, you will only have to copy the app folder to the remote server (unless you change config settings that is).
The final step before we can test our site on live is to setup the MySQL database on the DreamHost side to match the one we set up locally. Since we didn’t create any database tables, this is fairly simple to do through the DreamHost interface. Go to Goodies->Manage MySQL and repeat the same steps here as we did in step 8. You can also use HeidiSQL if you want to manage your database remotely that way. However, for now I recommend using the DreamHost web interface to do this work. All you need to ensure is that the database name and username/password for that database match the settings you specified in your database.yml file. I’m going to cover using databases in Rails in more detail in a future article. For now we just need to get an empty database and a user that has access to keep Rails happy.
Congratulations! Assuming that everything was wired up correctly, you should now be able to open a browser and navigate to http://www.MyDomainName.com to see your site being hosted remotely.
Hopefully this article will help you get up and running with a basic Rails site that is hosted remotely. The focus of this article was understanding the relationship between running a Rails site locally and hosting it on a remote server. Setting up your development in this way from day one will save a lot of headaches later when it comes to deployment time. Developing and testing locally, then deploying to a live host means that problems can be identified early and that changes can be tested locally rather than on a live site. I’m going to expand upon this article as part of my ongoing experiement with ASP.NET, Silverlight, PHP, and Ruby on Rails. Next we’re going to develop a database, understand models using ActiveRecord, and dig a little deeper into Rails. For now: happy hosting!
Posted in Rails, Ruby | Tagged: DreamHost, Instructions, Ruby on Rails, Setup, The Experiment | Leave a Comment »
The ASP.NET, Silverlight, PHP, Rails Experiment
Posted by stuartthompson on October 27, 2008
I’ve been working with Microsoft technologies for over ten years, specifically Microsoft’s web development technologies. During that time I have built a variety of sites ranging in scope from e-commerce, educational, service provision, SaaS, to dashboards, portals, internal tools, and even SAP-migration. While I praise the technology stack for what it allows me to do, it also comes with a whole host of limitations that make it hard for me to deliver the experience my clients would like. Throughout this decade of web development I have heard a lot from those around me about alternative technology stacks that promise all manner of improvements and experiences. Unfortunately there is a lot of resistance from any one technology stack to listen to and learn from the stacks around them, most of the cross-platform feedback comes in the form of “Microsoft sucks” or “PHP is for fan-boy script kiddies”. The truth is that a large number of successful business are hosted on a wide variety of platforms. Each technology stack has to at least be viable for that to be true. The problem is getting at the truth without the zealous noise of “my stacks better than your stack” getting in the way.
I decided that it was time for me to branch out and become more informed on these technologies myself so that I could truly understand the differences and what made each of them unique. I’m hoping that as part of this experience I can not only become a better developer but also learn the problems that Ruby on Rails or PHP addresses. I’ll like to be able to speak from an informed standpoint about the differences between the Microsoft and open-source approaches as well as better understand the problems each of those development worlds faces on a daily basis. Either way, it’s going to be a heck of a lot of fun.
The experiment I have in mind is to build the same web-site using four different technologies. From the Microsoft camp I have chosen ASP.NET and Silverlight. From the open-source perspective I have chosen PHP and Ruby on Rails. I chose PHP and RoR because they are two technologies that I have always wanted to learn. Learning both of those will also require some digging into Apache and Linux, another two areas that I have too little direct experience with to effectively participate in an informed conversation.
Our horses are ready to race. In terms of hosting, I have selected DreamHost for the PHP and Rails sites, and I’m going to use StormHosts for the ASP.NET and Silverlight projects (assuming that SH can do .NET 3.5, which I believe I saw at some point). The reason I’m using remote hosting services for this experiment is that I don’t believe you get the true experience of a technology stack until you host it in this way. It is very easy to get a Rails site up and running using WEBrick and a local installation of Ruby. Similarly, it is easy to get an ASP.NET site running on the personal web server that ships with Visual Studio 2008.
The first phase of the experiment is to get a “Hello World!” site up and running for each of the four environments. The specifications are that a single end-point be accessible that displays the text “Hello World!” and that this end-point is accessible in both Internet Explorer 7 and FireFox 3.
Posted in ASP.NET, PHP, Rails, Ruby, Silverlight | Tagged: ASP.NET, Open Source, PHP, Rails, Ruby, Silverlight | 1 Comment »
Technical Blog Reborn
Posted by stuartthompson on September 25, 2008
After the loss of my SubText blog following an failed upgrade, I am restarting my technical blog here at WordPress. I’m going to spend the next couple of weeks migrating my existing articles over before I get going again on web 2.0 and quality development practices.
Posted in Uncategorized | Leave a Comment »
VSLive! Day One – Architecting ASP.NET Applications Part 2 – Custom Providers
Posted by stuartthompson on October 16, 2007
Custom Providers
The second part of the discussion is opening with a discussion of custom provider development. This is of great interest to me as my recent work with the Model View Presenter pattern has caused me to research and implement dependency injection for many of the layers of my application. The current product that I’m working on is implementing the MVP pattern and is using dependency injection to dynamically load a data layer at run time. There is a need within the product to use a different data access layer assembly for the administrative tools than for the public side of the application. The murky details behind this decision (which I shall leave aside) are to do with the deployment environment and maintenance cycles of the applications going forward. There are a few mechanisms for achieving this dynamic load, however I’ve yet to find conclusive evidence that one method is preferable.
The idea behind dependency injection is improve the following fairly typical line of code:
MyClass myClass = new MyClass();
One potential drawback in this line is that the physical class MyClass has been hard-coded as the only implementation that can exist for myClass. If MyClass implements an interface IMyClass then it might be desirable in the code to switch out the implementation of the interface IMyClass that is being used. The example du jour is switching out an MS SQL data access library for an Oracle data access library. In that example, both implement the same interface but the application wishes to decide which library to use at runtime via a configuration setting. This is a common problem in applications that wish to implement several version of a library than perform very similar but ultimately different tasks. The provider model is based around this need.
The suggested methodology presented in this talk is to use:
Type myType = Type.GetType(“MyNamespace.MyClassName”);
IMyClass myClass = System.Activator.CreateInstance(myType);
The theory here is that Type.GetType returns an object that describes the type to be created. The System.Activator.CreateInstance line creates a concrete instance of the requested class except by this mechanism the class has been created using a string name versus a hard-coded class name. This methodology works for classes that exist within the same assembly, however will not work for classes that exist outside of this assembly. There is an extension to this will work for classes outside of this assembly.
Dynamically Loading Assemblies
In order to extend this methodology to work for classes that are in other assemblies, there is a need to first load that assembly. This is achieved via the following methodology:
Assembly asm = Assembly.LoadFile(MyAssemblyFileName);
IMyClass myClass = asm.CreateInstance(MyClassName);
The basic change here is that now the concrete class instance is created from the assembly reference versus System.Activator. This allows the dyanamically loaded class to reside in a separate assembly. Now we have the ability to specify which data access layer library is being used within the application at run-time. All calls within the application are made against the IMyClass interface, but the implementations now differ based upon the physical data access library that is loaded at run-time.
Interface Isolation
Finally, interfaces are isolated into a separate assembly from either (any) of the concrete implementations of that interface. The reason for this is that we do not want to require a reference from the main application to either of the implementations of the interface. Such a reference would defeat the purpose of the exercise as it would again tie the application directly to a particular implementation. Instead the main application references only the assembly that contains the interface. Now any implementation of that interface can be used from within the main application by dynamically instantiating the implementation using the mechanism above.
Posted in ASP.NET | Tagged: VSLive! | Leave a Comment »
VSLive! Day One – Architecting ASP.NET Applications Part 1
Posted by stuartthompson on October 16, 2007
Getting Situated
For the preconference, I decided to attend Paul Sherrif’s talk on Architecting ASP.NET Applications. Fortunately, I was able to get to the room about an hour early and find one of the few seats situated close to a power outlet. I really didn’t want to have to transfer my notes from paper to my laptop later; I’d rather just type them out directly!
N-Tier Development Benefits
The workshop has begun with a discussion of n-tier development; the benefits of logically separating services into different libraries and isolating functionality into discreet sections. The advantages of this approach are that the maintenance and extension of your application are vastly simplified. Refactoring common methods into reusable libraries minimizes the amount of work involved in fixing bugs because the buggy code needs only be fixed in one location. Adapting to large-scale architectural changes in the application is also easier if a modular development model is adopted. Switching out small components to adapt to technology shifts is far easier than making global code changes. This means that large-scale changes can be handled cheaply and quickly. The majority of the application libraries do not need to be run through a quality assurance cycle because they were not changed when the maintenance was performed. Only the new library needs to be tested in addition to running a full integration test, which is still far cheaper that re-testing the entire system. The following is a table detailing the suggested areas of isolation for an ASP.NET application:
| Business Rules | User Interface | Configuration Management |
| Data Access Service | Exception Management | Security Management |
| Data Layer | User Tracking | Log Management |
Configuration Management
As opposed to using the System.Configuration.ConfigurationManager.AppSettings["MyConfigItem"] approach for reading settings, a custom AppConfigManager class can be built that isolates access to configuration settings into static properties on that class. The argument for this architecture is that when and if the access mechanism for configuration settings changes in future versions of .NET, the changes will be isolated to only the AppConfigManager class. This is a valid argument because the mechanism for reading configuration settings changed from .NET 1.1 to .NET 2.0. In .NET 1.1 we used System.Configuration.ConfigurationSettings, however in .NET 2.0 we are encouraged to use System.Configuration.ConfigurationManager instead. Encapsulating application configuration settings is an architecture I’ve considered several times before but there is something that always makes me balk at the idea of a class full of statics. The difference here, which I like, is that a sound justification exists and that the statics aren’t just returning constants. Instead the static is returning a value using the System.Configuration.ConfigurationManager.AppSettings["MyConfigItem"] mechanism. This does have the nice effect of isolating the final method of configuration management from the rest of the code in the application. Should the mechanism for accessing configuration settings change in the future, only the AppConfigManager wrapper class will need to be updated.
I could be wrong, but I think Paul just compared using Intellisense to “using the force” ala Star Wars: <sigh>. At least the humor hasn’t changed since the last conference I attended. Actually, so far the guy has been pretty funny so I’ll give him a break.

Custom Collection Classes
The major philosophical question that has arisen so far is whether or not to use custom collection classes when transacting between a data layer and a business tier or user interface layer. The code samples presented use DataTable instances. The argument presented is that a DataTable is actually analogous to a custom collection class as it has proprietary column names within it that correspond to the unique properties and data types of the business object being modeled. The only concession offered in the workshop is that this does open a potential window for failure if Microsoft decided to drop support for the DataTable class in favor of a superior class.
Code Generation
For a while now I have separated data adapter classes from object builder classes. The data adapter classes are responsible for executing sql commands to a database and either writing or reading common data collection classes; such as IDataReader. The builder classes are responsible for digesting those data collections and building concrete objects from them. This allows for a nice separation between data interaction and data digestion. However, I’ve always written both classes by hand. They do not present a large chunk of work and I have usually disregarded the cost of coding such small functional classes as being negligible. Code generation is something that has been suggested for these classes in the past, but I have often found that building the required code generation framework can be just as expensive as writing the classes that are needed. However, the argument being presented in this workshop for code generation is that if the data builder level classes and stored procedures are generated then schema level changes are reflected more quickly. This is an interesting advantage to note in the argument for using code generation for parts of the data layer.
Deriving Business Rule Objects
The next part of this discussion addresses a second common problem with code generation, that of custom rule application. A code generator can easily intuit the basic rules that need to be enforced for objects built from a schema, for example that required fields are populated. However, a code generator cannot easily imply that a cost field needs to be between certain threshold values. To address this problem, Paul suggests that a custom business rule object be derived from the generated data class. The data class implements validation as virtual methods that can be overridden in the custom business class. The overridden method can then apply the additional validation to enforce proprietary business rules.
Posted in ASP.NET | Tagged: VSLive! | Leave a Comment »
Null-Coalescing Operator
Posted by stuartthompson on August 10, 2007
While at a rather disappointing MSDN event yesterday, I came across one gem of C# 3.0 candy in the form of a null-coalescing operator. This is basically a short-cut for the oft seen:
string emailAddress = parsedValue != null ? parsedValue : “(Not provided)”;
OR
string emailAddress = String.Empty;
if (parsedValue != null) {
emailAddress = parsedValue;
}
else {
emailAddress = “(Not provided)”;
}
Using the Null-Coalescing Operator
These can now instead be re-written using the new null-coalescing operator as:
string emailAddress = parsedValue ?? “(Not provided)”;
This can roughly be read as “Set emailAddress equal to parsedValue unless it is null, in which case set it to the literal (Not Provided)”.
Applications with Nullable Types
This is also very useful with the new nullable types. For example, when converting an integer to its value type:
int? recordsAffected = null;
… code that might cause recordsAffected to contain a value …
int totalRecordsAffected += recordsAffected ?? 0;
Here a nullable int type can be added to a regular int without fear of an exception by subsituting 0 in the place of a null value. It’s always nice to find new candy!
Posted in C# | Tagged: ??, Null-Coalescing Operator | Leave a Comment »
Using Anonymous Method Predicates to Search Lists
Posted by stuartthompson on August 7, 2007
I use System.Collections.Generic.List all over the place. Generics are a couple of years out of date and most people are done with them in terms of cool factor, but that doesn’t in any way detract from the coolness they add to my life each and every day. I still eat toast and that’s been around for ages. I answered a question this morning that made me realize that while the generic list class has been generally embraced by most, it perhaps has also been generally muddled by some attempting to keep up with the oft quick pace that is .NET. I’ve seen quite a few development shops that stuck around on .NET 1.1 for a long time because of migration concerns and then very quickly “updated their code” to embrace .NET 2.0 without really giving people the time to absorb all of the new information. One of these areas is with collection classes.
When a development shop moves to .NET 2.0, one of the first things you’ll see is a bunch of {blah}Collection class objects being removed from the codebase and their usage replaced with List throughout. This is all well and good. A smaller code surface area is easier to test and maintain, and most people didn’t ever fully finish building a complete collection class anyway, feeling that the code around finding, searching, comparing, etc… within the collection classes was always a little muddy. It’s true that building a robust collection class is difficult, especially when considering an object model that involves some serious aggregation.
However, we seem to have found a new source for confusion on how to search collections in the adoption of the System.Collections.Generic.List class. The question I answered this morning about searching a generic list is not the first I have received, so I thought I’d take the time to share a couple of techniques that I use and get feedback from others on their strategies. What prompted me to write this article was a small snippet of code I received that looked like this: (original code modified to protect the innocent)
string targetName = “Thompson”;
List myObjectList = new List();
… list is populated with some items …
MyObj selectedObject = null;
foreach (MyObj obj in myObjectList)
{
if (obj.Name == targetName)
{
selectedObject = obj;
}
}
The code looks reasonable from a first glance. The original code was actually copied from within a collection class’ SearchByName() method when the class was being replaced with a System.Collections.Generic.List. This is scary for a couple of reasons. First of all, original code contains a couple of bugs that weren’t addressed as part of the migration probably because very little time was given to “move to .NET 2.0″. &nbp;Secondly, this probably isn’t an isolated case. I suspect that this kind of refactoring is happening in a lot of other projects. Let’s look at the code in a little more detail and think about some of the opportunities for improvement.
The first obvious bug is that if two objects exist in the list with the target name, the last one searched that matches is being set as the selected object. This shouldn’t simply be handled by adding a “return” within the loop to return the first either (which I’ve seen in “fixes” before). In this case it is probably important to know that more than one object matched the target name. While seemingly minor, there is no lock statement around the foreach search, meaning that the list could be modified during the search by code in any thread with a reference to the list. Wouldn’t it be nice if there were a way to find an item in a list without having to worry about such things?
The System.Collections.Generic.List class provides Find() and FindAll() methods that take a System.Predicate as a parameter. Most developers I’ve watched tend to browse this method in Intellisense, think “Oh my god, I have no idea what this Predicate class is” and then code a method similar to the one listed above. However, the System.Predicate generic really isn’t all that scary and is actually a really elegant solution to the problem. Look at the following code for a second:
string targetName = “Thompson”;
List myObjectList = new List();
… list is populated with some items …
List matches = myObjectList.FindAll(delegate(MyObj compare)
{
return compare.Name == targetName;
});
Here, an anonymous method was used as an implementation of System.Predicate to determine whether the comparison of an object’s name to the target name was true. That’s essentially how predicates work, they assert whether a particular predicate is true or not. In this case, we are using them to determine whether or not a particular item in a collection matches certain search criteria. The way that the FindAll() method works is to pass each object in the collection to the specified predicate and add the object to a match list if the predicate is true. In the one call to FindAll() our code was able to determine all items in the list that have the specified target name. Also, the Find() and FindAll() method correctly issue a lock statement upon the list to protect the search, as well as other finery around error handling for null objects in the list. All of this code for free in a single method call.
Anonymous delegates do not have to be used for predicates, although they present the most graceful solution for a parameterized search. What I mean by this is that if your search does not rely upon a parameter like targetName in the example above, you could pass a delagate implementation to the find method. The example below shows how a predicate can be used to find items in the list with a name longer than 5 characters:
List myObjectList = new List();
… list is populated with some items …
List matches = myObjectList.FindAll(ObjNameLongEnough);
The method ObjNameLongEnough is defined as follows:
private bool ObjNameLongEnough(MyObj compare)
{
return compare.Name.Length > 5;
}
This example gives a better idea of how the anonymous method delegate is working by showing the signature of the System.Predicate that is expected. Notice that the method signature of ObjNameLongEnough() takes a MyObj parameter. The FindAll() method simply calls this delegate for each item in the list and adds the object to the match collection if the predicate returns true. If the desired behavior was to find only the first match in the list, use the Find() method instead.
Astute readers are probably wondering if there is an overloaded version of System.Predicate that takes an additional search parameter. This would have allowed for the first example that compared to target name to be coded as an actual delegate as opposed to an anonymous method by passing the targetName variable into the search delegate. However, unfortunately, there is not an overloaded version. This appears to stem from the computer science root that a predicate is simply a test that something is true of something. Therefore a predicate cannot be parameterized as it would be testing its trueness(TM) to something in relation to something else.
IMHO anonymous methods are still a great solution to the problem and provide compact, readable code for searching generic list collections without having to worry about the finer points of locking, object null testing, and first match versus all matches. Enjoy!
Posted in C# | Tagged: Anonymous Methods, Predicates, Search | Leave a Comment »













