Don’t Be A BRUTE, Be GREEDY!

Recently I was conducting a few interviews for my company. I was generally impressed with the  candidates and their abilities to “think on their feet.”

One of the things that I like to explore during the interview is how the candidate handles improving on a “brute force” solution. In general I think its good if you come up with a solution that works and then go back and discuss with the interviewer how you might improve the solution to make it more efficient for time and space.

Normally it doesn’t matter so much because even the most basic PC’s these days have very fast processors and you probably aren’t dealing with enormous sets of data. Nevertheless it’s an interesting exercise to challenge yourself to see if you can improve your code and get the max efficiency out of your logic.

Oh No!

As a quick refresher “computer scientists” express the efficiency of an algorithm using “Big O” notation. Its an easy way to describe how many passes an algorithm might have to iterate over a set/list/array etc . . .

Key points to know about Big O

  1. Know the order of best to worse:  O(1), O(n), O(log n), O(n^2), O(2^n)
  2. Drop Constants –  ex if you are looping through a list 4 times it’s still basically O(n)

One technique that I find useful for eliminating unnecessary loops is a “greedy” algorithm.

What’s really cool is that it can sometimes be used to turn a nested loop algorithm O(n^2) into a single loop solution. i.e. a single pass through the list O(n).

For large lists of data the efficiency difference between an O(n) solution and an O(n^2) can be huge!

So Whats the Problem?

The main value in the “greedy” approach is that you can get an answer efficiently by iterating through a list of data once. I have boiled down the main concepts to these:

  1. Initialize your “test”, “target” and your “so far” variables outside the loop.
  2. Evaluate your “test” value using the current “so far” in the beginning of the loop.
  3. Evaluate your “target” using the “test” and the “so far” values.
  4. Re-assign your “so far” value at the end of the loop.

To illustrate the technique assume you have an array of positive numbers and you want to determine what is the max difference between two of the numbers. Additionally, the max difference must be between two numbers where the index of the first number in the equation is greater than the index of the second. (i.e. You’re not allowed to sort the array)

Sample input array of numbers :  { 13, 18, 1, 6, 2, 9 }

The answer for max (sequential) difference would be: 8
index [5]  – index[2] = 8   // Where index[5] = 9 and index[2] = 1

You probably did this “in your head” by scanning the list, recognizing that the number “1” was the smallest number and then you saw that “9” was the greatest number afterwards.

You were doing the greedy method intuitively! Isn’t the brain amazing?

Approach Cautiously with Brute Force

When tackling this kind of question in an interview you should strive to solve it straightforwardly and then look to see how you can improve on it.

This is what people call the “brute force” method. It just gets it done correctly even if it ends up doing a lot of extra work.

public int GetMaxSeqDiff(int[] nums)
{
    int maxdiff = 0;

    // Go through every number from first to last
    for (int i = 0; i < nums.Length; i++)
    {
        // get a number
        int currentVal = nums[i];

        // And get diffs with all the FOLLOWING numbers
        for (int y = i + 1; y < nums.Length; y++)
        {
            int otherVal = nums[y];

            // See what diff would be 
            int testDiff = otherVal - currentVal;

            // see if testDiff is the MAX diff and then capture it
            maxDiff = Math.Max(maxDiff, testDiff);
        }
    }

    return maxDiff;
}

This definitely works, but as soon as you see nested loops ( On^2) you should take another look and see if its possible to eliminate the inner loop.

It’s So Nice To Be GREEDY!

Think back to how you solved this when figuring it out just looking at it. A key to the strategy was that you scanned the list quickly and found that the number “1” (index[2]) was the smallest number in the list. Once you identified the smallest number you knew you had one piece of the equation.

Algorithm: Max Sequential Diff = max number(with index > index of min number)  – min number

The min number is a great example of what I call the “so far” number. What I mean is as you traverse the list and examine each number you store what the min number is “so far.”

public static int GetMaxSeqDiff(int[] nums)
{
   // Default your "So Far", "Test" and "Target" vals
   int minNumSoFar = nums[0]; // The first num is the min num "so far"  
   int maxDiff = nums[1] - minNumSoFar; // Default your target/return val 
   int testDiff = 0;
            
   // You can start the loop from 1 since you already
   // have set minValueSoFar to nums[0] 
   for(int i = 1; i < nums.Length; i++)
   {
      // Greedy Step 1 = Get your test val 
      // in the BEGINNING of the LOOP  
      testDiff = nums[i] - minNumSoFar;
      
      // Greedy Step 2 = Test for your target result
      maxDiff = Math.Max(maxDiff, testDiff);
                
      // Greedy Step 3 = THE KEY STEP !!!!
      // Update your "So Far" AT THE END of the LOOP
      minNumSoFar = Math.Min(nums[i], minNumSoFar);
   }
   return maxDiff;
}

Pretty cool, right? One Loop!

Have fun and keep coding!

Taking a Byte Out of BitMasks

BitMasking is a technique that allows you to store multiple values in a single Byte. Yes, you read that right – more than one property value in a single byte of memory.

“How does this work?” you may ask. Well, it all has to do with how math works with Bits. As you probably know all the Bits in a Byte are 0s or 1s. When you add two 0s the result is 0 when you add two 1s the answer is also 0 but the next bit is set to 1. Add a 1 and a 0 and – you guessed it – the result is a 1.

The really cool thing is that because each byte is mapped to only one power of 2 you can reliably identify if a unique byte value is included in a byte. You can “pack” a byte with more than 1 byte def and then “test” if that value is included in the “packed byte.”

So What

I usually use this technique to store multlple Enums in a single Enum property of an object. In order for this to work you must define your Enum as powers of 2.

Uh … 2 Divisions? We can’t do that… Can we?

Suppose you want to maintain what division an Employee works in or manages. First you define a Enum to identify the Divisions.

public enum Divisions
{
       NotAssigned = 0,
       PersonalProducts = 1,
       Industrial = 2,
       Childrens = 4,
       Experimental = 8,
       TopSecret = 16
 }
Note how the Enums are specifically declared as powers of 2

Next you create your Employee class and create the Division property which is defined as your Enum type.

public Divisions Division { get; set;}

Now in your code you can assign and test what Division the Employee has been assigned to using your tidy Enum.

_employees.Add(new Employee() { Name = "Karl", Division = Divisions.TopSecret });
_employees.Add(new Employee() { Name = "Carol", Division = Divisions.Industrial });

Nice, right?

But wait! What happens if Carol is promoted and becomes the manager of the TopSecret Division while still maintaining her position in the Industrial Division?

One solution might be to create Boolean flags within the Employee class that represent each Division. Maybe you could create a Hash with the Division as the Key and a bool as the Value? Furthermore, what happens when new Divisions are created? You would have to update the Hashes or add new properties. Yuck!

You get the picture. Is there a way to do it without adding new properties? Well the answer is “Yes!” It turns out that you can “add” multiple Divisions to the Employee.Division property and still be able to determine the unique Divisions for the Employee.

A Bit of Math

If Carol is currently in the Industrial Division her Employee.Division = 2. That’s because we defined the Divisions Enum as Powers of 2 and explicitly set Industrial = 2.

The TopSecret Division has a value of 16, so if we add that to Carol’s current Division value she ends up with Division = 18. (16 + 2)

So think about this for a sec – If we know that the max value of the Divisions Enum == 16 and Carol.Division > 16, Carol must be in more than one Division. In fact, since we used only powers of 2 in our definitions there is only one combination of Divisions that totals a value of 18!

  • This assumes that a Division can be only added once to an Employee.
    Ex. Employee.Division = 6 should not be Industrial 3 times!

Here’s how it works under the covers –

Industrial 2 0000 0010
Top Secret 16 0000 1000
added/combined 18 0000 1010

The way you add the bytes is by using one of the “Bitwise” operators.

Divisions division = Divisions.Industrial | Divisions.TopSecret;

To add 2 bytes you use the bitwise OR – |. This makes sense when you think about it because you are trying to get 00 | 00 = 00, 01 | 00 = 01, 00 | 01 = 01 and 01 | 01 = 11.

Not surprisingly you can also subtract a byte. To do this you use the EXCLUSIVE-OR – ^ operator which only returns 1 (true) if only 1 of the operands is true.

00 ^ 00 = 00, 01 ^ 00 = 01, 00 ^ 01 = 01 and  01 ^ 01 = 00.

division = division ^ Divisions.TopSecret;   // would “remove” TopSecret
Combined Division 18 0000 1010
Top Secret 16 0000 1000
^ (notice the result is Industrial ) 2 0000 0010

Now this is the really awesome part. You can use the AND – & bitwise operator to apply the “mask” of the value you are looking for. The bitwise & returns true only when both operands are true. This quality of & can be used to check if the bits you are looking for are currently set!

00 & 00 = 00, 01 & 00 = 00, 00 & 01 = 00 and 01 & 01 = 01

// Carol is in the Top Secret Division if true! 
if ((Carols.Division & Divisions.TopSecret) == Divisions.TopSecret)
Combined Division 18 0000 1010
Looking for Top Secret 16 0000 1000
& (notice the result is TopSecret ) 16 0000 1000
Combined Division 18 0000 1010
Looking for Industrial 2 0000 0010
& (notice the result is Industrial ) 2 0000 0010
Combined Division 18 0000 1010
Looking for Personal Products 1 0000 0001
& (notice the result is NOT Personal Products ) 19 0000 1011

Xamarin.Forms! – Too Good To Be True?

Wow, I am really excited about Xamarin Studio 3.0 and especially its inclusion of the new Xamarin Forms package.

XF lets you design a form via C# and then compile to iOS, Android and Windows Phones all in with one code base! What’s really interesting to me is that you can describe the XF controls in C# or in XAML!

Hurrah! All those years working in WPF may not have been for naught.

I’ve already signed up for the Xamarin University course Intro to Xamarin Forms this coming Tues. I am sure to learn a lot and have quite a few questions.

Definitely check it out. 🙂

 

This Is Far As You Can Go Mr. Context Menu – When PlacementTarget Is Just Not Enough.

Going Up.

Accessing ContextMenus via RightClick is a very common (and expected) paradigm used in Windows desktop apps. WPF provides the ContextMenu element and you normally “attach it” in the XAML through the ContextMenu Property of some visual.

<Image.ContextMenu>
   <ContextMenu ItemsSource="{Binding TileConfigItems}" 
                ItemTemplateSelector="{StaticResource templateSelector}"
                ItemContainerStyle="{StaticResource StretchMenuItem}"/>
</Image.ContextMenu>

A very interesting (and surprising) thing to know about the ContextMenu is that it is essentially a separate “Visual Tree.” This means that if you try to use the RelativeSource syntax in your ContextMenu Binding to traverse upwards to find the DataContext of some Parent visual you will be limited to the ContextMenu itself! What I’m trying to say is that using RelativeSource Mode=AncestorType or AncestorLevel etc … will not be able to access anything other than the visuals within the ContextMenu definition, with the ContextMenu visual being the root.

Nice Place You’ve Got Here.

To solve this problem Microsoft provides the PlacementTarget DependencyProperty to allow you a way to “jump” to the Visual Tree that had invoked the ContextMenu.

In this example a simple context menu is being invoked on a Button within a UserControl. By using the PlacementTarget you can access the Button.DataContext. Without the PlacementTarget you would have no way of getting any farther than the ContextMenu.DataContext.

        
<Button Grid.Row="1" Content="Right Click For Context Menu">
  <Button.ContextMenu>
    <ContextMenu>
      <MenuItem Header="{Binding RelativeSource={RelativeSource Mode=FindAncestor, 
                              AncestorType={x:Type Grid}}, Path=DataContext.ZooName}" />
      <MenuItem Header="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
                              AncestorType={x:Type ContextMenu}},
                                Path=PlacementTarget.DataContext.ZooName}" />
    </ContextMenu>
  </Button.ContextMenu>
</Button>

The Button gets its DataContext from the UserControl. The UserControl has its DataContext set to a ViewModel (ZooVM.cs) which exposes a public string property ZooName. To illustrate how PlacementTarget allows you get to the underlying visual’s tree, I attempt to set the MenuItem.Header to the ZooName property of the Button’s DataContext. As you can see from the screen shot the first MenuItem Binding doesn’t display the ZooName but the second does.

MenuItem1 tries to get to Button.DataContext using AncestorType=Button.

MenuItem1 cannot get to the Button.DataContext.

How come?

The reason the second binding works is because I am employing the PlacementTarget of the ContextMenu, which in this case is the Button. In the first binding I am attempting to traverse to AncestorType = Button. Since the binding starts in the MenuItem the “Max Ancestor” it can get to is the ContextMenu.

OK, Simple Enough. Not!

As the title of this article suggests, using the PlacementTarget won’t help you when you need to get to an “outer” DataContext in a nested situation. (i.e. Grid, ListBox, ListItem)

This diagram below illustrates a typical WPF pattern. The “enclosing” UserControl has a DataContext of ZooVM. When you bind the ItemSource of an ItemsControl to ZoomVm.Cages WPF sets the DataContext to CageVM for the list’s items. Similarly, when you bind an additional ItemsControl to the CageVM.Animals WPF sets the DataContext for each item to an individual Animal.

Nested DataContexts – How will you get to the ZooVM when you are stuck in a cage?

As I demonstrated in the previous example, the PlacementTarget allows you to get to the VisualTree that your ContextMenu was nested within. But . . . there is no way using XAML to get the Ancestor of the PlacementTarget. As the nested diagram shows, you can’t reach the ZooVM from a PlacementTarget of Animal.

Tag, you’re it!

I reasoned that I would be able to access the Ancestral DataContext of the PlacementTarget if I could somehow store it in an exposed property. My solution was to use a strategy from my old Win/Office Forms days.

Just like in WinForms, WPF has many elements that support a Tagproperty. You can populate the Tag with pretty much anything. I store the Ancestors DataContext in the Tag property of the “inner ListBox” so I can access it from the ContextMenu’s PlacementTarget.Tag.

The following XAML is from the definition of the DataTemplate for a ListItem in the “innermost ListBox” of the diagram. It’s DataContext is {Animal}. The Label is in the VisualTree of the UserControl, so I can use the RelativeSource AncestorType syntax to access the WrapPanel’s DataContext, which is ZooVM.

<Label Content="{Binding Name}" 
  Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type WrapPanel}},
  Path=DataContext}">

Now that the desired DataContext has been stored I can access it from the ContextMenu’s PlacementTarget without any problem.

<Label.ContextMenu>
   <ContextMenu >
      ...
      <MenuItem Header="Option 2" 
         Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, 
            AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.Tag.OuterVMCommand}"
               CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Header}" />
   </ContextMenu>
</Label.ContextMenu>

So there you have it!

I have attached a sample app for your enjoyment. 🙂

[download id=”167″]

The Overriding Theme Of It All.

My Style Is Not Being Applied To My Elements!

I was playing around with a third party tool set and applied their theme to my app. This worked great and I was pretty happy with the overall look. As I progressed through my QA I noticed at least one weird byproduct of using themes.

I Said Collapse! (Please?)

The GUI element I call “Super Tiles” allows the user to select/deselect elements that are displayed in a ListBox. I do this by setting the DataTemplate to bind to an IsVisible property on the VM.

        
<DataTemplate x:Key="TotalISPerfWithExpectedCost">
    <UniformGrid Columns="2" HorizontalAlignment="Stretch" Visibility="{Binding IsVisible,
                    Converter={StaticResource boolToVisibility }}" >
    <Label Content="{Binding Label}" HorizontalContentAlignment="Right" />
    <Label Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBox},
                         Mode=FindAncestor}, Path=DataContext.TotalISPerfWithExpectedCost}"
                         ContentStringFormat="{Binding ValueFormatString}" Grid.Column="1"
                         HorizontalContentAlignment="Right" />
        <i:Interaction.Behaviors>
            <behaviors:FrameworkElementDragBehavior/>
        </i:Interaction.Behaviors>
    </UniformGrid>
</DataTemplate>

 

ThemedNothingHidden

I can see that the vertical spacing between items is already wrong!

After applying the themes, I noticed that the vertical spacing between the “hidden” ListBoxItems was not being fully collapsed. Ugh!

Themed2ThingsHidden

See the weird space between the 4th and 5th Item?

 Even though I explicitly set the ListBox.ItemContainer.Style to have 0 margin etc , etc, the weird behavior persisted. To debug the issue I set the highlighting on the selected item to an extreme (and ugly Olive Drab) color. Sure enough, when running the app and selecting an item, the highlight would not render as expected. This was a hint that my explicitly set style was being overridden.

So that’s how it works.

Obviously this had to have something to do with the recently applied theme. Previously everything was working as expected, but now I seemed to have no control over the styles.

Here is the issue. When you set a theme, all the effected controls get their BasedOn properties set to the current theme’s resource dictionary. So what this means is that your explicitly set styles using TargetType etc. won’t do anything because you are not instructing WPF to override/change the theme’s  settings.

If the current theme is unchanged, the default BasedOn is also unchanged.

Solution

In order to inform WPF that I wanted to circumvent the theme’s definitions I needed to explicitly define a Style BasedOn the Static Definition of the ListboxItem.

First – Set up a Style in the Resources of your control and ref the Static x:Type of the desired element.

<Style x:Key="DataPointListItemStyle" TargetType="ListBoxItem" 
          BasedOn="{StaticResource {x:Type ListBoxItem}}">
   <Style.Resources>
     <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
                         Color="LightBlue"  Opacity=".5"/>
   </Style.Resources>
</Style>

Second – implement the Style in your element

<ListBox.ItemContainerStyle>
   <Style TargetType="ListBoxItem" BasedOn="{StaticResource DataPointListItemStyle}" />
</ListBox.ItemContainerStyle>

Check it out!

StyledNothingHidden

Smaller spacing vertically between items

Styled2ThingsHidden

“Hidden” elements are now fully collapsed! (avoiding the themed ListBoxItem definitions)

Cool! 🙂

I Can’t Hear You.

I can see and hear my friend on Skype but he can only see me.

I tried to set up Skype with my friend last night so we could use the video conferencing feature and review a project we are collaborating on.

Well. . . it took us a while to figure out why I could hear him but he could not hear me. Our first guess was that it was some config/setting on his iPad. Nothing seemed to work so my friend tried the Skype test call. Confusingly, the test call worked perfectly and he could hear the test tones.

Undeterred I searched the interwebs and got nowhere.

What could possibly be wrong?

The only thing that seemed to be common to the complaints I saw was that users had recently upgraded to iOS 7.  My friend had not upgraded (he is afraid) but I had!

I proceeded to check my iPad settings and first looked at Sounds. I also checked the Skype node and the General. Nowhere was there any hint as to why he couldn’t hear me.

Ah Ha!

Eventually, I ended up checking every node in settings and found something promising in Privacy.

Microphone!

So look, I’m not going to pass judgment or anything here but I really don’t see how placing microphone settings in Privacy makes a lot of sense.

Sure enough, when I expanded the microphone submenu there was one item and it had the name Skype next to it. The slider was set off, so I turned it on, basically giving Skype access to the Mic.

Not sure how I feel about this exercise but I’m glad its over.

Here is hoping  that this helps someone else.

Bah!

 

 

Genymotion – the way to go

I downloaded the XamarinStore app (cause I want the T-Shirt)  and was bummed out with the way the app looked in the v14 Android emulator. (I couldn’t see the all the text so I couldn’t tell what was needed to complete the next steps.)

Luckily, Nick at Xamarin mentioned that I should check out GenyMotion and get the free android emulators from them.

Wow, big difference! And much better!

 

Persisting User Config Settings – Including Deployments With ClickOnce

Wow! You let me customize that?

Very often I have had to allow users to make changes to the UI like column widths, font sizes, colors etc. When I discovered that I could set up defaults by editing the solutions app.config I was pretty psyched. Unfortunately the mood was soured when complaints came in from my users that all their precious custom settings would get overridden every time I deployed a new release. 🙁

No Way! … Way!

Sure enough, every time the project was re-compiled and deployed the click once package would override all config values to the pre-set values in the app.config. This could end up being really annoying for the users, especially if they had spent time setting up connection parameters and path variables.

My first instinct was to devise a cool custom set of methods that would handle persisting and retrieving some XML that would hold my apps settings. I knew it would need to be smart enough to choose between “defaults” I could include in the deployment and values the user set at their particular installation.

Once I started to realize how tedious it would be to code the “smart” logic of juggling defaults vs. user settings. I quickly lost interest and searched for a better way.

An added level of complexity of when you install an app via “Click Once” is that Visual Studio will create and deploy your app to a directory somewhere on the users hard drive and give it a hashed name that you can’t possibly predict. So, if you are planning on implementing some sort of custom config files for your app, you will have to manage setting a path to some custom location for your app or figure out how to ask .NET where the heck it installed the .exe. I figured .NET must know how to find where it deployed my app so there has to be a way for me to get that info too.

Configure This

I found quite a bit of information on the ConfigurationManager object but it left me really confused. Amazingly, I didn’t find one (simple) example of how to manage the user settings. Instead I found tons of articles on how to create my own Custom Settings Sections etc.  I just couldn’t believe that Microsoft didn’t have some built in scheme for managing user configs.

Well of course they did! And here is how I ended up implementing it.

Use Case: App executes and retrieves config values from app.config. User sets values as desired. App is executed subsequently and uses the new settings as set by the user.

 Solution

  • Set a Reference to System.Configuration
  • In VS go to Project/App Name Properties. Select the Settings Tab
      • Set up your user config settings as desired. Make sure to set the Scope to USER!
      • What’s really awesome about setting these config variables up is that they will appear in the intellisense!  Nice one Microsoft!
  • Observe the XML of the app.config and you will see that a new section has been added.
  <userSettings>
    <UserConfigDeploymentSample.Properties.Settings>
      <setting name="ID" serializeAs="String">
        <value>OriginalID</value>
      </setting>
      <setting name="Info" serializeAs="String">
        <value>Original Information</value>
      </setting>
    </UserConfigDeploymentSample.Properties.Settings>
  </userSettings>
  •  You access these settings using the Properties object. As I said, this is awesome because config keys will be provided by the intellisense.
IdTextBox.Text = Properties.Settings.Default.ID; // .NET automatically makes named properties of the user settings
  •  When you invoke the Save() method of the Properties object, .NET will create a “special” folder with your user.config file!
// Note you will have needed to set at least one key to cause the user.config to be persisted
Properties.Settings.Default.ID = "Custom ID Value";
// this creates the special directory and user.config file (if it doesn't exist yet)
Properties.Settings.Default.Save();
  • Going forward, all Properties.Settings.Default.xxx will return the values in the user.config not the original app.config user settings values!
  • Finally, you can use the ConfigurationManager to get the path to where .NET is storing the config files. Even if it was click once!
// Where the exe is running -- very useful in the case of ClickOnce
System.IO.Path.GetDirectoryName(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath);
// Where the custom user.config will be stored 
UserLevelPerUserRoamingAndLocalConfigPath.Text = System.IO.Path.GetDirectoryName(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath);

Sample App:

[download id=”73″]

Fun!

 

Help! My app is minimized and my dialog won’t pop up!

Recently, one of our clients complained that they weren’t “adequately” notified when some of their trading orders stopped. The big problem with this is that they only noticed the Idle orders near the end of the trading day.  Apparently, they didn’t see the awesome “Errors and Exceptions” dialog that is supposed to pop up anytime the server throws an exception on an order.

Don’t Minimize Me Bro!

After I let the trader vent his frustration, I tried to do some detective work and recreate the situation and figure out what happened. Sure enough the user found a use case I hadn’t considered before. To save screen real estate he had minimized the app and left it on auto-pilot.

The code that responded to the error messages and displayed the Errors Dialog worked correctly but will not show a dialog if the parent window is minimized.

Who’s Your Daddy?

Some searching of the interwebs suggested that I set the dialog windows Topmost = “True” but that wasn’t enough to get the job done.  I figured that it probably had to do with the fact that I was assigning the ErrorDialog.Owner to the MainWindow and since the MainWindow was minimized it must be forcing all its “children” to be minimized as well.

The Code 🙂

I severed the relationship between the two windows and then I added an “else” so that if the user had minimized the Error Dialog instead of closing it, it would still pop up without creating additional Dialogs.

        public void ViewErrorListManager(object param)
        {            
            // Can only call from Main Dispatcher so check before proceeding and switch if necessary
            // Note the best way to check if the UI thread is active is to use .CheckAccess()
            // Dispatcher.CurrentDispatcher.Thread == Thread.CurrentThread is NOT 
            // a good way to check for UI thread. This is becasue Dispatcher.CurrentDispatcher will
            // create a new Dispatcher associated with the current Thread. This is not what you want!
            if (Application.Current.Dispatcher.CheckAccess())
            {
                // check if window is already open
                if (!Application.Current.Windows.OfType<SystemAlertDialog>().Any())
                {
                    SystemAlertDialog dlg = new SystemAlertDialog();
                    dlg.DataContext = _alertVM;
                    dlg.Show();
                }
                else
                {
                    SystemAlertDialog dlg = Application.Current.Windows.OfType<SystemAlertDialog>().First();
                    if (dlg != null)
                    {
                        dlg.WindowState = WindowState.Normal;
                        dlg.Focus();
                    }
                }
            }
            else
            {
                // Invoke the call from the "Main Dispatcher"
                // Note this.Dispatcher is not valid on a non Window class
                // Note Dispatcher.CurrentDispatcher.BeginInvoke() will also not work 
                // because only the main UI thread has a message queue and pump
                Application.Current.Dispatcher.BeginInvoke(new Action(() => ViewErrorListManager(new object())));
            }
        }

Yes!