XCEED Datagrid

June 2, 2009

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

May 12, 2009

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

February 20, 2009

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,
System.Globalization.CultureInfocultureInfo);
        public overrideValidationResult Validate(objectvalue,
System.Globalization.CultureInfo cultureInfo)
        {
            if(!IsActive)
            {
                returnValidationResult.ValidResult;
            }
            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 .


Serializing

February 2, 2009

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

February 2, 2009

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

January 8, 2009

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.

image

Then select like the next picture

image

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

image

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.

Questions

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.

Conclusions

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.


Programmatically managing IIS

November 27, 2008

I wrote an article about managing IIS through code. In the attached file there is a library that will be extender with Active Directory Functionality and possibly Microsoft Exchange.

The article can be found here


WPF vs Windows Forms

November 25, 2008

Today I was at a DevDay in Athens, Greece with subject the 3 W of .NET 3 and 3.5. WPF, WCF and WWF.

First of all, I want to say that for one for time, it was just like reading glorious posts on the net about how easy stuff are with Microsoft technologies. Guys, business applications are not a paper for a university lesson. Programmers in companies should not be carried away by tricks that show of, but not give a resolve issues that enterprise developers must solve.

Based on that, once again WCF was great. Hell its not because of reasons discussed  here and here. In the WWF, a colleague of mine asked a very logical question, but there was no answer either. I don’t know whether those presenting the technologies don’t have a deep understanding of the technologies discussed or they purpose is to market them.

In the subject that I understand best, that is WPF, I really must say that based on what was presented, no one would migrate to the technology. The speaker made the usual mistake of basing his presentation on the usual wrong stuff, Graphic, Animation Fantastic UI and the so called developer – designer better cooperation. But when a member of the audience asked the logical question, of why should I migrate,  when all there are so huge differences and especially when a dedicated designer will be required still there was no clear answer to point out that true power of WPF.

So I will try to point out what are the overwhelming advantages of WPF and also point out some of the wrongs that I have found in the last six months.

Yes there is a tough learning curve, but the true power of WPF resides in the data binding mechanism and the way it shares resources across the application. On extra benefit that comes from the learning curve is that who learn how to decouple logic from UI. It’s not because of a pattern, but because of the data binding mechanism. Truly an application will last longer, when the UI can be changed without producing problems to the logic. Use the templates right and you can change a piece of UI code that reflects to the entire application. And don’t get me started about the usage of Control Templates.

Routed events are also great but the resource sharing is awesome. Just create a themed application in windows forms and compare the memory used by heavy brushes with a WPF themed application.

All the above comes with greatly improved performance, bonus from .NET 3.5 SP1.

My first problem with WPF and with Microsoft is the total disregard for Datasets and especially typed datasets. WPF will be on a client which if it is an enterprise application, it will require an application server. What better way to have related data transferred over the wire than from dataset? This is why I say that Microsoft has great ideas, but tends to forget the real needs of business. All examples are with simple objects which have set and get methods. But that is the simple way. That would be the solution for a university exercise because in real world you cant hit the application server continually, wcf or not.

Second problem with WPF is the Command mechanism that is used. Don’t get me wrong, the idea is great but why it must be static the Command instance? If I want to create the same form twice as non modal window, what will happen? It is not clear to me why they have chosen static for commands.

For the last six months I’ve been developing with colleagues a WPF application that can handle several modules not known at design time, and all these modules and the shell can must present themselves in various languages based on the installation. I really don’t know how some things could have been made with windows forms.

For me WPF and WCF are the most powerful add-ons in the .NET3 version and older. I just wish Microsoft would be a little more serious about the needs of true enterprise applications and not just glowingly showing little demos.


WPF Themes

November 19, 2008

I knew for a time that Visual State Manager from Silverlight had been ported for WPF, via the WPF.Toolkit project.

Today I found out that there some interesting themes based on the Visual State Manager.

Here is the post

I especially like DavesGlossyControls


WPF ShowDialog

September 12, 2008

There is an issue with ShowDialog for Windows not always obeying Modal Dialogs rules.

So I have created a static class which all ShowDialog calls will be redirected.

public static bool ShowDialog(Window dialog,Window owner)
{
    if (owner != null)
    {
        WindowInteropHelper helper = new WindowInteropHelper(dialog);
        helper.Owner = new WindowInteropHelper(owner).Handle;
    }
    bool? dialogResult = dialog.ShowDialog();
    return dialogResult.HasValue ? dialogResult.Value : false;
}

 

I’ve made some corrections so this is the new code

public static bool ShowDialog(Windowdialog, Windowowner)
{
   WindowInteropHelper helper = newWindowInteropHelper(dialog);
   if(owner != null)
   {
      helper.Owner = newWindowInteropHelper(owner).Handle;
   }
   else
  
{
      helper.Owner = GetActiveWindowClass.GetActiveWindow();
   }
   bool? dialogResult = dialog.ShowDialog();
   returndialogResult.HasValue ? dialogResult.Value : false;
}

where GetActiveWindowClass.GetActiveWindow is a interop wrapper

public static class GetActiveWindowClass
{
    [DllImport("user32.dll")]
    public static extern IntPtr GetActiveWindow();
}