IndexOutOfBoundsException fix

IndexOutOfBoundsException fix

IndexOutOfBoundsException. The buffer from ToUnicodeEx was returning a
an index of zero. ?????? (this is a bug in the operating system). I tested this by pressing
(Ctrl + alt + all keys on my keyboard, specifically Ctrl + alt + [ and
Ctrl + alt + numpad return key, that were causing the crashes)

--- MouseKeyHook/WinApi/KeyboardNativeMethods.cs
+++ MouseKeyHook/WinApi/KeyboardNativeMethods.cs
@@ -1,364 +1,365 @@
-// This code is distributed under MIT license.
-// Copyright (c) 2015 George Mamaladze
-// See license.txt or http://opensource.org/licenses/mit-license.php
-
-using System;
-using System.Runtime.InteropServices;
-using System.Text;
-using System.Windows.Forms;
-using Gma.System.MouseKeyHook.Implementation;
-
-namespace Gma.System.MouseKeyHook.WinApi
-{
-    internal static class KeyboardNativeMethods
-    {
-        //values from Winuser.h in Microsoft SDK.
-        public const byte VK_SHIFT = 0x10;
-        public const byte VK_CAPITAL = 0x14;
-        public const byte VK_NUMLOCK = 0x90;
-        public const byte VK_LSHIFT = 0xA0;
-        public const byte VK_RSHIFT = 0xA1;
-        public const byte VK_LCONTROL = 0xA2;
-        public const byte VK_RCONTROL = 0xA3;
-        public const byte VK_LMENU = 0xA4;
-        public const byte VK_RMENU = 0xA5;
-        public const byte VK_LWIN = 0x5B;
-        public const byte VK_RWIN = 0x5C;
-        public const byte VK_SCROLL = 0x91;
-        public const byte VK_INSERT = 0x2D;
-        //may be possible to use these aggregates instead of L and R separately (untested)
-        public const byte VK_CONTROL = 0x11;
-        public const byte VK_MENU = 0x12;
-        public const byte VK_PACKET = 0xE7;
-        //Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods
-        private static int lastVirtualKeyCode = 0;
-        private static int lastScanCode = 0;
-        private static byte[] lastKeyState = new byte[255];
-        private static bool lastIsDead = false;
-
-        /// <summary>
-        ///     Translates a virtual key to its character equivalent using the current keyboard layout without knowing the
-        ///     scancode in advance.
-        /// </summary>
-        /// <param name="virtualKeyCode"></param>
-        /// <param name="fuState"></param>
-        /// <param name="chars"></param>
-        /// <returns></returns>
-        internal static void TryGetCharFromKeyboardState(int virtualKeyCode, int fuState, out char[] chars)
-        {
-            var dwhkl = GetActiveKeyboard();
-            int scanCode = MapVirtualKeyEx(virtualKeyCode, (int) MapType.MAPVK_VK_TO_VSC, dwhkl);
-            TryGetCharFromKeyboardState(virtualKeyCode, scanCode, fuState, dwhkl, out chars);
-        }
-
-        /// <summary>
-        ///     Translates a virtual key to its character equivalent using the current keyboard layout
-        /// </summary>
-        /// <param name="virtualKeyCode"></param>
-        /// <param name="scanCode"></param>
-        /// <param name="fuState"></param>
-        /// <param name="chars"></param>
-        /// <returns></returns>
-        internal static void TryGetCharFromKeyboardState(int virtualKeyCode, int scanCode, int fuState, out char[] chars)
-        {
-            var dwhkl = GetActiveKeyboard(); //get the active keyboard layout
-            TryGetCharFromKeyboardState(virtualKeyCode, scanCode, fuState, dwhkl, out chars);
-        }
-
-        /// <summary>
-        ///     Translates a virtual key to its character equivalent using a specified keyboard layout
-        /// </summary>
-        /// <param name="virtualKeyCode"></param>
-        /// <param name="scanCode"></param>
-        /// <param name="fuState"></param>
-        /// <param name="dwhkl"></param>
-        /// <param name="chars"></param>
-        /// <returns></returns>
-        internal static void TryGetCharFromKeyboardState(int virtualKeyCode, int scanCode, int fuState, IntPtr dwhkl, out char[] chars)
-        {
-            StringBuilder pwszBuff = new StringBuilder(64);
-            KeyboardState keyboardState = KeyboardState.GetCurrent();
-            byte[] currentKeyboardState = keyboardState.GetNativeState();
-            bool isDead = false;
-
-            if (keyboardState.IsDown(Keys.ShiftKey))
-                currentKeyboardState[(byte) Keys.ShiftKey] = 0x80;
-
-            if (keyboardState.IsToggled(Keys.CapsLock))
-                currentKeyboardState[(byte) Keys.CapsLock] = 0x01;
-
-            var relevantChars = ToUnicodeEx(virtualKeyCode, scanCode, currentKeyboardState, pwszBuff, pwszBuff.Capacity, fuState, dwhkl);
-
-            switch (relevantChars)
-            {
-                case -1:
-                    isDead = true;
-                    ClearKeyboardBuffer(virtualKeyCode, scanCode, dwhkl);
-                    chars = null;
-                    break;
-
-                case 0:
-                    chars = null;
-                    break;
-
-                case 1:
-                    chars = new[] { pwszBuff[0] };
-                    break;
-
-                // Two or more (only two of them is relevant)
-                default:
-                    chars = new[] { pwszBuff[0], pwszBuff[1] };
-                    break;
-            }
-
-            if (lastVirtualKeyCode != 0 && lastIsDead)
-            {
-                if (chars != null)
-                {
-                    StringBuilder sbTemp = new StringBuilder(5);
-                    ToUnicodeEx(lastVirtualKeyCode, lastScanCode, lastKeyState, sbTemp, sbTemp.Capacity, 0, dwhkl);
-                    lastIsDead = false;
-                    lastVirtualKeyCode = 0;
-                }
-
-                return;
-            }
-
-            lastScanCode = scanCode;
-            lastVirtualKeyCode = virtualKeyCode;
-            lastIsDead = isDead;
-            lastKeyState = (byte[]) currentKeyboardState.Clone();
-        }
-
-
-        private static void ClearKeyboardBuffer(int vk, int sc, IntPtr hkl)
-        {
-            var sb = new StringBuilder(10);
-
-            int rc;
-            do
-            {
-                byte[] lpKeyStateNull = new Byte[255];
-                rc = ToUnicodeEx(vk, sc, lpKeyStateNull, sb, sb.Capacity, 0, hkl);
-            } while (rc < 0);
-        }
-
-        /// <summary>
-        ///     Gets the input locale identifier for the active application's thread.  Using this combined with the ToUnicodeEx and
-        ///     MapVirtualKeyEx enables Windows to properly translate keys based on the keyboard layout designated for the
-        ///     application.
-        /// </summary>
-        /// <returns>HKL</returns>
-        private static IntPtr GetActiveKeyboard()
-        {
-            IntPtr hActiveWnd = ThreadNativeMethods.GetForegroundWindow(); //handle to focused window
-            int dwProcessId;
-            int hCurrentWnd = ThreadNativeMethods.GetWindowThreadProcessId(hActiveWnd, out dwProcessId);
-            //thread of focused window
-            return GetKeyboardLayout(hCurrentWnd); //get the layout identifier for the thread whose window is focused
-        }
-
-        /// <summary>
-        ///     The ToAscii function translates the specified virtual-key code and keyboard
-        ///     state to the corresponding character or characters. The function translates the code
-        ///     using the input language and physical keyboard layout identified by the keyboard layout handle.
-        /// </summary>
-        /// <param name="uVirtKey">
-        ///     [in] Specifies the virtual-key code to be translated.
-        /// </param>
-        /// <param name="uScanCode">
-        ///     [in] Specifies the hardware scan code of the key to be translated.
-        ///     The high-order bit of this value is set if the key is up (not pressed).
-        /// </param>
-        /// <param name="lpbKeyState">
-        ///     [in] Pointer to a 256-byte array that contains the current keyboard state.
-        ///     Each element (byte) in the array contains the state of one key.
-        ///     If the high-order bit of a byte is set, the key is down (pressed).
-        ///     The low bit, if set, indicates that the key is toggled on. In this function,
-        ///     only the toggle bit of the CAPS LOCK key is relevant. The toggle state
-        ///     of the NUM LOCK and SCROLL LOCK keys is ignored.
-        /// </param>
-        /// <param name="lpwTransKey">
-        ///     [out] Pointer to the buffer that receives the translated character or characters.
-        /// </param>
-        /// <param name="fuState">
-        ///     [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.
-        /// </param>
-        /// <returns>
-        ///     If the specified key is a dead key, the return value is negative. Otherwise, it is one of the following values.
-        ///     Value Meaning
-        ///     0 The specified virtual key has no translation for the current state of the keyboard.
-        ///     1 One character was copied to the buffer.
-        ///     2 Two characters were copied to the buffer. This usually happens when a dead-key character
-        ///     (accent or diacritic) stored in the keyboard layout cannot be composed with the specified
-        ///     virtual key to form a single character.
-        /// </returns>
-        /// <remarks>
-        ///     http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp
-        /// </remarks>
-        [Obsolete("Use ToUnicodeEx instead")]
-        [DllImport("user32.dll")]
-        public static extern int ToAscii(
-            int uVirtKey,
-            int uScanCode,
-            byte[] lpbKeyState,
-            byte[] lpwTransKey,
-            int fuState);
-
-        /// <summary>
-        ///     Translates the specified virtual-key code and keyboard state to the corresponding Unicode character or characters.
-        /// </summary>
-        /// <param name="wVirtKey">[in] The virtual-key code to be translated.</param>
-        /// <param name="wScanCode">
-        ///     [in] The hardware scan code of the key to be translated. The high-order bit of this value is
-        ///     set if the key is up.
-        /// </param>
-        /// <param name="lpKeyState">
-        ///     [in, optional] A pointer to a 256-byte array that contains the current keyboard state. Each
-        ///     element (byte) in the array contains the state of one key. If the high-order bit of a byte is set, the key is down.
-        /// </param>
-        /// <param name="pwszBuff">
-        ///     [out] The buffer that receives the translated Unicode character or characters. However, this
-        ///     buffer may be returned without being null-terminated even though the variable name suggests that it is
-        ///     null-terminated.
-        /// </param>
-        /// <param name="cchBuff">[in] The size, in characters, of the buffer pointed to by the pwszBuff parameter.</param>
-        /// <param name="wFlags">
-        ///     [in] The behavior of the function. If bit 0 is set, a menu is active. Bits 1 through 31 are
-        ///     reserved.
-        /// </param>
-        /// <param name="dwhkl">The input locale identifier used to translate the specified code.</param>
-        /// <returns>
-        ///     -1 <= return <= n
-        ///     <list type="bullet">
-        ///         <item>
-        ///             -1    = The specified virtual key is a dead-key character (accent or diacritic). This value is returned
-        ///             regardless of the keyboard layout, even if several characters have been typed and are stored in the
-        ///             keyboard state. If possible, even with Unicode keyboard layouts, the function has written a spacing version
-        ///             of the dead-key character to the buffer specified by pwszBuff. For example, the function writes the
-        ///             character SPACING ACUTE (0x00B4), rather than the character NON_SPACING ACUTE (0x0301).
-        ///         </item>
-        ///         <item>
-        ///             0    = The specified virtual key has no translation for the current state of the keyboard. Nothing was
-        ///             written to the buffer specified by pwszBuff.
-        ///         </item>
-        ///         <item> 1    = One character was written to the buffer specified by pwszBuff.</item>
-        ///         <item>
-        ///             n    = Two or more characters were written to the buffer specified by pwszBuff. The most common cause
-        ///             for this is that a dead-key character (accent or diacritic) stored in the keyboard layout could not be
-        ///             combined with the specified virtual key to form a single character. However, the buffer may contain more
-        ///             characters than the return value specifies. When this happens, any extra characters are invalid and should
-        ///             be ignored.
-        ///         </item>
-        ///     </list>
-        /// </returns>
-        [DllImport("user32.dll")]
-        public static extern int ToUnicodeEx(int wVirtKey,
-            int wScanCode,
-            byte[] lpKeyState,
-            [Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)] StringBuilder pwszBuff,
-            int cchBuff,
-            int wFlags,
-            IntPtr dwhkl);
-
-        /// <summary>
-        ///     The GetKeyboardState function copies the status of the 256 virtual keys to the
-        ///     specified buffer.
-        /// </summary>
-        /// <param name="pbKeyState">
-        ///     [in] Pointer to a 256-byte array that contains keyboard key states.
-        /// </param>
-        /// <returns>
-        ///     If the function succeeds, the return value is nonzero.
-        ///     If the function fails, the return value is zero. To get extended error information, call GetLastError.
-        /// </returns>
-        /// <remarks>
-        ///     http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp
-        /// </remarks>
-        [DllImport("user32.dll")]
-        public static extern int GetKeyboardState(byte[] pbKeyState);
-
-        /// <summary>
-        ///     The GetKeyState function retrieves the status of the specified virtual key. The status specifies whether the key is
-        ///     up, down, or toggled
-        ///     (on, off—alternating each time the key is pressed).
-        /// </summary>
-        /// <param name="vKey">
-        ///     [in] Specifies a virtual key. If the desired virtual key is a letter or digit (A through Z, a through z, or 0
-        ///     through 9), nVirtKey must be set to the ASCII value of that character. For other keys, it must be a virtual-key
-        ///     code.
-        /// </param>
-        /// <returns>
-        ///     The return value specifies the status of the specified virtual key, as follows:
-        ///     If the high-order bit is 1, the key is down; otherwise, it is up.
-        ///     If the low-order bit is 1, the key is toggled. A key, such as the CAPS LOCK key, is toggled if it is turned on. The
-        ///     key is off and untoggled if the low-order bit is 0. A toggle key's indicator light (if any) on the keyboard will be
-        ///     on when the key is toggled, and off when the key is untoggled.
-        /// </returns>
-        /// <remarks>http://msdn.microsoft.com/en-us/library/ms646301.aspx</remarks>
-        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
-        public static extern short GetKeyState(int vKey);
-
-        /// <summary>
-        ///     Translates (maps) a virtual-key code into a scan code or character value, or translates a scan code into a
-        ///     virtual-key code.
-        /// </summary>
-        /// <param name="uCode">
-        ///     [in] The virtual key code or scan code for a key. How this value is interpreted depends on the
-        ///     value of the uMapType parameter.
-        /// </param>
-        /// <param name="uMapType">
-        ///     [in] The translation to be performed. The value of this parameter depends on the value of the
-        ///     uCode parameter.
-        /// </param>
-        /// <param name="dwhkl">[in] The input locale identifier used to translate the specified code.</param>
-        /// <returns></returns>
-        [DllImport("user32.dll", CharSet = CharSet.Auto)]
-        internal static extern int MapVirtualKeyEx(int uCode, int uMapType, IntPtr dwhkl);
-
-        /// <summary>
-        ///     Retrieves the active input locale identifier (formerly called the keyboard layout) for the specified thread.
-        ///     If the idThread parameter is zero, the input locale identifier for the active thread is returned.
-        /// </summary>
-        /// <param name="dwLayout">[in] The identifier of the thread to query, or 0 for the current thread. </param>
-        /// <returns>
-        ///     The return value is the input locale identifier for the thread. The low word contains a Language Identifier for the
-        ///     input
-        ///     language and the high word contains a device handle to the physical layout of the keyboard.
-        /// </returns>
-        [DllImport("user32.dll", CharSet = CharSet.Auto)]
-        internal static extern IntPtr GetKeyboardLayout(int dwLayout);
-
-        /// <summary>
-        ///     MapVirtualKeys uMapType
-        /// </summary>
-        internal enum MapType
-        {
-            /// <summary>
-            ///     uCode is a virtual-key code and is translated into an unshifted character value in the low-order word of the return
-            ///     value. Dead keys (diacritics) are indicated by setting the top bit of the return value. If there is no translation,
-            ///     the function returns 0.
-            /// </summary>
-            MAPVK_VK_TO_VSC,
-
-            /// <summary>
-            ///     uCode is a virtual-key code and is translated into a scan code. If it is a virtual-key code that does not
-            ///     distinguish between left- and right-hand keys, the left-hand scan code is returned. If there is no translation, the
-            ///     function returns 0.
-            /// </summary>
-            MAPVK_VSC_TO_VK,
-
-            /// <summary>
-            ///     uCode is a scan code and is translated into a virtual-key code that does not distinguish between left- and
-            ///     right-hand keys. If there is no translation, the function returns 0.
-            /// </summary>
-            MAPVK_VK_TO_CHAR,
-
-            /// <summary>
-            ///     uCode is a scan code and is translated into a virtual-key code that distinguishes between left- and right-hand
-            ///     keys. If there is no translation, the function returns 0.
-            /// </summary>
-            MAPVK_VSC_TO_VK_EX
-        }
-    }
+// This code is distributed under MIT license.
+// Copyright (c) 2015 George Mamaladze
+// See license.txt or http://opensource.org/licenses/mit-license.php
+
+using System;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Windows.Forms;
+using Gma.System.MouseKeyHook.Implementation;
+
+namespace Gma.System.MouseKeyHook.WinApi
+{
+    internal static class KeyboardNativeMethods
+    {
+        //values from Winuser.h in Microsoft SDK.
+        public const byte VK_SHIFT = 0x10;
+        public const byte VK_CAPITAL = 0x14;
+        public const byte VK_NUMLOCK = 0x90;
+        public const byte VK_LSHIFT = 0xA0;
+        public const byte VK_RSHIFT = 0xA1;
+        public const byte VK_LCONTROL = 0xA2;
+        public const byte VK_RCONTROL = 0xA3;
+        public const byte VK_LMENU = 0xA4;
+        public const byte VK_RMENU = 0xA5;
+        public const byte VK_LWIN = 0x5B;
+        public const byte VK_RWIN = 0x5C;
+        public const byte VK_SCROLL = 0x91;
+        public const byte VK_INSERT = 0x2D;
+        //may be possible to use these aggregates instead of L and R separately (untested)
+        public const byte VK_CONTROL = 0x11;
+        public const byte VK_MENU = 0x12;
+        public const byte VK_PACKET = 0xE7;
+        //Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods
+        private static int lastVirtualKeyCode = 0;
+        private static int lastScanCode = 0;
+        private static byte[] lastKeyState = new byte[255];
+        private static bool lastIsDead = false;
+
+        /// <summary>
+        ///     Translates a virtual key to its character equivalent using the current keyboard layout without knowing the
+        ///     scancode in advance.
+        /// </summary>
+        /// <param name="virtualKeyCode"></param>
+        /// <param name="fuState"></param>
+        /// <param name="chars"></param>
+        /// <returns></returns>
+        internal static void TryGetCharFromKeyboardState(int virtualKeyCode, int fuState, out char[] chars)
+        {
+            var dwhkl = GetActiveKeyboard();
+            int scanCode = MapVirtualKeyEx(virtualKeyCode, (int) MapType.MAPVK_VK_TO_VSC, dwhkl);
+            TryGetCharFromKeyboardState(virtualKeyCode, scanCode, fuState, dwhkl, out chars);
+        }
+
+        /// <summary>
+        ///     Translates a virtual key to its character equivalent using the current keyboard layout
+        /// </summary>
+        /// <param name="virtualKeyCode"></param>
+        /// <param name="scanCode"></param>
+        /// <param name="fuState"></param>
+        /// <param name="chars"></param>
+        /// <returns></returns>
+        internal static void TryGetCharFromKeyboardState(int virtualKeyCode, int scanCode, int fuState, out char[] chars)
+        {
+            var dwhkl = GetActiveKeyboard(); //get the active keyboard layout
+            TryGetCharFromKeyboardState(virtualKeyCode, scanCode, fuState, dwhkl, out chars);
+        }
+
+        /// <summary>
+        ///     Translates a virtual key to its character equivalent using a specified keyboard layout
+        /// </summary>
+        /// <param name="virtualKeyCode"></param>
+        /// <param name="scanCode"></param>
+        /// <param name="fuState"></param>
+        /// <param name="dwhkl"></param>
+        /// <param name="chars"></param>
+        /// <returns></returns>
+        internal static void TryGetCharFromKeyboardState(int virtualKeyCode, int scanCode, int fuState, IntPtr dwhkl, out char[] chars)
+        {
+            StringBuilder pwszBuff = new StringBuilder(64);
+            KeyboardState keyboardState = KeyboardState.GetCurrent();
+            byte[] currentKeyboardState = keyboardState.GetNativeState();
+            bool isDead = false;
+
+            if (keyboardState.IsDown(Keys.ShiftKey))
+                currentKeyboardState[(byte) Keys.ShiftKey] = 0x80;
+
+            if (keyboardState.IsToggled(Keys.CapsLock))
+                currentKeyboardState[(byte) Keys.CapsLock] = 0x01;
+
+            var relevantChars = ToUnicodeEx(virtualKeyCode, scanCode, currentKeyboardState, pwszBuff, pwszBuff.Capacity, fuState, dwhkl);
+
+            switch (relevantChars)
+            {
+                case -1:
+                    isDead = true;
+                    ClearKeyboardBuffer(virtualKeyCode, scanCode, dwhkl);
+                    chars = null;
+                    break;
+
+                case 0:
+                    chars = null;
+                    break;
+
+                case 1:
+                    if (pwszBuff.Length > 0) chars = new[] { pwszBuff[0] };
+                    else chars = null;
+                    break;
+
+                // Two or more (only two of them is relevant)
+                default:
+                    chars = new[] { pwszBuff[0], pwszBuff[1] };
+                    break;
+            }
+
+            if (lastVirtualKeyCode != 0 && lastIsDead)
+            {
+                if (chars != null)
+                {
+                    StringBuilder sbTemp = new StringBuilder(5);
+                    ToUnicodeEx(lastVirtualKeyCode, lastScanCode, lastKeyState, sbTemp, sbTemp.Capacity, 0, dwhkl);
+                    lastIsDead = false;
+                    lastVirtualKeyCode = 0;
+                }
+
+                return;
+            }
+
+            lastScanCode = scanCode;
+            lastVirtualKeyCode = virtualKeyCode;
+            lastIsDead = isDead;
+            lastKeyState = (byte[]) currentKeyboardState.Clone();
+        }
+
+
+        private static void ClearKeyboardBuffer(int vk, int sc, IntPtr hkl)
+        {
+            var sb = new StringBuilder(10);
+
+            int rc;
+            do
+            {
+                byte[] lpKeyStateNull = new Byte[255];
+                rc = ToUnicodeEx(vk, sc, lpKeyStateNull, sb, sb.Capacity, 0, hkl);
+            } while (rc < 0);
+        }
+
+        /// <summary>
+        ///     Gets the input locale identifier for the active application's thread.  Using this combined with the ToUnicodeEx and
+        ///     MapVirtualKeyEx enables Windows to properly translate keys based on the keyboard layout designated for the
+        ///     application.
+        /// </summary>
+        /// <returns>HKL</returns>
+        private static IntPtr GetActiveKeyboard()
+        {
+            IntPtr hActiveWnd = ThreadNativeMethods.GetForegroundWindow(); //handle to focused window
+            int dwProcessId;
+            int hCurrentWnd = ThreadNativeMethods.GetWindowThreadProcessId(hActiveWnd, out dwProcessId);
+            //thread of focused window
+            return GetKeyboardLayout(hCurrentWnd); //get the layout identifier for the thread whose window is focused
+        }
+
+        /// <summary>
+        ///     The ToAscii function translates the specified virtual-key code and keyboard
+        ///     state to the corresponding character or characters. The function translates the code
+        ///     using the input language and physical keyboard layout identified by the keyboard layout handle.
+        /// </summary>
+        /// <param name="uVirtKey">
+        ///     [in] Specifies the virtual-key code to be translated.
+        /// </param>
+        /// <param name="uScanCode">
+        ///     [in] Specifies the hardware scan code of the key to be translated.
+        ///     The high-order bit of this value is set if the key is up (not pressed).
+        /// </param>
+        /// <param name="lpbKeyState">
+        ///     [in] Pointer to a 256-byte array that contains the current keyboard state.
+        ///     Each element (byte) in the array contains the state of one key.
+        ///     If the high-order bit of a byte is set, the key is down (pressed).
+        ///     The low bit, if set, indicates that the key is toggled on. In this function,
+        ///     only the toggle bit of the CAPS LOCK key is relevant. The toggle state
+        ///     of the NUM LOCK and SCROLL LOCK keys is ignored.
+        /// </param>
+        /// <param name="lpwTransKey">
+        ///     [out] Pointer to the buffer that receives the translated character or characters.
+        /// </param>
+        /// <param name="fuState">
+        ///     [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.
+        /// </param>
+        /// <returns>
+        ///     If the specified key is a dead key, the return value is negative. Otherwise, it is one of the following values.
+        ///     Value Meaning
+        ///     0 The specified virtual key has no translation for the current state of the keyboard.
+        ///     1 One character was copied to the buffer.
+        ///     2 Two characters were copied to the buffer. This usually happens when a dead-key character
+        ///     (accent or diacritic) stored in the keyboard layout cannot be composed with the specified
+        ///     virtual key to form a single character.
+        /// </returns>
+        /// <remarks>
+        ///     http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp
+        /// </remarks>
+        [Obsolete("Use ToUnicodeEx instead")]
+        [DllImport("user32.dll")]
+        public static extern int ToAscii(
+            int uVirtKey,
+            int uScanCode,
+            byte[] lpbKeyState,
+            byte[] lpwTransKey,
+            int fuState);
+
+        /// <summary>
+        ///     Translates the specified virtual-key code and keyboard state to the corresponding Unicode character or characters.
+        /// </summary>
+        /// <param name="wVirtKey">[in] The virtual-key code to be translated.</param>
+        /// <param name="wScanCode">
+        ///     [in] The hardware scan code of the key to be translated. The high-order bit of this value is
+        ///     set if the key is up.
+        /// </param>
+        /// <param name="lpKeyState">
+        ///     [in, optional] A pointer to a 256-byte array that contains the current keyboard state. Each
+        ///     element (byte) in the array contains the state of one key. If the high-order bit of a byte is set, the key is down.
+        /// </param>
+        /// <param name="pwszBuff">
+        ///     [out] The buffer that receives the translated Unicode character or characters. However, this
+        ///     buffer may be returned without being null-terminated even though the variable name suggests that it is
+        ///     null-terminated.
+        /// </param>
+        /// <param name="cchBuff">[in] The size, in characters, of the buffer pointed to by the pwszBuff parameter.</param>
+        /// <param name="wFlags">
+        ///     [in] The behavior of the function. If bit 0 is set, a menu is active. Bits 1 through 31 are
+        ///     reserved.
+        /// </param>
+        /// <param name="dwhkl">The input locale identifier used to translate the specified code.</param>
+        /// <returns>
+        ///     -1 <= return <= n
+        ///     <list type="bullet">
+        ///         <item>
+        ///             -1    = The specified virtual key is a dead-key character (accent or diacritic). This value is returned
+        ///             regardless of the keyboard layout, even if several characters have been typed and are stored in the
+        ///             keyboard state. If possible, even with Unicode keyboard layouts, the function has written a spacing version
+        ///             of the dead-key character to the buffer specified by pwszBuff. For example, the function writes the
+        ///             character SPACING ACUTE (0x00B4), rather than the character NON_SPACING ACUTE (0x0301).
+        ///         </item>
+        ///         <item>
+        ///             0    = The specified virtual key has no translation for the current state of the keyboard. Nothing was
+        ///             written to the buffer specified by pwszBuff.
+        ///         </item>
+        ///         <item> 1    = One character was written to the buffer specified by pwszBuff.</item>
+        ///         <item>
+        ///             n    = Two or more characters were written to the buffer specified by pwszBuff. The most common cause
+        ///             for this is that a dead-key character (accent or diacritic) stored in the keyboard layout could not be
+        ///             combined with the specified virtual key to form a single character. However, the buffer may contain more
+        ///             characters than the return value specifies. When this happens, any extra characters are invalid and should
+        ///             be ignored.
+        ///         </item>
+        ///     </list>
+        /// </returns>
+        [DllImport("user32.dll")]
+        public static extern int ToUnicodeEx(int wVirtKey,
+            int wScanCode,
+            byte[] lpKeyState,
+            [Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)] StringBuilder pwszBuff,
+            int cchBuff,
+            int wFlags,
+            IntPtr dwhkl);
+
+        /// <summary>
+        ///     The GetKeyboardState function copies the status of the 256 virtual keys to the
+        ///     specified buffer.
+        /// </summary>
+        /// <param name="pbKeyState">
+        ///     [in] Pointer to a 256-byte array that contains keyboard key states.
+        /// </param>
+        /// <returns>
+        ///     If the function succeeds, the return value is nonzero.
+        ///     If the function fails, the return value is zero. To get extended error information, call GetLastError.
+        /// </returns>
+        /// <remarks>
+        ///     http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp
+        /// </remarks>
+        [DllImport("user32.dll")]
+        public static extern int GetKeyboardState(byte[] pbKeyState);
+
+        /// <summary>
+        ///     The GetKeyState function retrieves the status of the specified virtual key. The status specifies whether the key is
+        ///     up, down, or toggled
+        ///     (on, off—alternating each time the key is pressed).
+        /// </summary>
+        /// <param name="vKey">
+        ///     [in] Specifies a virtual key. If the desired virtual key is a letter or digit (A through Z, a through z, or 0
+        ///     through 9), nVirtKey must be set to the ASCII value of that character. For other keys, it must be a virtual-key
+        ///     code.
+        /// </param>
+        /// <returns>
+        ///     The return value specifies the status of the specified virtual key, as follows:
+        ///     If the high-order bit is 1, the key is down; otherwise, it is up.
+        ///     If the low-order bit is 1, the key is toggled. A key, such as the CAPS LOCK key, is toggled if it is turned on. The
+        ///     key is off and untoggled if the low-order bit is 0. A toggle key's indicator light (if any) on the keyboard will be
+        ///     on when the key is toggled, and off when the key is untoggled.
+        /// </returns>
+        /// <remarks>http://msdn.microsoft.com/en-us/library/ms646301.aspx</remarks>
+        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
+        public static extern short GetKeyState(int vKey);
+
+        /// <summary>
+        ///     Translates (maps) a virtual-key code into a scan code or character value, or translates a scan code into a
+        ///     virtual-key code.
+        /// </summary>
+        /// <param name="uCode">
+        ///     [in] The virtual key code or scan code for a key. How this value is interpreted depends on the
+        ///     value of the uMapType parameter.
+        /// </param>
+        /// <param name="uMapType">
+        ///     [in] The translation to be performed. The value of this parameter depends on the value of the
+        ///     uCode parameter.
+        /// </param>
+        /// <param name="dwhkl">[in] The input locale identifier used to translate the specified code.</param>
+        /// <returns></returns>
+        [DllImport("user32.dll", CharSet = CharSet.Auto)]
+        internal static extern int MapVirtualKeyEx(int uCode, int uMapType, IntPtr dwhkl);
+
+        /// <summary>
+        ///     Retrieves the active input locale identifier (formerly called the keyboard layout) for the specified thread.
+        ///     If the idThread parameter is zero, the input locale identifier for the active thread is returned.
+        /// </summary>
+        /// <param name="dwLayout">[in] The identifier of the thread to query, or 0 for the current thread. </param>
+        /// <returns>
+        ///     The return value is the input locale identifier for the thread. The low word contains a Language Identifier for the
+        ///     input
+        ///     language and the high word contains a device handle to the physical layout of the keyboard.
+        /// </returns>
+        [DllImport("user32.dll", CharSet = CharSet.Auto)]
+        internal static extern IntPtr GetKeyboardLayout(int dwLayout);
+
+        /// <summary>
+        ///     MapVirtualKeys uMapType
+        /// </summary>
+        internal enum MapType
+        {
+            /// <summary>
+            ///     uCode is a virtual-key code and is translated into an unshifted character value in the low-order word of the return
+            ///     value. Dead keys (diacritics) are indicated by setting the top bit of the return value. If there is no translation,
+            ///     the function returns 0.
+            /// </summary>
+            MAPVK_VK_TO_VSC,
+
+            /// <summary>
+            ///     uCode is a virtual-key code and is translated into a scan code. If it is a virtual-key code that does not
+            ///     distinguish between left- and right-hand keys, the left-hand scan code is returned. If there is no translation, the
+            ///     function returns 0.
+            /// </summary>
+            MAPVK_VSC_TO_VK,
+
+            /// <summary>
+            ///     uCode is a scan code and is translated into a virtual-key code that does not distinguish between left- and
+            ///     right-hand keys. If there is no translation, the function returns 0.
+            /// </summary>
+            MAPVK_VK_TO_CHAR,
+
+            /// <summary>
+            ///     uCode is a scan code and is translated into a virtual-key code that distinguishes between left- and right-hand
+            ///     keys. If there is no translation, the function returns 0.
+            /// </summary>
+            MAPVK_VSC_TO_VK_EX
+        }
+    }
 }


Add property access to FullName

Add property access to FullName

--- ProjectTracker20cs/ProjectTracker.Library/ProjectResource.cs
+++ ProjectTracker20cs/ProjectTracker.Library/ProjectResource.cs
@@ -48,7 +48,13 @@

     public string FullName
     {
-      get { return string.Format("{0}, {1}", LastName, FirstName); }
+      get
+      {
+        if (CanReadProperty("FirstName") && CanReadProperty("LastName"))
+          return string.Format("{0}, {1}", LastName, FirstName);
+        else
+          throw new System.Security.SecurityException("Property read not allowed");
+      }
     }

     public string Assigned


Version upped

Version upped

--- NadekoBot.Core/Services/Impl/StatsService.cs
+++ NadekoBot.Core/Services/Impl/StatsService.cs
@@ -23,7 +23,7 @@
         private readonly IBotCredentials _creds;
         private readonly DateTime _started;

-        public const string BotVersion = "2.26.1";
+        public const string BotVersion = "2.26.2";
         public string Author => "Kwoth#2560";
         public string Library => "Discord.Net";


DocGen: fix member names ordering (#248)

--- ReferenceCore/ExtenderDoc.cs
+++ ReferenceCore/ExtenderDoc.cs
@@ -29,18 +29,18 @@
             RenderTypeDescription(typeDoc.Summary);
             RenderTypeRemarks(typeDoc.Remarks);

-            RenderProperties(typeDoc.Properties);
-            RenderMethods(typeDoc.Methods, "Methods");
-            RenderEvents(typeDoc.Events);
-
-            RenderClientProperties(typeDoc.ClientProperties);
-            RenderMethods(typeDoc.ClientMethods, "Client methods");
-            RenderClientEvents(typeDoc.ClientEvents);
-
-            RenderClientPropertiesExpanded(typeDoc.ClientProperties);
-            RenderMethodsExpanded(typeDoc.Methods, "Methods");
-            RenderMethodsExpanded(typeDoc.ClientMethods, "Client methods");
-            RenderClientEventsExpanded(typeDoc.ClientEvents);
+            RenderProperties(typeDoc.Properties.OrderBy(p => p.Name));
+            RenderMethods(typeDoc.Methods.OrderBy(m => m.Name), "Methods");
+            RenderEvents(typeDoc.Events.OrderBy(e => e.Name));
+
+            RenderClientProperties(typeDoc.ClientProperties.OrderBy(p => p.Name));
+            RenderMethods(typeDoc.ClientMethods.OrderBy(m => m.Name), "Client methods");
+            RenderClientEvents(typeDoc.ClientEvents.OrderBy(e => e.Name));
+
+            RenderClientPropertiesExpanded(typeDoc.ClientProperties.OrderBy(p => p.Name));
+            RenderMethodsExpanded(typeDoc.Methods.OrderBy(m => m.Name), "Methods");
+            RenderMethodsExpanded(typeDoc.ClientMethods.OrderBy(m => m.Name), "Client methods");
+            RenderClientEventsExpanded(typeDoc.ClientEvents.OrderBy(e => e.Name));

             return _markupStringBuilder.ToString();
         }


added MergeSort method; made Merge private

--- MergeSort/MergeSort/Program.cs
+++ MergeSort/MergeSort/Program.cs
@@ -9,7 +9,7 @@
             Console.WriteLine("Hello World!");
         }

-        static void Merge(int[] array, int low, int mid, int high)
+        private static void Merge(int[] array, int low, int mid, int high)
         {
             int left = low;
             int right = mid + 1;
@@ -50,5 +50,16 @@
                 array[low + i] = temp[i];
             }
         }
+
+        public static void MergeSort(int[] array, int low, int high)
+        {
+            if (low < high)
+            {
+                int mid = (low / 2) + (high / 2);
+                MergeSort(array, low, mid);
+                MergeSort(array, mid + 1, high);
+                Merge(array, low, mid, high);
+            }
+        }
     }
 }


Add tests for generic deep equality comparer.

--- Rock.Core.UnitTests/Collections/DeepEqualityComparerTests.cs
+++ Rock.Core.UnitTests/Collections/DeepEqualityComparerTests.cs
@@ -1061,6 +1061,46 @@
         }
     }

+    public class TheGenericDeepEqualityComparer
+    {
+        [Test]
+        public void DoesTheSameThingAsTheNonGenericDeepEqualityComparer()
+        {
+            var nonGenericDeepEqualityComparer = new DeepEqualityComparer();
+            var genericDeepEqualityComparer = new DeepEqualityComparer<Dictionary<Waldo, IEnumerable<int>>>();
+
+            var obj = new Dictionary<Waldo, IEnumerable<int>>
+            {
+                { new Waldo { Foo = "a", Bar = 1, Baz = MyEnum.Foo }, new[] { 1, 2, 3 } },
+                { new Waldo { Foo = "b", Bar = 2, Baz = MyEnum.Bar }, new[] { 4, 5, 6 } }
+            };
+
+            var compare1 = new Dictionary<Waldo, IEnumerable<int>>
+            {
+                { new Waldo { Foo = "a", Bar = 1, Baz = MyEnum.Foo }, new[] { 1, 2, 3 } },
+                { new Waldo { Foo = "b", Bar = 2, Baz = MyEnum.Bar }, new[] { 4, 5, 6 } }
+            };
+
+            var compare2 = new Dictionary<Waldo, IEnumerable<int>>
+            {
+                { new Waldo { Foo = "a", Bar = 1, Baz = MyEnum.Foo }, new[] { 1, 2, 3 } },
+                { new Waldo { Foo = "b", Bar = 2, Baz = MyEnum.Bar }, new[] { 4, 5, 7 } }
+            };
+
+            Assert.That(
+                genericDeepEqualityComparer.Equals(obj, compare1),
+                Is.EqualTo(nonGenericDeepEqualityComparer.Equals(obj, compare1)));
+
+            Assert.That(
+                genericDeepEqualityComparer.Equals(obj, compare2),
+                Is.EqualTo(nonGenericDeepEqualityComparer.Equals(obj, compare2)));
+
+            Assert.That(
+                genericDeepEqualityComparer.GetHashCode(obj),
+                Is.EqualTo(nonGenericDeepEqualityComparer.GetHashCode(obj)));
+        }
+    }
+
     public class MyEnumerable : IEnumerable
     {
         private readonly ArrayList _list = new ArrayList();


Update Cert2 data model

Update Cert2 data model

--- SSLLabsApiWrapper/Models/Response/EndpointSubModels/Cert2.cs
+++ SSLLabsApiWrapper/Models/Response/EndpointSubModels/Cert2.cs
@@ -4,8 +4,14 @@
 	{
 		public string subject { get; set; }
 		public string label { get; set; }
+		public object notBefore { get; set; }
+		public object notAfter { get; set; }
 		public string issuerSubject { get; set; }
 		public string issuerLabel { get; set; }
+		public string sigAlg { get; set; }
+		public string keyAlg { get; set; }
+		public int keySize { get; set; }
+		public int keyStrength { get; set; }
 		public string raw { get; set; }
 	}
 }


Fix obsolete call.

Fix obsolete call.

--- NtApiDotNet/Win32/SecurityInformationImpl.cs
+++ NtApiDotNet/Win32/SecurityInformationImpl.cs
@@ -160,7 +160,7 @@
             Dictionary<uint, string> names, GenericMapping generic_mapping)
             : this(obj_name, names, generic_mapping, true)
         {
-            _sd = sd.ToByteArray();
+            _sd = sd.ToArray();
         }

         public void GetAccessRights(ref Guid pguidObjectType, SiObjectInfoFlags dwFlags, out IntPtr ppAccess, out uint pcAccesses, out uint piDefaultAccess)


Add support for getting the path to installed miners for various algos

--- MultiMiner.Engine/MinerPath.cs
+++ MultiMiner.Engine/MinerPath.cs
@@ -1,4 +1,5 @@
 using MultiMiner.Utility.OS;
+using MultiMiner.Xgminer.Data;
 using System;
 using System.IO;

@@ -6,51 +7,87 @@
 {
     public static class MinerPath
     {
-        private const string BfgminerName = "bfgminer";
-
-        public static string GetPathToInstalledMiner()
+        public static string GetPathToInstalledMiner(CoinAlgorithm algorithm)
         {
             string executablePath = string.Empty;
-            string minerName = GetMinerName();
+            string minerName = MinerFactory.Instance.GetMiner(algorithm).Name;
+            string minerFileName = MinerFactory.Instance.GetMiner(algorithm).FileName;

-            switch (OSVersionPlatform.GetConcretePlatform())
+            switch (algorithm)
             {
-                case PlatformID.MacOSX:
-                    //try local path first
-                    executablePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format(@"Miners/{0}/bin/{0}", minerName));
-
-                    if (!File.Exists(executablePath))
-                        //try global path (Homebrew)
-                        executablePath = string.Format(@"/usr/local/bin/{0}", minerName);
-
+                case CoinAlgorithm.SHA256:
+                    executablePath = GetPathToBFGMiner(minerFileName);
                     break;
-
-                //support Unix - there is no bin folder for the executables like on Mac OS X
-                case PlatformID.Unix:
-                    //try local path first
-                    executablePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format(@"Miners/{0}/{0}", minerName));
-
-                    if (!File.Exists(executablePath))
-                        //try /usr/local/bin
-                        executablePath = string.Format(@"/usr/local/bin/{0}", minerName);
-
-                    if (!File.Exists(executablePath))
-                        //try /usr/bin
-                        executablePath = string.Format(@"/usr/bin/{0}", minerName);
-
+                case CoinAlgorithm.Scrypt:
+                    executablePath = GetPathToBFGMiner(minerFileName);
                     break;
-
-                default:
-                    executablePath = string.Format(@"Miners\{0}\{0}.exe", minerName);
+                case CoinAlgorithm.ScryptJane:
+                    executablePath = GetPathToMinerOnWindows(minerName, minerFileName);
+                    break;
+                case CoinAlgorithm.ScryptN:
+                    executablePath = GetPathToMinerOnWindows(minerName, minerFileName);
+                    break;
+                case CoinAlgorithm.X11:
+                    executablePath = GetPathToMinerOnWindows(minerName, minerFileName);
                     break;
             }

             return executablePath;
         }

-        public static string GetMinerName()
+        private static string GetPathToBFGMiner(string minerName)
         {
-            return BfgminerName;
+            string executablePath;
+
+            switch (OSVersionPlatform.GetConcretePlatform())
+            {
+                case PlatformID.MacOSX:
+                    executablePath = GetPathToMinerOnMacOSX(minerName);
+                    break;
+
+                //support Unix - there is no bin folder for the executables like on Mac OS X
+                case PlatformID.Unix:
+                    executablePath = GetPathToMinerOnLinux(minerName);
+                    break;
+
+                default:
+                    executablePath = GetPathToMinerOnWindows(minerName, minerName);
+                    break;
+            }
+            return executablePath;
+        }
+
+        private static string GetPathToMinerOnMacOSX(string minerName)
+        {
+            string executablePath;
+            //try local path first
+            executablePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format(@"Miners/{0}/bin/{0}", minerName));
+
+            if (!File.Exists(executablePath))
+                //try global path (Homebrew)
+                executablePath = string.Format(@"/usr/local/bin/{0}", minerName);
+            return executablePath;
+        }
+
+        private static string GetPathToMinerOnLinux(string minerName)
+        {
+            string executablePath;
+            //try local path first
+            executablePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format(@"Miners/{0}/{0}", minerName));
+
+            if (!File.Exists(executablePath))
+                //try /usr/local/bin
+                executablePath = string.Format(@"/usr/local/bin/{0}", minerName);
+
+            if (!File.Exists(executablePath))
+                //try /usr/bin
+                executablePath = string.Format(@"/usr/bin/{0}", minerName);
+            return executablePath;
+        }
+
+        private static string GetPathToMinerOnWindows(string minerName, string minerFileName)
+        {
+            return Path.Combine(Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Miners"), minerName), minerFileName + ".exe");
         }
     }
 }


Fix commit 0285d51ecbb5788d7e320998eb21e46d762a081c

--- Samples/Connectors/SampleConnection/SecuritiesWindow.xaml.cs
+++ Samples/Connectors/SampleConnection/SecuritiesWindow.xaml.cs
@@ -453,7 +453,6 @@
 			{
 				var mdMsg = new MarketDataMessage
 				{
-					SecurityId = security.ToSecurityId(),
 					IsSubscribe = true,
 					DataType2 = DataType.TimeFrame(tf),
 					From = settings.From,
@@ -462,6 +461,7 @@
 					Skip = settings.Skip,
 					Count = settings.Count,
 				};
+				security.ToMessage().CopyTo(mdMsg);
 				var chartWnd = new ChartWindow(mdMsg);

 				_chartWindows.Add(chartWnd);


Fixed bug with RunOnce not applied

Fixed bug with RunOnce not applied

--- NBi.NUnit.Runtime/TestSuite.cs
+++ NBi.NUnit.Runtime/TestSuite.cs
@@ -99,6 +99,11 @@
                     {
                         var impl = new DecorationFactory().Get(command);
                         impl.Execute();
+                        if (command is IGroupCommand)
+                        {
+                            var groupCommand = (command as IGroupCommand);
+                            groupCommand.HasRun=true;
+                        }
                     }
                 }
             }


DefCoinSelector: prevent NRE when null Random is used (#1012)

* DefCoinSelector: prevent NRE when null Random is used

* fixup

* fixup

--- NBitcoin/TransactionBuilder.cs
+++ NBitcoin/TransactionBuilder.cs
@@ -75,14 +75,17 @@
 	{
 		public DefaultCoinSelector()
 		{
-
-		}
-		Random _Rand = new Random();
+			_Rand = new Random();
+		}
+
+		Random? _Rand;
+
 		public DefaultCoinSelector(int seed)
 		{
 			_Rand = new Random(seed);
 		}
-		public DefaultCoinSelector(Random random)
+
+		public DefaultCoinSelector(Random? random)
 		{
 			_Rand = random;
 		}
@@ -128,7 +131,8 @@
 			List<OutputGroup> applicable_groups = new List<OutputGroup>();
 			var nTotalLower = zero;
 			var targetMinChange = target.IsCompatible(MinimumChange) ? target.Add(MinimumChange) : target;
-			Utils.Shuffle(groups, _Rand);
+			if (_Rand != null)
+				Utils.Shuffle(groups, _Rand);

 			foreach (var group in groups)
 			{
@@ -241,7 +245,7 @@
 						//that the rng is fast. We do not use a constant random sequence,
 						//because there may be some privacy improvement by making
 						//the selection random.
-						if (nPass == 0 ? _Rand.Next(0, 2) == 0 : !vfIncluded[i])
+						if ((nPass == 0 && _Rand != null) ? _Rand.Next(0, 2) == 0 : !vfIncluded[i])
 						{
 							nTotal = nTotal.Add(groups[i].Amount);
 							vfIncluded[i] = true;


Validate args

Validate args

--- Octokit/Models/Response/GitIgnoreTemplate.cs
+++ Octokit/Models/Response/GitIgnoreTemplate.cs
@@ -4,6 +4,9 @@
     {
         public GitIgnoreTemplate(string name, string source)
         {
+            Ensure.ArgumentNotNullOrEmptyString(name, "name");
+            Ensure.ArgumentNotNullOrEmptyString(source, "source");
+
             Name = name;
             Source = source;
         }


Fixed bug of avie going under the terrain when crossing regions in certain directions. This was a 1-off bug: the terrain was being placed in 127, 127 resulting in a bounding box if -2, 256. I placed it in 128, 128 resulting in a bounding box of -1, 257.

--- OpenSim/Region/Physics/OdePlugin/OdeScene.cs
+++ OpenSim/Region/Physics/OdePlugin/OdeScene.cs
@@ -3430,7 +3430,7 @@
         private void SetTerrain(float[] heightMap, Vector3 pOffset)
         {
             int startTime = Util.EnvironmentTickCount();
-            m_log.DebugFormat("[ODE SCENE]: Setting terrain for {0}", Name);
+            m_log.DebugFormat("[ODE SCENE]: Setting terrain for {0} with offset {1}", Name, pOffset);

             // this._heightmap[i] = (double)heightMap[i];
             // dbm (danx0r) -- creating a buffer zone of one extra sample all around
@@ -3544,7 +3544,7 @@

                 d.RFromAxisAndAngle(out R, v3.X, v3.Y, v3.Z, angle);
                 d.GeomSetRotation(GroundGeom, ref R);
-                d.GeomSetPosition(GroundGeom, (pOffset.X + ((int)Constants.RegionSize * 0.5f)) - 1, (pOffset.Y + ((int)Constants.RegionSize * 0.5f)) - 1, 0);
+                d.GeomSetPosition(GroundGeom, (pOffset.X + ((int)Constants.RegionSize * 0.5f)), (pOffset.Y + ((int)Constants.RegionSize * 0.5f)), 0);
                 IntPtr testGround = IntPtr.Zero;
                 if (RegionTerrain.TryGetValue(pOffset, out testGround))
                 {


Fixed incorrect PM Message Link in the HoverCards

--- yafsrc/YetAnotherForum.NET/Classes/YafResourceHandler.cs
+++ yafsrc/YetAnotherForum.NET/Classes/YafResourceHandler.cs
@@ -539,7 +539,8 @@
                                        ImageThemeTag = "PM",
                                        TitleLocalizedTag = "PM_TITLE",
                                        TitleLocalizedPage = "POSTS",
-                                       NavigateUrl = YafBuildLink.GetLinkNotEscaped(ForumPages.pmessage, "u={0}", userId),
+                                       NavigateUrl = YafBuildLink.GetLinkNotEscaped(ForumPages.pmessage, "u={0}", userId).Replace(
+                                               "resource.ashx", "default.aspx"),
                                        ParamTitle0 = userName,
                                        Visible =
                                            !userData.IsGuest && this.Get<YafBoardSettings>().AllowPrivateMessages


Fix value of GenerateDebugInformation in vcxproj

Write DebugFastLink/true/false in case GenerateDebugInformation is DebugFastLink/Enabled/Disabled.
Note that MS compiler accepts Debug/No or true/false, but those last values are the one written by visual studio, so now we use them too.

This also fixes #12

--- Sharpmake.Generators/VisualStudio/ProjectOptionsGenerator.cs
+++ Sharpmake.Generators/VisualStudio/ProjectOptionsGenerator.cs
@@ -2051,12 +2051,7 @@
                     }
                 }

-                var toolsetVersion = Options.GetObject<Options.Vc.General.PlatformToolset>(context.Configuration);
-                context.Options["GenerateDebugInformation"] = isFastLink ? "DebugFastLink" :
-                    (
-                        toolsetVersion == Options.Vc.General.PlatformToolset.v140 &&
-                        !PlatformRegistry.Get<IPlatformDescriptor>(context.Configuration.Platform).IsUsingClang
-                    ) ? "Debug" : "true";
+                context.Options["GenerateDebugInformation"] = isFastLink ? "DebugFastLink" : "true";

                 context.SelectOption
                 (
@@ -2113,11 +2108,7 @@
             }),
             Options.Option(Options.Vc.Linker.GenerateDebugInformation.Disable, () =>
             {
-                context.Options["GenerateDebugInformation"] =
-                (
-                    context.DevelopmentEnvironment >= DevEnv.vs2015 &&
-                    context.Configuration.Platform.IsUsingClang()
-                ) ? "No" : "false";
+                context.Options["GenerateDebugInformation"] = "false";
                 context.Options["CompilerProgramDatabaseFile"] = FileGeneratorUtilities.RemoveLineTag;
                 context.Options["LinkerProgramDatabaseFile"] = FileGeneratorUtilities.RemoveLineTag;
                 context.Options["FullProgramDatabaseFile"] = FileGeneratorUtilities.RemoveLineTag;


fix multiple connection time

fix multiple connection time

--- SignalGo.Server/ServiceManager/Providers/BaseHttpProvider.cs
+++ SignalGo.Server/ServiceManager/Providers/BaseHttpProvider.cs
@@ -612,7 +612,7 @@
                         await client.ClientStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
                     }
                     //delay to fix fast dispose before client read data
-                    await Task.Delay(5000).ConfigureAwait(false);
+                    await Task.Delay(TimeSpan.FromMilliseconds(100)).ConfigureAwait(false);
                     file.FileStream.Dispose();
                 }
                 else


Fixed claimed todo item formatting.

Fixed claimed todo item formatting.

--- SlackCommander/SlackCommander.Web/Todo/TodoItemExtensions.cs
+++ SlackCommander/SlackCommander.Web/Todo/TodoItemExtensions.cs
@@ -31,7 +31,7 @@
                 todoItem.Done ? ":white_check_mark:" : ":white_square:",
                 todoItem.Text,
                 todoItem.ClaimedBy.Missing() ? string.Empty : ":lock:",
-                todoItem.ClaimedBy).Trim();
+                todoItem.ClaimedBy.Missing() ? string.Empty : string.Format("<@{0}>", todoItem.ClaimedBy)).Trim();
         }
     }
 }


#1459 Add caching to FindDataPortalMethod

--- Source/Csla.Shared/Reflection/ServiceProviderMethodCaller.cs
+++ Source/Csla.Shared/Reflection/ServiceProviderMethodCaller.cs
@@ -7,6 +7,7 @@
 // <summary>Dynamically find/invoke methods with DI provided params</summary>
 //-----------------------------------------------------------------------
 using System;
+using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.Linq;
 using System.Reflection;
@@ -23,6 +24,8 @@
   {
     private static readonly BindingFlags _bindingAttr = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
     private static readonly BindingFlags _factoryBindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
+    private static readonly ConcurrentDictionary<string, System.Reflection.MethodInfo> _methodCache =
+      new ConcurrentDictionary<string, System.Reflection.MethodInfo>();

     /// <summary>
     /// Find a method based on data portal criteria
@@ -55,8 +58,10 @@
       if (targetType == null)
         throw new ArgumentNullException("targetType");

-      var typeOfT = typeof(T);
+      var typeOfOperation = typeof(T);
       var candidates = new List<System.Reflection.MethodInfo>();
+
+      var cacheKey = targetType.FullName + GetCriteriaTypeNames(criteria);

       var factoryInfo = Csla.Server.ObjectFactoryAttribute.GetObjectFactoryAttribute(targetType);
       if (factoryInfo != null)
@@ -64,13 +69,13 @@
         var factoryType = Csla.Server.FactoryDataPortal.FactoryLoader.GetFactoryType(factoryInfo.FactoryTypeName);
         if (factoryType != null)
         {
-          if (typeOfT == typeof(CreateAttribute))
+          if (typeOfOperation == typeof(CreateAttribute))
             candidates = factoryType.GetMethods(_factoryBindingAttr).Where(m => m.Name == factoryInfo.CreateMethodName).ToList();
-          else if (typeOfT == typeof(FetchAttribute))
+          else if (typeOfOperation == typeof(FetchAttribute))
             candidates = factoryType.GetMethods(_factoryBindingAttr).Where(m => m.Name == factoryInfo.FetchMethodName).ToList();
-          else if (typeOfT == typeof(DeleteAttribute))
+          else if (typeOfOperation == typeof(DeleteAttribute))
             candidates = factoryType.GetMethods(_factoryBindingAttr).Where(m => m.Name == factoryInfo.DeleteMethodName).ToList();
-          else if (typeOfT == typeof(ExecuteAttribute))
+          else if (typeOfOperation == typeof(ExecuteAttribute))
             candidates = factoryType.GetMethods(_factoryBindingAttr).Where(m => m.Name == factoryInfo.ExecuteMethodName).ToList();
           else
             candidates = factoryType.GetMethods(_factoryBindingAttr).Where(m => m.Name == factoryInfo.UpdateMethodName).ToList();
@@ -89,7 +94,7 @@
         // if no attribute-based methods found, look for legacy methods
         if (candidates.Count == 0)
         {
-          var attributeName = typeOfT.Name.Substring(0, typeOfT.Name.IndexOf("Attribute"));
+          var attributeName = typeOfOperation.Name.Substring(0, typeOfOperation.Name.IndexOf("Attribute"));
           if (attributeName.Contains("Child"))
           {
             var methodName = "Child_" + attributeName.Substring(0, attributeName.IndexOf("Child"));
@@ -117,7 +122,7 @@
       if (candidates.Count == 0)
       {
         if (throwOnError)
-          throw new MissingMethodException($"{targetType.FullName}.[{typeOfT.Name.Replace("Attribute", "")}]{GetCriteriaTypeNames(criteria)}");
+          throw new MissingMethodException($"{targetType.FullName}.[{typeOfOperation.Name.Replace("Attribute", "")}]{cacheKey}");
         else
           return null;
       }
@@ -138,7 +143,7 @@
             var index = 0;
             foreach (var c in criteria)
             {
-              if (c == null)
+              if (c == null)
               {
                 if (methodParams[index].ParameterType.IsPrimitive)
                   break;
@@ -175,7 +180,7 @@
         foreach (var item in candidates)
         {
           var lastParam = item.GetParameters().LastOrDefault();
-          if (lastParam != null && lastParam.ParameterType.Equals(typeof(object[])) &&
+          if (lastParam != null && lastParam.ParameterType.Equals(typeof(object[])) &&
             lastParam.GetCustomAttributes<ParamArrayAttribute>().Any())
           {
             matches.Add(new ScoredMethodInfo { MethodInfo = item, Score = 1 });
@@ -185,7 +190,7 @@
       if (matches.Count == 0)
       {
         if (throwOnError)
-          throw new TargetParameterCountException($"{targetType.FullName}.[{typeOfT.Name.Replace("Attribute", "")}]{GetCriteriaTypeNames(criteria)}");
+          throw new TargetParameterCountException($"{targetType.FullName}.[{typeOfOperation.Name.Replace("Attribute", "")}]{GetCriteriaTypeNames(criteria)}");
         else
           return null;
       }
@@ -216,12 +221,18 @@
         if (maxCount > 1)
         {
           if (throwOnError)
-            throw new AmbiguousMatchException($"{targetType.FullName}.[{typeOfT.Name.Replace("Attribute", "")}]{GetCriteriaTypeNames(criteria)}");
+            throw new AmbiguousMatchException($"{targetType.FullName}.[{typeOfOperation.Name.Replace("Attribute", "")}]{GetCriteriaTypeNames(criteria)}");
           else
             return null;
         }
       }
+      _methodCache.TryAdd(cacheKey, result.MethodInfo);
       return result.MethodInfo;
+    }
+
+    private static string GetCacheKeyName(Type targetType, Type operationType, object[] criteria)
+    {
+      return targetType.FullName + "." + operationType.Name + GetCriteriaTypeNames(criteria);
     }

     private static string GetCriteriaTypeNames(object[] criteria)


show client icon

show client icon

--- p2pChat/MainWindow.xaml.cs
+++ p2pChat/MainWindow.xaml.cs
@@ -51,8 +51,13 @@
             };
         }

-        private void ShowMessage(string message) {
-            var image = ResourceHelper.GetEmbeddedImage("Images/NoName.png");
+        private void ShowMessage(string sender, string message) {
+            ChatClient client;
+            var image = String.IsNullOrEmpty(sender) ||
+                !_clients.ContainsKey(sender) ||
+                (client = _clients[sender]) == null ?
+                ResourceHelper.GetEmbeddedImage("Images/NoName.png") :
+                client.Icon;
             if (image != null) {
                 _paragraph.Inlines.Add(new InlineUIContainer(new Image() {
                     Source = image,
@@ -60,7 +65,7 @@
                     Height = _settings.FontSize, // image.PixelHeight
                 }));
             }
-            _paragraph.Inlines.Add(new Run(message));
+            _paragraph.Inlines.Add(new Run((!String.IsNullOrEmpty(sender) ? sender + "\t" : "") + message));
             _paragraph.Inlines.Add(new LineBreak());
         }

@@ -90,7 +95,7 @@
                     image_ListenStatus.Source = ResourceHelper.GetImage("Images/Play.png");
                 }
                 catch (Exception ex) {
-                    ShowMessage(ex.GetAllMessages());
+                    ShowMessage(null, ex.GetAllMessages());
                 }
             }
         }
@@ -132,7 +137,7 @@
                 _talker.Talk(new ChatClient(textBox_Name.Text, _settings.MyIcon).ToRegisterMessage());
             }
             catch (Exception ex) {
-                ShowMessage(ex.GetAllMessages());
+                ShowMessage(null, ex.GetAllMessages());
             }
         }

@@ -171,7 +176,7 @@
                 _settings.Save();
             }
             catch (Exception ex) {
-                ShowMessage(ex.Message);
+                ShowMessage(null, ex.Message);
                 Disconnect();
             }
         }
@@ -193,12 +198,12 @@
                             DispatcherPriority.Background,
                             new Action(() => {
                                 if (connected) {
-                                    ShowMessage("Connect: " + talker.Host + ":" + talker.Port);
+                                    ShowMessage(null, "Connect: " + talker.Host + ":" + talker.Port);
                                     button_Connect.IsEnabled = false;
                                     button_Disconnect.IsEnabled = true;
                                     button_Send.IsEnabled = true;
                                 } else {
-                                    ShowMessage("Disconnect: " + talker.Host + ":" + talker.Port);
+                                    ShowMessage(null, "Disconnect: " + talker.Host + ":" + talker.Port);
                                     button_Connect.IsEnabled = true;
                                     button_Disconnect.IsEnabled = false;
                                     button_Send.IsEnabled = false;
@@ -210,7 +215,7 @@
                         var message = e.NewValue as string;
                         Dispatcher.BeginInvoke(
                             DispatcherPriority.Background,
-                            new Action(() => ShowMessage(message))
+                            new Action(() => ShowMessage(null, message))
                         );
                         break;
                 }
@@ -222,7 +227,7 @@
                         var message = e.NewValue as string;
                         Dispatcher.BeginInvoke(
                             DispatcherPriority.Background,
-                            new Action(() => ShowMessage(message))
+                            new Action(() => ShowMessage(null, message))
                         );
                         break;
                 }
@@ -269,7 +274,7 @@
             );
             Dispatcher.BeginInvoke(
                 DispatcherPriority.Background,
-                new Action(() => ShowMessage(message.Sender + "\t" + body))
+                new Action(() => ShowMessage(message.Sender, body))
             );
         }
     }


Add documentation to Page.cs.

Add documentation to Page.cs.

--- csogg/Page.cs
+++ csogg/Page.cs
@@ -25,58 +25,107 @@
 namespace csogg
 {
 	/// <summary>
-	/// Summary description for Page.
+	/// Used to encapsulate the data in one Ogg bitstream page.
 	/// </summary>
-	public class Page
+	public sealed class Page
 	{
 		private static readonly uint[] crc_lookup = new uint[256];
-
+
+		public int header;
+		public int header_len;
+		public byte[] header_base;
+
+		public int body;
+		public int body_len;
+		public byte[] body_base;
+
+		/// <summary>
+		/// Constructor
+		/// </summary>
+		public Page()
+		{
+			for (uint i = 0; i < crc_lookup.Length; i++)
+			{
+				crc_lookup[i] = crc_entry(i);
+			}
+		}
+
 		private static uint crc_entry(uint index)
 		{
 			uint r = index << 24;
+
 			for(int i=0; i<8; i++)
 			{
 				if((r& 0x80000000)!=0)
 				{
-					r=(r << 1)^0x04c11db7; /* The same as the ethernet generator
-											polynomial, although we use an
-											unreflected alg and an init/final
-											of 0, not 0xffffffff */
+					r=(r << 1)^0x04c11db7;  // The same as the ethernet generator
+											// polynomial, although we use an
+											// unreflected alg and an init/final
+											// of 0, not 0xffffffff.
 				}
 				else
 				{
 					r <<= 1;
 				}
 			}
+
 			return (r & 0xffffffff);
 		}

-		public byte[] header_base;
-		public int header;
-		public int header_len;
-		public byte[] body_base;
-		public int body;
-		public int body_len;
-
+		/// <summary>
+		/// Gets the version of ogg_page used in this page.
+		/// </summary>
+		/// <returns>the version of ogg_page used in this page.</returns>
 		internal int version()
 		{
 			return header_base[header+4]&0xff;
 		}
+
+		/// <summary>
+		/// Gets whether this page contains packet data which
+		/// has been continued from the previous page.
+		/// </summary>
+		/// <returns>
+		/// 0 if this page does not contain continued data.
+		/// 1 if this page contains packet data continued from the last page.
+		/// </returns>
 		internal int continued()
 		{
 			return (header_base[header+5]&0x01);
 		}
+
+		/// <summary>
+		/// Gets whether or not this page is at the beginning of the logical bitstream.
+		/// </summary>
+		/// <returns>
+		/// 0 if this page is the beginning of a bitstream.
+		/// Greater than zero if the page is from any other location in the stream.
+		/// </returns>
 		public int bos()
 		{
 			return (header_base[header+5]&0x02);
 		}
+
+		/// <summary>
+		/// Gets whether or not this page is at the end of the logical bitstream.
+		/// </summary>
+		/// <returns>
+		/// 0 - This page is from any other location in the stream.
+		/// Greater than zero - This page contains the end of a bitstream.
+		/// </returns>
 		public int eos()
 		{
 			return (header_base[header+5]&0x04);
 		}
+
+		/// <summary>
+		/// Gets the exact granular position of the packet data contained at the end of this page.
+		/// </summary>
+		/// <returns>the exact granular position of the packet data contained at the end of this page.</returns>
 		public long granulepos()
 		{
 			long foo = header_base[header+13]&0xff;
+
 			foo = (foo<<8) | (uint)(header_base[header+12]&0xff);
 			foo = (foo<<8) | (uint)(header_base[header+11]&0xff);
 			foo = (foo<<8) | (uint)(header_base[header+10]&0xff);
@@ -84,23 +133,38 @@
 			foo = (foo<<8) | (uint)(header_base[header+8]&0xff);
 			foo = (foo<<8) | (uint)(header_base[header+7]&0xff);
 			foo = (foo<<8) | (uint)(header_base[header+6]&0xff);
-			return(foo);
+
+			return foo;
 		}
+
+		/// <summary>
+		/// Gets the unique serial number for the logical bitstream of this page.
+		/// Each page contains the serial number for the logical bitstream that it belongs to.
+		/// </summary>
+		/// <returns>the unique serial number for the logical bitstream of this page.</returns>
 		public int serialno()
 		{
-			return (header_base[header+14]&0xff)|
-				((header_base[header+15]&0xff)<<8)|
-				((header_base[header+16]&0xff)<<16)|
-				((header_base[header+17]&0xff)<<24);
+			return (header_base[header+14]&0xff)      |
+				  ((header_base[header+15]&0xff)<<8)  |
+				  ((header_base[header+16]&0xff)<<16) |
+				  ((header_base[header+17]&0xff)<<24);
 		}
+
+		/// <summary>
+		/// Gets the sequential page number.
+		/// </summary>
+		/// <returns>the sequential page number.</returns>
 		internal int pageno()
 		{
-			return (header_base[header+18]&0xff)|
-				((header_base[header+19]&0xff)<<8)|
-				((header_base[header+20]&0xff)<<16)|
-				((header_base[header+21]&0xff)<<24);
+			return (header_base[header+18]&0xff)      |
+				  ((header_base[header+19]&0xff)<<8)  |
+				  ((header_base[header+20]&0xff)<<16) |
+				  ((header_base[header+21]&0xff)<<24);
 		}

+		/// <summary>
+		/// Checksums a page.
+		/// </summary>
 		internal void checksum()
 		{
 			uint crc_reg=0;
@@ -113,6 +177,7 @@
 				crc_reg = (crc_reg<<8)^crc_lookup[a^b];
 				//crc_reg = (crc_reg<<8)^(uint)(crc_lookup[((crc_reg >> 24)&0xff)^(header_base[header+i]&0xff)]);
 			}
+
 			for(int i=0;i<body_len;i++)
 			{
 				a = body_base[body+i] & 0xffu;
@@ -121,18 +186,11 @@

 				//crc_reg = (crc_reg<<8)^(uint)(crc_lookup[((crc_reg >> 24)&0xff)^(body_base[body+i]&0xff)]);
 			}
-			header_base[header+22]=(byte)crc_reg/*&0xff*/;
-			header_base[header+23]=(byte)(crc_reg>>8)/*&0xff*/;
-			header_base[header+24]=(byte)(crc_reg>>16)/*&0xff*/;
-			header_base[header+25]=(byte)(crc_reg>>24)/*&0xff*/;
-		}

-		public Page()
-		{
-			for(uint i=0; i<crc_lookup.Length; i++)
-			{
-				crc_lookup[i]=crc_entry(i);
-			}
+			header_base[header+22]=(byte)crc_reg;
+			header_base[header+23]=(byte)(crc_reg>>8);
+			header_base[header+24]=(byte)(crc_reg>>16);
+			header_base[header+25]=(byte)(crc_reg>>24);
 		}
 	}
 }


Fix #2 - Rename "lazy loading" to "lazy initialization"

--- SCPI.Tests/Commands_Tests.cs
+++ SCPI.Tests/Commands_Tests.cs
@@ -22,7 +22,7 @@
         }

         [Fact]
-        public void LazyLoadingWorks()
+        public void LazyInitializationWorks()
         {
             // Arrange
             var commands = new Commands();


Camera rotation bug fix

Camera rotation bug fix

--- Source/HelixToolkit.Wpf.SharpDX/Controls/CameraController.cs
+++ Source/HelixToolkit.Wpf.SharpDX/Controls/CameraController.cs
@@ -2258,7 +2258,7 @@
             if (this.rotationSpeed.LengthSquared > 0.1)
             {
                 this.rotateHandler.Rotate(
-                    PointZero, (this.rotationSpeed * time).ToPoint(), this.rotationPoint3D);
+                    this.rotationPosition, this.rotationPosition + (this.rotationSpeed * time), this.rotationPoint3D);
                 this.rotationSpeed *= factor;
                 needUpdate = true;
                 this.spinningSpeed = VectorZero;
@@ -2269,8 +2269,8 @@
                 if (this.isSpinning && this.spinningSpeed.LengthSquared > 0.1)
                 {
                     this.rotateHandler.Rotate(
-                        PointZero, (this.spinningSpeed * time).ToPoint(), this.spinningPoint3D);
-
+                        this.spinningPosition, this.spinningPosition + (this.spinningSpeed * time), this.spinningPoint3D);
+                    Debug.WriteLine(this.spinningSpeed * time);
                     if (!this.InfiniteSpin)
                     {
                         this.spinningSpeed *= factor;


gio: Implement GioStream.SetLength

gio: Implement GioStream.SetLength

--- gio/GioStream.cs
+++ gio/GioStream.cs
@@ -218,9 +218,16 @@
 		{
 			if (!CanSeek || !CanWrite)
 				throw new NotSupportedException ("This stream doesn't support seeking");
-			if (is_disposed)
-				throw new ObjectDisposedException ("The stream is closed");
-			throw new NotImplementedException ();
+
+			var seekable = stream as Seekable;
+
+			if (!seekable.CanTruncate ())
+				throw new NotSupportedException ("This stream doesn't support truncating");
+
+			if (is_disposed)
+				throw new ObjectDisposedException ("The stream is closed");
+
+			seekable.Truncate (value, null);
 		}

 		public override void Close ()


Fixed null reference exception when writing alarm state to external databases

--- Source/Libraries/openPDC.Adapters/DeviceAlarmStateAdapter.cs
+++ Source/Libraries/openPDC.Adapters/DeviceAlarmStateAdapter.cs
@@ -29,6 +29,7 @@
 using GSF.Threading;
 using GSF.TimeSeries;
 using GSF.TimeSeries.Adapters;
+using GSF.Units;
 using openPDC.Model;
 using System;
 using System.Collections.Generic;
@@ -38,7 +39,6 @@
 using System.Linq;
 using System.Text;
 using System.Timers;
-using GSF.Units;
 using AlarmStateRecord = openPDC.Model.AlarmState;
 using ConnectionStringParser = GSF.Configuration.ConnectionStringParser<GSF.TimeSeries.Adapters.ConnectionStringParameterAttribute>;

@@ -574,6 +574,7 @@
                             continue;

                         AlarmState state = m_alarmStates.First(record => record.Value.ID == alarmDevice.StateID).Key;
+                        alarmedDeviceMetadata = metadata;

                         if (ExternalDatabaseReportSingleCompositeState)
                         {
@@ -621,8 +622,9 @@
                 substitutions["{MappedAlarmState}"] = "0";

             // Use device metadata columns as possible substitution parameters
-            foreach (DataColumn column in metadata.Table.Columns)
-                substitutions[$"{{{column.ColumnName}}}"] = metadata[column.ColumnName].ToString();
+            if ((object)metadata != null)
+                foreach (DataColumn column in metadata.Table.Columns)
+                    substitutions[$"{{{column.ColumnName}}}"] = metadata[column.ColumnName].ToString();

             List<object> parameters = new List<object>();
             string commandParameters = parameterTemplate.Execute(substitutions);


Added two features to TreeView sample.

Added two features to TreeView sample.

--- Samples/Samples/TreeViews.cs
+++ Samples/Samples/TreeViews.cs
@@ -80,6 +80,20 @@
 					Console.WriteLine ("D:" + args.DeleteSource);
 				};
 			};
+
+			Button addButton = new Button ("Add");
+			addButton.Clicked += delegate(object sender, EventArgs e) {
+				store.AddNode ().SetValue (text, "Added").SetValue (desc, "Desc");
+			};
+			PackStart(addButton);
+
+			Button removeButton = new Button ("Remove Selection");
+			removeButton.Clicked += delegate(object sender, EventArgs e) {
+				foreach (TreePosition row in view.SelectedRows) {
+					store.GetNavigatorAt (row).Remove ();
+				}
+			};
+			PackStart(removeButton);
 		}

 		void HandleDragOver (object sender, DragOverEventArgs e)


Renamed to halfTransparentImageAttributes to reflect recent change.

--- Sandra.UI.WF/PlayingBoard.cs
+++ Sandra.UI.WF/PlayingBoard.cs
@@ -53,7 +53,7 @@
             // Highlight by setting a gamma smaller than 1.
             var highlight = new ImageAttributes();
             highlight.SetGamma(0.6f);
-            highlightImgAttributes = highlight;
+            highlightImageAttributes = highlight;

             // Half-transparent foreground image at the source square, when moving.
             var halfTransparent = new ImageAttributes();
@@ -66,11 +66,11 @@
                 new float[] {0, 0, 0, 0, 0}
             });
             halfTransparent.SetColorMatrix(halfTransparentMatrix);
-            moveSourceImageAttributes = halfTransparent;
-        }
-
-        private readonly ImageAttributes highlightImgAttributes;
-        private readonly ImageAttributes moveSourceImageAttributes;
+            halfTransparentImageAttributes = halfTransparent;
+        }
+
+        private readonly ImageAttributes highlightImageAttributes;
+        private readonly ImageAttributes halfTransparentImageAttributes;

         private readonly PropertyStore propertyStore = new PropertyStore
         {
@@ -1328,7 +1328,7 @@
                             destinationRectangle,
                             0, 0, image.Width, image.Height,
                             GraphicsUnit.Pixel,
-                            moveSourceImageAttributes);
+                            halfTransparentImageAttributes);
             }
             else if (imgAttribute == ForegroundImageAttribute.Highlight)
             {
@@ -1337,7 +1337,7 @@
                             destinationRectangle,
                             0, 0, image.Width, image.Height,
                             GraphicsUnit.Pixel,
-                            highlightImgAttributes);
+                            highlightImageAttributes);
             }
             else
             {
@@ -1351,8 +1351,8 @@
         {
             if (disposing)
             {
-                highlightImgAttributes.Dispose();
-                moveSourceImageAttributes.Dispose();
+                highlightImageAttributes.Dispose();
+                halfTransparentImageAttributes.Dispose();

                 // To dispose of stored disposable values such as brushes.
                 propertyStore.Dispose();


Set connect key when start client

Set connect key when start client

--- Scripts/LiteNetLibManager.cs
+++ Scripts/LiteNetLibManager.cs
@@ -178,14 +178,17 @@

         public virtual LiteNetLibClient StartClient()
         {
-            return StartClient(networkAddress, networkPort);
-        }
-
-        public virtual LiteNetLibClient StartClient(string networkAddress, int networkPort)
+            return StartClient(networkAddress, networkPort, connectKey);
+        }
+
+        public virtual LiteNetLibClient StartClient(string networkAddress, int networkPort, string connectKey)
         {
             if (Client != null)
                 return Client;

+            this.networkAddress = networkAddress;
+            this.networkPort = networkPort;
+            this.connectKey = connectKey;
             if (LogDev) Debug.Log("Client connecting to " + networkAddress + ":" + networkPort);
             Client = new LiteNetLibClient(this, connectKey);
             RegisterClientMessages();
@@ -209,7 +212,7 @@

         protected virtual LiteNetLibClient ConnectLocalClient()
         {
-            return StartClient("localhost", Server.NetManager.LocalPort);
+            return StartClient("localhost", Server.NetManager.LocalPort, connectKey);
         }

         public void StopHost()


updates

updates

--- PropertyGraphs/Schema/GraphSchemaHandling.cs
+++ PropertyGraphs/Schema/GraphSchemaHandling.cs
@@ -185,15 +185,17 @@

                 #region Register [Vertex|Edge]Added events: PropertyGraph -> SchemaGraph

-                Graph.OnVertexAddition.OnNotification += (g, v) => SchemaGraph.AddVertexIfNotExists(Id:    v.Label,
-                                                                                Label: VertexLabel.Vertex);
-
-                Graph.OnEdgeAddition.OnNotification   += (g, e) => SchemaGraph.AddEdgeIfNotExists(Id:              e.Label,
-                                                                                OutVertex:       SchemaGraph.VertexById(e.OutVertex.Label).AsMutable(),
-                                                                                Label:           EdgeLabel.IsConnectedWith,
-                                                                                InVertex:        SchemaGraph.VertexById(e.InVertex.Label).AsMutable(),
-                                                                                EdgeInitializer: Edge => Edge.SetAdd(GraphSchemaHandling.AlternativeUsage, e.OutVertex.Label.ToString() + " -> " + e.InVertex.Label.ToString()),
-                                                                                AnywayDo:        Edge => Edge.SetAdd(GraphSchemaHandling.AlternativeUsage, e.OutVertex.Label.ToString() + " -> " + e.InVertex.Label.ToString()));
+                Graph.OnVertexAddition.OnNotification +=
+                    (g, v) => SchemaGraph.AddVertexIfNotExists(Id:    v.Label,
+                                                               Label: VertexLabel.Vertex);
+
+                Graph.OnEdgeAddition.OnNotification   +=
+                    (g, e) => SchemaGraph.AddEdgeIfNotExists(Id:              e.Label,
+                                                             OutVertex:       SchemaGraph.VertexById(e.OutVertex.Label).AsMutable(),
+                                                             Label:           EdgeLabel.IsConnectedWith,
+                                                             InVertex:        SchemaGraph.VertexById(e.InVertex.Label).AsMutable(),
+                                                             EdgeInitializer: Edge => Edge.SetAdd(GraphSchemaHandling.AlternativeUsage, e.OutVertex.Label.ToString() + " -> " + e.InVertex.Label.ToString()),
+                                                             AnywayDo:        Edge => Edge.SetAdd(GraphSchemaHandling.AlternativeUsage, e.OutVertex.Label.ToString() + " -> " + e.InVertex.Label.ToString()));

                 #endregion


Mysql Long Text

Mysql Long Text

--- Src/Asp.Net/SqlSugar/Realization/MySql/DbBind/MySqlDbBind.cs
+++ Src/Asp.Net/SqlSugar/Realization/MySql/DbBind/MySqlDbBind.cs
@@ -38,6 +38,9 @@
                     new KeyValuePair<string, CSharpDataType>("text",CSharpDataType.@string),
                     new KeyValuePair<string, CSharpDataType>("char",CSharpDataType.@string),
                     new KeyValuePair<string, CSharpDataType>("enum",CSharpDataType.@string),
+                    new KeyValuePair<string, CSharpDataType>("mediumtext",CSharpDataType.@string),
+                    new KeyValuePair<string, CSharpDataType>("tinytext",CSharpDataType.@string),
+                    new KeyValuePair<string, CSharpDataType>("longtext",CSharpDataType.@string),

                     new KeyValuePair<string, CSharpDataType>("tinyint",CSharpDataType.@byte),
                     new KeyValuePair<string, CSharpDataType>("smallint",CSharpDataType.@short),


Fixed temperature generation for moons.

Fixed temperature generation for moons.

This also fixed a problem where only ice moons were generated.

--- Pulsar4X/Pulsar4X.Lib/SystemGen/SystemGen.cs
+++ Pulsar4X/Pulsar4X.Lib/SystemGen/SystemGen.cs
@@ -668,12 +668,11 @@
             if (planet.LengthOfDay < TimeSpan.FromHours(6))
                 planet.LengthOfDay += TimeSpan.FromHours(6);  // just a basic sainty check to make sure we dont end up with a planet rotating once every 3 minutes, It'd pull itself apart!!

-            // to calculate base temp see: http://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law
             // Note that base temp does not take into account albedo or atmosphere.
-            double starTemp = (star.Temperature + Constants.Units.DEGREES_C_TO_KELVIN); // we need to work in kelvin here.
-            double planetTemp = starTemp * Math.Sqrt(star.Radius / (2 * planet.Orbit.SemiMajorAxis));
-            planetTemp += Constants.Units.KELVIN_TO_DEGREES_C;  // convert back to degrees.
-            planet.BaseTemperature = (float)planetTemp;
+            if (IsMoon(planet.Type))
+                planet.BaseTemperature = (float)CalculateBaseTemperatureOfBody(star, parent.Orbit.SemiMajorAxis);
+            else
+                planet.BaseTemperature = (float)CalculateBaseTemperatureOfBody(star, planet.Orbit.SemiMajorAxis);

             // generate Plate techtonics
             if (m_RNG.Next(0,1) == 0)
@@ -1033,8 +1032,9 @@
             ///< @todo Get had coded numbers out of here... again...
             // now we need to work out the moon type
             // we will do this by looking at the base temp of the parent.
-            // if the base temp of the planet / 200K is  > 1 then it will always be terrestrial.
-            double tempRatio = (parent.BaseTemperature + Constants.Units.DEGREES_C_TO_KELVIN) / 200;
+            // if the base temp of the planet / 150K is  > 1 then it will always be terrestrial.
+            // i.e. a moon hotter then 150K will always by PlanetType.Moon.
+            double tempRatio = (parent.BaseTemperature + Constants.Units.DEGREES_C_TO_KELVIN) / 150;
             Planet.PlanetType pt = Planet.PlanetType.Moon;

             // esle if a random number is > tempRatio it will be an ice moon:
@@ -1443,6 +1443,20 @@
                                                                                // 0.3333333333 should be 1/3 but 1/3 gives radius of 0.999999 for any mass/density pair, so i used 0.3333333333
             return radius / 1000 / 100 / Constants.Units.KM_PER_AU;     // convert from cm to AU.
         }
+
+        /// <summary>
+        /// Calculates the temperature of a body given its parent star and its distance from that star.
+        /// @note For info on how the Temp. is calculated see: http://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law
+        /// </summary>
+        /// <param name="parentStar">The star this body is orbiting.</param>
+        /// <param name="distanceFromStar">the SemiMojorAxis of the body with regards to the star. (i.e. for moons it is the sma of its parent planet).</param>
+        /// <returns>Temperature in Degrees C</returns>
+        public static double CalculateBaseTemperatureOfBody(Star parentStar, double distanceFromStar)
+        {
+            double temp = (parentStar.Temperature + Constants.Units.DEGREES_C_TO_KELVIN); // we need to work in kelvin here.
+            temp = temp * Math.Sqrt(parentStar.Radius / (2 * distanceFromStar));
+            return temp + Constants.Units.KELVIN_TO_DEGREES_C;  // convert back to degrees.
+        }

         #endregion
     }


Fixed that string fields in PG Editor utility would initialize as blank. Now, they have default values.


Sort document types in the dropdown

Sort document types in the dropdown

--- R7.University/Controls/EditDocuments.ascx.cs
+++ R7.University/Controls/EditDocuments.ascx.cs
@@ -57,7 +57,7 @@
             var documentTypeViewModels = DocumentTypeViewModel.GetBindableList (documentTypes, ViewModelContext, true);
             ViewState ["documentTypes"] = XmlSerializationHelper.Serialize (documentTypeViewModels);

-            comboDocumentType.DataSource = documentTypeViewModels;
+            comboDocumentType.DataSource = documentTypeViewModels.OrderBy (dt => dt.LocalizedType);
             comboDocumentType.DataBind ();
         }

@@ -91,7 +91,6 @@
             datetimeDocumentStartDate.SelectedDate = item.StartDate;
             datetimeDocumentEndDate.SelectedDate = item.EndDate;
             urlDocumentUrl.Url = item.Url;
-            ;
         }

         protected override void OnUpdateItem (DocumentViewModel item)


Added route "api/photos/all" in photos controller.

--- Telerickr/Telerickr.Services/Controllers/PhotosController.cs
+++ Telerickr/Telerickr.Services/Controllers/PhotosController.cs
@@ -1,12 +1,11 @@
 namespace Telerickr.Services.Controllers
 {
+    using Data;
+    using Models.Photos;
     using System;
     using System.Linq;
     using System.Web.Http;
-
-    using Data;
     using Telerickr.Models;
-    using Models.Photos;

     public class PhotosController : ApiController
     {
@@ -42,6 +41,20 @@
             {
                 return this.NotFound();
             }
+
+            return this.Ok(result);
+        }
+
+        [Route("api/photos/all")]
+        public IHttpActionResult Get(int page, int pageSize = 10)
+        {
+            var result = this.photos
+                .All()
+                .OrderByDescending(p => p.UploadDate)
+                .Skip((page - 1) * pageSize)
+                .Take(pageSize)
+                .Select(PhotoResponseModel.FromModel)
+                .ToList();

             return this.Ok(result);
         }


Enhanced creation of account store in android of cs client

--- src/CSharpClient/Bit.CSharpClient.All/ViewModel/Extensions/IContainerRegistryExtensions.cs
+++ src/CSharpClient/Bit.CSharpClient.All/ViewModel/Extensions/IContainerRegistryExtensions.cs
@@ -40,7 +40,11 @@

             containerBuilder.RegisterType<DefaultSecurityService>().As<ISecurityService>().SingleInstance().PreserveExistingDefaults();

+#if Android
+            containerBuilder.Register(c => AccountStore.Create(c.Resolve<Android.Content.Context>(), c.Resolve<IClientAppProfile>().AppName)).SingleInstance().PreserveExistingDefaults();
+#else
             containerBuilder.Register(c => AccountStore.Create()).SingleInstance().PreserveExistingDefaults();
+#endif

             containerBuilder.Register((c, parameters) =>
             {


FIX tests for CI

FIX tests for CI

--- RDFSharp.Test/Model/RDFModelUtilitiesTest.cs
+++ RDFSharp.Test/Model/RDFModelUtilitiesTest.cs
@@ -283,8 +283,8 @@

             Assert.IsNotNull(result);
             Assert.IsTrue(result.ToList().TrueForAll(chr => !char.IsControl(chr)));
-            Assert.IsFalse(result.IndexOf("\0") == -1);
-            Assert.IsTrue(result.IndexOf("\\u0000") > -1);
+            Assert.IsFalse(result.Contains("\0"));
+            Assert.IsTrue(result.Contains("\\u0000"));
         }

         [DataTestMethod]
@@ -295,8 +295,8 @@

             Assert.IsNotNull(result);
             Assert.IsTrue(result.ToList().Any(chr => char.IsControl(chr)));
-            Assert.IsTrue(result.IndexOf('\n') > -1);
-            Assert.IsTrue(result.IndexOf('\u0009') == -1);
+            Assert.IsTrue(result.Contains("\n"));
+            Assert.IsFalse(result.Contains("\\u0009"));
         }

         [DataTestMethod]
@@ -1700,4 +1700,4 @@
         }
         #endregion
     }
-}+}


Add drill animation to root pages animation

--- TestAppUWP/Samples/RootNavigation/RootNavigationViewModel.cs
+++ TestAppUWP/Samples/RootNavigation/RootNavigationViewModel.cs
@@ -10,6 +10,8 @@
 using Windows.Storage;
 using Windows.UI.Core;
 using Windows.UI.Xaml;
+using Windows.UI.Xaml.Controls;
+using Windows.UI.Xaml.Media.Animation;

 namespace TestAppUWP.Samples.RootNavigation
 {
@@ -54,7 +56,13 @@

             ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;

-            RootFrame = new Windows.UI.Xaml.Controls.Frame();
+            RootFrame = new Frame
+            {
+                ContentTransitions = new TransitionCollection
+                {
+                    new NavigationThemeTransition {DefaultNavigationTransitionInfo = new DrillInNavigationTransitionInfo()}
+                }
+            };
             RootFrame.Navigated += (sender, args) =>
             {
                 Type pageType = args.SourcePageType;


Add unit test

Add unit test

--- TestProjectCoreUseFulFunctions/UnitTestFunctionsMathPrime.cs
+++ TestProjectCoreUseFulFunctions/UnitTestFunctionsMathPrime.cs
@@ -8,7 +8,7 @@
   {
     /*
   Liste des nombres premiers allant de 1 à 10000
-    13,
+
     17,
     19,
     23,
@@ -23,7 +23,7 @@
     [DataRow(5)]
     [DataRow(7)]
     [DataRow(11)]
-    [DataRow(11)]
+    [DataRow(13)]
     [DataRow(2819)]
     [DataRow(2833)]
     [DataRow(2837)]


Changed label names and help text

Changed label names and help text

--- src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/EmployerCommitments/SelectName.cshtml
+++ src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/EmployerCommitments/SelectName.cshtml
@@ -5,7 +5,7 @@

-
Create commitment

+
Create cohort

@@ -14,12 +14,12 @@

-                    Legal entity
+                    Employer
                     @Model.Data.LegalEntityName

-                    Provider
+                    Training provider
                     @Model.Data.ProviderName

@@ -27,8 +27,8 @@

         <form method="POST" action="@Url.Action("CreateCommitment")">

-                Name
-
Give this commitment a name, for example a code or reference - your training provider will see this.

+                Cohort name
+
Give your cohort a name to help you to identify it, for example 'September cohort' or 'Coventry apprentices' - your training provider will see this.

                     <input class="form-control form-control-3-4" id="Name" name="Name" type="text"
                        aria-required="true" />


Dispose not being called when stopping service

Found a bug where the host instance variable inside of the
RhinoServiceBusHost was never being set anymore.  This was resulting in
dispose not being called when the service was stopped.

It looks like this was introduced in commit cafe6758c05368607738226012bf7752dcb1bc06

--- Rhino.ServiceBus.Host/RhinoServiceBusHost.cs
+++ Rhino.ServiceBus.Host/RhinoServiceBusHost.cs
@@ -31,26 +31,24 @@

         protected override void OnStart(string[] ignored)
         {
-            RemoteAppDomainHost remoteAppDomainHost;
-
             if (string.IsNullOrEmpty(bootStrapper) == false)
             {
                 var assembly = LoadAssembly();
                 var bootStrapperType = LoadBootStrapperType(assembly);
-                remoteAppDomainHost = new RemoteAppDomainHost(bootStrapperType);
-                remoteAppDomainHost.Configuration(cfg);
+                host = new RemoteAppDomainHost(bootStrapperType);
+                host.Configuration(cfg);
             }
             else
             {
-                remoteAppDomainHost = new RemoteAppDomainHost(asm, cfg);
+                host = new RemoteAppDomainHost(asm, cfg);
             }

             if (string.IsNullOrEmpty(hostType) == false)
             {
-                remoteAppDomainHost.SetHostType(hostType);
+                host.SetHostType(hostType);
             }

-            remoteAppDomainHost.Start();
+            host.Start();
         }

         private Assembly LoadAssembly()