Archive for the ‘Code and Development’ Category

Do annotate fields in the database

June 8th, 2010

It is, at least in MSSqlserver, possible to annotate fields.  Please do.

There are people coming after you to maintain the code base.  One day it might be you who come after someone.  Start paying it forward.

The field explanation might be in the Documentation but the Documentation is too often faulty, not accessible and almost always not up to date.  The database is closer and probably easer to keep in sync with reality.

Don’t think a field name is self explanatory.  The field CustomerID in table Customer might be.  But the same field in Region is not.  Is it the region master or the primary customer or what?  By the time the field was created the meaning of this field was clear but not a year afterwards.

The reason I write this is that I presently work in a project where the habile predecessor has written down the meaning of the fields and saved me lots of time and lots more of confidence of what the figures mean and tons of debugging time.

List of lists and dictionaries in dotnet

June 2nd, 2010

Update: I wrote a longer article here.

List<T> is the work horse of list handling in dotnet.  But there are several more to choose from; ArrayList, Hashtable, SortedList, DictionaryEntry, ListDictionary, StringCollection, NameValueCollection, StringDictionary, HybridDictionary andOrderedDictionary for instance. Several of these are replaceable by generic lists so don’t memorise them.

Here is a link to a better explanation: http://www.platinumbay.com/blogs/dotneticated/archive/2007/06/08/hashtables-and-stacks-and-linkedlists-oh-my.aspx

*Update*: I wrote some more, and later, info here.

DesignMode in Visual Studio, inheritance, process name and a work around

February 4th, 2010

The text and code below is only tested for Winform. WPF might behave differently; hopefully behaves differently.

I won’t go into any details on why the ISite.DesignMode is good and sometimes even crucial to have. It is much better done in the link at the bottom.

First out there is unfortunately a caveat with DesignMode, it doesn’t work with inherited forms and user controls. This is a problem since I always inherit from the base form in my projects and tell others to do the same. It also doesn’t work inside the form’s or the user control’s constructor and then by any method that is called by the constructor. Long call chains to might make this hard to track down.
Secondly there is another way to check for design mode and that is to check for the LicenseManager.UsageMode but this in turn doesn’t work in event handlers.
Thirdly one can set a flag in the base Form and base UserControl. But this doesn’t solve the problem since we cannot be sure with what to set this value.
Fourthly is a workaround where one can check for the name of the process itself which is Visual Studio’s process name (devenv) in case of design mode. This process name might change in future releases of Visual Studio and is also different for other IDEs.
Fifthly is other process information like the name of the module and stuff. Check into the Process and you’ll see that the app is called MyApp.vshost.exe while being debugged.

The fourth solution (processname=devenv) seems to be the most viable but I believe there is something useful in the fifth (other process information). There must be a way to notice that the name of all your code doesn’t match the name of the running environment; namespace, assembly name, whatever. I still haven’t figured out how though.

Below is some code to copy-paste.
It is not 100% correct though since the DesignMode property isn’t virtual. This might end with some really tough-to-track-down bugs where one iterates the forms but don’t get the overloaded DesignMode flag. The code also doesn’t promise to work forever since there is a magic string naming the name of the Visual Studio process.

public partial class MyAppForm : System.Windows.Forms.Form{protected new bool DesignMode{get{return HelperMethods.IsDesignMode(this);}}}

public partial class MyAppUserControl : UserControl{protected new bool DesignMode{get{return HelperMethods.IsDesignMode(this);}}}

class HelperMethods{public static bool IsDesignMode(System.ComponentModel.Component x){var site = x as System.ComponentModel.ISite;return( null == site ? false : site.DesignMode ) ||System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime ||System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv";}}

The code above is also in pastebin for easier copy-paste.
A good article is here: http://dotnetfacts.blogspot.com/2009/01/identifying-run-time-and-design-mode.html
There is a description of how to debug this here: http://brennan.offwhite.net/blog/2006/08/30/design-time-debugging-aspnet-20-in-visual-studio-2005/

Error 4 The type or namespace name ‘AccountController’ could not be found (are you missing a using directive or an assembly reference?) C:\myprojectpath\MvcApplication1.Tests\Controllers\AccountControllerTest.cs 317 24 MvcApplication1.Tests

Changed keyboard settings

January 24th, 2010

In Windows 7 (and possibly Vista) the keyboard layout is sometimes changed back to some sort of default.

The problem shows itself like this – I use the 1337 keyboard layout in Visual Studio.  Then without warning the keyboard layout changes to US layout; a layout I don’t even have installed.  The 1337 layout is based on US though so somehow it shines through.

To get back to 1337 I choose “Open the language bar” in the systray context menu.  The language bar then pops up in another place (top of screen for me) and I can then choose keyboard layout.

The problem will reappear more times until I reboot.

Get calling method’s name automatically in dotnet

January 16th, 2010

Way too many times have I written

void MyFunction( int aNumber){ MyHomemadeLogClass.Logg( "MyFunction", "aNumber=" + aNumber.ToString()); ...}

to get logging functionality.

It would be so nice to just write

void MyFunction( int aNumber){ MyHomemadeLogClass.Logg(); ...}

It is no hard to do. Use reflection to get the call stack to get to the method and the parameters. Convert all this to a readable string.
Unfortunately it is not that easy to log the contents of the parameters, one has to get into some sort of debugger area to do that.

 class ReflectionUtility {     private static System.Reflection.MethodBase GetCallingMethod()     {         return new System.Diagnostics.StackTrace().GetFrame(2).GetMethod();     }     public static string GetCallingMethodFullNameReturnParametertypes()     {         return MethodFullNameReturnParametertypes(GetCallingMethod());     }     private static string MethodFullNameReturnParametertypes(System.Reflection.MethodBase method)     {         return string.Format("{0} {1}.{2} ({3})",             ((System.Reflection.MethodInfo)method).ReturnType,    // System.Void, System.Int32 etc.             method.DeclaringType.FullName,   // MyNamespace.MyClass.             method.Name,   // MyMethod.             string.Join(",", method.GetParameters().Select(p => p.ParameterType.ToString() + " " + p.Name).ToArray())   // () or (int) or (int,string) etc.             );     } }

To use this in a Logging class one must implement a GetCallingCallingMethod or even worse, but it would make this example hard to read.

One can use the Conditional attribute to avoid the call when not debugging.

I also put the code on pastebin to make the copy-paste easier. (I have yet to find a good way to present code.)

Update: go to http://compulsorycat.googlecode.com for the source code in a LGPLd project.

Catch property, field and method name changes compile time in dotnet (RTTI)

January 6th, 2010

When you want to populate a dropdown listbox with customers

class Customer{ int Id; string Name; ...}

and have to write

myDropdownListbox.DisplayMember = "Name";myDropdownListbox.DataMember = "Id";

or

myGridColumnCustomerName.DatatMeber = "Name";

you really get a sour taste in your mouth.

Having magic strings like above spread in your code is really bad since it always compiles but might fail runtime. This means more manual tests. Which in turns means a certain friction against renaming properties while refactoring.
I have been in way too many projects where one table has a field ItemNumber when it should have been ItemCount and where some fields are called Nr while another Number and these names are spread up in the layers to reach the presentation layer where they surface as magic strings like the examples above.

Luckily there is a solution in Dotnet 3 with LINQ. It isn’t the prettiest but it fails compile time when it should and that is considered a good thing.

( I won’t bother with explanation – just read the code. )

When you want to populate a dropdown listbox with customers

class Customer{ int Id; string Name; ...}

and have to write

myDropdownListbox.DisplayMember = "Name";myDropdownListbox.DataMember = "Id";

or

myGridColumnCustomerName.DatatMeber = "Name";

you really get a sour taste in your mouth.

Having magic strings like above spread in your code is really bad since it always compiles but might fail runtime. This means more manual tests. Which in turns means a certain friction against renaming properties while refactoring.
I have been in way too many projects where one table has a field ItemNumber when it should have been ItemCount and where some fields are called Nr while another Number and these names are spread up in the layers to reach the presentation layer where they surface as magic strings like the examples above.

Luckily there is a solution in Dotnet 3 with LINQ. It isn’t the prettiest but it fails compile time when it should and that is considered a good thing.

( I won’t bother with explanation – just read the code. )

// The Code.

< 

    class ReflectionUtility
    {

        public static string GetPropertyName<T, TReturn>(Expression<Func<T, TReturn>> expression)
        {
            MemberExpression body = (MemberExpression)expression.Body;
            return body.Member.Name;
        }

        public static string GetMethodName<T, TReturn>(Expression<Func<T, TReturn>> expression)
        {
            var body = expression.Body as UnaryExpression;
            var operand = body.Operand as MethodCallExpression;
            var argument = operand.Arguments[2] as ConstantExpression;
            var methodInfo = argument.Value as System.Reflection.MethodInfo;

            return methodInfo.Name;
        }

    }


    class MyClass
    {
        public int MyField;
        public int MyPublicProperty { get; set; }
        public  string MyReadonlyProperty { get { return string.Empty; } }
        public int MyMethod() { return 0; }

        private MyClass() { }   // To make sure the class doesn't need a default constructor.
    }


    class Program
    {
        static void Main(string[] args)
        {
            string fieldName = ReflectionUtility.GetPropertyName((MyClass x) => x.MyField);
            Console.WriteLine(string.Format("MyClass.MyField:{0}", fieldName));
            Debug.Assert("MyField" == fieldName);

            string propertyName = ReflectionUtility.GetPropertyName((MyClass x) => x.MyPublicProperty);
            Console.WriteLine(string.Format("MyClass.MyPublicProperty:{0}", propertyName));
            Debug.Assert("MyPublicProperty" == propertyName);

            propertyName = ReflectionUtility.GetPropertyName((MyClass x) => x.MyReadonlyProperty);
            Console.WriteLine(string.Format("MyClass.MyReadonlyProperty :{0}", propertyName));
            Debug.Assert("MyReadonlyProperty" == propertyName);

            string methodName = ReflectionUtility.GetMethodName<MyClass, Func<int>>((MyClass x) => x.MyMethod);
            Console.Write(string.Format("MyClass.MyMethod:{0}", methodName));
            Debug.Assert("MyMethod" == methodName);

            Console.Write(Environment.NewLine + "Press any key.");
            Console.ReadKey();
        }

< }

Honor those who should.  (This link contains a comment regarding generic methods that I’d like to impolement in CompulsoryCat.)

Update: When copy-pasting through manoli.net some angle brackets got dropped. This is, hopefully, fixed now.  Otherwise – get the source here: http://selfelected.pastebin.com/f77563a02

Update:

Check out Compulsorycat.  It is my F/OSS library with some of these functions.

Honor those who should.  (This link contains a comment regarding generic methods that I’d like to impolement in CompulsoryCat.)

Update: When copy-pasting through manoli.net some angle brackets got dropped. This is, hopefully, fixed now.  Otherwise – get the source here: http://selfelected.pastebin.com/f77563a02

Update:

Check out Compulsorycat.  It is my F/OSS library with some of these functions.

IsNot in vbnet – a more readable way to check for Nothing

November 29th, 2009

When I have written Vbnet and checked for Nothing I have chosen between

If Not( o Is Nothing ) Then

and

If False = o Is Nothing Then

and

If o Is Nothing Then
‘    NOP.
Else

all ugly and/or hard to read but in their own way.

Some days ago I stumbled upon IsNot and since then my code looks nicer like so:

If o IsNot Nothing Then

I have been writing Vbnet for years without finding IsNot so I thought there are more out there with the same problem.

Unable to open the physical file Operating system error 5: "5(failed to retrieve text for this error. Reason: 15105)". (Microsoft SQL Server, Error: 5

October 18th, 2009

Try to attach a database with Management Studio when using Windows 7 and SQLServer 2008 developer edition and one might get an error message similar to the title of the article.

Whether this is a bug or not is beyond my knowledge but the solution/workaround is to connect as SA and not as windows authentication.

Login failed for user ‘IIS APPPOOL\DefaultAppPool’.

October 18th, 2009

If one uses trusted connection to a sqlserver database under Windows 7 and II7 one might get the error message “Login failed for user ‘IIS APPPOOL\DefaultAppPool’.” when trying to run a web application.  There are several articles for this but all points to a different GUI than mine (earlier versions of Windows7/IIS7?).

Update: as I lightly noted, to give the apppool SystemLocal rights is Not the right way to go.

Set up the application pool in IIS

Fire up Internet Information Services Manager.  (windowbutton-iis-return)

Find the Application Pools item in the Connections toolbar.  One can reuse the default application pool or create a new one.  Go for the latter since it is slightly more complicated and hence more fun.

or in Win8:

Add application pool in Win8

(I don’t grok what Managed pipleline mode does.)

Select your newly created application pool and the advanced settings.  Change the Process model to LocalSystem.
(I had planned to create a “better” account with the proper limited rights but ran out of time.  Someone else…?)

Update: Don’t change to LocalSystem, instead add the user to allowed SQLServer logins as noted in the bottom here.  I suggest “IIS AppPool\MySite” for now.

The recommended Microsoft solution is to create a separate account. However, if your solution is small, you can instead add the ‘IIS APPPOOL\DefaultAppPool’ user as a database user in your SQL instance, then providing the proper ‘User Mappings’ to the databases you need the DefaultAppPool user to access. You may not necessarily be able to search for this user, but you can still enter it in the ‘Login name’ field in the “Login – New” window as “IIS APPPOOL\DefaultAppPool” (without the quotes).

Follow this link as a reference and pay attention to the last post: http://social.msdn.micro…-4a71-a448-3e3eef9ee404/

Application pool settings

Getting to advanced settings.

Getting to advanced settings.

 

Application pool advanced settings

Application pool advanced settings

Site settings

Now change your web application to use this application pool.  This could be made simpler by moving the menu for this to the same place as the other menus.  To make the story short – select your site and look to the right of the IIS manager.

Site advanced settings

Site advanced settings.

Site advanced setting IIS7

Site advanced setting IIS7.

Application pool

Application pool.

Application pool in IIS7

Application pool in IIS7.

 

Set up Sqlserver

Honour those who should.

To add a new user to SQLServer go to your database->security and add user connected to IIS APPPOOL\DefaultAppPool.  This way the user can log in to the database.

Sqlserver -> new login

Sqlserver -> new login.

New login to database

New login to database. Don’t forget to change default database to appropriate.

Then go to the SQLServer->security and add this user to be allowed to login to the server through the user and properties.

The users of a database

The users of a database.

 

That is all there is to it.

Tools I use

July 28th, 2009

Below are the tools, sites and stuff I use.  I plan to update it as it goes.

Correction: I planned but haven’t.

Also: I have a shorter and similarly not-propertly-updated list as a article here.

7-zip
http://www.7-zip.org/
Even though I have a Winzip license I haven’t bothered installing it for several years.  I guess Microsoft killed Winzip through having simple zip support out of the box and for all other needs there are 7-zip.
Open source.
Winzip deserves an extra mentioning though due to their license: your payment is also valid for all updates.  Many many other software companies have something to learn there.

Agent ransack
http://www.mythicsoft.com/agentransack/
The built in searching software in Windows XP and forward sucks big time.  To its defense I must say that it searches Microsoft office documents.  But since it doesn’t search all folders it is rendered useless for a developer like me.  Agent ransack searches fast, very fast, and has a simple regex tool to refine searches. One can limit files and folders searched in and search in system files too.

Update:
The built in search in Vista is weird. It might work for office people, you know the kind that really can’t tell the difference between windows, word, internet explorer and internet. This search was probably updated for Win7 and very much so for Win8. But Agent ransack still has its use for really doing searches in files with regex and stuff.

Autohotkey
http://www.autohotkey.com/
This open source solution is handy for global shortcuts.  I use it to set the size of windows to cover half the left, right, top or bottom.  I also send my windows between my monitors with a similar keystroke.  It has a wierd scripting language and some bugs regarding how big monitors and windows are.

Update:
Sending the windows around between two or more monitors is done win Vista and later with window-arrow keys.

Connectionstrings.com
http://connectionstrings.com/

In Windows one have to have a connection string to connect to a database.  These come in all colours and tastes.  This site has a comprehensive list.  Gratis.

Dpack
http://www.usysware.com/dpack/
It is an addin to Visual Studio.  Gratis.  A must-have if you develop in Visual studio.
The most used shortcuts, for me, are alt-u to open files and alt-m to go to a method.  With this there is no more searching for files in the solution explorer or scrolling up and down looking for the right method.

Update:
Open source.
I still use it since Visual studio 2013 still hasn’t caught up. Not even with Resharper.

Filezilla
http://filezilla-project.org/
Filezilla is a free FTP server and client.  I only use the client.  I cannot say if it is the best of its crop or has some whiz-bang stuff that oushines the competition but it is free and fairly simple to use.

Keepass
http://keepass.info/
I have lots of passwords and so do most of us.  Instead of having the same password for most places or a system of passwords, use unique ones; then you don’t have to worry about people getting your hotmail because they got hold of the passwords for a small site somewhere and successfullly try it on hotmail too.
I have the same database synchronized with my Windows mobile phone; this requires an older version of the software unfortunately, but I keep the passwords with me without the need of a computer.
It is open source so you can inspect the source code at will.

Media-convert.com
http://media-convert.com/
A gratis site for converting all sorts of formats, not only video and sound.

MyGeneration
http://www.mygenerationsoftware.com/
I am a sucker for not writing code I don’t have to.  Automatic code generation is the way to go.
Open source.

Update:
T4 is a tough competitor.

Notepad2
http://www.flos-freeware.ch/notepad2.html
http://code.kliu.org/misc/notepad2/
I don’t think Notepad2 is the best editor out there.  Not even close really.  But it makes it easy to exchange your Notepad.exe with the vastly superior and open source Notepad2.  Notetab does the same pre WinXP and possibly many other editors too but this is the only I have tried (post win2k) and I use it.

Update:
I have since switched to Notepad++. Before that I used Notetab.

NUnit
http://nunit.org/index.php
Automatic testing is considered good.  I might be too much to test everything but the important things and the difficult things are worth while to test automatically.
Open source.

NUnitEx
http://code.google.com/p/nunitex/
This open source extension lib to NUnit makes it more fluent to write assertions.  The best return of investment is when writing tests for exception throwing.

Opera
http://www.opera.com/
This is my primary web browser and has been since before 2000.  For certain development things Firefox is better and one must have Internet explorer around for about one site a year but for the other 8759 hours Opera is to prefer.Web browsers are a pain to user with the keyboard.  Opera lets you navigate between the controls with shift-arrows; so much easier debugging when one doesn’t have to grab for the mouse all the time.
Gratis.

Opera mobile
http://www.opera.com/mobile/
Arguably the best mobile browser for fat mobile phones.  It is gratis.
For smaller phones I would use Opera mini that renders the web page in a farm and then sends just the result.  It doesn’t work with javascript heavy sites though.
There is an application, Skyfire, that I believe works like Opera mini. Don’t mix up Opera mobile and Opera mini.

Update:
Other mobile browsers has caught up.
A couple of years ago I did a comparison and couldn’t spot a winner.
As of today I believe Firefox mobile is the only one that supports Ghostery so right now it is used as much as Opera.

Pastebin.com
http://pastebin.com/
If you ever have tried sending a snippet over email or especially chat you know bad how the layout gets scrambled.  Enter Pastebin.
Paste the code into Pastebin and send the unique URL.  It even has history so when chatting you can update the code and resend.
Gratis.
There are competitors but I havn’t found any as good.

PDFCreator
http://sourceforge.net/projects/pdfcreator/
To create PDF documents I use an open source solution.  It installs itself as a printer so it is usable for everything from everywhere.  For reading I use OpenOffice instead of the competitor-for-the-worst-software-written-ever program from Adobe themselves.

PowerCommand for Visual Studio 2008
http://code.msdn.microsoft.com/PowerCommands
Gratis.  Source code available but I don’t know if there are any strings attached.
It has Copy reference and Open folder and Open command prompt.  No more tedious searching for references or walking all over the hard drive to find the correct folder.

Spam gourmet
http://www.spamgourmet.com/
An online solution for one time email addresses.  Good for avoiding spam.  It is gratis but it sometimes takes a while for the emails to pass through.Approximately the same result can be gained by having a spare email account for this but Spam gourmet comes with a number-of-possible-sendings solution that might be handy.

VLC
http://www.videolan.org/vlc/
There are many media players.  VLC is one of them.  I use it since it takes most formats.
It went version 1 in 2009.
Open source.There is another well known application, Media player classic, that does approximately the same.  To be honest, I use both.

Winmerge
http://winmerge.org/
This is an open source diff tool.  It has a nice keyboard navigation, something that the diff program that comes with Visual studio has totally messed up.  None of these two have any knowledge about classes and methods so if you swap two methods it is recognized as add and delete instead of the move it really is.
Somewhere I found a program that can diff 3 files at once but the URL is since long forgotten.