Visual Studio

Visual Studio “No EditorOptionDefinition export found for the given option name” error.

I received the following error message in Visual Studio 2013 when trying to open a c sharp file. I have done nothing and this was came suddenly.

VS2013

I have searched for a solution and found lot of visual studio loading issues due to ComponentModelCache. I deleted ComponentModelCache folder and restarted VS, and VS automatically regenerated files required for ComponentModelCache. After that it worked without any errors.

ComponentModelCache file path for VS 2013 : %LocalAppData%\Microsoft\VisualStudio\12.0\

C#, WPF, XAML

WPF ListBox Selection Issue on Windows Tab Devices

On Windows Tab devices users are able to use Finger scrolling to scroll list box. But sometimes this causes an issue when selecting list box items. If the user preformed a finger scroll before selecting a list box item many times the list box item is only highlighted and it is not always selected.

To avoid this behavior need to handle TouchMove and TouchUp event and forcefully set selected item.

public partial class SearchDialog : UserControl
{
private double startPosition = 0;
private double endPosition = 0;
private const int LISTBOX_ROW_HEIGHT = 20;

public SearchDialog()
{
InitializeComponent();

listBox.TouchMove += listBox_TouchMove;
listBox.TouchUp += listBox_TouchUp;
}

void listBox_TouchUp(object sender, System.Windows.Input.TouchEventArgs e)
{
var touchDifference = endPosition – startPosition;
endPosition = 0;
startPosition = 0;

//If difference between touch start and end is less than list box row height
if (touchDifference < LISTBOX_ROW_HEIGHT)
{
var touchPosition = e.GetTouchPoint(listBox);
UIElement elem = listBox.InputHitTest(touchPosition.Position) as UIElement;

while (elem != null)
{
if (elem == listBox)
return;

ListBoxItem item = elem as ListBoxItem;

if (item != null)
{
item.IsSelected = true;
return;
}
elem = System.Windows.Media.VisualTreeHelper.GetParent(elem) as UIElement;
}
}
}

void listBox_TouchMove(object sender, System.Windows.Input.TouchEventArgs e)
{
System.Windows.Input.TouchPoint currentPoint = e.GetTouchPoint(listBox);

if (startPosition == 0)
{
startPosition = currentPoint.Position.Y;
endPosition = currentPoint.Position.Y;
return;
}
//Calculate touch start and end positions.
if (currentPoint.Position.Y < startPosition) startPosition = currentPoint.Position.Y; if (currentPoint.Position.Y > endPosition)
endPosition = currentPoint.Position.Y;
}
}

C#, WPF

How to Open/Close console window from a WPF application


[DllImport("Kernel32")]
public static extern void AllocConsole();

[DllImport("Kernel32")]
public static extern void FreeConsole();

private void btnShowConsole_Click(object sender, RoutedEventArgs e)
{
//Open Console
AllocConsole();
Console.WriteLine("Console text");
}

private void btnCloseConsole_Click(object sender, RoutedEventArgs e)
{
//Close Console
FreeConsole();
}

C#, WPF, XAML

Create a WPF Switch Control Using a Check Box

Most of the time peoples like fancy stuff. They expect same behaviour with more creative manner. In WPF we can change controls default look and feel by editing its control template. Below XAML style shows how to change look and feel of a Check Box to a Switch Control.

<!– Create Style –>

<Style x:Key=”CheckBoxStyle1″ TargetType=”{x:Type CheckBox}”>
<Setter Property=”Foreground” Value=”White”/>
<Setter Property=”Background” Value=”#FF2A343F”/>
<Setter Property=”Content” Value=”Off”/>
<Setter Property=”Template”>
<Setter.Value>
<ControlTemplate TargetType=”{x:Type CheckBox}”>
<ControlTemplate.Resources>
<Storyboard x:Key=”OnChecking”>
<DoubleAnimationUsingKeyFrames BeginTime=”00:00:00″ Storyboard.TargetName=”slider” Storyboard.TargetProperty=”(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)”>
<SplineDoubleKeyFrame KeyTime=”00:00:00.3000000″ Value=”26″/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key=”OnUnchecking”>
<DoubleAnimationUsingKeyFrames BeginTime=”00:00:00″ Storyboard.TargetName=”slider” Storyboard.TargetProperty=”(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)”>
<SplineDoubleKeyFrame KeyTime=”00:00:00.3000000″ Value=”0″/>
</DoubleAnimationUsingKeyFrames>
<ThicknessAnimationUsingKeyFrames BeginTime=”00:00:00″ Storyboard.TargetName=”slider” Storyboard.TargetProperty=”(FrameworkElement.Margin)”>
<SplineThicknessKeyFrame KeyTime=”00:00:00.3000000″ Value=”1,1,1,1″/>
</ThicknessAnimationUsingKeyFrames>
</Storyboard>
</ControlTemplate.Resources>

<DockPanel x:Name=”dockPanel” >
<ContentPresenter Margin=”0,0,5,0″ HorizontalAlignment=”Right” VerticalAlignment=”Center” SnapsToDevicePixels=”{TemplateBinding SnapsToDevicePixels}” Content=”{TemplateBinding Content}” ContentStringFormat=”{TemplateBinding ContentStringFormat}” ContentTemplate=”{TemplateBinding ContentTemplate}” RecognizesAccessKey=”True” />
<Grid Width=”44″ Height=”16″>
<Border Margin=”0″ BorderThickness=”2″ BorderBrush=”#FF615E5E”>
<Grid Width=”40″ Background=”#FF2A343F” >
<Border Margin=”2″ x:Name=”baseRectangle” BorderThickness=”0″ Background=”#FF615E5E”>
</Border>
</Grid>
</Border>
<Border x:Name=”slider” HorizontalAlignment=”Left” Margin=”0″ Width=”16″ BorderThickness=”0″ BorderBrush=”#FF1E252D” RenderTransformOrigin=”0.5,0.5″ >
<Border.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX=”1″ ScaleY=”1″/>
<SkewTransform AngleX=”0″ AngleY=”0″/>
<RotateTransform Angle=”0″/>
<TranslateTransform X=”0″ Y=”0″/>
</TransformGroup>
</Border.RenderTransform>
<Border.Background>
<SolidColorBrush >White</SolidColorBrush>
</Border.Background>
</Border>
</Grid>
</DockPanel>
<ControlTemplate.Triggers>
<Trigger Property=”IsChecked” Value=”True”>
<Trigger.ExitActions>
<BeginStoryboard Storyboard=”{StaticResource OnUnchecking}” x:Name=”OnUnchecking_BeginStoryboard”/>
</Trigger.ExitActions>
<Trigger.EnterActions>
<BeginStoryboard Storyboard=”{StaticResource OnChecking}” x:Name=”OnChecking_BeginStoryboard”/>
</Trigger.EnterActions>
<Setter Property=”Content” Value=”On”/>
<Setter Property=”Background” TargetName=”baseRectangle” Value=”#FF148583″/>
</Trigger>
<Trigger Property=”IsEnabled” Value=”False”>
<Setter Property=”Foreground” Value=”{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}”/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

<!– Apply Style –>
<CheckBox Style=”{StaticResource CheckBoxStyle1}” />

Here how it is look like…

Switch

C#, Lambda Expression, LINQ

LINQ OrderBy versus ThenBy

Nowadays LINQ and Lambda expressions are very popular among .Net developers for query data. To control the sort order we use “OrderBy” clause and most of the times we need to use more than one field to use for sorting.

Here is my data collection.

List customers = new List() {
new Customer("ADAMS", "DEANIE"),
new Customer("AARON", "ELVIA"),
new Customer("ADAMS", "DAVID"),
new Customer("AARON", "KIMBERLEI"),
new Customer("ADAMS", "DENIS"),
new Customer("ALLEN", "SAGE"),
new Customer("CHRIS", "ANDERSEN"),
new Customer("ADAMS", "ANDREWS"),
new Customer("MICHAEL", "AUSTIN"),
new Customer("MICHAEL", "AMATO")};

Here is the LINQ query without using Lambda expressions for sort data against multiple fields.

var sortedCustomers = from customer in customers
orderby customer.FirstName, customer.LastName
select customer;

How can we write this with Lambda expressions? Most of developers write it as below.

var orderBy = customers.OrderBy(c => c.FirstName).OrderBy(c => c.LastName);

But this is not gives expected result. Second OrderBy command executes over the previously sorted collection and effectively it will reorder the sequence completely two times. Effectively it will sort according to last field. Following image will shows the results of two queries.

Results

So, what is the correct way to implement this? We can do it using both OrderBy and ThenBy clause.

Use OrderBy clause for most important field and use ThenBy clause for others. It will be like below format.

Collection.OrderBy().ThenBy().ThenBy()…

var thenBy = customers.OrderBy(c => c.FirstName).ThenBy(c => c.LastName);

Here is the result..

Results with ThenBy

C#, WPF

HTML 5 Content in WPF Browser Control

WPF Browser control used to browse HTML pages. Even your machine has latest version than IE 7 WPF normally used IE 7 to render HTML and unfortunately IE 7 does not support for HTML 5. But if we need to render HTML 5 content inside Browser control, what can we do?
There are two solutions for this.

1) Change Registry to use IE 9 or your latest IE version in WPF Browser control.
2) Add Meta tag to web page which IE version should used to render.

1) Change Registry to use IE 9 or your latest IE version in WPF Browser control

Open Registry Editor (By Using “Start” -> “Run” -> “REGEDIT” hit “Enter” Key)
Go to :
HKEY_LOCAL_MACHINE -> SOFTWARE -> Microsoft -> Internet Explorer -> Main -> FeatureControl -> FEATURE_BROWSER_EMULATION

RegPath

Right click on empty space and “New” -> “DWORD (32 bit) Value”. This will add new entry, then type your application exe name.

RegAdd

Right click on new record and select “Modify”. Add your latest browser version. E.g. For IE 9 it is 270f.

RegChange

You can find full list from this link.

2) Add Meta tag to web page IE version should used to render.

Add the “X-UA-Compatible” meta tag inside the head tag before any links to CSS, JavaScript files of your HTML page.

<meta http-equiv="X-UA-Compatible" content=" IE=edge " >

or

<meta http-equiv="X-UA-Compatible" content="IE=9" >

By adding “IE=edge” will use latest installed IE version or we can add browser version directly.

C#, WPF, XML

WPF Multiple Style Inheritance using Markup Extension

WPF default provides “BasedOn” attribute to inherit one style from another.

<Style TargetType="Button" x:Key="BigButtonStyle" BasedOn="{StaticResource BaseButtonStyle}">

Recently we got a requirement which need inherit from multiple styles. But unfortunately WPF does not support multiple style inheritance. What we could have create new style manually by merging those styles. But if styles are very complex or have lot of styles then it will be painful.
Fortunately I found this article which describes how we can achieve multiple style inheritance using Markup Extension.
Markup Extensions are a XAML technique for obtaining a value of a property. In usage Markup extensions are surrounded by curly braces.
Example:

<Setter Property="Background" Value="{StaticResource BackgroundBrush}" />
<ControlTemplate TargetType="{x:Type CheckBox}">

WPF has predefined Markup Extesions and also we can create our own extension by deriving MarkupExtension and override ProvideValue. XAML parser calls this ProvideValue to get the output value from MarkupExtension. Name your custom markup extensions with the “Extension” suffix to avoid the suffix in XAML.
MultipleStyleExtension merges styles together and returns new style by copying Setters and Triggers. Here I used vertical bar (Pipe) character as style separator.

[MarkupExtensionReturnType(typeof(Style))]
    public class MultipleStyleExtension : MarkupExtension
    {
        private string[] styleKeys;

        public MultipleStyleExtension(string resourceKeys)
		{
            if (string.IsNullOrEmpty(resourceKeys))
			{
                throw new ArgumentNullException("resourceKeys");
			}

            this.styleKeys = resourceKeys.Split(new char[] { '|' });

            if (this.styleKeys.Length == 0)
			{
				throw new ArgumentException("No input resource keys specified.");
			}
		}

		public override object ProvideValue(IServiceProvider serviceProvider)
		{
			Style mergedStyle = new Style();

            foreach (string key in styleKeys)
			{
				Style style = null;

                try
                {
                    StaticResourceExtension se = new StaticResourceExtension(key);
                    style = new StaticResourceExtension(key).ProvideValue(serviceProvider) as Style;
                }
                catch { }

                if (style == null)
				{
                    throw new InvalidOperationException("Could not find style " + key);
				}

                Merge(mergedStyle,style);
			}
            return mergedStyle;
		}

        private static void Merge(Style style1, Style style2)
        {
            if (style1 == null)
            {
                throw new ArgumentNullException("style1");
            }
            if (style2 == null)
            {
                throw new ArgumentNullException("style2");
            }

            if (style1.TargetType.IsAssignableFrom(style2.TargetType))
            {
                style1.TargetType = style2.TargetType;
            }

            if (style2.BasedOn != null)
            {
                Merge(style1, style2.BasedOn);
            }

            // Merge Setters
            foreach (SetterBase currentSetter in style2.Setters)
            {
                style1.Setters.Add(currentSetter);
            }

            // Merge Triggers
            foreach (TriggerBase currentTrigger in style2.Triggers)
            {
                style1.Triggers.Add(currentTrigger);
            }
        }
    }

Here I define styles in a Resource Dictionary, but is you want you can define styles in Window also.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="Button" x:Key="BaseButtonStyle">
        <Setter Property="HorizontalAlignment" Value="Center" />
        <Setter Property="VerticalAlignment" Value="Center" />
        <Setter Property="Margin" Value="5" />
    </Style>
    <Style TargetType="Button" x:Key="BigButtonStyle" BasedOn="{StaticResource BaseButtonStyle}">
        <Setter Property="Width" Value="120" />
        <Setter Property="Height" Value="50" />
        <Setter Property="FontSize" Value="16" />
    </Style>
    <Style TargetType="Button" x:Key="RedButtonStyle" BasedOn="{StaticResource BaseButtonStyle}">
        <Setter Property="Background" Value="Red" />
    </Style>
    <Style TargetType="Button" x:Key="GreenButtonStyle" BasedOn="{StaticResource BaseButtonStyle}">
        <Setter Property="Background" Value="Green" />
    </Style>
</ResourceDictionary>

We can use MultipleStyleExtension in XAML as below.

<Button Style="{local:MultipleStyle BigButtonStyle|GreenButtonStyle}" Content="Big and Green"/> 

Finally its look like this…
MultipleStyles