Archive Page 3

Jetbrains dotTrace: Profiling VS2008 Web Apps

We are currently running traces against a web applications that we are developing and one of my colleagues was telling me that the JetBrains dotTrace applications didn’t allow running profiles against the ASP.net web development server (it way grayed out). The reason was that only Visual Studio 2008 was installed, which by default puts the WebDev.WebServer.exe (which is the ASP.net web development server) into the c:\<program files>\<shared files>\Microsoft Shares\DevServer directory instead of the old Visual Studio 2005 path which was c:\windows\Microsoft .NET\Framework\v2.x.y.z\.

There is a way to profile against the VS08 web server as described here, but you can also just copy the WebDev.WebServer.exe from the one directory to the Windows\Framework directory. This probably isn’t the best way to do it (because patches will only go to the original install directory), but with it dotTrace can start a profiling session with the ASP.net web server.

Microsoft Sync Framework CTP2 is out…

Tomorrow I’m off to the academic community launch and will have to wait until next week to take a look at it, but it’s available for download:

http://www.microsoft.com/downloads/details.aspx?FamilyId=C88BA2D1-CEF3-4149-B301-9B056E7FB1E6&displaylang=en

Remember to uninstall all previous editions.

Technorati Tags:

A Reusable Secure Login Form

For the impatient, source and binaries and quick explanation available at: http://code.msdn.microsoft.com/UtilsCommonViews/

How many of the last ten projects you implemented had a login form of some kind? Thanks to all those wonderful apis that you coded applications against, probably the majority of them did. Now try to remember how many of those login forms used strings for storing passwords in memory and how many saved the password to a settings file in plain text. I know most of my small utilities did and I’m not proud of it, but it happened and I’m almost sure you have some of those lying around in your src folder.

Anyway, today I had a couple of hours of spare time and decided to implement a reusable secure login form. My goals were to use SecureString for storing the password in memory and encrypt the username and password in a settings file for storing them between the sessions. I started off with a little research about the components I’d need to use.

SecureString is a class that was introduced in .NET Framework 2.0. Why not simply use a string for storing a password? Well let’s have the MSDN do the explaining:

An instance of the System.String class is both immutable and [...] cannot be programmatically [...] deleted from computer memory. Consequently [...] there is a risk the information [stored in it] could be revealed after it is used [...].

A SecureString object is similar to a String object in that it has a text value. However, the value of a SecureString object is automatically encrypted, can be modified until your application marks it as read-only, and can be deleted from computer memory by either your application or the .NET Framework garbage collector.

That’s a great scenario for our password. Next up I found this great secure textbox control that handles the user input into a SecureString object. The original control and source can de downloaded at: http://www.theglavs.com/DownloadItem.aspx?FileID=46. (Thanks to Glav and Dominik Zemp who created or extended the control.)

Then I wrote this simple extension method to get the characters of the contents of the SecureString because it can get quite dirty to do it inline. It uses requires execution of unmanaged code and some marshalling.


public static Char[] GetCharacters(this SecureString secureString)
{
	if (secureString == null)
		throw new ArgumentNullException("secureString");

	lock (secureString)
	{
		char[] _chars = new char[secureString.Length];
		IntPtr _ptrToChars = IntPtr.Zero
		try
		{
			_ptrToChars = Marshal.SecureStringToBSTR(secureString);
			Marshal.Copy(_ptrToChars, _chars, 0, secureString.Length);
		}
		finally
		{
			if (_ptrToChars != IntPtr.Zero)
				Marshal.ZeroFreeBSTR(_ptrToChars);
		}

		return _chars;
	}
}

The second feature was to encrypt the username and password in a file. I looked at encrypting the configuration file but decided against that path and went with encrypting the data using the ProtectedData API (in System.Security.Cryptography). It’s a simple call to the static method:


ProtectedData.Protect(byte[] data, byte[] entropy, DataProtectionScope);

The entropy specifies a kind of salt for your application and the DataProtectionScope can be set so that only the current user can decrypt the data or to local machine. The library will save a file UserData.bin to the local application directory (including the calling assemblies name). Additionally I decided to encrypt the file using the FileInfo.Encrypt method. This works only on NTFS, so the library will currently only work on NTFS systems. Now that I’ve written that sentence I think I’ll make that optional in the next release.Which brings me to the release and the source code. I want to try out MSDN code gallery so I’ve published the project here: http://code.msdn.microsoft.com/UtilsCommonViews/

Using the library is very simple:


LoginController _loginController = new LoginController();
_loginController.GetCredentials();

string _username = _loginController.Username;
char[] _password = _loginController.Password;
// _password needs to be zero'ed a.s.a.p. after usage

That last comment is important. If you don’t zero out that char array, the password will be floating around in memory.

Comments, suggestions are of course welcome! Here or in the MSDN code gallery.

Note: The project uses another utility library (Utils.Extensions) of mine that I’ve built-up over the last weeks that contains a few extension methods for common stuff I was missing in the BCL. The source is not clean enough yet for publishing but it’s in the pipe. For now it’s only available in this project as a release dll.

LINQ to SQL for SQL Compact Edition - Did you know?

You can’t actually drag and drop a SQL Compact Edition 3.5 database to the LINQ to SQL designer. But it is very easy to create the classes and work beautifully. Fire up a VS08 prompt and find the SDF file that your database is stored in, then run the following command:

Prompt: SqlMetal /code:DotNetBooksDB.cs /pluralize /namespace:Books.Client.Library.Store.SqlCe dotNetBooks.sdf
Microsoft (R) Database Mapping Generator 2008 version 1.00.21022
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.

The parameters are simple.

/code = the path where you would like to save the generated code.

/pluralize = changes the table book into books so you can write code like this: var x = from b in _ctx.Books (just looks a bit nicer)

/namespace = which namespace would you like your classes to have

and finally the path to the sdf file.

There is no output, but if you run the command your csharp should have been generated and just include that file into your project (and switch the project to .net Framework 3.5).

Sync Framework: Where does the metadata come from for SqlCeClientSyncProvider (Sync Services for ADO.net 2.0)?

I was preparing some demos for the upcoming Academic Community Launch Tour that we - a bunch of Microsoft Student Partners in Austria - are organizing (see http://anuga.at for details). I had just finished a wonderful little app using SQL Compact Edition, Sync Framework, ASP.net MVC and all the funky stuff. Just before I wanted to call it a night I noticed the sync portion of my app suddenly wasn’t working anymore. Somehow I had done something bad and the sync framework wasn’t finding any rows that had changed. This morning I got up and took a closer look underneath the covers of SqlCeClientSyncProvider. This is what I found out.

A word of warning: The information here only applies to Sync Services for ADO.net and is based on Version 2.0 with some help of Reflector. Use the information and my interpretation with caution. Especially beware of the fact that Sync Services for ADO.net in the Sync Framework are handled completely differently than Sync Services for File Systems and Custom Sync Providers.

The sync framework uses anchors to determine what rows have changed. These anchors are compared to the metadata in the table. When creating the tables on the server you probably inserted columns such as InsertTimestamp or UpdateTimestamp. That’s the metadata. Fine, but what happens on the client side in a SQLce database? At first I thought the metadata columns are transferred to the client in the schema (remember the SqlCeClientSyncProvider retrieves the schema to create on the table from the server) and then used for the change tracking there too.

Well not quite. In the app I’m working on I created the SQLce database first (and used used SQLMetal to generate my Linq2Sql classes by the way which is really easy. I’ll do another post in a moment). SQLce doesn’t support triggers so I only created a timestamp column called ‘TS’. When it came to sync’ing the client with a server database, that looked similar but had more metadata columns, I noticed I had no idea how the metadata part worked on the client. (It’s actually quite nice too know that for standard use cases it just works out of the book.)

Enough bla, let’s get to the details. Thanks to a couple of hours with reflector and running queries against my SQLce database I found out where the metadata goes.

Preparing my custom tables for the meta data

When you configure your SqlCeClientSyncProvider you add SyncTables with a couple of options:


foreach (SyncTable _syncTable in syncTables)
{
_syncTable.CreationOption = TableCreationOption.UploadExistingOrCreateNewTable;
_syncTable.SyncTableTransferOption = SyncTableTransferOption.Bidirectional;
m_clientProv.Configuration.SyncTables.Add(_syncTable);
//
// This would recreate the schema for each table on each sync, which resets the timestamps to 0.
// m_clientProv.CreateSchema(_syncTable, null);
}

You can see a line at the bottom that I commented out. I figured that since my client database was in place and I specified UploadExistingOrCreateNewTable that my client database needed to be adapted to include the sync metadata. So I called CreateSchema on the provider which does just that. But you don’t want to create the schema every time, so I should actually move the call into my database initialization code, but I didn’t want to mix my sync code with my DAL code and I didn’t need to. CreateSchema is called at the beginning of the sync session only if the metadata is not found in the table.

Once that method has run all sync tables now have two extra columns: __sysChangeTxBsn and __sysInsertTxBsn. These are initialized with 0 and contain a binary timestamp.

CreateSchema also creates some more tables. First of all it creates a sync subscription table called ‘__sysSyncSubscriptions’. This contains the client’s id and it’s pairing with any server sync providers. Next up is an article table called ‘__sysSyncArticles’. An article is just a sync table, so it contains the table name, the last sent and last received anchors for a specific table.

Once it has done that it just switched on the built-in SQLce change tracking which in turn updates the metadata columns when ever a change occurs.

But wait there is one thing missing. What happens to deleted rows? So far we don’t have any tombstone or archive tables. Actually we do, a table called ‘__sysOcsDeletedRows’ was created that is used by the SQLce change tracking to store deleted rows. It has columns ‘__sysTName’ (the table name), ‘__sysRK’ (the reference key = primary key that was deleted) and the timestamp value when it was deleted and inserted.

Windows 2008 - 3 things I wish I had known…

Ok, so I decided to setup a new VPC image with Windows 2008, SQL 2005, WSS 3.0 and Visual Studio 2008. Basically everything is going quite well, but there are a couple of things I encountered while installing, that I thought I would share.

1. Installing SQL Server 2005 with Reporting Services

w08_features From previous experience I knew that Reporting Services requires IIS if you want to install it. The first thing you notice that the server manager has changed a little. I went ahead and installed ASP.net and the Application Server which also installed IIS, but when I started my SQL Server Setup Reporting Services was disabled, so there was something wrong with the IIS install. It took a few minutes, but it seems you actually have to install the IIS role separately. (I had chosen ASP.net, and activated further options manually.) Anyway once the following picture appeared I was set to restart my setup. This time no problem.

2. Internet Explorer Enhanced Security

I don’t like it, so I always go and uninstall it after finishing my base setup. (Usually when I start downloading stuff I need to install.) So I go to my Control Panel, go to Programs & Features and click on Manage Windows Features. Woha, the server manager appears. Ok, this is different to Windows 2003. I think it was David Platt who said something along te lines of “If you want people to use it, make it obvious. If you don’t want people to switch it off, hide it”. Well done, it’s hidden.

It took a bit of googling (sorry, but live’ling just doesn’t sound well as a verb) to find the right option to change. The feature is called IE ESC which can be found in the overview page of server manager. Now I know, now you know.

w08_ieesc

3. Installing Windows Sharepoint Services 3.0

Ok, I live’d for “Windows Sharepoint Services 3.0″ (I really did use live this time.) and downloaded the package. Started Sharepoint.exe and voila “This program is blocked.”. WTF? I read on and it asks you to install the setup package with the latest service pack and won’t accept anything else. Ok, my mistake, don’t blindly take the first link presented (I bet google would have pointed me to the service pack 1 download package - but I didn’t check).

Turning a class library project into a MSTest project (or using MBUnit, MSTest and other frameworks in one project)

I know it’s been a while. I’ve been busy talking about SyncFramework at the VSOne conference, helping a bit of at the Sync Framework forums and lot’s of studying going on. I promise I have some new longer posts coming soon.

Yesterday I wrote a unit test that I wanted other members on my team to execute this week to check for some problems. Where’s the problem you may ask? Well I personally like TestDriven.net and MBUnit whereas my colleagues rely on the testing suite in Team System. Fair enough, usually we don’t exchange that many tests (and no - I’m sorry about that myself actually - we don’t have continuous integration. But even if we did that probably wouldn’t be a major problem).

Anyhow I created my class library project and wrote my test. Worked great on my computer (don’t hit me for saying that). I then remembered that it needed to run under MSTest on the other dev machines. Fair enough, can’t be that hard. I referenced

Microsoft.VisualStudio.QualityTools.UnitTestFramework

and gave my methods additional attributes. (The top ones are MSTest, the bottom ones are MBUnit.)


[Microsoft.VisualStudio.TestTools.UnitTesting.TestClass]
[TestFixture]
public class EvaluatorTestSuite 

[Microsoft.VisualStudio.TestTools.UnitTesting.TestInitialize()]
[TestFixtureSetUp()]
public void SetUp() 

[Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanup()]
[TestFixtureTearDown()]
public void TearDown() 

[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod]
[Test]
public void Evaluate_ValidEvaluationModel_ReturnsValidEvaluationResult()

Then I went to the Test menu in Team System and wanted to execute all tests in this solution. But VS told me there aren’t any. Basically I figured out the test projects must have some special attribute that make them “testable”. They are basically just class libraries but they have a special Guid in their project file. Not quite sure why Microsoft would do that, seeing as they could just check for the attributes on the classes like TestDriven.net does, but ok. This is a quick solution to turning a class library into a MSTest testable project. Open the CSproj file of the class library project and just before the first propertygroup closes insert the following line:

<ProjectTypeGuids>

{3AC096D0-A1C2-E12C-1390-A8335801FDAB};

{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}

</ProjectTypeGuids>

Those two guids make it MSTest testable. And no, I didn’t have time to figure out why there are two and what they do exactly. If anybody cares to explain, I would love to hear about it. The file should look something like this:


<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>9.0.21022</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{5273D187-1B0D-40DC-A415-36761976438B}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>TheGrandestProjectOfThemAll</RootNamespace>
    <AssemblyName>TheGrandestProjectOfThemAll</AssemblyName>
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
  </PropertyGroup>
Technorati Tags: ,,

Sync Framework Interview on Channel 8

While I am getting prepared to speak about the Sync Framework at the german conference VSone, my colleague Christian has put up an interview from TechEd with the lead program manager on the Sync Framework team: Moe Khosravy

Check it out here: http://channel8.msdn.com/Posts/425/

Learn VB.net - German Screencasts Series

A bit out of the ordinary (I am in between writing up some more Sync Framework articles) but a fellow student partner Mario from Linz has put together a series of screen casts to get you started on Visual Basic .NET. He covers the basics but also some of the new VB.net features. If you are interested and understand german, take a look at: http://www.vb-magazin.de/casts/video_index.aspx

Sync Framework Tutorial - Part #5 - Some client provider schema details

(shameless plug at the beginning. Who am I? A Microsoft Student Partner from Austria on his quest to keep up with an ever expanding universe of must-know technologies and working on taking the next step as an intern at Microsoft… A friendly hello to any Microsoft team members reading here, check out the about page. Sorry, for that - life’s all about marketing - now back to the content…)

In the last part (part 1, part 2, part 3, part 4) we saw how to setup the synchronization between a local SQLce database and a server database.

The SyncAgent was setup with two providers, one for the server which had SyncAdapters to specify which tables on the server side are used, which columns hold the metadata. Another for the client that used a local compact edition database and a number of SyncTable objects to setup the sync.

Upon Synchronization the SyncAgent downloads the schema from the server provider, creates the tables on the client if required and transfers changes between the databases since the last synchronization.

And it works, but you will soon notice something is missing.

The client schema

The server provides a schema so that the client can create an identical set of tables to use on the client. But if you attempt to insert a row on the client you will notice that the default values are missing. The primary keys are not specified and foreign key constraints on the client are not available.

This is not required but it would be nice to have them anyway. But there is only one way to do it. You have to manually alter the tables after they have been created by the client sync provider.

Adapting the client schema after it has been automatically created

The SqlCeClientSyncProvider provides a number of events, two of which are: CreatingSchema and SchemaCreated.

In the CreatingSchema handler you should set the primary key for each table using the CreatingSchemaEventArgs:

e.Schema.Tables[_mySchema.TableName].Columns[_mySchema.PK].RowGuid = true;

And you will also want to add foreign key constraints:

e.Schema.Tables[_mySchema.TableName].ForeignKeys.
                        Add(
                            _fkName,
                            _fkSchema.ParentTable,
                            _fkSchema.ParentColumn,
                            _fkSchema.ChildTable,
                            _fkSchema.ChildColumn);

The second event handler for SchemaCreated is used to run custom sql commands inside the same transaction used by the sync provider for creating the tables ensuring data integrity:

SqlCeCommand _cmdAlterTableDef = new SqlCeCommand();
_cmdAlterTableDef.Connection = (SqlCeConnection)e.Connection;
_cmdAlterTableDef.Transaction = (SqlCeTransaction)e.Transaction;
_cmdAlterTableDef.CommandText = _alterCmdString;
_cmdAlterTableDef.ExecuteNonQuery();

Summary

So far we have created an application that synchronizes data between a client database and a server database and done taken a look at some nice-to-have schema changes on the client.

Next-up is the distributed scenario where the server provider is called via a WCF proxy. Hopefully I can post that before Christmas.

« Previous PageNext Page »


Subscribe / Search

Imagine Cup 2009 - Egypt

msplogo_small.jpg

mcprgb.png

XING

a

 

November 2008
M T W T F S S
« Aug    
 12
3456789
10111213141516
17181920212223
24252627282930

Blog Stats

  • 26,740 hits