C#

You are currently browsing articles tagged C#.

I have created a simple C# WinForms sample to interface CDYNE.com SMS API. More information on the API can be found here: http://wiki.cdyne.com/?title=SMS_Notify!

The API source code is on GitHub: https://github.com/gunsh/CDYNESmsSample

Additionally, here is a simple video showing the process of simple console app creation. Enjoy!

kick it on DotNetKicks.com

Tags: , , , , ,

New Microsoft® Surface® 2.0 SDK has been released along with the Microsoft® Surface® Migration Power Toy which is aimed at helping all the Surface 1.0 code to the new SDK.

There have been numerous changes in the new SDK to play along with the WPF 4 and its integrated touch support. The Power Toy is there to help migrate all the Surface 1.0 code with a very low estimated manual work needed for seamless transition.

I tried the Power Toy and immediately hit the brick wall. I kept getting a failure from the tool.

Error: Project "System.__ComObject" could not be loaded. Error: Object not set to an instance of an object.

When I dug a little deeper in the source code it turned out that one specific case was not handled properly. Luckily there is a simple fix without getting much deeper into understanding the specifics of the code. There is a method RemoveReference() in ProjectExtensions.cs on line 31 that is doing a C# “as” instead of a cast but not checking for a null. Actually, “as” is perfectly valid here but the null check is definitely missing. All of my Surface 1.0 projects have a “Miscellaneous Files” Project but these do not cast to VSProject and thus the exception.

Luckily, all that needs to be done is to just add a single line of code and all starts working beautifully. Add the following on line 34 and life will be good again.

            if (vsProject == null) return false;

Hopefully this saves someone a sleepless night. Cheers!

kick it on DotNetKicks.com

Tags: , , , ,

I encountered a XAML puzzle today. Luckily, it was easy to solve although it did take some time to find out.

Suppose that you want to keep part of your WPF UI in a file external to your main application. Normally, all of your XAML is embedded as a Page resource in your application. This translates to a compiled XAML, also known as BAML. Allowing the outside world to specify a piece of XAML that you will show in your app can be useful in a number of scenarios. It is not something you will do every day but there are applications that could hardly do without this.

Now let’s suppose you create a brand new UserControl in your Visual Studio project. You will get a UserControl1.xaml and a UserControl1.xaml.cs. We can’t (or don’t want to) load code so just remove the .CS file. Now, we add something specific. We want to reference say some attached property from our own project. Let’s say the namespace is Email and the property is Caption on class Details.

<UserControl x:Class="Email.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:Email="clr-namespace:Email"
             Email:Details.Caption="Test">
    <Grid>
        <TextBlock Text="Hey!" />
    </Grid>
</UserControl>

How can we load this XAML file in our application and make it work as if it was compiled as part of the project? XamlReader comes to mind. Let’s try.

var userControl = XamlReader.Load(fileStream) as UserControl;
var caption = Email.Details.GetCaption(userControl);

Ok, this works but if we check the value of attached property we will discover it has a default value. Now why is that? Maybe we are using a wrong approach. If we try to load this with Application.LoadComponent() it will succeed beautifully.

var userControl = Application.LoadComponent(new Uri("/Email;component/usercontrol.xaml", UriKind.Relative)) as UserControl;

That worked with a local resource but what if we want to use LoadComponent() to load the file external to the application from an arbitrary URL? No, that won’t work. LoadComponent() will throw an exception complaining about the absolute URL. Basically, you can’t use LoadComponent() on anything but a local URL.

So what are our options? Huh, reflection perhaps? Doing what LoadComponent() does but skipping the relative URL check? No, that won’t work because relative URLs are there for a reason. LoadComponent() really loads from BAML not XAML.

After hours of pondering, searching and trial and error I finally came up with a surprisingly simple solution. We go back to the trusted XamlReader. What we need to do is just slightly change the xmlns:Email declaration by adding the assembly=Email like this:

<UserControl x:Class="Email.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:Email="clr-namespace:Email;assembly=Email"
             Email:Details.Caption="Test">
    <Grid>
        <TextBlock Text="Hey!" />
    </Grid>
</UserControl>

Voila! The XAML is finally loaded properly with our attached property accurately set.

Tags: , , , ,

First of all, let me start by saying I love WPF! :- ) I do Winforms when I really must. It reminds me of my MFC days and all the Win32 tricks and compatibility issues. Good old days are well behind now. Luckily, new technologies like WPF are making those issues just remnants of the past.

If you do Winforms development and especially work with ListView control, you may experience flickering. This is most notable when adding many items in succession.

To rectify this fortunately there is a very easy way. It involves a simple SendMessage to the ListView control. This is of course possible because in Winforms, a ListView control is just a wrapper around Win32 list view control. Unfortunately, even in NET4 Winforms there are no properties exposed that would make this job absolutely trivial. Instead, one must revert to P/Invoke trickery.

ListView maintains a few “extended” list view styles which are unrelated to WS_EX standard Win32 extended styles. These special extended styles are accessed by sending LVM_SETEXTENDEDLISTVIEWSTYLE / LVM_GETEXTENDEDLISTVIEWSTYLE to set / get the current value.

So, to disable ListView flickering we need to get the current “extended” style, add LVS_EX_DOUBLEBUFFER and set it back. See the image above for the effect as seen in Windows Explorer. If you want your ListView to look even more fancy, you may experiment by adding LVS_EX_BORDERSELECT too.

    public static class ListViewHelper
    {
        private const int LVM_FIRST = 0x1000;
        private const int LVM_SETEXTENDEDLISTVIEWSTYLE = (LVM_FIRST + 54);
        private const int LVM_GETEXTENDEDLISTVIEWSTYLE = (LVM_FIRST + 55);
        private const int LVS_EX_DOUBLEBUFFER = 0x10000;
        private const int LVS_EX_BORDERSELECT = 0x8000;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

        public static void SetPrettyStyle(this ListView listView)
        {
            var oldStyles = (int) SendMessage(listView.Handle, LVM_GETEXTENDEDLISTVIEWSTYLE, (IntPtr) 0, (IntPtr) 0);
            SendMessage(listView.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, (IntPtr) 0, (IntPtr) (oldStyles | LVS_EX_DOUBLEBUFFER));
        }
    }

As this is implemented as extension method, all you need to do now is make call like this:

    public void MyMethod()
    {
        _myListView.SetPrettyStyle();
    }

Tags: , , ,