Encrypt / Decrypt Configuration Sections Internal and External

I just posted an article about encrypting and decrypting configuration files on  codeproject

The article can be found here, and as it explains it provides a tool that can encrypt or decrypt sections of configuration files, regardless of them being in the file or in external ones.

Maybe I’m wrong but no matter what I tried and googled, the tools and API provided did not process the sections in the external files so I had either to do it by hand with copy paste or create and automated tool that is not error prone to manual procedures.

Kill Open Database Processes

When a database has open connections left, and that happens a lot, you can kill them by using the script below after replacing $DBNAME$ with your database name.

DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'$DBNAME$'

DECLARE @SQL varchar(max)
SET @SQL = ''

SELECT @SQL = @SQL + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId


This is very useful when trying to execute functions take offline, restore and other similar ones.

Database Size

    sd.name as DBName
    ,mf.name as FileName
    ,case mf.file_id
        when 1 then 'Main'
        when 2 then 'Log'
    END as FileType    
    ,CONVERT(varchar(100), Convert(decimal(10,2),(((Sum(Convert(decimal(10,2),mf.size)) 
8000)/1024)/1024)))+' MB' as SIZE from sys.databases sd join sys.master_files mf on sd.database_ID = mf.database_ID AND sd.name=@dbName GROUP BY sd.name,mf.name,mf.database_id,mf.file_id

The above script when @dbName is set calculates the size of a database for the mdf and log file seperately.

Jobs seaching and LinkedIN

Today I created my LinkedIn ID.

I live in Greece but I would be interested in working abroad as long as the income / living cost is rational.

Since I’m posting here, I should describe what exactly I’ve been doing for the current company I’m working for.

During the last year of my professional life I had the role of IT Director, while I’ve been building latest .net technologies application with my coleagues. For the latest application, I’ve created a Modular, Multilanguage framework infrastructure with workflow support. The infrastructure provides a viable solution to give each customer whatever module they want with or without workflow and add a special customization that does not impede on the base modules, thus increasing support and reducing testing costs. The above solution can be plugged in with any identity system that I have come across.

One potential (implemented) of the above infrastrucre is that you can add workflow support to any other 3rd party application by creating a 3rd party specific module for authentication, and a module for the 3rd’s party objects that we want to make workflow relevant. A generic interface is provided for the 3rd party application to query its objects regarding to the workflow.

The above infrastrucre supports Client / Server application through WPF, WCF and WWF and is intented to support Web and Silverlight with the same specifications.

I hope for the best.

XCEED Datagrid

is changing licensing for the express edition. I’ve been using XCEED’s datagrid control for WPF for a year now, because it was the best grid control I could find, and for some of the controls for Date Time and numeric included in the library.

XCEED is changing licensing for the express edition and  has launched a campain in order to notify everyone interested in the express edition and still wants to have the benefits he had before the change.

So just visit http://xceed.com/freegrid and update your license.

Microsoft.Practices.EnterpriseLibrary.Data DiscoverParameters() Error

I’m generally against the Enterprise Library, but for reasons that are not to be discussed they are consumed in the framework I have developed.

Yesterday I encountered a serious error, that I tracked to the enterprise library.

Keep in mind that the target provider is SQL Server 2005.

At some point the framework builds an sql command that will be user to execute a stored procedure. One of the only two commands used from the library is DiscoverParameters which queries the procedure on the server and fills the paramaters collection on the command object.

The problem is that even though a parameter is defined as OUTPUT on the database server, the enterprise library insists on marking the parameter with INPUTOUTPUT direction. I surveyed the problem through Internet and Reflector and the database reported the parameters as trully OUTPUT only.

The solution is to either write your own DiscoverParameters which is not that difficult rather time consuming, or in my case tamper your code to work with some additional assumptions that are not correct and you I will surelly come across as a problem in the future.

Enable / Disable Binding Validation

Today a came across a situation where I need to stop a binding from validating through the validation rules.

There is no easy way to do this. One should think that you can change the hole binding etc etc.

After doing a little snipping while in debug, I saw that the BindingExpression return from BindingExpression GetBindingExpression(DependencyPropertydp) holds in the ParentBinding.ValidationRules the validation rules declared in xaml or not.

So I decided to create a BaseValidationRule from which all validation rules will subclass.

public abstract classBaseValidationRule:ValidationRule
        protected BaseValidationRule()
            IsActive = true;
        public bool IsActive { get; set; }

        protected abstract ValidationResult DoValidate(objectvalue,
        public overrideValidationResult Validate(objectvalue,
System.Globalization.CultureInfo cultureInfo)
            return DoValidate(value, cultureInfo);


As you can see if the rule is not active then it will simply return a ValidationResult.ValidResult so everything will be as though as you didn’t have validation rules in xaml.

I created some extention methods in order to quickly and transparently enable or disable validation rules at will.

Note that in order for the binding to be reevaluated based on the new status of your validation rules, you need to call UpdateSource on you BindingExpression .


I thought I understood fully serialization, but for some reason when building something for WWF I forgot a very important thing and a day was lost trying to find the cause of a mysterious problem.

The problem came because the workflow I persisted wouldn’t resume as I described here.

At the end, I found the problem and the exception was that for a type contained in my worflow the contructor could not be found. But I had spesifically declared a public contructor and marked is as Serializable.

I decided to debug in the native code which is not easy, and at some point I found where the exception about the constructor was througn.

RuntimeSerializer was requesting through reflection a constructor that took 2 type arguments. I wen’t back to my class declaration, which was a child of Dictionary<,>. I decided to look for a base contructor that took 2 arguments. I was going nuts, when I saw the constructor with these parameters
(SerializationInfo info, StreamingContext context)

It all came clean to me then. Dictionary<,> implements ISerializable. This means that custom serialization is done when required. When serializing its ok, because ISerializable.GetObjectData is called. But when deserializing a specific constructor with the above signature was required that I had hidden because I didn’t specifically declare it in my class.

The whole mistake was really silly, I just wanted to emphasize on the caution that need to be taken when subclassing objects with ISerializable.

I would like to make a comment. Runtime serializer should through a more specific exception about the problem. It searched for a very specific constructor that can be easily forgoten when sublassing a class that implement ISerializable

Persisted Worklow won’t resume

Lately I have been assigned to work with the Windows Workflow Foundation.

My feelings about it are mixed. There was a bug, that hold me for one day and I want to share with you, a troubleshooting technique that helped me.

First of all, out runtime service need to be persisted. In order to test persistance with Workflow out of the box activities, just create a while (true) activitiy with a seqeunce activity with a delay and something that can be debugged. I have create a Debug Activity.

The runtime is initialized with an sql persistance service like this

NameValueCollection persistenceParams = new NameValueCollection();
persistenceParams.Add("ConnectionString", ConnectionString);
persistenceParams.Add("UnloadOnIdle", Convert.ToString(true));
persistenceParams.Add("LoadIntervalSeconds", "5");

this.runtime.AddService(new SqlWorkflowPersistenceService(persistenceParams));
Every time a delay or a timer is reached because of UnloadOnIdle, it will be persisted.
My problem was that the workflow never resumed although, the entries in the database were correct.
I monitored its flow, by capturing these events
  • WorkflowIdled
  • WorkflowSuspended
  • WorkflowUnloaded
  • WorkflowPersisted
  • WorkflowLoaded

But WorkflowLoaded never came through. The reason I know it should was because I was actually refactoring I knew the sequence of events that would be fired.

Finally, and after some time I decided to capture ServicesExceptionNotHandled event. It turns out that although you may have declared to capture all exceptions form Visual Studio (Ctrl+Alt+E), if you do not capture that event you will never know what’s wrong.

The event provides a ServicesExceptionNotHandledEventArgs that basically holds the exception of what wen’t wrong.

In my case the problem was with serialization. The actual problem I will discuss in my next post.


Self Issued X509 Certification Token

At the company I work for, there was a need to create a n-tier application with username authentication.

For some reason WCF requires a certificate which is understandable, but shouldn’t this be a choice of my company?I will not get deep with WCF about this part. Maybe in another section.

So what is the problem. The problem is that everyone talks about making a self issued certification token and using it to run in development, but few talk about deploying the application. And most of those few have posted questions that remain unanswered or have posted some guidelines that do not work entirely.

My development machine is Vista 32 based and target deployment was for both Vista 32 and Windows Server 2003 both environments under their respective IIS.

First of all, the token must be created. At start as many of you, I knew little about certificates. I really believe this not to be a common interest for developers, so it has been really annoying not to really understand what has been happening or why that command was user. It is fair to say that at the moment, I haven’t really understood why the solution works, probably because after not being able to find solutions for my problems I had to resort to trial and error. Additionally Microsoft does not make public a lot of information about the subject or relevant APIS and their errors. There are some tools for example that generate a very common error message that one can not track the reason causing it.

Certificates manager console will be required with knowledge of it for importing and exporting.

Anyway, lets start.

First I will discuss how to create a self issued token through the development token. To token is created for a WCF service and its store location will be LocalMachine and store name My. My post is not for WCF so I assume that one knows what the above means for WCF.

Then I will discuss how to setup IIS in the development machine.

Last in this post I will tell you how to reuse the above token in other machines.

Token Creation

In order to create a self issued token, you must have installed in the machine Windows SDK. Because the machine is a development the above should be found in :\Program Files\Microsoft SDKs\Windows\v6.0A\Bin for Vista and XP and C:\Program Files\Microsoft Platform SDK\Bin for Windows 2003.If not found for windows 2003 you can download it from here. In any case WSDK will refer from now on to the appropriate path.

In order to create the token a certification authority token must be created first and then the token itself issued by the above. In order to keep it simple we assume that TokenCA is the certificate authority token and TokenCert is the certification token based on TokenCA.

In order for the above to work for wcf, the key must be exportable so in each command that it is required the appropriate flag is used. I will not analyze the commands, you can do it from the help or Internet.

The goal of the next steps is to create a zip file with the reusable token.All files will be saved in C:\ . Password will be required. I chose one and used it everywhere.

Create Certification Authority

Open a command prompt for the WSDK path.

Execute makecert -n “CN=TokenCA” -r -sky exchange -pe -sv C:\TokenCA.pvk C:\TokenCA.cer

Create Certification Token

Execute makecert -sk =TokenCert -iv C:\TokenCA.pvk -n “CN=TokenCert” -ic C:\TokenCA.cer -sky exchange -pe C:\TokenCert.cer -sr LocalMachine -ss My

Import Token

In order to Import Token you must open the Certificates manager from the mmc.

In the Trusted Root Certification Authorities under certificated select import and choose the TokenCA.cer we created.

Then in the Personal under Certificated select import and choose TokenCert.cer.

At this stage the token is ready to be used by the development WCF Service.

Export Token

In the Personal under Certificated select import and choose the token we created and select export. On the question if you want the export the private key, choose YES.


Then select like the next picture


Then enter password, and select where it should be stored. I entered c:\Token.pfx.

At this stage in c:\ there should be 4 files starting with token which you can pack but the reusable part is the Token.pfx.

Deploying in another machine

Now we want to use the above certificate. In the certificates manager in Certificates node under Personal you import the TokenCert.pfx enter the password and mark the key as exportable like this


IIS Setup

In order for any process to use the token we created or imported, that process must have read rights under the user it is running over the actual file windows created for the certificate token (TokenCert).

So for IIS NETWORK_SERVICE must have read access over the file.

If the OS is Windows 2003 you can use WinHttpCertCfg.exe which has two problems. First it is deprecated for Vista and second most important it gives the user Full Control access. So I do not recommend it. In any case use it like this winhttpcertcfg -g -c LOCAL_MACHINE\My -s “TokenCert” -a “NETWORK SERVICE”

Windows itself want tell you the file itself. In order to locate it you must follow these instructions.After you have located is just give the right like every other folder/file sharing.

Now the IIS can access the certificate. If you don’t do this the service will fail in every attempt including just hitting the svc which I used as a test.

In Vista there is another way through the certificates manager. You can select the certificate token (TokenCert) and right click -> All Tasks -> Manage Private Keys will display the access rights dialog for the actual file.


I can’t understand why in other machines the TokenCA is not needed. When I had also imported that, there were errors both from the finding tool and the winhttpcertcfg. This problem was resolved based truly on trial and error, but I still can’t understand why when creating the TokenCert, TokenCA is needed and then not. I know that the key is contained in the pfx, but as a mentioned my knowledge of certificates is superficial so the question still remains.

If I use the TokenCert outside the intranet will it still work?

Future Stuff

Because I want/ need automate the procedure, tools will be written to do the above in sequence. When I do, I surely post here or on codeproject.


Any questions you might have, please just ask and if I can help I will. The above process has taken me 2 days to find and I personally find it unacceptable especially when there is a WCF authorization system that requires the use of a token.

This article is based again on a specific WCF deployment that was required of me, but I think it is irrelevant.

Hope I didn’t forget anything.

Finally let me just say that the simplest and oldest authorization has been turned into a deployment nightmare. Hope this article helps the community. As always everything is great when Microsoft evangelist advertise. You guys, we are not making an assignment for IT bachelors.