Posts Tagged ‘.Net’

December 7th, 2007

SEO and C# Extention Methods

I previously talked about the importance of using the correct kind of redirect to optimize your website for search engines in an article titled. World Of HTTP/1.1 Status Codes. I just recently decided to create a C# Utility class to help me in this endeavor and to extended the far from complete HttpResponse.Redirect method. I am using a new C# 3.0 language extension called Extension Methods. Basically what the extension method does is, it allows you to, add methods to types that you don’t have the ability to modify, in my case the HttpResponse class.

I have created the following code to give me better control over my redirects in the HttpResponse class.

public static void Redirect(this HttpResponse response, int type, string url)
{
	response.Clear();

	switch (type)
	{
		case 301:
			response.StatusCode = (int)HttpStatusCode.MovedPermanently;
			response.StatusDescription = "Moved Permanently";
			break;

		case 302:
			response.StatusCode = (int)HttpStatusCode.Found;
			response.StatusDescription = "Found";
			break;

		case 303:
			response.StatusCode = (int)HttpStatusCode.SeeOther;
			response.StatusDescription = "See Other";
			break;

		case 304:
			response.StatusCode = (int)HttpStatusCode.NotModified;
			response.StatusDescription = "Not Modified";
			break;

		case 307:
			response.StatusCode = (int)HttpStatusCode.TemporaryRedirect;
			response.StatusDescription = "Temporary Redirect";
			break;

		default:
			goto case 302;
	}

	response.RedirectLocation = url;

	response.ContentType = "text/html";
	response.Write("<html><head><title>Object Moved</title></head><body>");
	response.Write("<h2>Object moved to <a href=\"" + HttpUtility.HtmlAttributeEncode(url) + "\">here</a>.</h2>");
	response.Write("</body></html>");

	response.End();
}

So now in your code you don’t have to jump through hoops to chance the StatusCode, StatusDescription, RedirectLocation, and ContentType, just so you can respond with a 301 Redirect instead of a 302 Redirect (the default for HttpResponse.Redirect and the most dangerous of the redirects from an SEO point of view). All that you need to have access to is the Response property from your Page or Context and you are good to go.

Response.Redirect(301, "http://www.coderjournal.com");

So that is all you need to do to give your self better control over your redirects in .NET. You can also use this same C# 3.0 Extension Methods for any object that you need to add a custom method on to.

Tags: ,

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

November 19th, 2007

Visual Studio 2008 and .NET 3.5 Released

Scott Guthrie has announced that Visual Studio 2008 and .NET 3.5 are now available for download and provides a tour of some of the new features.

  • If you are a MSDN subscriber, you can download your copy from the MSDN subscription site (note: some of the builds are just finishing being uploaded now - so check back later during the day if you don’t see it yet).
  • If you are a non-MSDN subscriber, you can download a 90-day free trial edition of Visual Studio 2008 Team Suite here. A 90-day trial edition of Visual Studio 2008 Professional (which will be a slightly smaller download) will be available next week. A 90-day free trial edition of Team Foundation Server can also be downloaded here.
  • If you want to use the free Visual Studio 2008 Express editions (which are much smaller and totally free), you can download them here.
  • If you want to just install the .NET Framework 3.5 runtime, you can download it here.

Tags: , , , , , ,

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

July 11th, 2007

Wii Debugging Your .NET Code On Linux

It’s official MainSoft developers have too much time on their hands. I personally think so, but if you are one of those coders who always wished they could debug .NET code on Linux using your Wii remote you might disagree with me.


Video: Debugging .NET On Linux Using a Wii Remote

Tags:

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

July 9th, 2007

Evolution Of LINQ And Its Impact C# 3.0

One of the things I love to learn about is the history of how things come to be. Specifically my interests have always been in the evolutions of religion and the tech world (yeah I know pretty much polar opposites, but that is what I like to learn about). I came across an interesting article in my MSDN subscription that talked about how language features of C# 3.0 came to be. The features I am talking about are:

  • Lambda Expressions
  • Extension Methods
  • Anonymous Types
  • Implicitly Typed Local Variables
  • Object Initializers
  • Query Expressions
  • LINQ

All these features were made possible because of they wanted to add a feature that let you query collections much like how you query SQL (LINQ) and the strong convictions of the C# language maintainers to not implement hacked together solutions. Much of the same convictions that I try to promote on this blog, and because of these convictions C# developers got some very nice features out of the language.

If you have not heard of LINQ before, this is the basic C# language construct (notice the similarities to SQL):

var overdrawnQuery = from account in db.Accounts
                     where account.Balance < 0
                     select new { account.Name, account.Address };

This article, The Evolution Of LINQ And Its Impact On The Design Of C#, is well worth the read and I recommend it to anybody that wants to learn more about C# 3.0 or is just interested in how good coding practices can have great impact on projects.

Tags: , , ,

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

June 26th, 2007

SQL Server 2008 Will Have 7 New Datatypes

I haven’t even herd of a new version of SQL Server 2008, coming out, but according to this blog the new version has some very interesting and new data types that will come in useful for geography processing.

DATE - ANSI-compliant date data type
TIME - ANSI-compliant time data type with variable precision
DATETIMEOFFSET - timezone aware/preserved datetime
DATETIME2 - like DATETIME, but with variable precision and large date range

GEOMETRY - “flat earth” spatial data type
GEOGRAPHY - “round earth” spatial data type
HIERARCHYID - represents hierarchies using path enumeration model

The first four datatypes are regular SQL datatypes but the last three datatypes are exposed as .NET system UDTs.

Tags: , ,

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

June 1st, 2007

Less Rules Imposed The Better

Recently I read an article from Jeff Atwood, where he basically claimed the brevity leads to better code. Personally I think his example he gave:

if (s == String.Empty)
if (s == "")

Is just plain wrong, and this is the comment I put on his website:

I think this is a very bad example using “” and String.Empty. Because essentially “” is a magic number of sorts, I am talking totally theoretical here, I know that “” is never going to change from representing a empty string, but what happens when developers start using “\n\r” instead of Environment.NewLine, not only does it cause a problem if you move to Mono on Linux it also requires a higher knowledge level to understand what “\n\r” means and you even have to remember what order it goes in.

It is good practice to get developers thinking that magic values such as “” and “\n\r” and any number is not the right way to code. Because if you tell them it is okay to use “” then why is it not okay to use 3.14F for PI instead of using Math.Pi?

It’s all about staying consistent and having the least amount of rules as possible, that is how you keep code simple across your organization.

Also by your same logic a developer should never use VB.NET because the language is way to verbose. I personally am a C# developer, but if a person is more productive in VB.NET and it meets the requirements for the project who am I to tell them they should use C# because it is less verbose.

Tags: ,

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

May 11th, 2007

Understanding C#: ?? Operator

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.

int? i = null;
int count = i ?? 0;

The value that count is set to is 0. The ?? operator is short hand for:

int? i = null;
int count = i.HasValue ? i.Value : 0;

Or

int? i = null;
int count = 0;
if (i.HasValue)
	count = i.Value;

The Understanding C# series at Coder Journal will be an on going project to help the readers to better understand the C# programming language that doesn’t get covered except at the more advanced levels.

Tags: ,

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

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 | 5 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 7th, 2007

Visual Studio 2005 Update for Windows Vista

I was reading Tim Sneath’s blog today and noticed his post on the release of a Visual Studio 2005 Update for Windows Vista was released. It is a recommenced update for anybody using both of these products.

The final release of the VS 2005 update for Windows Vista is now available. This update fixes most of the issues that you may have faced with running Visual Studio 2005 on Windows Vista. Install Visual Studio 2005, the Service Pack 1 update, and then the Windows Vista update to get a fully-supported developer environment.

It is a pretty quick update, I updated my laptop as I was writing this post.

Tags: , ,

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