Archive for the ‘.NET’ Category.

Plain ol’ XML

So let’s say you are working on an application in the .NET sphere of influence, and you have an object that you want to turn into XML. However, you shoot it through an XmlSerializer and you think you are done.

Ugh, what’s all that cruft in the XML stream?

Well there are some options you can play with to get rid of the extra stuff and just get plain ol’ XML. Here is a code snippet, where you will pass in your own object instead of the generic Order as shown below:

public String GetPlainOldXML(Order order)
{
    var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
    var settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = true;
 
    XmlSerializer xsSubmit = new XmlSerializer(typeof(Order));
    var xmlString = "";
    using (var sww = new StringWriter())
    {
        using (XmlWriter writer = XmlWriter.Create(sww, settings))
        {
            xsSubmit.Serialize(writer, order, emptyNamepsaces);
            xmlString = sww.ToString();
        }
    }
 
    return xmlString;
}

BTW, Happy Birthday to Leslie West of Mountain fame.

Error 404 on web service with map route

If you are getting an error 404 on your web service with a map route decorator on your methods, you might want to check your IIS settings to make sure that it is configured correctly.

Apparently, your app pool must be set up in integrated mode as opposed to classic mode in order for the routing to work.

BTW, Happy 10th Anniversary to the iPhone.

The final word on .NET background processing (for now)

While snooping around for information on .NET background processing, I came across a bunch of interesting articles by .NET MVP Stephen Cleary that go into great detail about using Task.Run vs. a BackgroundWorker control. Here is the link to the introduction of the series of articles:

Task.Run vs BackgroundWorker: Intro

BTW, I am impressed so far with the content that was revealed at the WWDC 2015 conference. I have been going through the presentations and, while there were no “knock your socks off” moments, there is still a ton of great stuff that they are packing into the new versions of iOS, OS X, and watchOS.

Cross a bridge at night

OK, here is a scenario. Four people on a journey together need to cross a bridge at night as quickly as possible. Among the four of them, they have one flashlight. They cannot continue their journey until all four reach the other side together. Since the bridge is narrow and slippery, and it is pitch black out being night and all, they decide to have two people cross with the flashlight, then one person returns with the flashlight back to the original side, and they continue until everyone is on the other side.

Oh, and also, the people can all walk at different paces, so when two people cross together, it takes them the amount of time that it takes the slower person to cover the distance.

For example, let’s say that the four people that need to cross can cover the distance of the bridge in 1 minute, 2 minutes, 5 minutes, and 10 minutes. What would be the shortest possible time?

The naive solution would be to have the 1 minute person be the primary flashlight runner and send them with the 2 minute person, return, then the 5 minute person, return, and finally cross with the 10 minute person, for a grand total of 19 minutes.

Now of course this is not the optimal solution, but more on that in a minute.

So how would we design an algorithm to solve this problem? Conventional wisdom says to create some kind of tree where you iterate through all of the possible combinations of initial crossings, then off those branches, combinations of reverse crossings, etc. Then once the tree is built, you can walk to all the branch tips and calculate the times, and then just display the shortest time.

But why do something logical? With all this computing power, I say that we implement my favorite algorithm for producing solutions to problems… The Monte Carlo method.

Here is the code for a C# .NET console app I threw together to solve this issue:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace BridgeAtNight
{
    public class BridgeState
    {
        public List<int> peopleOnLeft;
        public List<int> peopleOnRight;
        public int totalTime;
        public string peopleMovement;
 
        public BridgeState(int[] people)
        {
            totalTime = 0;
            peopleMovement = "";
            peopleOnLeft = new List<int>(people);
            peopleOnRight = new List<int>();
        }
 
        public void MoveLeftToRight(int leftToRight1, int leftToRight2)
        {
            peopleMovement = peopleMovement + string.Format("{0}>> {1}>> ", leftToRight1, leftToRight2);
            totalTime += Math.Max(leftToRight1, leftToRight2);
 
            peopleOnRight.Add(leftToRight1);
            peopleOnRight.Add(leftToRight2);
            peopleOnRight.Sort();
 
            peopleOnLeft.Remove(leftToRight1);
            peopleOnLeft.Remove(leftToRight2);
        }
 
        public void MoveRightToLeft(int rightToLeft)
        {
            peopleMovement = peopleMovement + string.Format("{0}<< ", rightToLeft);
            totalTime += rightToLeft;
 
            peopleOnLeft.Add(rightToLeft);
            peopleOnLeft.Sort();
 
            peopleOnRight.Remove(rightToLeft);
        }
 
        public void SolveWithNaivete()
        {
            peopleOnLeft.Sort();
            while (peopleOnLeft.Count > 1)
            {
                // move 2 people from the left to the right
                int leftToRight1 = peopleOnLeft[0];
                int leftToRight2 = peopleOnLeft[1];
                MoveLeftToRight(leftToRight1, leftToRight2);
 
                // move 1 person from right to left if there are any remaining people on the left
                if (peopleOnLeft.Count > 0)
                {
                    int rightToLeft = peopleOnRight[0];
                    MoveRightToLeft(rightToLeft);
                }
            }
 
            Console.WriteLine("Solution with naivete:");
            Console.WriteLine(string.Format("Time: {0} minutes", totalTime));
            Console.WriteLine(string.Format("Sequence: {0}", peopleMovement));
        }
 
        public void SolveRandomly()
        {
            Random rnd = new Random();
            while (peopleOnLeft.Count > 1)
            {
                // move 2 people from the left to the right
                var leftToRightRandom = peopleOnLeft.OrderBy(x => rnd.Next()).Take(2).ToList();
                int leftToRight1 = leftToRightRandom[0];
                int leftToRight2 = leftToRightRandom[1];
                MoveLeftToRight(leftToRight1, leftToRight2);
 
                // move 1 person from right to left if there are any remaining people on the left
                if (peopleOnLeft.Count > 0)
                {
                    var rightToLeftRandom = peopleOnRight.OrderBy(x => rnd.Next()).Take(1).ToList();
                    int rightToLeft = rightToLeftRandom[0];
                    MoveRightToLeft(rightToLeft);
                }
            }
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            BridgeState naiveBridgeState = new BridgeState(new int[] { 1, 2, 5, 10 });
            naiveBridgeState.SolveWithNaivete();
 
            List<string> bestTimeResults = new List<string>();
            int bestTime = 999999;
            for (int idx = 1; idx < 1000000; idx++)
            {
                BridgeState randomBridgeState = new BridgeState(new int[] { 1, 2, 5, 10 });
                randomBridgeState.SolveRandomly();
                if (randomBridgeState.totalTime < bestTime)
                {
                    Console.WriteLine(string.Format("Better random solution found in pass {0}:", idx));
                    Console.WriteLine(string.Format("Time: {0} minutes", randomBridgeState.totalTime));
                    Console.WriteLine(string.Format("Sequence: {0}", randomBridgeState.peopleMovement));
                    bestTime = randomBridgeState.totalTime;
                    bestTimeResults = new List<string>();
                    bestTimeResults.Add(randomBridgeState.peopleMovement);
                }
                else if (randomBridgeState.totalTime == bestTime)
                {
                    if (!bestTimeResults.Contains(randomBridgeState.peopleMovement))
                    {
                        Console.WriteLine(string.Format("Sequence: {0}", randomBridgeState.peopleMovement));
                        bestTimeResults.Add(randomBridgeState.peopleMovement);
                    }
                }
            }
 
            Console.WriteLine("Press any key to exit the application");
            Console.ReadKey();
        }
    }
}

There are undoubtedly some optimizations I can make to this code above, such as ordering the times in the MoveLeftToRight function. However, I was kind of surprised to see this run, as sometimes the optimal solution of 17 minutes was found in the first few thousand random walk throughs, and other times it would take a few hundred thousand walk throughs before the 17 minute solution was found. To me, it did not seem like there were enough different combinations that would make it so difficult to randomly find the solution.

For those who cannot/will not run this code, the crux of the biscuit, given the times of the walkers above (1 minute, 2 minutes, 5 minutes, and 10 minutes), is to send the slowest people across together once there is someone faster on the other side. Or in other words, first send 1 and 2 across, then have 1 come back. Then, send 5 and 10 across, and have 2 come back. Then 1 and 2 make the final crossing.

BTW, Happy Talk Like A Pirate Day today.

VB.NET simpler Async Await example

Well, I couldn’t let this rest, so here is an even simpler example of doing Async Await in VB.NET.

For this example code, I created a simple forms application with two buttons named cmdSynchronous and cmdAsynchronous, a label called lblStatus, and just to demonstrate the UI locking up effect, a combo box with some entries in it. Here is the code behind this form:

Public Class Form1
 
    Sub LongOperation()
 
        Threading.Thread.Sleep(5000)
 
    End Sub
 
    Private Sub cmdSynchronous_Click(sender As Object, e As EventArgs) Handles cmdSynchronous.Click
 
        lblStatus.Text = "Running a long operation synchronously... (UI thread should lock up)"
        Application.DoEvents()  ' needed here so that the label will update
 
        LongOperation()
 
        lblStatus.Text = "Done running the long operation synchronously."
 
    End Sub
 
    Private Async Sub cmdAsynchronous_Click(sender As Object, e As EventArgs) Handles cmdAsynchronous.Click
 
        lblStatus.Text = "Running a long operation asynchronously... (UI thread should be fully responsive)"
 
        Await Task.Run(Sub()
                           LongOperation()
                       End Sub)
 
        lblStatus.Text = "Done running the long operation asynchronously."
 
    End Sub
 
End Class

Notice that both button click events call the LongOperation method, which just sleeps for 5 seconds. However, the synchronous button click will lock up the UI (try to open the combo box, you will see that it waits until the sleep is done before displaying the choice list), whereas the asynchronous one will not.

Now in general, you would probably want to keep the tasks from piling up, as they would if you keep clicking the asynchronous button. I leave this as an exercise to the reader on preventing this problem.

BTW, Happy Birthday to Gary Hoey and Terje Rypdal, two of my favorite guitarists.

VB.NET simple Async Await example

I scoured the interwebs looking for a VB.NET simple Async Await example, and kind of came up empty. So, I decided to try to use bits and pieces of the examples I could find to roll my own.

The background here is that I am working on an application that accesses resources on the internet, and did not want to block the UI while the communications code was running.

Here is the code that I came up with:

Async Function GetDetails(theID As String) As Task
 
    Dim url As String
    url = GET_DETAILS_URL & "?theid=" & theID
 
    Dim request As WebRequest = WebRequest.Create(url)
    Dim response As WebResponse = Await request.GetResponseAsync()
    Dim dataStream As Stream = response.GetResponseStream()
    Dim reader As New StreamReader(dataStream)
    Dim responseFromServer As String = reader.ReadToEnd()
 
    reader.Close()
    response.Close()
 
    ' do something here with responseFromServer
 
End Function
 
Async Sub lstItems_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstItems.SelectedIndexChanged
 
    Dim idx As Integer = lstItems.SelectedIndex
 
    ' get the selected item
    Dim theItem As Object = itemsList(idx)
    Dim theItemID As String = theItem.itemID.ToString()
    Await GetDetails(theItemID)
 
End Sub

BTW, Happy Bennington Battle Day to our Green Mountain friends.

How to use a C# .NET interface to send messages between classes

I have used delegates in Objective-C to send message back and forth between classes for years. (And in fact, I did a blog post on Setting up an Objective-C delegate for the iPhone SDK a few years back on this very subject.) Indeed, delegates are a critical part of the Objective-C language, as it is usually good for objects to be able to let other objects know what is going on.

Well now, in my .NET development duties, I have a very similar situation. My code has a bunch of user controls that I use, and I need to have messages sent from one user control to another as the user works with the various pieces of the application.

Of course, in order to keep the compiler happy and get it working, you can do something quick and dirty like putting in an instance variable into the class that points back to your user control, and then when you need to let that user control know what is going on, just use the instance variable reference to call a method in that user control’s class.

But this is not scalable. If you have a bunch of different user controls calling a specific user control, you would have to put a reference to each different type of calling control, and then walk through them and determine which one you need to call in each case.

C# interface to the rescue. By using a C# interface, you can put an instance variable for your interface into your called class, which will then allow your calling class (which of course follows the interface) to have a method fired in it.

Here is a tutorial using C# for a console application that demonstrates the principles:

using System;
 
namespace ConsoleApplication1
{
    interface IMyClass  // 1
    {
        void PassMessage(string theMessage);
    }
 
    public class MyClass  // 2
    {
        private IMyClass parentClass;  // 3
 
        public void SetParentClass(object c)  // 4
        {
            parentClass = c as IMyClass;
        }
 
        public void Nudge()  // 5
        {
            parentClass.PassMessage("MyClass hath been nudged.");
        }
    }
 
    public class MainClass : IMyClass  // 6
    {
        public void DoStuff()  // 7
        {
            Console.WriteLine("About to DoStuff in MainClass");
            var c = new MyClass();
            c.SetParentClass(this);
            c.Nudge();
 
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
 
        public void PassMessage(string theMessage)  // 8
        {
            Console.WriteLine("Message passed from MyClass: " + theMessage);
        }
    }
 
    public class Program
    {
        static void Main(string[] args)
        {
            var mainClass = new MainClass();
            mainClass.DoStuff();
        }
 
    }
}

So let’s break this down a bit. The numbers below correspond to the comments in the code above.

1. This is the interface definition. You need to put in here a listing of the methods that you want to be calling, sort of like an abstract class.

2. This is the class definition for the called class, or the class that needs to send a message back to the calling class.

3. Here is where the reference back to the calling class is kept. Since it’s type is an interface, any object that follows that interface can receive the caller’s message.

4. In this method, I am setting the reference back to the calling class. You can do this in the constructor as well if desired.

5. The Nudge method is a method in the called class that when executed, needs to send a message back to the calling class.

6. This is the class definition for the calling class. Notice that it follows the interface above, which requires that you provide the method specified in the interface.

7. This method creates the called class and sets up the interface reference, and then sends the Nudge message to the called class, which in turn calls back by firing the PassMessage method.

8. Here is where I do the processing necessary when the calling class is sending the message.

This is a pretty trivial example, but it should give you an idea on how to start setting up more complex cases.

BTW, Happy Birthday to John Myung, the fantastically talented bass player and founding member of Dream Theater. They are playing in a town near me this spring, but unfortunately I will be out of town and unable to see them. Great sadness.

HTTP post in VBA

I have some very nice C# .NET web services that I created and use from some web sites, .NET desktop applications, and iOS apps. But of course, this is not a wide enough range of technologies that I have to deal with, so I needed to figure out how I could call my web service from within an Access database using Visual Basic for Applications (VBA).

The web service just takes in a couple of form variables, chugs through the database looking for the matching records, and returns a string with the pertinent data. Here is the VBA code that I put together to accomplish this task:

Sub Method1()
 
    Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    URL = "https://www.mywebsite.com/WebService.asmx/StatusCall"
    objHTTP.Open "POST", URL, False
 
    objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
    objHTTP.send "formVariable1=value1&formVariable2=value2"
 
    If objHTTP.Status = 200 Then
        MsgBox objHTTP.responseText
    Else
        MsgBox "Failed at getting response from web service:" & objHTTP.Status
    End If
 
End Sub

The response text is being sent to a message box, but you could just as easily return that string, or better yet, use an XML parser to dig into the data for just what you need. Perhaps I will save that code for another post later.

BTW, Happy Birthday to Julie Newmar, by far the best Catwoman from any Batman live action or animated TV show or movie.

.NET regex to find strings inside curly braces

Regular expressions all by themselves have the magical ability to amaze and confound all at the same time. Throw in a dash of .NET string interpretation and you have a recipe for pulling out the remaining hair that you might have on your head.

So I was trying to use a regex to do some searching inside of a large string for strings inside curly braces, such as {this} and {these three words}. My string matching routine would return “this” and “these three words”, without the quotes of course. It took a bit of trial and error, but here is the important stuff for the routine that I put together to accomplish this task:

const string pattern = @"\{([^\}]+)\}";
foreach (Match match in Regex.Matches(theLargeString, pattern))
{
    Console.WriteLine("Found a field match: " + match);
}

BTW, a special birthday shout out to one of the mega stars of our generation, who turns 50 years young today. Happy birthday, Larry The Cable Guy.

Overriding a TargetType Style without a Key in WPF

I have been doing a lot of work in WPF lately, and it is a different animal.

The default styles of a button did not look right for my application, so I came up with the following XAML that styles up all of the button objects in my application:

<Style TargetType="{x:Type Button}">
    <Setter Property="SnapsToDevicePixels" Value="true"/>
    <Setter Property="OverridesDefaultStyle" Value="true"/>
    <Setter Property="Background" Value="CornflowerBlue" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border x:Name="Border" CornerRadius="0" BorderThickness="0" 
                            Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding Background}">
                    <ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True" />
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter TargetName="Border" Property="Background" Value="#4667A5" />
                    </Trigger>
                    <Trigger Property="IsPressed" Value="true">
                        <Setter TargetName="Border" Property="Background" Value="#3C588C" />
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter TargetName="Border" Property="Background" Value="LightGray" />
                        <Setter TargetName="Border" Property="BorderBrush" Value="#AAAAAA" />
                        <Setter Property="Foreground" Value="DarkGray"/>
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="true">
                        <Setter Property="Foreground" Value="White"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

As you can see, I am using TemplateBinding to bind to the desired background color.

However, in one of my user controls, I want to be able to change the background color of the button in certain situations. Initially, I just created a copy of the above XAML, gave it a Key, and then used that key name to style up the Buttons that I wanted to.

As always, there is a better way. I found that there was a way to use a BasedOn in my new style to pull in the style from the global resources and just change what I needed, here is what it looks like:

<Style x:Key="SpecialButton" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
    <Setter Property="Width" Value="20" />
    <Setter Property="Visibility" Value="Collapsed" />
    <Setter Property="Content" Value=">" />
    <Setter Property="IsTabStop" Value="False" />
    <Setter Property="Background" Value="LightGray" />
</Style>

BTW, Happy Birthday to Eugene Levy, by far one of the funniest actors out there.