Monday, December 29, 2008

Add file header

To add C# file header according to StyleCop's SA1633 you can use this macro:

Sub AddFileHeader()


        DTE.ActiveDocument.Selection.Text = "//-----------------------------------------------------------------------"


        DTE.ActiveDocument.Selection.Text = "// <copyright file=""" + DTE.ActiveDocument.Name() + """ company=""MyCompany d.o.o."">"


        DTE.ActiveDocument.Selection.Text = "//    Copyright (c) MyCompany d.o.o. All rights reserved."


        DTE.ActiveDocument.Selection.Text = "// </copyright>"


        DTE.ActiveDocument.Selection.Text = "//-----------------------------------------------------------------------"


    End Sub

Friday, December 26, 2008

Visual Studio - Create Blank Solution

If you want first to create blank solution in Visual Studio on specific location and then to add existing projects or create new one you will be very disappoint if you expect to find "Create Blank Solution" item under the New menu.
To create blank solution do the following:
  1. On the File menu, select New and then click Project.

  2. In the Project types pane, select Other Project Types and then select Visual Studio Solutions.

  3. In the Templates pane, select Blank Solution.

Thursday, December 18, 2008

Visual studio test environment and provide additional files

If you want, for example, to copy additional files to test location for some unit test, for example, some XML file, do the following:
  1. Add test.xml to test project
  2. Set "Copy to output directory" property of file to "Copy always"
  3. For test method add [DeploymentItem("test.xml")] attribute.

Get current exe assembly folder location

string folderPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

Thursday, December 11, 2008

ASP.NET IIS trouble

If you, by mistake, first installed .net framework, and after that IIS you may have trouble to run your IIS/Web service applications.
One of the possible error messages can be: "Failed to access IIS metabase", or "service unavailable"...
To repair ASP.NET you should run:

aspnet_regiis -u
aspnet_regiis -i

It worked for me :)

Monday, December 08, 2008

This will save you some time

If you get error message "Association references unmapped class" from nhibernate check settings for Build Action for hbm.xml file. It should be "Embedded Resource".

Wednesday, December 03, 2008

Get calling method name

To get method name that was called current method use:

System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();
System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(1);
System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
string methodName = methodBase.Name;
Console.WriteLine("Method name: "+ methodName);

Tuesday, December 02, 2008

ctor snippet upgrade

According to the StyleCop you should put this comment above constructor.

/// Initializes a new instance of the MyClass class.

In order to do this automatically you can use SnippetDesigner (or you can do it by yourself) to change default ctor snippet.
It should be:

/// Initializes a new instance of the $classname$ class.

public $classname$ ()

Snippet location is:
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC#\Snippets\1033\Visual C#\ctor.snippet

Friday, November 28, 2008

Lazy loading class

/// Lazy loading class. When the value is required object will ask for item provider and cache result.

/// Item type.
/// Key type.
internal class LazyLoadingBase
public delegate TItem GetItemWithNameDelegate(TKey name);

GetItemWithNameDelegate getItemWithName;

TKey key;
TItem item;
bool itemSet;

public LazyLoadingBase(GetItemWithNameDelegate GetItemWithName)
itemSet = false;
item = default(TItem);
getItemWithName = GetItemWithName;

public object Value
if (!itemSet)
item = getItemWithName(key);
itemSet = true;
return item;

if (value is TItem)
item = (TItem)value;
itemSet = true;
else if (value is TKey)
key = (TKey)value;
throw new InvalidOperationException();

/// Cast operator.

public static implicit operator TItem(LazyLoadingBase lazyLoadingBaseObject)
return (TItem)lazyLoadingBaseObject.Value;

Customize debug view

I made a wrapper class for some other class. And every time when I wanted to see in debugger what does it wraps I had to view the class members and theirs members just to view that name of the wrapped class is something.

In order automatically to view important members of class and help you to fast identify object put this attribute to class:

[DebuggerDisplay("Name = {name}")]

...where "name" is class property or field name.

Wednesday, November 26, 2008

Remove tabs and spaces from end of line

If you are frustrated when you press "End" key and cursor goes much behind your last character, you can use this macro to remove all spaces and tabs from end of the line:

Sub RemoveTabsAndSpacesFromEnd()
DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxRegExpr
DTE.Find.Action = vsFindAction.vsFindActionReplaceAll
DTE.Find.FindWhat = ":b+{\n}"
DTE.Find.ReplaceWith = "\1"
DTE.Find.Target = vsFindTarget.vsFindTargetFiles
DTE.Find.MatchCase = True
DTE.Find.MatchWholeWord = False
DTE.Find.MatchInHiddenText = True
DTE.Find.SearchPath = "Current Document"
DTE.Find.SearchSubfolders = True
DTE.Find.KeepModifiedDocumentsOpen = False
DTE.Find.FilesOfType = ""
DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResults1
End Sub

Now, just assign some keyboard shortcut to this macro.

Tuesday, November 25, 2008

Exception handling block and log in the same file

If your exception handling block log exceptions in separate file, beside the fact that you set everything to use existing log category, maybe you need to set "UseDefaultLogger" to have "true" value.

Enterprice library, exception handling and logging application block

I have started to get this error message on deployment configuration:

The current build operation (build key Build Key[Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyImpl, ...]) failed: The type 'Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35' cannot be resolved. Please verify the spelling is correct or that the full type name is provided. (Strategy type Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.ConfiguredObjectStrategy, index 2)

Logging works well but logging exceptions failed.

It seems that I was forgot to deploy Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll. When I put this assembly everything started to work fine.

Replace variable values

Do You know how to replace variable values without using third variable?

int x = 100;
int y = 200;

x ^= y;
y ^= x;
x ^= y;

Friday, November 21, 2008

Rhino Mock and "Type is not public, so a proxy cannot be generated"

When you try to create mock object using rhino mocks and object should implement internal interface you may get following error:
Type is not public, so a proxy cannot be generated
In order to fix it, put following line in interface assembly:

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

More information at: link

Wednesday, November 05, 2008

Debug inside .net framework source code

To enable debugging inside .net framework source code follow instructions on this page:

(For symbol location enter:

Thursday, October 30, 2008

KeePass custom autotype

I will explain how to create custom auto-type in keepass on example.
Let's create autotype for WinSCP.
  1. Start WinSCP. You will get loggin form.
  2. Start KeePass. Choose Add Entry
  3. Set Title, username , password and url
  4. Tools button (bottom-left) | Auto-type: Select target window
  5. Choose WinSCP Login
  6. You will get in notes edit box: Auto-Type-Window: WinSCP Login
  7. In the notes edit box type on the : Auto-Type: {URL}{TAB}{USERNAME}{TAB}{PASSWORD}{ENTER}
That's it. Now, when WinSCP login dialod is opened chose your entry and press CTRL-V

Saturday, October 25, 2008

.NET Disassembler

You can download here free disassembler. This disassembler does not have export functions. To enable export function you can download plugin here.

Thursday, October 23, 2008

Accessing object anywhere in code

If you want to see some object wherever in code (in watch window) do the following:
  • Set breakpoint in a place where you create this object
  • Right mouse button and "Add Watch"
  • In Watch window, right mouse button on your object and select "Make Object ID"
  • You will see something like {1#}. 1# is your object ID
  • Now, wherever you break your code you can add in watch window 1# and you will see your object

Load xsd file from assembly

First, you need to add xsd file to resource by changing build action to "Embedded Resource".
To access this file from code write something like:

XmlSchemaSet schemas = new XmlSchemaSet();
Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream("Namespace.ServiceDescription.xsd");
schemas.Add("", XmlReader.Create(new StreamReader(stream)));

Friday, October 17, 2008

Firefox, Redirect Loop and Google Calendar

If you have trouble to open google calendar using firefox maybe this can helps:
  1. Tools->Options->Privacy->Accept Cookies
  2. Tools->Options->Privacy->Clear Now-> (check cookies) -> Clear private data
  3. Restart firefox

Tuesday, October 14, 2008

WCF, IIS, Keyset does not exist

- Error: Keyset does not exist error when I try to test WCF project with X509 security.

  1. Check if WCF support is installed for IIS:
  2. If you are using certificate, check if application pool have access permissions for private key. To provide access permissions do:
    1. Find IIS application pool identity
    2. Find private key file name for certificate (FindPrivateKey.exe):
    3. Add read permissions for IIS application pool identity (cacls.exe) or just open windows explorer and set permissions

Friday, October 10, 2008

Test run pending trouble

Sometimes when I start unit test from visual studio all test are in pending phase and no test will run.
Open task manager find proses named as VSTestHost.exe and kill it. After that try to start tests again.
It works for me.

And here is macro to do that for you

Sub KillDeadTestProcess()
Dim objProcess As System.Diagnostics.Process
For Each objProcess In System.Diagnostics.Process.GetProcesses()
If (objProcess.ProcessName = "VSTestHost") Then
End If
End Sub

Create certificate

To create certificate for use in WCF for example you can use Visual Studio command line tool makecert and pvk2pfx

For more information look here

Thursday, October 09, 2008

SqlRoleProvider - change password length

To change required password length add this section in config file:


<roleManager enabled="true" > </roleManager>




<add name="AspNetSqlMembershipProvider"













type="System.Web.Security.SqlMembershipProvider, System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>



Wednesday, October 08, 2008

Remove from wcf service

To remove you should define your own namespace in service contract atribute


Tuesday, October 07, 2008

The Address property on ChannelFactory.Endpoint was null

You created web service client, set up config file using Service Configuration Editor and you get

The Address property on ChannelFactory.Endpoint was null


You probably forgot to add configuration name in

new ChannelFactory();


Friday, October 03, 2008

Writing code in blogspot

Here is a nice way to write code in blogspot

<pre style="border: 1px dashed rgb(153, 153, 153); padding: 5px; overflow: auto; font-family: Andale Mono,Lucida Console,Monaco,fixed,monospace; color: rgb(0, 0, 0); background-color: rgb(238, 238, 238); font-size: 12px; line-height: 14px; width: 100%;">


Some code here



Code will looks like:

Some code here

... or you can use "Copy as html" addin for visula studio. Link is:

Thursday, September 25, 2008

Sandcastle warning in inherited classes

If you comment member functions of interface and you don't want to comment the same functions in class that implement specific interface you will get warning from compiler. To avoid this warning and keep the comments from interface use:

        /// <inheritdoc/>

Monday, September 15, 2008

SVN global ignore pattern for c#

*.resharperoptions Web_Data log */[Bb]in [Bb]in */obj obj */TestResults TestResults *.svclog Debug Release *.suo *.StyleCop StyleCop.Cache *.user *.vsp *.dll _ReSharper.*

Thursday, August 14, 2008

Regular expressions: Remove last appearance of some element

If you want to match A, B and C but don't want C to be the last element you can do it using this regular expression:


Note that [ABC]+ can be mutch more complex then this is.

Wednesday, August 13, 2008

Binding ASP.NET TreeView to a DataSet or an ObjectDataSource

Excellent article:

Wednesday, August 06, 2008

Monday, August 04, 2008

Retrieve local ip address

CStringArray straIPAddresses;


WSADATA wsa_Data;

int wsa_ReturnCode = WSAStartup(0x101,&wsa_Data);

char szHostName[255];

gethostname(szHostName, 255);

struct hostent *host_entry;

host_entry = gethostbyname(szHostName);

int nAdapter = 0;

while ( host_entry->h_addr_list[nAdapter] )


char * szLocalIP;

szLocalIP = inet_ntoa (*(struct in_addr *)host_entry->h_addr_list[nAdapter]);





Saturday, August 02, 2008

Detect available serial ports

You can use class found at to detect available serial ports on your PC. Class is using seven different methods to enumerate serial ports.

Monday, July 21, 2008

Remote Debugging

Sometimes you need to debug application on remote machine. To do that you need to copy files for remote debugging on to remote machine. You can find those files in:

c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Remote Debugger

Run msvsmon.exe on remote machine and set security.

In Visual Studio, in project settings, go to Configuration Properties Debugging, chose Remote Windows Debugger (from Debugger to launch), set other parameters and press F5.
If you have set all correctly, application on remote machine will be started.

Friday, June 27, 2008

Locate current opened file in solution explorer

To locate current opened file in solution explorer you can use this macro:

Sub LocateInSolutionExplorer()
End Sub

Tuesday, June 24, 2008

Convert std::string to std::wstring

// std::string -> std::wstring
std::string s("string");
std::wstring ws;
ws.assign(s.begin(), s.end());

// std::wstring -> std::string
std::wstring ws(L"wstring");
std::string s;
s.assign(ws.begin(), ws.end());

Monday, June 16, 2008

Add custom library or form in Visual Studio Macros

  1. Create custom class library in language that you prefer.
  2. In Build events Post build events add: copy "$(TargetPath)" "$(DevEnvDir)PublicAssemblies\"
  3. In macro from where you whant to use your custom library add reference to your class library
  4. You are now free to use your custom library in your macro

Tuesday, June 10, 2008

Find commented peace of code

In the process of re factoring of your code you may wish to delete commented peaces of code. You can use this regular expression to find potential trash in your code


Friday, May 16, 2008

Force debugger to stop when some variable change value

Sometimes is very useful to know when value of some variable is changed. To force debugger to stop when it happens run debugger to place from where you want to monitor your variable (Variable must be instanced because you need to know it's address).

In Breakpoints window chose NewNew data breakpoint.
Now, fill breakpoint parameters and next time when your variable is changed, anywhere in code, debugger will stop.

Tuesday, May 13, 2008

How to check memmory coruption

To check if heap is corrupted set following flag using watch window:
{,,msvcrtd.dll}_crtDbgFlag = 5

Tuesday, April 29, 2008

Delete all .svn subfolders using Total Commander

You can easily delete all .svn sub folders using Total Commander in few steps:
  • Search for .svn (ALT + F7)
  • Chouse Feed to listbox (ALT + L)
  • Press * to select all results
  • Press delete to delete all .svn subfolders

Friday, April 25, 2008

Set value to unbound column

To set value in unbound column cells you have to handle CellFormating event. Then, check DataGridViewCellFormattingEventArgs and set value. For example:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
if (e.ColumnIndex == 2)
e.Value = "Test";

Tuesday, April 22, 2008

Compiling .NET to Machine Code

Compiling .NET to Machine Code
Normally, when a .NET application is run, the JIT (Just In Time) compiler transforms the .NET intermediate code into machine code just before it gets executed. Because of this, the compiler only has very little time to optimize the code.
However, there's a feature many .NET developers aren't even aware of: ahead-of-time compilation or AOT in short. AOT means compiling an entire .NET assembly to machine code before it is executed and usually takes place either when the an application is installed or continuously in the background while the system is idle. It allows for time-consuming optimizations to be performed on the code that normally only a traditional C or C++ compiler would have time to do.
The advantage of this method over traditional compilation however is that it takes place on the end-user's machine. Microsoft's .NET framework for example will compile .NET 2.0 assemblies to 32 bit code on a 32 bits operating system and to 64 bit code on a 64 bits operating system unless you tell it to do otherwise.
Microsoft .NET Framework
Microsoft's utility for AOT compilation is named ngen.exe, short for native image generator. It can be found in the directory the .NET runtime is installed in, eg. C:\Windows\Microsoft.NET\Framework\v2.0.50727 for the .NET Framework 2.0.
ngen.exe can be invoked from the command line in two different modes:
ImmediateUse ngen install or ngen update to immediately compile the given assembly to machine code. ngen.exe will compile the assembly and exit when it's done.
QueuedUsing this mode, assemblies are placed into a queue and will be compiled either at your measure or by a low-priority process while the system is idle. This mode can be accesses by adding the /queue:{123} argument at the command line.
ngen.exe will not modify the assemblies specified on the command line but instead put the compiled assemblies into a special folder that is checked whenever .NET needs to load an assembly.
(taken from

Custom WWF Persistence Services

I found this great article about making custom WWF persistence service

Open new command prompt for cout

If you run your library from environment that don't provide you console window for your messages you can open new one using:
AllocConsole(); freopen("CONOUT$", "w", stdout);

Total commander and Winmerge

In order to use Winmerge as comparision tool add following line to wincmd.ini:

CompareTool="d:\Program Files\WinMerge\WinMerge.exe"

stl: list vs vector

They solve different problems, so it depends on the "shape" of your data, and which is more important to you, inserting, deleting or accessing quickly.Lists are double-linked lists, so insertion at either end, or in the middle (providing you know an existing element in the middle) is equally fast. Also, splicing is fast (eg. putting a list into the middle of another) - all that does is re-arrange the end pointers. All of those operations would be slower with vectors, because you would need to copy Inserting into the middle of a vector of 1000 items would involve moving 500 items up one. Similarly with deleting. In fact, vectors are really only good for insertion and deletion at the end.For things that require insertion and deletion, but only at *each* end (like a queue) then there is a dequeue (double-ended queue) which is really a collection of vectors. This is more efficient.However, vectors shine in random access - since they are organised sequentially in memory, whilst this is slow for insertion at anywhere other than the end, you can easily find, say, element 500, you simply index into the vector. Thus, vectors can be sorted, shuffled, and accessed randomly.When playing with STL - and these other MUD-related ideas - I am asking myself what is the need for each case - random access or fast insertion, and using the container appropriate to the case at hand.For instance, in the event management code I will post shortly, as I remove events from the queue I am keeping a copy of the auto-repeat ones, for later re-insertion. Now the copy is a temporary copy, and I don't need to access it in any special way, so I am using a simple vector. However the event queue itself is a priority queue (which I suspect is implemented as a map of queues).Vectors are designed to auto-grow, with the size - I believe they double in size each time they grow. eg. 2, 4, 8, 16 and so on. So, if you keep adding to them the number of memory allocations is pretty small. However if you know in advance how much they need (even roughly) then you can tell the vector to reserve that amount in advance.
(Thanks to
Nick Gammon. Article taken from

Source code organisation of templates

in the H file:
#ifndef __MY_TEMPLATE_H
#define __MY_TEMPLATE_H

... #include "mytemplate.cpp"

#endif __MY_TEMPLATE_H

and in the CPP file

#include "mytemplate.h"

Detecting memory leaks

If you put {,,msvcrtd.dll}_crtBreakAlloc (or change msvcrtd.dll with proper dll, maybe msvcr80d.dll) in watch window. Press F10 and you should see -1 as value. Change value with memory allocation number and debuger will stop at this memory allocation number!!! Great thing for memory leak hunting!!!

Note, if you have multi thread application you will not have always the same allocation number.

Sourcesafe and "An Error Occurred in the Secure Channel Support" message

I tried to enable VSS on IIS. Installation pass correctly but when I try to connect SourceSafe I was getting this error message “An Error Occurred in the Secure Channel Support”. I tried everything but with no results. And finally I found that the problem was that some process didn’t have permission on Windows\temp folder.

Useful links:

Useful tools (if you have any problem to enable VSS on Internet:

Monday, April 21, 2008

Visual studio 2005 toolbox icons screwed up

Right click on toolbox and select "Reset toolbox" from context menu to get icons back

WIA Scanning without user interaction

WiaClass wiaManager = null; // WIA manager COM object
CollectionClass wiaDevs = null; // WIA devices collection COM object
ItemClass wiaRoot = null; // WIA root device COM object
CollectionClass wiaPics = null; // WIA collection COM object
ItemClass wiaItem = null; // WIA image COM object
try {
wiaManager = new WiaClass(); // create COM instance of WIA manager
wiaDevs = wiaManager.Devices as CollectionClass; // call Wia.Devices to get all devices
if( (wiaDevs == null) (wiaDevs.Count == 0) )
MessageBox.Show( this, "No WIA devices found!", "WIA", MessageBoxButtons.OK, MessageBoxIcon.Stop );
object selectUsingUI = System.Reflection.Missing.Value; // = Nothing
wiaRoot = (ItemClass) wiaManager.Create( ref selectUsingUI ); // let user select device
if( wiaRoot == null ) // nothing to do
((Item)wiaRoot.Children[0]).Transfer("C:\\a.tmp", false);
Note: Tnx to unknown author of "WIA Scripting and .Net" at

Avoid flickering in C# custom control

Whent it is set BackgroundImage to custom control and Invalidate is call you can see flickering. To avoid that try like this:

publicpartial class MyControl: UserControl
public MyControl()
SetStyle(ControlStyles.AllPaintingInWmPaint ControlStyles.OptimizedDoubleBuffer, true);
protected override void OnPaint(PaintEventArgs e)

How to dealocete char* str = "something";

char* str = "something";
If you try to delete str you will get exception at _CrtIsValidHeapPointer.

The thing is that you can not dealoce str because you didn't alocated it at all.
And don't wory. You will not get memory leaks. This string is already in memory. When this command is executed str just get pointer to that part of memory.
Compile program, open it (.exe) in some hex editor and search for "something". It's there :))))

Debuging tips & tricks

In visual studio 6.0 in watch window add variable "@err, hr" and you will get useful information when some function fails

Windows XP Embedded check disk

To run check disk on xp embedded you will need chkdsk.exe and autochk.exe in windows\system32 folder.
In command line type: chkdsk c: /F
System will ask to check disk after restart. Confirm it.

With a little luck error will be corrected.

Convert Byte Array 2 Variant Array and reverse

VARIANT ByteArray2VarArray(CByteArray &ba)
rgsBounds[0].lLbound = 0;
rgsBounds[0].cElements = ba.GetSize();
psa = SafeArrayCreate(VT_UI1, 1, rgsBounds);
for (int i = 0; i <>
SafeArrayPutElement(psa, (long*)&i, (ba.GetData() + i));
vt.vt = VT_ARRAYVT_UI1;

vt.parray = psa;
return vt;


bool VarArray2ByteArray(VARIANT var, CByteArray &ba)

if ( ! (var.vt & VT_UI1))

return false;
if ( ! (var.vt & VT_ARRAY))

return false;
if (var.vt & VT_BYREF)
psa = *(var.pparray);
psa = (var.parray);
long lLbound, lUbound;
SafeArrayGetLBound(psa, 1, &lLbound);

SafeArrayGetUBound(psa, 1, &lUbound);
for (long i = lLbound; i <= lUbound; i++)
unsigned char b;
if( SafeArrayGetElement(psa, &i, &b) == S_OK)
return true;

ATL COM Wizard Error

I have generated empty ATL COM Wizard project in VC++ 6.0, and when I compile it I get this error:
urlmon.idl error MIDL2025 ... expecting a type specification near "IClassFactory".
And what was the problem?
Problem is because Language for non-unicode programs in regional options in control panel was set to language other then English.
When I set it back to English everything was OK.
I hope that I save someone’s time.