ASP.NET MVC provided anti-forgery token error

I kept getting the following message when a user was logged in and go to the login page and try to login again:

The provided anti-forgery token was meant for user “username”, but the current user is “”.

To fix it I adjusted the Login method to look as follows:

[AllowAnonymous]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
public ActionResult Login()
{
    Session.Abandon();
 
    if (User.Identity.IsAuthenticated)
    {
        FormsAuthentication.SignOut();
        Session.Clear();
        Session.Abandon();
        return RedirectToAction("Login");
    } 
 
    return View();
}

WPF RichTextBox Find Extension Method

I needed to be able to find text in a WPF RichTextBox.

I ended up with the following:

public static int Find(this RichTextBox richTextBox, string text, int startIndex = 0)
{
    var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
    richTextBox.Selection.Select(textRange.Start, textRange.Start);     // clear previous select if there was one
 
    textRange.ClearAllProperties();
    var index = textRange.Text.IndexOf(text, startIndex, StringComparison.OrdinalIgnoreCase);
    if (index > -1)
    {
        var textPointerStart = textRange.Start.GetPositionAtOffset(index);
        var textPointerEnd = textRange.Start.GetPositionAtOffset(index + text.Length);
 
        var textRangeSelection = new TextRange(textPointerStart, textPointerEnd);
        textRangeSelection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
        richTextBox.Selection.Select(textRangeSelection.Start, textRangeSelection.End);
        richTextBox.Focus();
    }
 
    return index;
}

It is used as follows:

var startIndex = 0;     // index to start find at.  Allows for a find next option.
var index = richTextBox1.Find(textBoxFindText.Text, startIndex);

If index < 0 then there was no text found. Extension method is set up as forward only.

Javascript – Simple async – await example

The following is a very simple async – await example:

// async - await example
async function example() {
    try {
        const data = await Promise.all([getdata1(), getdata2()]);   // will wait till the requests are completed
        processData(data);
    }
    catch (err) {
        console.error(err);
    }
}
 
const processData = (data) => {
    console.log('Data to process:', data);
}

Javascript check for undefined and null

In Javascript, how to check if a value is not undefined or null.

If the typeof variable is string then check to see if it has length.

const hasValue = (value) => {
    let valid = typeof value != 'undefined' &&  value != null;
    if (valid && typeof value === 'string') {
      valid = value.length > 0;      
    }
    return valid;
}

usage:

var message = 'Hello World';
if (hasValue(message)) {
    console.log(message);
}

.Net Winform checking which keys are pressed

I wanted to be able to check for which key(s) were pressed on a form.

KeyPreview = true for the form was not working.

I was able to use the following:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.Control | Keys.S))     // Ctrl-S
    {
        return true;    // indicate that you handled this keystroke
    }
    else if (keyData == (Keys.Control | Keys.N))    // Ctrl-N
    {
        return true;    // indicate that you handled this keystroke
    }
    else if (keyData == Keys.F9)    // F9 Key
    {
        return true;    // indicate that you handled this keystroke
    }
    // Call the base class
    return base.ProcessCmdKey(ref msg, keyData);
}

Javascript get number with comma and two decimal places

In Javascript, how to get a number with a comma and two decimal places:

function numberWithCommaTwoDecimalPlaces(number) {
    var formattedNumber = number.toLocaleString('en-US', 
                            { 
                                style: 'decimal', 
                                maximumFractionDigits : 2, 
                                minimumFractionDigits : 2 
                            });
    return formattedNumber;
}

var number = 123434.5;

Will display as:

123,434.50

C# know when WebBrowser Download is complete – Inline

I wanted to know exactly when a web page has downloaded into the WebBrowser.

By using the DocumentCompleted event I was able flag that it has been downloaded.

private void ConfirmWebPageDownloadComplete(string address)
{
    var webBrowser = new WebBrowser { ScriptErrorsSuppressed = true, };
    webBrowser.Navigate(address);
    var documentComplete = false;
    webBrowser.DocumentCompleted += (s, ea) => { documentComplete = true; };
    while (!documentComplete)
    {
        Application.DoEvents();
    }
    // Document has completed
    var html = webBrowser.Document.Body.Parent.OuterHtml;
}

Setting ScriptErrorsSuppressed = true is needed otherwise if there is a Javascript error it will display a message.

By using webBrowser.Document.Body.Parent.OuterHtml it gives the Html for the page.

WPF Checkbox style based upon bound value

I have a WPF Checkbox that I wanted to have a different background color based upon a bound value.

So if IsChecked = true I wanted one color and IsChecked = false I wanted a different color.

I noticed that if the Content is filled in then it affects how it functions.

Finally after several attempts I got the following to work (all in XAML):

<CheckBox IsChecked="{Binding CheckBoxBoundProperty, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true, UpdateSourceTrigger=PropertyChanged}" FlowDirection="RightToLeft">
    <CheckBox.Style>
        <Style TargetType="{x:Type CheckBox}">
            <Setter Property="Content">
                <Setter.Value>
                    <TextBlock Text="Unchecked" />
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                    <Setter Property="Content">
                        <Setter.Value>
                            <TextBlock Text="Checked" Background="Gainsboro" />
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </CheckBox.Style>
</CheckBox>

The result functions exactly as I want.

Adding shortcut keys to WPF Application

To add shortcut keys to a WPF application I used the following:

<Window x:Class="ProjectName.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ProjectName"
    mc:Ignorable="d"
    Title="MainWindow" 
    Height="350" Width="525">
 
    <Window.CommandBindings>
        <CommandBinding Command="local:MainWindow.NewItem" Executed="MenuItem_Click" />
    </Window.CommandBindings>
 
    <Window.InputBindings>
        <KeyBinding Command="local:MainWindow.NewItem" Key="N" Modifiers="Ctrl" />
    </Window.InputBindings>
 
    <Grid>
        <Menu HorizontalAlignment="Stretch" VerticalAlignment="Top">
            <MenuItem Header="_File">
                <MenuItem Header="_New Item" Command="local:MainWindow.NewItem" InputGestureText="Ctrl+N" />
            </MenuItem>
        </Menu>
    </Grid>
 
</Window>

The Window.CommandBindings contains the mapping to the commands. It also has the method to execute in Executed.

The Window.InputBindings contains the mappings to the Keys used for shortcuts.

The MenuItem contains the Header as well as the Shortcut display using InputGestureText.

namespace ProjectName
{
    public partial class MainWindow : Window
    {
        public static readonly RoutedUICommand NewItem = new RoutedUICommand("NewItem", "NewItem", typeof(MainWindow));
 
        /// <summary>
        /// Shared method for MenuItems and Shortcut Keys using Commands
        /// </summary>
        /// <param name="menuItem">Name of the selected item</param>
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            var item = string.Empty;
            var menuItem = sender as MenuItem;
            if (menuItem != null)
            {
                item = menuItem.Header.ToString();
            }
            else
            {
                // Needed to be cast to get to the ExecutedRoutedEventArgs Type
                var executedRoutedEventArgs = e as ExecutedRoutedEventArgs;
                if (executedRoutedEventArgs != null)
                {
                    item = (executedRoutedEventArgs.Command as RoutedUICommand).Text;
                }
            }
            if (!string.IsNullOrEmpty(item))
            {
                ProcessMenuItem(item);
            }
        }
 
        private void ProcessMenuItem(string menuItem)
        {
            switch (menuItem)
            {
                case "NewItem":
                    break;
                case "E_xit":
                    Application.Current.Shutdown();
                    break;
            }
        }
    }
}

The RoutedUICommand is the command that is mapped in the XAML.

The Window.CommandBindings, Window.InputBindings and the MenuItem all mapped to an item. This is how the shortcut is wired up.

The MenuItem_Click is the method that is executed when the shortcut is pressed or the menu is clicked. This method handles getting which item was chosen and passes that to the ProcessMenuItem method.

The ProcessMenuItem then processes the item as needed. As many items can be added as needed.

.Net Winform setting click event for all ToolStrip Items and MenuStrip Items

I wanted to run all click event through one method. That way I can update them as needed as well as call them from other places in the code.

After looking around I was able to use the following:

My form has a ToolStrip and a MenuStrip.

public Form1()
{
    InitializeComponent();
 
    // Get All Menu Items and all Tool Strip Buttons into a list
    var toolStripItems = toolStrip1.Items.OfType<ToolStripItem>().ToList().Union(menuStrip1.Items.GetAllToolStripMenuItems().OfType<ToolStripItem>()).ToList();
    // Set All Click Events for controls
    toolStripItems.ForEach(i => i.Click += Item_Click);
}
 
private void Item_Click(object sender, EventArgs e)
{
    ProcessMenuItem((sender as ToolStripItem).Text);
}
 
private void ProcessMenuItem(string menuItem)
{
    switch (menuItem)
    {
        case "&New":
            break;
        case "E&xit":
            Application.Exit();
            break;
    }
}

Extension Method:

public static class Extensions
{
    public static IEnumerable<ToolStripMenuItem> GetAllToolStripMenuItems(this ToolStripItemCollection toolStripItemCollection)
    {
        var toolStripMenuItems = new List<ToolStripMenuItem>();
        foreach (var toolStripItem in toolStripItemCollection.OfType<ToolStripMenuItem>())
        {
            toolStripMenuItems.Add(toolStripItem);
            toolStripMenuItems.AddRange(GetAllToolStripMenuItems(toolStripItem.DropDownItems));
        }
        return toolStripMenuItems;
    }
}

By using the above it becomes very straight forward to add what is needed by a click event.

All ToolStripItems are wired up to use and just by adding the text to the ProcessMenuItem method and the code that is needed to execute it makes it pretty straight forward to add the needed code.