Merry Christmas (Happy Holidays) 2007-2008

It's been a while. The reason was a) had the MCPD exam to prepare for (failed it again, thats a year) and b) a fairly important deadline that had to, and was, met. So basically it's been full on and unfortunately the blog suffered. I'm just getting ready for a 2 week holiday over in China but though that I take the time to wish everyone a merry christmas and a happy new year (if you don't celebrate then have a good holiday). Thanks also for taking the time for reading my blog and sorry for the lack of content lately but that should hopefully change next year.

 All the best folks.

Posted by dsmyth

Getting around Jet Engine not installed error on 64 bit Vista

There is a problem with 64 bit Vista and that is the Jet Engine, used by ADO.NETs OleDb Data Provider, is not supported. It's also no longer supported by Microsoft so a 64 bit version is not planned. If you develop with OleDb on 64 bit Vista you get an error saying something along the lines of the Jet Engine is not installed.

The solution to the problem is fairly straightforward and that is any application you write that uses OleDb should target the x86 CPU architecture. This forces your application to run in 32 bit mode. The application still runs in 64 bit under WOW64 so there is no problem. You change this setting using the Configuration Manager in Visual Studio or by compiling your application with the /platform:x86 switch.

This is fine for your own developments but what about applications you get that use OleDb and have been compiled with the AnyCPU option. With out source code your pretty much stuck, all OleDb calls will fail. However, after a bit of poking about in the invaluable MSDN library I came across one little piece of information that allows you to get around the problem.

On 64 bit Windows operating systems a DLL (read assembly) compiled with AnyCPU will execute on the same CLR as the process into which it is loaded. Interesting, because since an EXE file is also an assemby that means if you can load and execute an EXE in a process targetting the 32 bit CLR then you can get an compiled application, targeting AnyCPU and using OleDb, to run in 32 bit mode, meaning OleDb will work of 64 bit.

The good thing is you can do this with only a couple of lines of code.

using System;
using System.Collections.Generic;
using System.Text;

using System.Reflection;

namespace ApplicationStarter
{
	class Program
	{
		[STAThreadAttribute()]
		static void Main(string[] args)
		{
			AppDomain.CurrentDomain.ExecuteAssembly(@"C:\Application.exe");
		}
	}
}

if you place the above into an console application and make that application ttarget the x86 architecture then the specified application is executed in the 32 bit process and any OleDb calls that are made will work, no need to recompile. You need to use the STAThreadAttribute as you'll get a runtime error if you don't.
Posted by dsmyth

VistaDb (100% Managed Database Engine)

Wow it's been a while, sorry for the lack of updates. It is due to a combination of studying for the MCPD (second attempt is looming) and having a bit of a deadline to meet on a project. I've been spending most of my time helping folks out on the MSDN forums. Many people ask me questions through this blog, although I really appreciate you coming and reading my blog, your best bet is to post to the forum. Much more likely to get your questions answered there.

Anyway found this wonderful fully managed database engine by the name of VistaDB, here is the link... it does look pretty amazing even though I've only had a small look.

http://www.vistadb.net/default.asp

This is a fully managed (written completely in C#) file based database engine that has less than a 1Mb foot print. It's like Access without the Jet Engine and it's like an SQL database without SQL Express. You create your database as a file, deploy it with your software along with a 1Mb DLL file (referenced by your project) and thats it, a fully functional database and engine. There isn't much of a learning curve as it uses all the ADO.NET objects you'll be familiar with, here a dummy example....

VistaDBConnectionStringBuilder connString = new VistaDBConnectionStringBuilder();
connString.OpenMode = VistaDB.VistaDBDatabaseOpenMode.NonexclusiveReadWrite;
connString.DataSource = "MyFirst.vdb3";

VistaDBConnection conn = new VistaDBConnection(connString.ConnectionString);

VistaDBCommand cmnd = new VistaDBCommand("SELECT * FROM [Employee]", conn);
conn.Open();

VistaDBDataReader readr = cmnd.ExecuteReader();
while (readr.Read())
{ 
//and so on
}

conn.Close();

Fantastic, all you need to specify is the connection string which at its most basic is "Data Source = 'C:\databaseFile.vdbc3'"

There are some limitations (although not that many) and the only one I can think of is there is no TSQL Stored Procedures, but there are CLR Stored Procedures. These are, from the look of things, method calls from assemblies that are embedded into the database. Really thats about the only limitation I can really find and there is a question of performance but I can not comment on it as I haven't ran any benchmarks.

To be honest though it's worth looking at and I know I'm going to be buying a copy. No need for your users to install anything, no SQL Express, no Jet Engine (which is not supported on 64 bit). Ideal.  It also has XML support in that you can build a database from a schema and import XML data in, and I'm guessing out. It has CLR Triggers, Referential Integrity, Views, and have I said... I'm getting a copy. Cheap as chips.

Custom Error Provider (with Error count)

The Error Provider Component used on Windows Forms is a very useful way of displaying the errors on the form, however its missing one small piece of information; the number of errors that are currently on the form. This custom error provider fixes that problem and allows you, among other things, to check the number of errors on the form before performing some action. i.e. If Me.ErrorProvider.HasErrors = False then It's proved very useful in a project I'm helping out on. -------------------------------------------------------------------------------------------------------------------
Public Class ErrorProviderWithCount
Inherits System.Windows.Forms.ErrorProvider

Dim controlsWithErrors As New List(Of Windows.Forms.Control)

Public Sub New(ByVal components As System.ComponentModel.IContainer)
MyBase.New(components)
End Sub

Public Shadows Sub SetError(ByVal control As Windows.Forms.Control, ByVal value As String)
MyBase.SetError(control, value)
If String.IsNullOrEmpty(value) Then
If controlsWithErrors.Contains(control) = True Then
controlsWithErrors.Remove(control)
End If
Else
If controlsWithErrors.Contains(control) = False Then
controlsWithErrors.Add(control)
End If
End If
End Sub

Public ReadOnly Property Count() As Integer
Get
Return controlsWithErrors.Count
End Get
End Property

Public ReadOnly Property HasErrors() As Boolean
Get
Return controlsWithErrors.Count > 0
End Get
End Property

End Class
Posted by dsmyth
Filed under:

XmlResolver doesn't authenticate with Proxy server

Just had a problem in resolving a DTD, stored at a remote URI, while loading an XML file into a XmlDocument. Usually a XmlUrlResolver is used to resolve remote XSD or DTD defined in an XML document, however the XmlUrlResolver doesn't perform Proxy authentication meaning that as soon as you try to load the document a WebException is raised saying "The remote server returned an error: (407) Proxy Authentication Required.". The solution is to create your own XmlResolver that handles proxy authentication and here it is.

Public Class XmlProxyUrlResolver
Inherits XmlResolver

Private m_proxy As IWebProxy = WebProxy.GetDefaultProxy()
Private m_credentials As ICredentials

Public Overrides WriteOnly Property Credentials() As System.Net.ICredentials
Set(ByVal value As System.Net.ICredentials)
m_credentials = value
End Set
End Property

Public Overrides Function GetEntity(ByVal absoluteUri As System.Uri, ByVal role As String, _
ByVal ofObjectToReturn As System.Type) As Object
Dim request As WebRequest = WebRequest.Create(absoluteUri)
request.Proxy = m_proxy
request.Proxy.Credentials = m_credentials
request.Credentials = m_credentials
Return request.GetResponse().GetResponseStream()
End Function

End Class


The XmlProxyUrlResolver resolves the DTD at http://www.w3.org with authenticating with the proxy server.

Posted by dsmyth

CSSVista (Edit CSS Live)

http://litmusapp.com/cssvista/ CSSVista is a free Windows application for web developers which lets you edit your CSS code live in both Internet Explorer and Firefox simultaneously. Vista only.
Posted by dsmyth
Filed under:

XSL-FO to PDF, MathML, Virtual PC, and MSIs

First off many thanks to Digvijay for his comment, it was well appreciated. I'm not to clever at replying to comments, only to happy to help. You may have noticed that there was a noticable gap in time between some posts, the reason for this was two fold... I've started back with studying for the MCPD - Windows and my home computer died a death; I try not to post in my blog at work. 

Here are some links to some interesting things....

XSL-FO to PDF: This is a small tool (client and server .NET based api are available) that lets you create PDF's from XSL-FO files. I've been trying to convice my company to develop a web service that would allow anyone in the company to create PDF files, they liked the idea but the project was put on hold as there were no components that formatted XML to PDF, most were Office Documents or Printer drivers (not really suitable for a server). This component handles XML to PDF via XSL-FO format and also handles the new XML format of Office. There is a free client based utility, which is rather handy.

http://www.alt-soft.com/

MathML: this is an XML language that lets you write mathematical formulas for display in web pages. For any mechanical or structural engineers out there MathCAD fully supports MathML

http://en.wikipedia.org/wiki/MathML

http://www.integretechpub.com/zed/    (free MathML editor and I.E. browser addin here)

Virtual PC 2007: So my computer died, RIP, and I'm needing to buy a new computer and specifically one with 4Gb of RAM. Phoned the shop and talked through a spec and was annoyed to find out that 32bit operating systems only support 3Gb of RAM. 32bit Vista might say it supports 4Gb of RAM but it doesn't really as some memory is lost in maintaining memory mapping. So in order to get the 4Gb of RAM (I'm actually wanting 8Gb) I needed to go for a 64bit version of Vista which means all my 32bit applications won't work; a-n-n-o-y-i-n-g.

Then I found out Microsoft are offering Virtual PC 2007 for free as one of a number of work arounds to this problem and everything didn't seem so bad now. With 64bit Vista running as the main OS and a virtual PC running a host 32bit Windows XP Pro OS, taken from the deceased, then there will a 64bit and 32bit OS on one machine, I can develop using new and old technology.... in theory it sounds great but need to see how well it works out.... but at least I can go up to the 8Gb of RAM!!!

http://www.microsoft.com/downloads/details.aspx?FamilyId=04D26402-3199-48A3-AFA2-2DC0B40A73B6&displaylang=en

I'd recommend you getting a copy of this, although you will need a fairly decent machine.

MSIs: Orca is a small tool that lets you view the internals of an MSI. Unfortunately in order to get it you need to download a 300Mb CD. This is, of course, unless you visit the blog of Brent Norris.... cheers mate.

http://www.brentnorris.net/blog/?p=319

Thanks for reading folks... I appreciate it, and don't be annoyed if you don't get a reply to your comments. If your looking for my help in anyway then please check out the MSDN forums, I spend time there answering questions and if I don't get around to it, someone else there will.

Posted by dsmyth
Filed under:

TrueCrypt - Protecting USB Memory Sticks

For the last year I've been using a 8Gb JetFlash USB memory stick to store all my ebooks and projects on. It's a fantastic little memory stick because it comes with a piece of software called uFormat which partitions the stick into a unsafe and secure area. You need to login to the secure area.

I recently filled it, so I decided to go the next step and I upgraded to 16Gb (still a JetFlash).

Unfortunately it turned out uFormat was not supported on the higher memory stick, which was really annoying, and instead another tool JetElite was it's replacement. JetElite uses encryption instead to protect sensitive data and unfortunately it's slower than a week in jail, which was also very annoying.

So my memory stick was basically unusable because to make things safe required a slow encryption process. That was a problem, a big problem.... so I started searching.... and I found something wonderful.

TrueCrypt - http://www.truecrypt.org/

Here is a list of it's features....

It lets you create a single encrypted file that can be mounted as a real drive, a drive that you need to login to. It's encryption choices are so good that you can create a combined algorithim resulting in a 768 bit key (several universes would pass before being able to brute force crack it) and it is so blindingly fast you have no idea encryption is taking place, even though the data might be getting stored on a memory stick with limited transfer rates... and get this....

....it's free........ (everyone's favorite price).

There is also a traveller mode which makes it perfect for memory stick use. Traveller mode means you can run TrueCrypt from the memory stick your protecting without needing to do an install on the machine (although they say you need admin rights on the machine)

Your limited to 3.9 Gb on FAT formatted drives / memory sticks but thats a limitation on the FAT format and bsides it's not that bad creating different virtual drives for different types of data you might store. For example I split the 16Gb drive into 4 areas, one unsafe, one for books, one for projects, and one for personnal data, and it's better than before as each is protected differently; not so many eggs in one basket.

What a wonderful, wonderful, piece of software. A must have if you own a memory stick.

I'd even like to suggest a donation to the developers if you do decide to use it.

Posted by dsmyth
Filed under:

Microsoft Patterns and Practices April 2007 DVD

Microsoft Patterns and Practices April 2007 DVD

http://www.microsoft.com/downloads/details.aspx?FamilyID=6724E09B-CA2E-425A-8D71-8FEBAD3BA203&displaylang=en

Full DVD download of all the articles, videos, libraries, and tools posted by Microsofts Patterns and Practises team. Well worth the download wait.

Posted by dsmyth
Filed under:

Open Packaging Convention (OPC)

Was reading MSDN Magazine through the week and there is an article in it on OPC. In short OPC is a new standard for saving complex data, perhaps stored in multiple files, to a single file (a package) using a combination of two standard technologies zip and xml.

Here is the article...

OPC: A New Standard For Packaging Your Data
http://msdn.microsoft.com/msdnmag/issues/07/08/OPC/default.aspx

The idea is simple you store your data files seperately and use xml to create relationships between them. All the seperate files are then combined into a single zip file. Office 2007 uses these new file formats, calling them Open XML Formats, but there is nothing stopping you creating your own.

I'll give you an example a Word document is made up of text, styles, maybe a macro and perhaps some images. With the new format instead of saving this in binary the following happens, the text is stored as a WordML file, the styles are saved in an xml file, the macros are stored in a seperate binary file and each image is saved to a jpeg file. Relationships are then used to knit the document together and essentially describe how the document is built from each of the seperate files. All the files are then zipped into an single archive and the normal zip extenstion is changed to associate the single file package with Word.

Here is a noob friendly article that describes the file format, a good place to start

Ecma Office Open XML Formats architecture guide
http://office.microsoft.com/en-us/products/HA102057841033.aspx

and here is another thats not so noob.... but more complete

Introducing the Office (2007) Open XML File Formats
http://msdn2.microsoft.com/en-us/library/ms406049.aspx

You also don't need to wait until your financially paranoid company decides to upgrade to Office 2007. There are both software development kits and Office 2003 Compatibility Packs to get you up and running (although I haven't had time to give them a proper once over).

2007 Office System: Microsoft SDK for Open XML Formats
http://www.microsoft.com/downloads/details.aspx?familyid=ad0b72fb-4a1d-4c52-bdb5-7dd7e816d046&displaylang=en

Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint 2007 File Formats
http://www.microsoft.com/downloads/details.aspx?familyid=941B3470-3AE9-4AEE-8F43-C6BB74CD1466&displaylang=en

If any of the links don't work then do a search for the title and you'll get the pages.

It has always been a nightmare trying to extract data from Office files and if the company you work for is anything like the one I work for where the report is more important than the data held within the report, or you get many requests to extract data from Word or Excel, or even if your fed up telling people that the 36Mb spreadsheet that they cannot produce a report from should have been a database, then you'll be happy, very happy, as sometime soon things are going to get easier.

Posted by dsmyth

Embedding images into Mp3's

I'm a huge fan of electronic music and being the type of frood who knows where his towel is at I've got rather a nice selection of Mp3s and a lovely IRiver H340 to play them on. The H340 comes with it own built in firmware which although it's very colourful it's still crap. So some sexy developers have got together and produced Rockbox, a free alternative firmware for certain Mp3 players.

One of the custom themes of RockBox, iCatcher, appears to extract from the Id3v2 tag of the mp3 the embedded image stored as the album art (front cover, back cover, etc). That got me looking into software tools that let you embed images into mp3s and what I found wasn't good enough, so I created my own; it's great being a developer.

First off I had a look for some .NET libraries that let you get or create mp3 Id3v2 tags and low and behold....

TagLib#... http://www.taglib-sharp.com/Main_Page

An excellent API for altering mp3 (and many other formats) tags. So here is some code using this library that allows you to embed an image. This code only works if the image is correctly sized, 75 pixels by 75 pixels is suitable.

'get the mp3 file
Dim mp3 As TagLib.File = TagLib.File.Create("D:\Towers Of Dub.mp3")
'create the picture for the album cover
Dim picture As TagLib.Picture = TagLib.Picture.CreateFromPath("D:\UfOrb.jpg")
'create Id3v2 Picture Frame
Dim albumCoverPictFrame As New TagLib.Id3v2.AttachedPictureFrame(picture)
albumCoverPictFrame.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg
'set the type of picture (front cover)
albumCoverPictFrame.Type = TagLib.PictureType.FrontCover

'Id3v2 allows more than one type of image, just one needed
Dim pictFrames() As TagLib.IPicture = {albumCoverPictFrame}
mp3.Tag.Pictures = pictFrames 'set the pictures in the tag
mp3.Save()

Unfortunately!!

Microsofts Media Player only supports Id3 v2.3, which has been superceded, so you have to use the following lines of code to tell the TibLib library to use v2.3, otherwise it uses a default of v2.4.

TagLib.Id3v2.Tag.DefaultVersion = 3
TagLib.Id3v2.Tag.ForceDefaultVersion = True

If you have any need to work with mp3 tags TagLib# is the API to use!

Posted by dsmyth
Filed under:

Looping over resources

Here is a small code snippet that demonstrates looping over the resources stored in the My.Resources namespace. It was a response to a MSDN forum question where all the resources stored were images. If you want have more types of resources then you'll want to refine this a bit. Treat the code below as a starter for 10 and take it from there...

Dim res As Resources.ResourceManager = My.Resources.ResourceManager
Dim resSet As Resources.ResourceSet = _
res.GetResourceSet(Globalization.CultureInfo.CurrentUICulture, True, 
True)
Dim en As IDictionaryEnumerator = resSet.GetEnumerator()

While en.MoveNext()
'en.Key - name of the resourse
'en.Value - the resource as an object
images.Add(en.Value)
End While
Posted by dsmyth

The ListView and its ListViewGroups.

The ListView control is maybe the most commonly used control used by Windows. The reason being its used by the file explorer to let you view your files in a variety of ways, you can view directories as icons, you can view thumbnails, or you can view all the files details. One option of the file explorer that you might not make use of is the ability to group the icons. Here's an example...

 

It's not that useful in Windows to be honest, or at least I haven't been in a position when I needed to use it. However..... It's actually pretty good if you use it in your own applications to group certain common options, for example, you have a place where the user can print reports, rather than listing of all reports and letting the user scan through them you can instead group your reports into categories i.e. financial or informational. Another examle might be a list of products that the user can select from you can now list the products by category or price. It works really well and I've had some fairly positive feedback from users, which is surprising, users tend not to give feedback unless something doesn't work.

So here's how. I'll cover how to do it through code, once you understand that adding groups and items though Visual Studio IDE will be straightforward.

The concept first, simple really, the listview can be made up of groups which contains a collection of items (sub items are not supported), any item not in a group is placed in a default group. So the first thing to do is you need to add the groups to the ListView, I'll use the product example given above....

Step 1: Create your groups and add them to the ListView's Group property

Dim audio As New ListViewGroup("Audio CD")
Dim dvd As New ListViewGroup("DVD")
Dim vhs As New ListViewGroup("VHS")

Dim groups As New List(Of ListViewGroup)
groups.Add(audio)
groups.Add(dvd)
groups.Add(vhs)

Me.ListView1.Groups.AddRange(groups.ToArray())

This is done by creating instances of ListViewGroup objects, it's easier to create instance rather than to add the groups directly as when it comes to adding items you need to use the group instances as your about to see.

Step 2: Add the items to the ListView and specify the group it's to appear in. It's important to note that there is a one to many relationship between groups and items. One group can have many items but one item can only belong to one group. Here's some example code....

Dim viewItem As ListViewItem
viewItem = Me.ListView1.Items.Add("Biosphere - Substrata")
viewItem.Group = audio

viewItem = Me.ListView1.Items.Add("Night of the Living Dead")
viewItem.Group = dvd

viewItem = Me.ListView1.Items.Add("Chopper Chicks in Zombie Town")
viewItem.Group = vhs

When the ListViewItem is added to the ListView control you need to set it's Group property to an instance of a ListViewGroup object.

Step 3: When you use the ListView in this way the layout doesn't follow the usual grid like approach so you have to sort the layout of the items, which you do using a couple of properties. This will completely depend on what your control should look like and how it should act. Just make sure ListView.ShowGroups = True

You may also notice that the labels of your items aren't quite right. If you find this happening set ListView.View = Title and set ListView.LabelWrap = False and hopefully that will fix any problems you have.

Click here to download the code example... it's simple but demonstrates the idea.

Changing the display name and sorting properties of the Property Grid

This post assumes a bit of background knowledge on how to use and control the property grid when displaying the properties of an object.

The property grid is a great control, I like it a lot, but it does have some problems. One of these is the use of attributes to specify and control categories, display names and descriptions of each property it displays. The attributes, which are specified at design time, allow only string literals to be set. These are compiled into assembies metadata and because of this they cannot be changed at runtime. So, for example, you cannot look up the name or description of a property from a database, or a file, or even change it depending on a condition.

Another problem is there are no attributes to specify in which order the property grid should displays the object properties, so even though in code the properties of your object are defined in the order you want, the property grid won't display them in that order.

There are two classes that control how the property grid displays an objects properties that help fix these two problems, one class is used to look up the display name, category and description of a property while the other class indentifies which properties of the object, and more importantly in what order, these properties should be displayed.

The class System.ComponentModel.PropertyDescriptor is a class that tells the property grid how to describe a property. There are many methods and properties that need to be overriden but the three most useful are the read only DisplayName, Category and the Description properties. This descriptor class could be thought of as a class that describes how a single property is displayed in the property grid.

The second class allows you to select and sort the properties displayed on the property grid. The System.Component.CustomTypeDescriptor class allows to control how the properties of a type are displayed. It's main task is to build a collection of PropertyDescriptors.

If the PropertyDescriptor describes how each individual property of a type is displayed then the CustomTypeDescriptor completes the picture by allowing a type to describe how it's properties are displayed. As you can imagine the CustomTypeDescriptor creates instances of the PropertyDescriptor. Generally the object whos properties you want to display is inherited from the CustomTypeDescriptor and this allows the object to describe itself to the property grid.

Granted this description, without code samples, isn't particularly intuitive so here is a small sample application that demonstrates how to use the above two classes. The example displays a simple Employee class in the property grid. The employee class has no attributes describing how each of it's properties are displayed, that information is extracted from a comma delimited file by a EmployeePropertyDescriptor class, which doesn't do a very efficient job of the lookup, but it is only a demo. The employee class also inherits from the CustomTypeDescriptor and in the GetProperties() method specifies the order of the properties and using that order builds a collection of EmployeePropertyDescriptor objects which is used by the property grid. Very simple example.

DisplayName And Sorting PropertyGrid.zip

Very sorry !! Missed out a very small but important detail! You have to set the Property Grids PropertySort property (eh?) to Categorized. Otherwise you'll still get the list in alphabetic order. Sorry for missing that.

Posted by dsmyth
Filed under:

Catching up....

After a fairly intense period of full on study I finally sat the MCPD Windows Developer upgrade exam (70-552) and was pretty shocked to see that I failed. wtf? can I say wtf on the Internet? of course I can because I failed the exam, wtf? To be honest I don't like the new format they have introduced in the upgrade exams.

Basically you sit three one hour exams (70-526, 70-536, and 70-548), which in itself is fine but if you finish two exams in 30 minutes, then the hour isn't transferred into the last exam, which is a bit unfair. Basically I passed the two code based TS exams (70-526, and 70-536) taking about 30 minutes for each and messed up on the (70-548) questions to do with debugging performance and troubleshooting network problems, which you really need experience of, not something you can read in a book, if infact you can find a book on it. What was so annoying was the outstanding hour wasn't transferred and with 30 questions in 1 hour, 2 minutes a question, thats a bit harsh Microsoft.

So anyway I have been neglecting my blog and to a greater extent DotNetSlackers and everyone here, and for that I appologise. I have so much to write about as well. Lots of nice little juicy code snippets but just not getting around to posting them for some reason. Need to start posting from work more I think and recent changes in my position might make that more of a possibility. I'll make it happen.

Need to write an article as well, I haven't written one this year and that's rubbish. Think I'll write an article on the internals of the DES and 3DES encryption algorthims, which is a subject I've been reading up on, not DES specifically just crytography and security in general. I believe that, with the way the industry is going, the two most important subjects for a developer to know is security and threading.

But I do need to contribute more!!

Posted by dsmyth
More Posts Next page »
The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.