From everyone at BloggingAbout.NET
HAPPY NEW YEAR
I got a question during my latest presentation about automatic properties (full name is actually automatically implemented properties) with just a 'getter'. I could not remember the syntax, thought it was something with the readonly keyword. I was wrong, here's the correct syntax.
public class Training
{
public string Title { get; private set; }
public int Days { get; set; }
}
Note that this does have a setter, although it's set to private. The reason is that it's otherwise impossible to actually set the Title of the training. Normally we would set the backing field '_title', but as this is generated by the compiler, we can't access it yet.
The equivalent is:
private string _title;
private int _days;
public string Title
get { return _title; }
private set
_title = value;
public int Days
get { return _days; }
set { _days = value; }
Note that the private setter is still there. You can remove it completely and set the backing field as explained.
Why is it that in Oracle world, it's much more custom to have a database administrator (DBA) on your project than when you're working with SQL-Server? I believe it brings great value to a project to have a dedicated experienced DBA working in the team. And I think part of the problem is the fact that Oracle is much more complex to manage, whereas SQL-Server figures out a lot by itself. That's of course a lot of power coming from SQL-Server, but it has its negatives that most developers don't think they require a DBA that often.
I'm writing this because since LINQ and specifically LINQ to SQL has been released, I've had some discussions on wether the query engine of LINQ to SQL is smart enough to create solid and performing queries. There are a lot of things to say here, because when is a query fast enough? This also depends on the requirements of your architecture. Otherwise it's just a gut feeling of when it's not fast enough anymore.
But someone stated recently that
a LINQ to SQL query can never be as fast as a stored procedure written by a DBA
LINQ to SQL could never optimize your query because it doesn't know enough about the database, whereas a DBA does. The conclusion was that you should stick to regular ADO.NET. Of course this is nonsense. For multiple reasons
var query = db.CustomersByCity("London");
var query = from c in db.CustomersByCity("London")
select new { c.ContactName, c.City };
where c.ContactName.Contains('A')
I hope I've explained why it's not logical to easily ditch LINQ to SQL in favor of the regular ADO.NET and Stored Procedures, simply because of performance or other issues. I'm not saying you should use LINQ to SQL everywhere and I'm not saying it's the silver bullet. I'm also not saying you can never write more performing queries in Stored Procedures than LINQ to SQL can. When you're working with and querying large sets of data, you're probably better of using Stored Procedures instead of retrieving thousands of rows into your application. But not using it at all because of the wrong reasons and not giving it a try without some investigation or proof of concept, might be even worse. It can save you a serious amount of time in your development.
I blogged about new Unit Testing features in Visual Studio 2008, but missed the following features back then. I thought it's still cool to share these with you.
Short cut keys to run tests
I used to use TestDriven.NET in the past for executing my NUnit tests really fast. It always started them in the context you right-clicked for the menu, be it a test method, class or project. Visual Studio 2008 has the right-click context menu as well, but not in classes or projects. Luckily you can also access them with shortcut keys, which is even better1.
I only memorized and use the first two though. Remember also that when you hold the Ctrl key when pressing the second key you'll execute the tests with the debugger.
Clicking error result and go to your test
Why this is off by default still wonders me. Besides the context menu, this was my biggest pain in Visual Studio 2005. When you double-click a failed test, you'll get some error report. And when you had more than one Assert in your test and didn't use comments, you didn't even know which assert failed. Now you can turn on that whenever you double-click the failed test in the test results window, you'll be taken to the Assert that failed. Turn it on in options under Tools -> Options -> Test Tools -> Test Execution and check the last checkbox.
Disable deployment of tests
People that do Test Driven Development want to compile and execute their tests as fast as possible. By default however, Visual Studio copies all binaries, debug files, etc to a deployment folder where the tests are executed. If you want to disable this, find the folder "Solution Items" in your solution and double-click the .testrunconfig file. Select "Deployment" from the list and uncheck "Enable Deployement".
Private accessors
Visual Studio 2008 has another cool feature where you can access private types in an assembly. With the tool publicize.exe you can create a wrapper assembly that gives you access to the private types. I created a simple example class, as shown below.
public class Class1
private int _age;
private string Name { get; set; }
public int Age
get { return _age; }
set { _age = value; }
private string CheckThis(int i)
return (10 * i).ToString();
We'll use Visual Studio 2008 instead of directly accessing publicize.exe. You can create unit tests for this class by bringing up the context menu in the class (right-click in the code editor) and select to generate unit tests. Now make sure also the private method and property is checked and create the unit test. Your unit test will look as follows:
[TestMethod()]
[DeploymentItem("ClassLibrary1.dll")]
public void NameTest()
Class1_Accessor target = new Class1_Accessor(); // TODO: Initialize to an appropriate value
string expected = string.Empty; // TODO: Initialize to an appropriate value
string actual;
target.Name = expected;
actual = target.Name;
Assert.AreEqual(expected, actual);
Assert.Inconclusive("Verify the correctness of this test method.");
Note that I used stupid names like "ClassLibrary1" and "Class1", but that doesn't matter. You see that instead of the normal Class1 being initialized, the Class1_Accessor is being initialized. Where does it come from? Use the other new cool feature by right-clicking the project and at the bottom of the context menu you'll find "Open folder in Windows Explorer". Select the \bin\debug\ folder and you'll see a new assembly there. When looking at it with reflector, here's our Name property being exposed.
Visual Studio 2005 vs. Visual Studio 2008
Now you know a little more about Visual Studio 2008 unit testing. Note that you can use these features even on .NET 2.0 projects. It's only the solution files (.sln) that aren't compatible. The project files (.csproj) are compatible and can be freely exchanged. A good solution (no pun intended) is to create a Visual Studio 2005 solution and a Visual Studio 2008 solution. Just make sure that changes to the solution are made in both and you'll have a great Visual Studio 2008 experience, even though other team members aren't using it.
What is a good way to specify requirements? I actually have no idea... I come across many different companies and a lot of them all have the same problem. The customer wants some problem to be solved and multiple people start thinking of a solution. Sometimes the technology is already chosen before the problem is fully specified, but that's something for another post. :-)
Although I wouldn't know what the best solution for your company or product is to specify requirements, I know a good document when I come across one. I used to work with Use Cases at my previous employer, which worked quite well. It probably wasn't even the Use Case, but more the writer(s) of them.
But I've found some nice examples that Microsoft is using for specifying their requirements for Team Foundation Server (TFS). There's a somewhat older document that can be found via Buck Hodges (pronounce : Buck Rogers) his weblog. It's about the Continues Integration (CI)features in TFS 2008. You can also find three new documents on Rosario, the next version of TFS & Visual Studio. You can find all three here and probably more will appear in the future.
The first about CI contains just samples for the screens with explanations. The new three contain also a load of text. They might not 100% suit you, but you might probably get an idea to what both customers and developers might fully understand. And that's important, or else you'll get something like this.
For those that are still curious after my previous post about using C# 3.0 features in .NET 2.0. You can compile any .NET Framework 3.5 project and run it in a .NET Framework 2.0 environment (read, no .NET Framework 3.5 installed) without any problems... as long as there are no dependencies to the .NET 3.5 assemblies!
Create a new Console Application under .NET Framework 3.5. Check your references, System.Core will be automatically added to the project. This is a .NET Framework 3.5 assembly. Remove it.
Now add a single Console.WriteLine as follows:
using System;
using System.Collections.Generic;
using System.Text;
namespace FrameWork35ConsoleApp
class Program
static void Main(string[] args)
Console.WriteLine("Hello world from a .NET 3.5 application.");
Compile it and copy the executable to a .NET Framework 2.0 machine. Again, one without .NET Framework 3.5 installed.
Run the executable and watch the result.
Yesterday I wrote an article on the property snippet in Visual Studio 2008 and that it had changed from Visual Studio 2005. Only a few hours later, I questioned myself if even a few people might be interested in this. Not because of the snippet, but because of the abilities that Visual Studio 2008 and its C# compiler bring you.
Note : I do have interest for it, because I still have to teach people .NET 2.0. They look 'gobsmacked' at the automatic properties and as I don't want to confuse them, I still like to have the old property snippet! :-)
Daniel Moth reminded me of an article of him from back in may, where he wrote about using C# 3.0 features in .NET 2.0 and the confusion in discussions about this 'feature'.
The truth is, some of the new C# 3.0 features are purely compiler magic. So when you're using Visual Studio 2008 and are working on a .NET 2.0 project, you can use a selected set new features. Not because they're C# 3.0 features, but because they're features of the new compiler!
Daniel also explains that other features don't work, because they rely on the System.Core.dll assembly. If you want to use extension methods for example, that's not possible. You're missing the ExtensionAttribute. Copy the following code into a Visual Studio 2008 .NET 2.0 project.
public static class Extensions
/// <summary>
/// Example of an extension method in C# 2.0
/// </summary>
/// <param name="s">This disappears</param>
/// <param name="value">The character to look for in the string</param>
/// <returns>The number of times the specified character exists in the string.</returns>
public static int CountChars(this string s, char value)
int startIndex = 0, foundAt = 0, timesCounted = 0;
while ((foundAt = s.IndexOf(value, startIndex)) != -1)
startIndex = foundAt + 1;
timesCounted++;
return timesCounted;
Now you get a nice error...
Daniel again explains that this is really easy by adding that attribute ourselves. Check his C# 3.0 features in .NET 2.0 article for it. I've created a full solution though, which you can download at the bottom.
But Daniel goes even further by explaining how you can make LINQ work in .NET 2.0. Don't forget that LINQ isn't 'just' all compiler magic. The query expressions (using 'from', 'where', 'select', etc. (stand-alone) keywords) are, but the operators aren't. Daniel explains the differences over here. Of course all the implementations of LINQ to objects, LINQ to SQL, LINQ to XML, etc live in the .NET Framework 3.5 assemblies. But what if we were to write our own? Again, there's an example for this and you can guess from who. Find it here.
After implementing that class, you can easily write the following code in your .NET 2.0 project.
var ints = new[] { 1, 2, 3, 4 };
var res2 = from p in ints
where p > 2
select p;
Now isn't that just cool?
Remember though, if you're on a .NET 2.0 project and the other developers don't have Visual Studio 2008 installed, you're in for a problem. This doesn't work in Visual Studio 2005!
Download the solution with all the code here.
A while ago I read the excellent book by Robert C. Martin, called "Agile Software Development : Principles, Patterns and Practices", I think one of the -if not the- books on [wikipedia:Agile Software Development]. But when in the need for a book for a new course under development about exactly the same subjects, I found that the original now has a C# version.
This is truly a great book about a lot of Agile practices like pair programming, test driven development, project velocity and more. But it also contains a lot of important patterns and it explains the [wikipedia:Single responsibility principle], something I tend to tell every training I teach. Because the principle is just so powerful.
It's great to see that the examples now are in C# instead of that other language. It's weird though, the book seems to have 200 more pages, but is a lot cheaper than the original.
Find it on Amazon, ComCol or via the ISBN : 9780131857254
In .NET Framework 3.5, we've gained automatic properties. Automatic properties are really simple to understand. Instead of writing a full getter and setter with a private field (called a backing field, because it belongs to the property) you just write your property like this.
namespace ClassA.Examples.AutomaticProperties
public class Customer
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
The compiler creates a 'real' property with a backing field, which you can view with Reflector or ildasm.
If you want more info, check out this blog entry by Bart de Smet.
Why I'm writing this, is because of the property snippet. I used to use the property snippet a lot, which produces some handy templated code. Visual Studio 2008 supports multi targeting and you can write software focused on the .NET Framework 2.0, 3.0 or 3.5. So you can develop an application without ever touching .NET Framework 3.5 or C# 3.0. Until you want to create properties... The new property snippet is based on the automatic properties in C# 3.0.
To solve this problem, first change the name of your original snippet from prop.snippet to aprop.snippet, where aprop stands for "automatic property". You can find the property in the following folder, if installed at the default location.
Just changing the filename isn't it though. Below is the copy of the original Visual Studio 2005 property snippet. Notice the Title and ShortCut elements. In your aprop.snippet you should change this accordingly. Then copy the code below and create a new prop.snippet in the same folder. That's it.
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>prop</Title>
<Shortcut>prop</Shortcut>
<Description>Code snippet for VS2005 property and backing field</Description>
<Author>Microsoft Corporation</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>int</Default>
</Literal>
<ID>property</ID>
<ToolTip>Property name</ToolTip>
<Default>MyProperty</Default>
<ID>field</ID>
<ToolTip>The variable backing this property</ToolTip>
<Default>myVar</Default>
</Declarations>
<Code Language="csharp"><![CDATA[private $type$ $field$;
public $type$ $property$
get { return $field$;}
set { $field$ = value;}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
UPDATE : That's really funny, while writing this article, Daniel Moth was doing exactly the same... Well, not this one, but one a bit shorter. That's why my article was posted half an hour later! ;-)
On the frontpage of BloggingAbout.NET you can see who posted comments on which articles and I found a few recent comments on a rather old post by Arjen Bloemsma about the LocalSqlServer connection string and its binding to ASP.NET Membership provider. Arjen provides a fast and easy solution that's workable, but what if you want to configure everything completely yourself? Or better yet, you want to understand what you're doing?
Let's bypass the default connection string and the default Membership configuration. We'll need more options next to the default ones, found in the ASP.NET Web Site Administration Tool. When your website is open in Visual Studio, start the tool (website) from the menu (Website -> ASP.NET Configuration). Under the 'Provider' tab you can select the option 'Select a different provider for each feature (advanced)'. There you can see the default providers.
If you want to understand where these settings come from, you'll have to take a look inside the machine.config, located in the proper framework folder. Even if you're developing for .NET Framework 3.0 or 3.5, you'll need to be in the .NET Framework 2.0 folder, because they all run under the 2.0 Common Language Runtime (ref 1, ref 2).
In the folder there should be a file called machine.config in which the configuration for the Membership provider and the connectionstring should be. First have a look at the connectionstring.
Side-note : Since .NET Framework 3.5 and "Client application services" I finally understand why the provider settings are in the machine.config instead of the root web.config. If you have Visual Studio 2008 installed, you should seriously open a Windows Forms application and look up the 'Services' tab page under your project properties.
Here you can find the name and the data source (server) it's looking for, which is a SQL Server 2005 Express edition by default. That's where Arjen's problem originated from. But let's see why the Membership provider uses this specific connection string, besides the fact that it's the only one available. In your machine.config you can again find this information. Click the image below for a larger version.
Under the membership element you find the providers. There's only one provider here, called "AspNetSqlMembershipProvider". You'll notice the attribute "connectionStringName" and where it points at! I don't think it's wise to change these settings, even if you want to really badly. Again, Arjen gives an easy and fast solution that works much better than just changing the machine.config. But we decided that we wanted more.
We need to configure additional provider settings and have it use a new connection string. Note that the membership element is under the system.web element. We can copy the entire membership element into our own web.config, again under the system.web element.
After copying, we can make our own changes. In the example below you'll see that I've removed (cleared) the previously configured membership providers. This is not necessary, you don't need the clear attribute. Better yet, if you don't, you'll have something to choose from in the ASP.NET Web Site Administration tool. ;-)
Note that I've also changed the connectionStringName attribute to "MyAspNetDB". Here's the configuration of my connection string. If you don't know what connection string you should use, have a look at www.connectionstrings.com. e
<connectionStrings>
<add name="MyAspNetDB" connectionString="server=(local);database=aspnetdb;integrated security=true"/>
</connectionStrings>
The 'aspnetdb' is the default name of the database that aspnet_regsql.exe will generate. Note that you can work with multiple application names in a single 'aspnetdb' database! In the large configuration example above you can see that the default application name is just a slash, or actually nothing. You can use different application names so every website can have its own users, roles and profiles. But all of them in a single database. I find having the tables in my own personal database much easier with deployment though. Again, this is an option in the aspnet_regsql.exe tool.
Because you've copied the configuration from machine.config and added it to your own web.config, you can now alter every available setting to your likings.
I hope this example helps and you better understand how to configure and use the membership provider and where the original information comes from. Of course you can use the same information for the role and profile providers.