Archive for March, 2007

March 27th, 2007

Creating a Vista like Search Box

Introduction

In this post we are going to go over what it takes to create a control, and more specifically a Vista Search Box like control.

Definition of Current Search Box

The first thing to do when creating a new control for Windows Forms is determine all the states of the control. In our case the control states are rather simple:

Inactive:
Vista (Inactive)

Active:
Vista (Active)

Text Entered:
Vista (Text Entered)

Button Active:
Vista (Button Active)

Creating the Search Box

The next objective is to determine the inputs, outputs, and events for the control.

Inputs:

  • Text
  • Button Click

Outputs:

  • Text

Events:

  • Text Changed

So now that we have all the inputs, outputs, and events determined, we can start creating the control. The first thing to determine is if we already have a good starting point control that does mostly everything we need. You may be thinking that TextBox Control is a perfect starting point. Normally I would agree with you, but there are certain properties of the TextBox Control that provides states to our search box that shouldn’t be available, such as Multi-Line TextBox, and Password TextBox, both of these examples fall outside of the scope of what our TextBox is suppose to accomplish.

So that leaves us with Control, which is the basis, for all Graphical Objects in the Windows Form library. The pros of using Control over an already established object is that you get to define the exact inputs, outputs, and events that you need. We now need to define all the appearance related properties for our SearchTextBox.

  • HoverButtonColor
  • ActiveBackColor
  • ActiveForeColor
  • InactiveBackColor
  • InactiveForeColor
  • InactiveFont
  • InactiveText
[Category("Appearance")]
[DefaultValue(typeof(Color), "GradientInactiveCaption")]
public Color HoverButtonColor
{
	get { return _hoverButtonColor; }
	set { _hoverButtonColor = value; }
}

[Category("Appearance")]
[DefaultValue(typeof(Color), "WindowText")]
public Color ActiveForeColor
{
	get { return _activeForeColor; }
	set { _activeForeColor = value; }
}

[Category("Appearance")]
[DefaultValue(typeof(Color), "Window")]
public Color ActiveBackColor
{
	get { return _activeBackColor; }
	set { _activeBackColor = value; }
}

[Category("Appearance")]
[DefaultValue(typeof(Color), "GrayText")]
public Color InactiveForeColor
{
	get { return _inactiveForeColor; }
	set { _inactiveForeColor = value; }
}

[Category("Appearance")]
[DefaultValue(typeof(Color), "InactiveBorder")]
public Color InactiveBackColor
{
	get { return _inactiveBackColor; }
	set { _inactiveBackColor = value; }
}

[Category("Appearance")]
[DefaultValue(typeof(Cursor), "IBeam")]
public override Cursor Cursor
{
	get { return base.Cursor; }
	set { base.Cursor = value; }
}

[Browsable(false)]
public override Color ForeColor
{
	get { return base.ForeColor; }
	set { base.ForeColor = value; }
}

[Browsable(false)]
public override Color BackColor
{
	get { return base.BackColor; }
	set { base.BackColor = value; }
}

[Category("Appearance")]
[DefaultValue(DefaultInactiveText)]
public string InactiveText
{
	get { return _inactiveText; }
	set { _inactiveText = value; }
}

[Category("Appearance")]
[DefaultValue(typeof(Font), "Microsoft Sans Serif, 8.25pt")]
public Font ActiveFont
{
	get { return base.Font; }
	set { base.Font = value; }
}

[Category("Appearance")]
[DefaultValue(typeof(Font), "Microsoft Sans Serif, 8.25pt, style=Bold, Italic")]
public Font InactiveFont
{
	get { return _inactiveFont; }
	set { _inactiveFont = value; }
}

[Browsable(false)]
public override Font Font
{
	get { return base.Font; }
	set { base.Font = value; }
}

[Category("Appearance")]
public override string Text
{
	get { return searchText.Text; }
	set { searchText.Text = value; }
}

note: You will notice three different attributes on most of the class properties. They are Category, DefaultValue, Browsable, these are outside of the scope of this article, but I will tell you they effect how the Visual Studio IDE interacts with the SearchTextBox and its available properties at design time.

Next thing we need to do is hook up all the controls events to our specified properties so it acts as we expect it to as defined in our states above. The Control Events we are going to use in order to accomplish the for states that were listed above are: GotFocus, LostFocus, ForeColorChanged, BackColorChanged, Click, and TextChanged.

  • GotFocus
    Occurs when the control receives focus.
  • LostFocus
    Occurs when the control loses focus.
  • ForeColorChanged
    Occurs when the ForeColor property value changes.
  • BackColorChanged
    Occurs when the value of the BackColor property changes.
  • Click
    Occurs when the control is clicked.
  • TextChanged
    Occurs when the Text property value changes.

note: Please see the code listed below for how these events were implemented for our SearchTextBox.

Look & Feel

Well the Control Object isn’t quite as full featured as some of the other controls in the library. So in order to give our SearchTextBox a border to make it look more like a text box we need to tell Windows to draw it with some Native Constants that Windows uses. I am not going to go much in to what all this means, but I will tell you that it draws a thin border around the control.

protected override CreateParams CreateParams
{
	[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
	get
	{
		CreateParams createParams = base.CreateParams;
		createParams.ExStyle |= NativeConstants.WS_EX_CONTROLPARENT;
		createParams.ExStyle &= ~NativeConstants.WS_EX_CLIENTEDGE;

		// make sure WS_BORDER is present in the style
		createParams.Style |= NativeConstants.WS_BORDER;

		return createParams;
	}
}

The next and last thing we need to do to complete our control is set some more attributes that tells the Visual Studio IDE how to interact with our control.

	[Designer(typeof(CoderJournal.Controls.Design.SearchTextBoxDesigner))]
	[DefaultEvent("TextChanged")]
	[DefaultProperty("Text")]
	public partial class SearchTextBox : Control

The Designer Attribute is important because it tells Visual Studio IDE how to render our control. The most important part of the designer class which is outlined in the source package is it’s ability to control how our control is sized. Because when you have a normal TextBox Control you can only size it vertically if the multi-line property is not set. So in order to duplicate this behavior we need to create this designer class.

public override SelectionRules SelectionRules
{
	get
	{
		return base.SelectionRules & ~(SelectionRules.BottomSizeable | SelectionRules.TopSizeable);
	}
}

Example of Use

SearchTextBox searchText = new SearchTextBox();
searchText.TextChanged += delegate(object sender, EventArgs e) {
	outputLabel.Text += Environment.NewLine + searchText.Text;
}

Our Search Box

The following may note be the exact look and feel of Windows Vista, mostly for technical reasons, but there are also some legal ones too. However for the most part you should find the functionality the same.

Inactive:
My Code (Inactive)

Active:
My Code (Active)

Text Entered:
My Code (Text Entered)

Button Active:
My Code (Button Active)

Application & Source

The following is a download of the application and the source of the code that we just went over. Please use the following source code in anyway that you see necessary, just please give my self, Nick Berardi, and this post reference when you use it in its current or modified form. This code comes with no warranty, and for legal reasons is not supported by me.

If you have any questions or comments about this article or the code please feel free to reply below.

Tags: , , , ,

Posted in C#, How To, Programming | kick it on DotNetKicks.com | Bookmark | View blog reactions | 7 Comments »

March 26th, 2007

Google Pack a Computer Users Best Friend

Do you hate having to go to umpteen sites just to download your essential software to get your computer running?
Do you hate then having to again go to umpteen sites again to check for software updates, and then downloading and installing them?

Google Updater Installed Software ScreenWell I have the answer for you, it is call the Google Pack. Not only does the Google Pack include a wealth of Google software it also includes many non-Google software titles such as, Skype, RealPlayer, Adobe Reader, Norton AntiVirus 2005 SE, Ad-Aware SE Personal, Mozilla Firefox, and all the software is downloaded and installed according to your preferences. And as an added bonus there is a service that runs in the background called Google Updater and it will keep all of the supported installed programs updated to their latest and greatest version. See image to the right for a screen shot of Google Updater.

So if you would like to check out the Google Pack just click the button below:


The following wealth of programs is one of the main reasons I recommend it along with Firefox on the left side of my site.

List of Software in Google Pack

  • Google Earth
  • Google Desktop
  • Picasa
  • Google Pack Screensaver
  • Google Toolbar for Internet Explorer
  • Mozilla Firefox with Google Toolbar
  • Norton AntiVirus 2005 Special Edition
  • Ad-Aware SE Personal
  • Adobe Reader
  • Google Talk
  • Google Video Player
  • RealPlayer
  • GalleryPlayerHD Images
  • Skype

Tags: , , ,

Posted in Rant, SEO | kick it on DotNetKicks.com | Bookmark | View blog reactions | No Comments »

March 23rd, 2007

Bill Gates to finially graduate from college

According to Network Wold, Bill Gates will finally get his degree from Harvard. The article had the following to say:

It’s not like he needs it to beef up his résumé, but the world’s richest college dropout finally is getting his degree. Bill Gates, chairman of Microsoft, will speak at Harvard University’s commencement ceremony in June and, like all commencement speakers, will receive an honorary degree from the institution. It’s hard to guess if Gates, the wealthiest person in the world and co-founder of a company that brought in $44 billion in revenue last year, cares. But the programming whiz who once dropped out of Harvard will likely feel some sense of satisfaction.

Posted in Programming | kick it on DotNetKicks.com | Bookmark | View blog reactions | 1 Comment »

March 21st, 2007

New Novell Ad Campaign: Mac vs. PC vs. Linux

Since today was pretty busy for me, and I haven’t had time to post, I just wanted to share these two videos that gave me a good laugh. They came from Miguel de Icaza blog. You have to suspend reality for a second, while watching these videos, and forget that they are referring to PC as a operating system instead of a hardware platform and that Linux also runs on the PC platform and arguably so does Mac. Happy watching…

Apple Ad Spoof #1 from Novell

Apple Ad Spoof #2 from Novell

Tags: ,

Posted in Programming, Rant | kick it on DotNetKicks.com | Bookmark | View blog reactions | 1 Comment »

March 20th, 2007

Apple iTunes: Changing the error message doesn’t fix the problem

Well it’s been a whole 8 days since the last Apple iTunes release 7.1 where Apple wanted us Windows Vista users to be unsecured so they could install the iTunes software. Now the latest version of Apple iTunes has been release, version 7.1.1, and it has the exact same problem except now they changed the error message.
From:

—————————
iTunes + QuickTime
—————————
iTunes could not be installed because Visual Basic Script (VBScript) is not installed or has been disabled. Make sure VBScript is installed, turn off script blocking in anti-virus and personal firewall software, re-register VBScript, and then install iTunes.
—————————
OK
—————————

To:

—————————
iTunes + QuickTime
—————————
The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2738.
—————————
OK
—————————

Unfortunately for Apple changing the error message doesn’t mean you have fixed your past problem. If you check out Apple Support #304405, you see that Apple outlines the same steps I have provided in my previous post. So it is mostly definitely the same issue.

Note To Steve Jobs: Get off your butts and hire some Windows Developers, or fire the current Windows Developers because they aren’t worth their weight in beans. I really don’t understand how they have usability engineers and designers working on the un-packaging process of the Apple products in order to maximize the quality that goes in to every hardware device. How about having some of that rub off on your un-packaging of software?

Tags: , , ,

Posted in Programming, Rant | kick it on DotNetKicks.com | Bookmark | View blog reactions | 2 Comments »

March 16th, 2007

Windows Vista EULA Modified for Windows Anytime Upgrades - No More Limits

We’re making a small but significant modification to the Windows Vista End-User License Agreement (EULA) for Windows Anytime Upgrade. Customers who purchase a retail copy of Windows Vista and then upgrade to another version of Windows Vista using Windows Anytime Upgrade will be affected by this modification, while all other WAU licensing terms remain unchanged.

Now, those customers will be able to uninstall their upgraded copy of Windows Vista and re-install it on another device (usually, but not always, a PC). The number of device-to-device reassignments is no longer limited, provided that Windows Vista has been uninstalled from the original device.

The full text of the change can be found at this FAQ under the final question, “Am I allowed to transfer my software from one device to another when I upgrade using Windows Anytime Upgrade?”

read more | digg story

Tags: ,

Posted in Programming | kick it on DotNetKicks.com | Bookmark | View blog reactions | No Comments »

March 16th, 2007

Using Distributed Transactions in your Data Layer

Many developers use a pattern called ORM or Object Relation Mapping to generate data layers for their application. Many other developers choose to create their own data layers by hand. I have done both and I don’t have a preference of one over the other. With an ORM generator you have an easy to maintain data layer for your applications, when you create one by hand you have much more control of the data layer as far as object creation goes.

Most of the time a business layer will access the data layer in order to provide rules and logic to how the data objects in the data layer are accesses or relate to each other. An example of of how a business layer might relate to data layer is the following. You have a Sales table, a Products table, and a Customers table and objects for each of those in the data layer. In the business layer you may just have an object that is called Checkout that decrements the quantity in the Product table, and then combines the products and customer in the Sales table.

Data integrity is very important in applications like this, you cannot have a sale that is half complete because the revenue numbers would be off for the store. So one problem with keeping all these tables in separate objects is that it is hard to use some of the nice features that SQL provides, like Transactions.

Transactions:

A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties, called the atomicity, consistency, isolation, and durability (ACID) properties, to qualify as a transaction.

Properties of a transaction:

  • Atomicity:A transaction must be an atomic unit of work; either all of its data modifications are performed, or none of them is performed.
  • Consistency:When completed, a transaction must leave all data in a consistent state. In a relational database, all rules must be applied to the transaction’s modifications to maintain all data integrity. All internal data structures, such as B-tree indexes or doubly-linked lists, must be correct at the end of the transaction.
  • Isolation:Modifications made by concurrent transactions must be isolated from the modifications made by any other concurrent transactions. A transaction either recognizes data in the state it was in before another concurrent transaction modified it, or it recognizes the data after the second transaction has completed, but it does not recognize an intermediate state. This is referred to as serializability because it results in the ability to reload the starting data and replay a series of transactions to end up with the data in the same state it was in after the original transactions were performed.
  • Durability:After a transaction has completed, its effects are permanently in place in the system. The modifications persist even in the event of a system failure.

Creating Distributed Transactions:

A new feature introduced in the .NET Framework 2.0 is the System.Transactions namespace, which provides support for transactions across different types of transaction managers, which include data sources and message queues. The System.Transactions namespace defines the TransactionScope class, which automatically manages transactions for you.

To create and use transactions, create a TransactionScope block, and specify whether you want to create a new transaction context or enlist in an existing transaction context. You can also exclude operations from a transaction context if appropriate.

You can call multiple data layer objects, which really creates multiple database connection within the same transaction scope. The transaction scope decides whether to create a local transaction or a distributed transaction. The transaction scope, automatically promotes a local transaction to a distributed transaction if necessary, based on the following rules:

  • When you create a TransactionScope object, it initially creates a local, lightweight transaction. Lightweight transactions are more efficient than distributed transactions because they do not have the overhead of the Microsoft Distributed Transaction Coordinator (DTC).
  • For SQL Server 2005 databases the first connection that you open in a transaction is automatically set as a local transaction. The resource manager then works with the System.Transactions namespace and supports automatic promotion of local transactions to distributed transactions when additional connections are created in the transaction scope.
  • For Non SQL Server 2005 database the first connection that you open is automatically promoted to a distributed transaction. This promotion occurs because the resource managers for these Non SQL Server 2005 databases do not support automatic promotion from local to distributed transactions.

Integrating Transactions Into Your Code
So now that we have gone over what a transaction is and the different types of transactions that .NET can use depending on the database you are connecting too. Lets get to an actual example. We will once again use our example of the Store that needs to make a sales and deduct those quantities from the database.

public class ShoppingCart
{
	public Customer Customer { get; }

	public Product[] Products { get; }

	public bool Checkout ()
	{
		try
		{
			// create the transaction scope to guarantee that all the data gets committed to the database
			using (TransactionScope scope = new TransactionScope())
			{
				// create the sale
				Sale sale = new Sale();
				sale.Customer = this.Customer;

				// save the sale to the database
				sale.Save();

				decimal cost = 0.0M;

				foreach(Product p in Products)
				{
					SaleItem item = new SaleItem();
					item.SaleId = sale.SaleId;
					item.ProductId = p.ProductId;

					// subtract one item from quantity
					p.QuantityInStock--;

					// save the product quantity update to the database
					p.Save();

					// add cost of product
					cost += p.Cost;

					// save item to database
					item.Save();
				}

				sale.Cost = cost;

				// save the sale so the cost is reflected in the database
				sale.Save();

				// commit all database changes to database
				// if complete is not called, due to an exception from the code above, the transaction is rolled back
				scope.Complete();
			}
		}
		catch (Exception exc)
		{
			Debug.Write(exc.ToString());
		}
	}
}

What is happening above is two sales commits and a commit for each product. If any of the lines above the scope.Complete() were to throw an exception the TransactionScope using block would immediately exit and the database saves would be rolled back. Like I mentioned before this is done to keep the integrity of the data in the database intact. For instance if I never made it to the part where I updated the sale.Cost the revenue for the store would be out of whack.

Stay tuned I plan on documenting more of the new features coming in .NET 3.0 and .NET 3.5. I hope this post was informative.

Tags: , , , ,

Posted in C#, How To, Programming, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | 2 Comments »

March 14th, 2007

How To: Unit Test Hidden Classes

Unit testing is an important part of developing high quality software. Many of you are probably not familiar with the term Unit Testing. Wikipedia defines Unit Testing as

In computer programming, unit testing is a procedure used to validate that individual units of source code are working properly. A unit is the smallest testable part of an application. In procedural programming a unit may be an individual program, function, procedure, web page, menu etc, while in object-oriented programming, the smallest unit is always a Class; which may be a base/super class, abstract class or derived/child class. Units are distinguished from modules in that modules are typically made up of units.

One of the most popular ways to Unit Test .NET code is NUnit. However, I am not going to get in to the basics of Unit Testing in this post. If you are interesting in learning more about NUnit and Unit Testing please visit NUnit QuickStart page. This post is going to deal with how does a developer test a class that has a private or hidden constructor.

Private constructors are very useful tool in a developer arsenal, because there are many instances when you want to give the consumer of your code access to the object but not the ability to create it. I have provided an example below:

public class Customer
{
	public static Customer GetCustomer(int customerId)
	{
		// get information from database
		Customer customer = new Customer(customerId, database.GetString("CustomerName"), database.GetDecimal("CustomerAccountBalance"));

		return customer;
	}

	internal Customer (int id, string name, decimal accountBalance)
	{
		// set customer properties
	}

	public int Id { get { return _id; } }

	public string name { get { return _name; } }

	public decimal AccountBalance { get { return _balance; } }

	public void DebitBalance (decimal amount) { ; }

	public void CreditBalance (decimal amount) { ; }
}

There is no real way to test the constructor of this Customer object unless you embed your Unit Tests right in your code. But personally I find that method sloppy because you are mixing QA and Development together, and they should be seperate to at least maintain good software development practices.

If you were to create a Unit Test in the same assembly as the Customer class above, it would look something like this:

Customer customer = new Customer(/* ID */ 20, /* Name */ "Joe Customer", /* Account Balance */ 3400.0M);

// credit the customer $30.00
customer.CreditAccount(30M);

// assert that the original account balance plus the additional credit are equal
Assert.AreEqual(3430.0M, customer.AccountBalance);

But this isn’t very useful if you want to separate your code from your tests. So what is needed is a way to instantiate a private method from outside an assembly. So in order to solve this problem I created the following code that I use in all my Unit Test Projects for just this circumstance. (note: The following code is not for the faint of heart. It combines generics and use of the reflector namespace).

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security.Permissions;

public static class TestHelper
{
	public static T CreateInstanceForNonPublicConstructor<T>(params object[] parameters)
	{
		List<Type> constructorSignature = new List<Type>(parameters.Length);

		// add all the types in order of the parameters to create the consturctor
		// signature so that the correct constructor can be retreived
		foreach (object parameter in parameters)
			constructorSignature.Add(parameter.GetType());

		ConstructorInfo typeConstructor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, constructorSignature.ToArray(), null);
		return (T)typeConstructor.Invoke(parameters);
	}
}

In order to use this code to instantiate the Customer class above, in an external assembly, the same Unit Test from outside the assembly would look like this:

Customer customer = TestHelper.CreateInstanceForNonPublicConstructor<Customer>(new object[] { /* ID */ 20, /* Name */ “Joe Customer”, /* Account Balance */ 3400.0M });

// credit the customer $30.00
customer.CreditAccount(30M);

// assert that the original account balance plus the additional credit are equal
Assert.AreEqual(3430.0M, customer.AccountBalance);

So I have demonstrated that it is possible to fully test all objects from an external assembly using standard Unit Testing as well as keeping your code separate from your tests and upholding good software development practices.

Update: It wasn’t very clear that this code can apply to any type of constructor (public, private, and internal), this code I have in TestHelper can be used in any development process you need it in, I have just chosen to apply it to Unit Testing.

Tags:

Posted in C#, How To, Programming | kick it on DotNetKicks.com | Bookmark | View blog reactions | No Comments »

March 14th, 2007

Remote Desktop for Linux

One of features in Windows that I could not live with out is the Remote Desktop Protocol (RDP). It is one of the best tools out there for remote viewing of your desktop. I use it at work to keep track of my Windows servers as well as log in to my desktop at home to do programming or check personal e-mail. Remote Desktop is fast, flexible, and doesn’t have the problem of having to do a full screen refresh to see what has changed on your desktop. So in a sense it is smart because it only updates the part of the screen that have refreshed. You don’t even loose screen refresh performance when you login to a machine through RDP and then launch another instance of RDP to remote in to another machine from your already remote machine, I find that very impressive.

I have always been using VNC to monitor my Linux servers from my Windows desktop, I have also always wished there was a way login to my Linux servers the way I login to my Windows servers. Today I found the answer and it is 2X Terminal Server. You can read more about this at the digg link below.

read more | digg story

Tags: , , ,

Posted in Programming, Rant | kick it on DotNetKicks.com | Bookmark | View blog reactions | No Comments »

March 12th, 2007

5 Easy Steps To Get iTunes Working On Windows Vista x64

This morning I wrote about the problems I had installing the newly released iTunes for Windows Vista Ultimate x64. I just recently found a solution to the problem error that iTunes was giving me when I tried to install it this morning. The error was:

iTunes could not be installed because Visual Basic Script (VBScript) is not installed or has been disabled. Make sure VBScript is installed, turn off script blocking in anti-virus and personal firewall software, re-register VBScript, and then install iTunes.

And the solution is to simple register the vbscript.dll. To do this you just need to follow the next 3 steps:

  1. Open up the Command Prompt as an Administrator (Go to All Programs > Accessories and Right Click on Command Prompt and then choose Run as administrator)
  2. Type cd C:\Windows\SysWOW64
  3. Type regsvr32 vbscript.dll (This registers VB Script with your computer.)
  4. Now install iTunes as you normally would by double clicking on the install program and wait for iTunes to finish installing.
  5. Type regsvr32 /u vbscript.dll (This unregisters VB Script with your computer.)

If the above didn’t work for you, you may be using a 32-bit version of Windows. Please check out the Apple Support #304405, which will walk you through the process to enabled VBScript on Windows 32-bit.

Please read more if you would like to hear my rant against Apple and the security vulnerability this opens up in the Windows Operating System. On a side note Apple should be congratulated, I guess, for fixing a bug I documented almost 3 months ago when trying to install iTunes on Vista x64.
Read the rest of this entry »

Tags: , ,

Posted in How To, Rant | kick it on DotNetKicks.com | Bookmark | View blog reactions | 40 Comments »