Make Catch<T> return type T

Make Catch<T> return type T

--HG--
extra : convert_revision : charlie%40nunit.com-20090918192533-n81a8ont3vfkkkdb

--- src/framework/Shared/Framework/Assert.cs
+++ src/framework/Shared/Framework/Assert.cs
@@ -714,9 +714,9 @@
         /// <param name="code">A TestDelegate</param>
         /// <param name="message">The message that will be displayed on failure</param>
         /// <param name="args">Arguments to be used in formatting the message</param>
-        public static Exception Catch<T>(TestDelegate code, string message, params object[] args)
-        {
-            return Throws(new InstanceOfTypeConstraint(typeof(T)), code, message, args);
+        public static T Catch<T>(TestDelegate code, string message, params object[] args) where T : System.Exception
+        {
+            return (T)Throws(new InstanceOfTypeConstraint(typeof(T)), code, message, args);
         }

         /// <summary>
@@ -725,9 +725,9 @@
         /// </summary>
         /// <param name="code">A TestDelegate</param>
         /// <param name="message">The message that will be displayed on failure</param>
-        public static Exception Catch<T>(TestDelegate code, string message)
-        {
-            return Throws(new InstanceOfTypeConstraint(typeof(T)), code, message);
+        public static T Catch<T>(TestDelegate code, string message) where T : System.Exception
+        {
+            return (T)Throws(new InstanceOfTypeConstraint(typeof(T)), code, message);
         }

         /// <summary>
@@ -735,9 +735,9 @@
         /// or one derived from it when called and returns it.
         /// </summary>
         /// <param name="code">A TestDelegate</param>
-        public static Exception Catch<T>(TestDelegate code)
-        {
-            return Throws(new InstanceOfTypeConstraint(typeof(T)), code);
+        public static T Catch<T>(TestDelegate code) where T : System.Exception
+        {
+            return (T)Throws(new InstanceOfTypeConstraint(typeof(T)), code);
         }
 #endif
         #endregion


add zz for recenter

add zz for recenter

--- JustEnoughVi/NormalMode.cs
+++ JustEnoughVi/NormalMode.cs
@@ -37,6 +37,7 @@
             KeyMap.Add("x", DeleteCharacter);
             KeyMap.Add("y", Yank);
             KeyMap.Add("Y", YankLine);
+            KeyMap.Add("z", Recenter);
             KeyMap.Add("/", Search);
             KeyMap.Add("<", IndentRemove);
             KeyMap.Add(">", IndentAdd);
@@ -221,19 +222,19 @@

             if (args[0] == 'd')
             {
-                MonoDevelop.Ide.IdeApp.CommandService.DispatchCommand("MonoDevelop.Refactoring.RefactoryCommands.GotoDeclaration");
+                Dispatch("MonoDevelop.Refactoring.RefactoryCommands.GotoDeclaration");
                 return true;
             }

             if (args[0] == 't')
             {
-                MonoDevelop.Ide.IdeApp.CommandService.DispatchCommand(MonoDevelop.Ide.Commands.WindowCommands.NextDocument);
+                Dispatch(MonoDevelop.Ide.Commands.WindowCommands.NextDocument);
                 return true;
             }

             if (args[0] == 'T')
             {
-                MonoDevelop.Ide.IdeApp.CommandService.DispatchCommand(MonoDevelop.Ide.Commands.WindowCommands.PrevDocument);
+                Dispatch(MonoDevelop.Ide.Commands.WindowCommands.PrevDocument);
                 return true;
             }

@@ -420,7 +421,7 @@

         private bool Search(int count, char[] args)
         {
-            MonoDevelop.Ide.IdeApp.CommandService.DispatchCommand(MonoDevelop.Ide.Commands.SearchCommands.Find);
+            Dispatch(MonoDevelop.Ide.Commands.SearchCommands.Find);
             return true;
         }

@@ -513,10 +514,26 @@
             return true;
         }

+        private bool Recenter(int count, char[] args)
+        {
+            if (args.Length == 0)
+                return false;
+
+            if (args[0] == 'z')
+                Dispatch(MonoDevelop.Ide.Commands.TextEditorCommands.RecenterEditor);
+
+            return true;
+        }
+
         private bool MatchingBrace(int count, char[] args)
         {
             MiscActions.GotoMatchingBracket(Editor);
             return true;
+        }
+
+        private bool Dispatch(object command)
+        {
+            return MonoDevelop.Ide.IdeApp.CommandService.DispatchCommand(command);
         }

         #region implemented abstract members of ViMode


Adds enumeration to Filter and Where tests.

--- ShittyLinqTests/FilterAndWhereTests.cs
+++ ShittyLinqTests/FilterAndWhereTests.cs
@@ -63,6 +63,7 @@
             int[] numbers = new int[] { 1, 2, 3, 4, 5 };

             IEnumerable<int> result = numbers.Filter(null);
+            foreach(var num in result) { }
         }

         [TestMethod]
@@ -81,6 +82,7 @@
             int[] numbers = null;

             IEnumerable<int> result = numbers.Filter(x => x % 2 == 1);
+            foreach (var num in result) { }
         }

         [TestMethod]


- v10.1.6

- v10.1.6

--- Shuttle.Esb/Properties/AssemblyInfo.cs
+++ Shuttle.Esb/Properties/AssemblyInfo.cs
@@ -13,10 +13,10 @@
 [assembly: AssemblyTitle(".NET Standard 2.0")]
 #endif

-[assembly: AssemblyVersion("10.1.5.0")]
+[assembly: AssemblyVersion("10.1.6.0")]
 [assembly: AssemblyCopyright("Copyright © Eben Roux 2018")]
 [assembly: AssemblyProduct("Shuttle.Esb")]
 [assembly: AssemblyCompany("Shuttle")]
 [assembly: AssemblyConfiguration("Release")]
-[assembly: AssemblyInformationalVersion("10.1.5")]
+[assembly: AssemblyInformationalVersion("10.1.6")]
 [assembly: ComVisible(false)]


Treat void response as null. Do not throw JsonRpcContractException for this case. Though it's not standard.

--- JsonRpc.Standard/Client/JsonRpcProxyBase.cs
+++ JsonRpc.Standard/Client/JsonRpcProxyBase.cs
@@ -74,10 +74,13 @@
                 }
                 if (method.ReturnParameter.ParameterType != typeof(void))
                 {
-                    if (response.Result == null)
-                        throw new JsonRpcContractException(
-                            $"Expect \"{method.ReturnParameter.ParameterType}\" result, got void.",
-                            message);
+                    // VSCode will return void for null in `window/showMessageRequest`.
+                    // I mean, https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md#window_showMessageRequest
+                    // So just don't be picky…
+                    //if (response.Result == null)
+                    //    throw new JsonRpcContractException(
+                    //        $"Expect \"{method.ReturnParameter.ParameterType}\" result, got void.",
+                    //        message);
                     try
                     {
                         return (TResult) method.ReturnParameter.Converter.JsonToValue(response.Result, typeof(TResult));


* Added UnixTimeSinceEpoch() function to Util class (god knows how many times we have reimplemented this.)

--- OpenSim.Framework/Util.cs
+++ OpenSim.Framework/Util.cs
@@ -34,6 +34,13 @@
                 nextXferID++;
             }
             return id;
+        }
+
+        public static int UnixTimeSinceEpoch()
+        {
+            TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
+            int timestamp = (int)t.TotalSeconds;
+            return timestamp;
         }

         //public static int fast_distance2d(int x, int y)


Fixed borkness with previous merge.

Fixed borkness with previous merge.

--- OpenSim/Framework/Util.cs
+++ OpenSim/Framework/Util.cs
@@ -2004,26 +2004,14 @@
             // in the agent circuit data for foreigners
             if (lastName.Contains("@"))
             {
-                string agentsURI = acircuit.ServiceURLs["HomeURI"].ToString();
-                if (!agentsURI.EndsWith("/"))
-                    agentsURI += "/";
                 string[] parts = firstName.Split(new char[] { '.' });
                 if (parts.Length == 2)
                     return id.ToString() + ";" + agentsURI + ";" + parts[0] + " " + parts[1];
             }
             return id.ToString() + ";" + agentsURI + ";" + firstName + " " + lastName;
-
-        }
-
-                // This is ugly, but there's no other way, given that the name is changed
-                // in the agent circuit data for foreigners
-                if (acircuit.lastname.Contains("@"))
-                {
-                    string[] parts = acircuit.firstname.Split(new char[] { '.' });
-                    if (parts.Length == 2)
-                        return acircuit.AgentID.ToString() + ";" + agentsURI + ";" + parts[0] + " " + parts[1];
-                }
-                return acircuit.AgentID.ToString() + ";" + agentsURI + ";" + acircuit.firstname + " " + acircuit.lastname;
+
+        }
+
         /// <summary>
         /// Produces a universal (HG) user-facing name given the information
         /// </summary>
@@ -2038,9 +2026,6 @@
             {
                 uri = new Uri(homeURI);
             }
-            else
-                return acircuit.AgentID.ToString();
-        }
             catch (UriFormatException)
             {
                 return firstName + " " + lastName;


precision is hard

precision is hard


Rockridge Do not choke on directory entries that have no system use data just because RR extensions are present in the volume.

--- Library/DiscUtils.Iso9660/ReaderDirEntry.cs
+++ Library/DiscUtils.Iso9660/ReaderDirEntry.cs
@@ -41,12 +41,14 @@
             _record = dirRecord;
             _fileName = _record.FileIdentifier;

+            bool rockRidge = !string.IsNullOrEmpty(_context.RockRidgeIdentifier);
+
             if (context.SuspDetected && _record.SystemUseData != null)
             {
                 SuspRecords = new SuspRecords(_context, _record.SystemUseData, 0);
             }

-            if (!string.IsNullOrEmpty(_context.RockRidgeIdentifier))
+            if (rockRidge && SuspRecords != null)
             {
                 // The full name is taken from this record, even if it's a child-link record
                 List<SystemUseEntry> nameEntries = SuspRecords.GetEntries(_context.RockRidgeIdentifier, "NM");
@@ -83,24 +85,27 @@
             LastWriteTimeUtc = _record.RecordingDateAndTime;
             CreationTimeUtc = _record.RecordingDateAndTime;

-            if (!string.IsNullOrEmpty(_context.RockRidgeIdentifier))
+            if (rockRidge && SuspRecords != null)
             {
                 FileTimeSystemUseEntry tfEntry =
                     SuspRecords.GetEntry<FileTimeSystemUseEntry>(_context.RockRidgeIdentifier, "TF");

-                if ((tfEntry.TimestampsPresent & FileTimeSystemUseEntry.Timestamps.Access) != 0)
+                if (tfEntry != null)
                 {
-                    LastAccessTimeUtc = tfEntry.AccessTime;
-                }
+                    if ((tfEntry.TimestampsPresent & FileTimeSystemUseEntry.Timestamps.Access) != 0)
+                    {
+                        LastAccessTimeUtc = tfEntry.AccessTime;
+                    }

-                if ((tfEntry.TimestampsPresent & FileTimeSystemUseEntry.Timestamps.Modify) != 0)
-                {
-                    LastWriteTimeUtc = tfEntry.ModifyTime;
-                }
+                    if ((tfEntry.TimestampsPresent & FileTimeSystemUseEntry.Timestamps.Modify) != 0)
+                    {
+                        LastWriteTimeUtc = tfEntry.ModifyTime;
+                    }

-                if ((tfEntry.TimestampsPresent & FileTimeSystemUseEntry.Timestamps.Creation) != 0)
-                {
-                    CreationTimeUtc = tfEntry.CreationTime;
+                    if ((tfEntry.TimestampsPresent & FileTimeSystemUseEntry.Timestamps.Creation) != 0)
+                    {
+                        CreationTimeUtc = tfEntry.CreationTime;
+                    }
                 }
             }
         }


custom TabContainer.CssClass is appended to built-in class instead of replace

--- AjaxControlToolkit/Tabs/TabContainer.cs
+++ AjaxControlToolkit/Tabs/TabContainer.cs
@@ -35,6 +35,7 @@
         bool _useVerticalStripPlacement;
         Unit _verticalStripWidth = new Unit(120, UnitType.Pixel);
         bool _onDemand;
+        string _cssTheme = "ajax__tab_xp";

         public TabContainer()
             : base(true, HtmlTextWriterTag.Div) {
@@ -199,15 +200,22 @@

         /// <summary>
         /// The CSS class override used to define custom look and feel for tabs
-        /// </summary>
-        /// <remarks>
-        /// See the Tabs Theming section for more details
-        /// </remarks>
-        [DefaultValue("ajax__tab_xp")]
+        /// </summary>
+        [DefaultValue("")]
         [Category("Appearance")]
         public override string CssClass {
             get { return base.CssClass; }
             set { base.CssClass = value; }
+        }
+
+        /// <summary>
+        /// The CSS theme to pick from built-in CSS file
+        /// </summary>
+        [DefaultValue("ajax__tab_xp")]
+        [Category("Appearance")]
+        public string CssTheme {
+            get { return _cssTheme; }
+            set { _cssTheme = value; }
         }

         /// <summary>
@@ -351,8 +359,12 @@

         protected override Style CreateControlStyle() {
             var style = new TabContainerStyle(ViewState);
-            style.CssClass = String.IsNullOrEmpty(CssClass) ? "ajax__tab_xp" : CssClass;
+            style.CssClass = MergeWithTheme(CssClass);
             return style;
+        }
+
+        private string MergeWithTheme(string customCssClass) {
+            return String.Join(" ", customCssClass, _cssTheme);
         }

         int GetServerActiveTabIndex(int clientActiveTabIndex) {
@@ -427,8 +439,8 @@

         protected override void AddAttributesToRender(HtmlTextWriter writer) {
             Style.Remove(HtmlTextWriterStyle.Visibility);
-            if(!ControlStyleCreated)
-                writer.AddAttribute(HtmlTextWriterAttribute.Class, String.IsNullOrEmpty(CssClass) ? "ajax__tab_xp" : CssClass);
+
+            writer.AddAttribute(HtmlTextWriterAttribute.Class, MergeWithTheme(CssClass));

             if(_useVerticalStripPlacement)
                 writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "block");


versioning

versioning

--- Ds3Igt/Config.cs
+++ Ds3Igt/Config.cs
@@ -1,6 +1,6 @@
 namespace Ds3Igt {
     public static class Config {
-        public static string Version = "1.3.5";
+        public static string Version = "1.3.6";
         public static string Module = "DarkSoulsIII";
         public static long BasePointer1310 = 0x14469ADF8;
         public static int[] Offsets1310 = { 0x9C };
@@ -28,4 +28,4 @@
         public static int[] Offsets11200 = { 0xA4 };

     }
-}+}


Fixed double semicolon

Fixed double semicolon

--- AngleSharp/Parser/Html/HtmlTokenizer.cs
+++ AngleSharp/Parser/Html/HtmlTokenizer.cs
@@ -1314,7 +1314,7 @@
                 {
                     doctype.PublicIdentifier = _stringBuffer.ToString();
                     _stringBuffer.Clear();
-                    return DoctypePublicIdentifierAfter(doctype); ;
+                    return DoctypePublicIdentifierAfter(doctype);
                 }
                 else if (c == Specification.Null)
                 {


Added logging middleware.

Added logging middleware.

--- OwinSelfHosted/Program.cs
+++ OwinSelfHosted/Program.cs
@@ -6,9 +6,12 @@
 using System.Text;
 using System.Threading.Tasks;
 using System.IO;
+using Microsoft.Owin;

 namespace OwinSelfHosted
 {
+    using AppFunc = Func<IDictionary<string, object>, Task>;
+
     class Program
     {
         static void Main(string[] args)
@@ -29,7 +32,21 @@

         static void Startup(IAppBuilder app)
         {
+            app.Use(new Func<AppFunc, AppFunc>(LoggingMiddleware));
+
             app.Use(typeof(StartPageMiddleware));
+        }
+
+        static AppFunc LoggingMiddleware(AppFunc next)
+        {
+            return async environment =>
+                {
+                    Console.WriteLine("Receiving request for \"{0}\"", environment["owin.RequestPath"]);
+
+                    await next.Invoke(environment);
+
+                    Console.WriteLine("Returning with status {0}", environment["owin.ResponseStatusCode"]);
+                };
         }
     }
 }


Cosmetics

Cosmetics

--- AngleSharp/Parser/Html/HtmlTokenizer.cs
+++ AngleSharp/Parser/Html/HtmlTokenizer.cs
@@ -633,11 +633,13 @@
                 RaiseErrorOccurred(HtmlParseError.BogusComment);
                 return BogusComment(c);
             }
-
-            _state = HtmlParseMode.PCData;
-            RaiseErrorOccurred(HtmlParseError.AmbiguousOpenTag);
-            _textBuffer.Append(Symbols.LessThan);
-            return DataText(c);
+            else
+            {
+                _state = HtmlParseMode.PCData;
+                RaiseErrorOccurred(HtmlParseError.AmbiguousOpenTag);
+                _textBuffer.Append(Symbols.LessThan);
+                return DataText(c);
+            }
         }

         /// <summary>
@@ -648,15 +650,13 @@
         {
             if (c.IsLowercaseAscii())
             {
-                var tag = NewTagClose();
                 _stringBuffer.Clear().Append(c);
-                return TagName(tag);
+                return TagName(NewTagClose());
             }
             else if (c.IsUppercaseAscii())
             {
-                var tag = NewTagClose();
                 _stringBuffer.Clear().Append(Char.ToLower(c));
-                return TagName(tag);
+                return TagName(NewTagClose());
             }
             else if (c == Symbols.GreaterThan)
             {
@@ -895,8 +895,7 @@
                         break;
                     case Symbols.Null:
                         RaiseErrorOccurred(HtmlParseError.Null);
-                        c = Symbols.Replacement;
-                        _stringBuffer.Append(c);
+                        _stringBuffer.Append(Symbols.Replacement);
                         continue;
                     default:
                         _stringBuffer.Append(c);
@@ -1020,9 +1019,11 @@
                 Back();
                 return NewDoctype(true);
             }
-
-            RaiseErrorOccurred(HtmlParseError.DoctypeUnexpected);
-            return DoctypeNameBefore(c);
+            else
+            {
+                RaiseErrorOccurred(HtmlParseError.DoctypeUnexpected);
+                return DoctypeNameBefore(c);
+            }
         }

         /// <summary>


Updated attributes and some parameters in IShellWindows

--- PInvoke/Shell32/ExDisp.cs
+++ PInvoke/Shell32/ExDisp.cs
@@ -2402,7 +2402,7 @@
 		/// </remarks>
 		// https://docs.microsoft.com/en-us/windows/desktop/api/exdisp/nn-exdisp-ishellwindows
 		[PInvokeData("exdisp.h", MSDNShortId = "e609c8b6-2b2e-4188-894c-5c85960206ea")]
-		[ComImport, Guid("85CB6900-4D95-11CF-960C-0080C7F4EE85"), CoClass(typeof(ShellWindows))]
+		[ComImport, Guid("85CB6900-4D95-11CF-960C-0080C7F4EE85"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch), CoClass(typeof(ShellWindows))]
 		public interface IShellWindows
 		{
 			/// Gets the number of windows in the Shell windows collection.
@@ -2444,7 +2444,7 @@
 			/// <param name="swClass">A member of ShellWindowTypeConstants that specifies the type of window.</param>
 			/// <returns>The window's cookie.</returns>
 			[DispId(0x60020004)]
-			int RegisterPending([In] int lThreadId, [In, MarshalAs(UnmanagedType.Struct)] ref object pvarloc, [In, MarshalAs(UnmanagedType.Struct)] ref object pvarlocRoot, [In] ShellWindowTypeConstants swClass);
+			int RegisterPending([In] int lThreadId, [In, MarshalAs(UnmanagedType.Struct)] in object pvarloc, [In, MarshalAs(UnmanagedType.Struct)] in object pvarlocRoot, [In] ShellWindowTypeConstants swClass);

 			/// Revokes a Shell window's registration and removes the window from the Shell windows collection.
 			/// <param name="lCookie">The cookie that identifies the window to un-register.</param>
@@ -2478,7 +2478,7 @@
 			/// <returns>A reference to the window's IDispatch interface, or NULL if no such window was found.</returns>
 			[return: MarshalAs(UnmanagedType.IDispatch)]
 			[DispId(0x60020008)]
-			object FindWindowSW([In, MarshalAs(UnmanagedType.Struct)] ref object pvarloc, [In, MarshalAs(UnmanagedType.Struct)] ref object pvarlocRoot, [In] ShellWindowTypeConstants swClass, out int pHWND, [In] ShellWindowFindWindowOptions swfwOptions);
+			object FindWindowSW([In, MarshalAs(UnmanagedType.Struct)] in object pvarloc, [In, MarshalAs(UnmanagedType.Struct)] in object pvarlocRoot, [In] ShellWindowTypeConstants swClass, out int pHWND, [In] ShellWindowFindWindowOptions swfwOptions);

 			/// Occurs when a new Shell window is created for a frame.
 			/// <param name="lCookie">The cookie that identifies the window.</param>


one small fix to help when you go from zoom to pan

--- PMKS_Web/MainPage.xaml.cs
+++ PMKS_Web/MainPage.xaml.cs
@@ -489,11 +489,11 @@
                 : mainViewer.ScaleFactor / 1.05;

             double delta = mainViewer.ScaleFactor - newScaleFactor;
-            ScreenStartPoint = e.GetPosition(mainViewer.MainCanvas);
-             var oldTx = ((CompositeTransform)mainViewer.MainCanvas.RenderTransform).TranslateX;
+            var center = e.GetPosition(mainViewer.MainCanvas);
+            var oldTx = ((CompositeTransform)mainViewer.MainCanvas.RenderTransform).TranslateX;
             var oldTy = ((CompositeTransform)mainViewer.MainCanvas.RenderTransform).TranslateY;
-            mainViewer.MoveScaleCanvas(newScaleFactor, new Point(delta * ScreenStartPoint.X +oldTx,
-                      delta * ScreenStartPoint.Y+oldTy));
+            mainViewer.MoveScaleCanvas(newScaleFactor, new Point(delta * center.X + oldTx,
+                      delta * center.Y + oldTy));
         }

         internal void MouseUpStopPanning(object sender, MouseEventArgs e)
@@ -510,7 +510,7 @@
             var oldTx = ((CompositeTransform)mainViewer.MainCanvas.RenderTransform).TranslateX;
             var oldTy = ((CompositeTransform)mainViewer.MainCanvas.RenderTransform).TranslateY;
             ScreenStartPoint.X -= oldTx;
-            ScreenStartPoint.Y -= oldTy;
+            ScreenStartPoint.Y += oldTy;
         }


async

async

--- Plastic/PlasticContext.cs
+++ Plastic/PlasticContext.cs
@@ -109,7 +109,7 @@

             if (expression != null)
             {
-                return expression.Eval(this);
+                return await expression.Eval(this);
             }

             if (array != null)


Cleanup,

Cleanup,

--- Mathtone.MIST.Builder/NotificationWeaver.cs
+++ Mathtone.MIST.Builder/NotificationWeaver.cs
@@ -336,13 +336,9 @@
 				}

 				//Insert IL instructions before end of method body
-
 				//what I really need to do here is find all return statements in the method and raise notification there, this is a little more complicated.
-				//var insertionPoint = methodBody.Instructions[methodBody.Instructions.Count - 1];
+				//...Also any statements that branch to them and make correction.
 				var returnPoints = methodBody.Instructions.Where(a => a.OpCode == OpCodes.Ret).ToArray();
-
-				//InsertBefore(msil, beginInstructions, begin);
-
 				foreach (var instruction in returnPoints) {

 					InsertBefore(msil, endInstructions, instruction);
@@ -351,12 +347,8 @@
 					foreach (var b in branches) {
 						b.Operand = branchTarget;
 					}
-					;
-					//foreach(var branchInstruction in methodBody.Instructions.Where(a=>a.OpCode == OpCodes.Br && a.))
-				}
-
-
-				//InsertBefore(msil, endInstructions, insertionPoint);
+				}
+
 			}
 		}


minor

minor

--- MbCache.ProxyImpl.LinFu/CacheInterceptor.cs
+++ MbCache.ProxyImpl.LinFu/CacheInterceptor.cs
@@ -68,12 +68,12 @@
 			var method = info.TargetMethod;
 			var arguments = info.Arguments;
 			var key = _cacheKey.Key(_type, _cachingComponent, method, arguments);
-			var getInfo = new EventInformation(key, _type, method, arguments);
+			var eventInformation = new EventInformation(key, _type, method, arguments);
 			if (key == null)
 			{
 				return callOriginalMethod(info);
 			}
-			var cachedValue = _cache.Get(getInfo);
+			var cachedValue = _cache.Get(eventInformation);
 			if (cachedValue != null)
 			{
 				return cachedValue;
@@ -85,16 +85,16 @@
 			}
 			lock (lockObject)
 			{
-				var cachedValue2 = _cache.Get(getInfo);
+				var cachedValue2 = _cache.Get(eventInformation);
 				return cachedValue2 ?? executeAndPutInCache(info, key);
 			}
 		}

 		private object executeAndPutInCache(InvocationInfo info, string key)
 		{
-			var putInfo = new EventInformation(key, _type, info.TargetMethod, info.Arguments);
+			var eventInformation = new EventInformation(key, _type, info.TargetMethod, info.Arguments);
 			var retVal = callOriginalMethod(info);
-			_cache.Put(putInfo, retVal);
+			_cache.Put(eventInformation, retVal);
 			return retVal;
 		}


Fix read issue with GetContentFolder (#2980)

--- Source/ACE.Server/Program_DbUpdates.cs
+++ Source/ACE.Server/Program_DbUpdates.cs
@@ -132,7 +132,18 @@
             sqlConnect.Open();
             var sqlReader = sqlCommand.ExecuteReader();

-            var content_folder = sqlReader.HasRows ? sqlReader.GetString(0) : @".\Content";
+            var content_folder = "";
+
+            if (sqlReader.HasRows)
+            {
+                while (sqlReader.Read())
+                {
+                    content_folder = sqlReader.GetString(0);
+                    break;
+                }
+            }
+            else
+                content_folder = @".\Content";

             sqlReader.Close();
             sqlCommand.Connection.Close();


(GH-823) Update Cake.Figlet reference from 2.0.0 to 2.0.1

--- Source/Cake.Recipe/Content/addins.cake
+++ Source/Cake.Recipe/Content/addins.cake
@@ -11,7 +11,7 @@
 #addin nuget:?package=MimeTypesMap&version=1.0.8
 #addin nuget:?package=Cake.Email.Common&version=0.4.2
 #addin nuget:?package=Cake.Email&version=1.0.2
-#addin nuget:?package=Cake.Figlet&version=2.0.0
+#addin nuget:?package=Cake.Figlet&version=2.0.1
 #addin nuget:?package=Cake.Gitter&version=1.0.2
 #addin nuget:?package=Cake.Incubator&version=6.0.0
 #addin nuget:?package=Cake.Kudu&version=1.0.1


Remove comment

Remove comment

--- samples/dependadotnet/Program.cs
+++ samples/dependadotnet/Program.cs
@@ -37,8 +37,6 @@
   open-pull-requests-limit: 5
 */

-
-// will change this location in a subsequent update
 string packagesJsonUrl = "https://raw.githubusercontent.com/dotnet/core/b5ca8283def279b20eced6c0b14c4634659cd6eb/samples/dependadotnet/package-ignore.json";
 Dictionary<string, string[]> packageIgnore = await GetPackagesInfo(packagesJsonUrl);
 string validPackageReference = @"PackageReference.*Version=""[0-9]";


fix replacing stock contracts app, resize window

--- contractScenario.cs
+++ contractScenario.cs
@@ -300,9 +300,7 @@
 			{
 				appLauncherButton = gameObject.AddComponent<contractStockToolbar>();
 				if (blizzyToolbarButton != null)
-					Destroy(blizzyToolbarButton);
-				if (replaceStockToolbar)
-					appLauncherButton.replaceStockApp();
+						Destroy(blizzyToolbarButton);
 			}
 			else if (ToolbarManager.ToolbarAvailable && !stockToolbar)
 			{
@@ -892,7 +890,7 @@
 			if (windowMode[i] == 0)
 				windowPos[(i * 4) + 2] = (int)source.width - (windowSize * 30);
 			else
-				windowPos[(i * 4) + 2] = (int)source.width - (windowSize * 60);
+				windowPos[(i * 4) + 2] = (int)source.width - (windowSize * 100);
 			windowPos[(i * 4) + 3] = (int)source.height;
 		}

@@ -903,7 +901,7 @@
 			if (windowMode[i] == 0)
 				windowRects[i].width += (windowSize * 30);
 			else
-				windowRects[i].width += (windowSize * 60);
+				windowRects[i].width += (windowSize * 100);
 		}

 		#endregion


- PureModuleBuilder emits publically accessible stub for global functions (since global func can be only accessed within its assembly)
- ArgFull MethodInfo available!

Originally checked in by DEVSENSE\Jakub on 2012-02-03 18:36:32.06 as Changeset 2384

git-tfs-id: [https://devsense.visualstudio.com/DefaultCollection]$/Phalanger/Main;C6452

--- Source/Core/Emit/ModuleBuilders.CLR.cs
+++ Source/Core/Emit/ModuleBuilders.CLR.cs
@@ -93,6 +93,7 @@
 			PureCompilationUnit unit = this.PureCompilationUnit;
 			ILEmitter il = new ILEmitter(declareHelperBuilder);
 			IndexedPlace app_context_place = new IndexedPlace(PlaceHolder.Argument, 0);
+            TypeBuilder publicsContainer = null;    // container type for public stubs of global declarations (which are inaccessible from other assemblies)

 			foreach (PhpFunction function in unit.GetDeclaredFunctions())
 			{
@@ -112,10 +113,15 @@
 					il.LdcI4((int)function.MemberDesc.MemberAttributes);

                     // LOAD <argfull>
-                    if (function.ArgFullInfo != null && function.ArgFullInfo.DeclaringType != null)
-                        CodeGenerator.EmitLoadMethodInfo(il, function.ArgFullInfo/*, AssemblyBuilder.DelegateBuilder*/);
+                    if (function.ArgFullInfo != null)
+                        CodeGenerator.EmitLoadMethodInfo(
+                            il,
+                            (function.ArgFullInfo.DeclaringType != null)
+                                ? function.ArgFullInfo
+                                : EmitPhpFunctionPublicStub(ref publicsContainer, function) // function.ArgFullInfo is real global method not accessible from other assemblies, must be wrapped
+                            /*, AssemblyBuilder.DelegateBuilder*/);
                     else
-                        il.Emit(OpCodes.Ldnull); // TODO: argfull is real global method, cannot be called from different module; emit public stub that can be called
+                        il.Emit(OpCodes.Ldnull);

 					// CALL <application context>.DeclareFunction(<stub>, <name>, <member attributes>, <argfull>)
 					il.Emit(OpCodes.Call, Methods.ApplicationContext.DeclareFunction);
@@ -147,7 +153,55 @@
 			}

 			il.Emit(OpCodes.Ret);
-		}
+
+            // complete the publicsContainer type, if created:
+            if (publicsContainer != null)
+                publicsContainer.CreateType();
+		}
+
+        /// <summary>
+        /// Emit publically accessible stub that just calls argfull of <paramref name="function"/>.
+        /// </summary>
+        /// <returns><see cref="MethodInfo"/> of newly created function stub.</returns>
+        private MethodInfo/*!*/EmitPhpFunctionPublicStub(ref TypeBuilder publicsContainer, PhpFunction/*!*/function)
+        {
+            Debug.Assert(function != null);
+            Debug.Assert(function.ArgFullInfo != null, "!function.ArgFullInfo");
+
+            if (publicsContainer == null)
+            {
+                publicsContainer = PureAssemblyBuilder.RealModuleBuilder.DefineType(
+                    string.Format("{1}<{0}>",
+                        StringUtils.ToClsCompliantIdentifier(Path.ChangeExtension(PureAssemblyBuilder.FileName, "")),
+                        QualifiedName.Global.ToString()),
+                    TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class | TypeAttributes.SpecialName);
+            }
+
+            Type returnType;
+            var parameterTypes = function.Signature.ToArgfullSignature(1, out returnType);
+            parameterTypes[0] = Types.ScriptContext[0];
+
+            var mi = publicsContainer.DefineMethod(function.GetFullName(), MethodAttributes.Public | MethodAttributes.Static, returnType, parameterTypes);
+            var il = new ILEmitter(mi);
+
+            // load arguments
+            for (int i = 0; i < parameterTypes.Length; i++)
+            {
+                if (function.Builder != null)
+                    mi.DefineParameter(i + 1, ParameterAttributes.None, function.Builder.ParameterBuilders[i].Name);
+
+                il.Ldarg(i);
+            }
+
+            // call function.ArgFullInfo
+            il.Emit(OpCodes.Call, function.ArgFullInfo);
+
+            // .ret
+            il.Emit(OpCodes.Ret);
+
+            //
+            return mi;
+        }

         #endregion
 	}


webapi route registration

webapi route registration

--- MvcCodeRouting/Api/CodeRoutingExtensions.cs
+++ MvcCodeRouting/Api/CodeRoutingExtensions.cs
@@ -18,6 +18,8 @@
 using System.Globalization;
 using System.Linq;
 using System.Web;
+using System.Web.Http;
+using System.Web.Http.Routing;
 using System.Web.Mvc;
 using System.Web.Routing;

@@ -97,7 +99,7 @@
                webRoutes.Add(webRoute);
                routes.Add(webRoute);
             } else {
-               // TODO:
+               webRoutes.Add(RegisterHttpRoute(routes, route));
             }
          }

@@ -108,6 +110,13 @@
          }

          return webRoutes;
+      }
+
+      static Route RegisterHttpRoute(RouteCollection routes, object route) {
+
+         GlobalConfiguration.Configuration.Routes.Add(null, (IHttpRoute)route);
+
+         return (Route)RouteTable.Routes.Last();
       }

       /// <summary>


updated User model with collections of ShortStories, Ratings and Comments(one-to-many relationship)

--- Source/Data/SciHub.Data.Models/User.cs
+++ Source/Data/SciHub.Data.Models/User.cs
@@ -1,18 +1,53 @@
 namespace SciHub.Data.Models
 {
     using System;
+    using System.Collections.Generic;
     using System.ComponentModel.DataAnnotations;
     using System.Security.Claims;
     using System.Threading.Tasks;
     using Data.Common.Models;
+    using Book;
     using Enumerators;
     using Microsoft.AspNet.Identity;
     using Microsoft.AspNet.Identity.EntityFramework;
+    using Movie;
     using SciHub.Common.Constants;
     using SciHub.Common.Constants.Models;
+    using ShortStory;
+    using TvShow;

-    public class User : IdentityUser, IAuditInfo, IDeletableEntity
+    public class User : IdentityUser, IAuditInfo, IDeletableEntity
     {
+        private ICollection<ShortStory.ShortStory> shortStories;
+
+        private ICollection<MovieComment> movieComments;
+        private ICollection<BookComment> bookComments;
+        private ICollection<ShortStoryComment> shortStoryComments;
+        private ICollection<TvShowComment> tvShowComments;
+
+        private ICollection<MovieRating> movieRatings;
+        private ICollection<BookRating> bookRatings;
+        private ICollection<ShortStoryRating> shortStoryRatings;
+        private ICollection<TvShowRating> tvShowRatings;
+
+
+        public User()
+        {
+            this.CreatedOn = DateTime.Now;
+
+            this.shortStories = new HashSet<ShortStory.ShortStory>();
+
+            this.movieComments = new HashSet<MovieComment>();
+            this.bookComments = new HashSet<BookComment>();
+            this.shortStoryComments = new HashSet<ShortStoryComment>();
+            this.tvShowComments = new HashSet<TvShowComment>();
+
+            this.movieRatings = new HashSet<MovieRating>();
+            this.bookRatings = new HashSet<BookRating>();
+            this.shortStoryRatings = new HashSet<ShortStoryRating>();
+            this.tvShowRatings = new HashSet<TvShowRating>();
+        }
+
         [Required]
         [MinLength(UserModelConstants.FirstNameMinLength)]
         [MaxLength(UserModelConstants.FirstNameMaxLength)]
@@ -46,6 +81,60 @@

         public DateTime? DeletedOn { get; set; }

+        public virtual ICollection<ShortStory.ShortStory> ShortStories
+        {
+            get { return this.shortStories; }
+            set { this.shortStories = value; }
+        }
+
+        public virtual ICollection<MovieComment> MovieComments
+        {
+            get { return this.movieComments; }
+            set { this.movieComments = value; }
+        }
+
+        public virtual ICollection<BookComment> BookComments
+        {
+            get { return this.bookComments; }
+            set { this.bookComments = value; }
+        }
+
+        public virtual ICollection<ShortStoryComment> ShortStoryComments
+        {
+            get { return this.shortStoryComments; }
+            set { this.shortStoryComments = value; }
+        }
+
+        public virtual ICollection<TvShowComment> TvShowComments
+        {
+            get { return this.tvShowComments; }
+            set { this.tvShowComments = value; }
+        }
+
+        public virtual ICollection<MovieRating> MovieRatings
+        {
+            get { return this.movieRatings; }
+            set { this.movieRatings = value; }
+        }
+
+        public virtual ICollection<BookRating> BookRatings
+        {
+            get { return this.bookRatings; }
+            set { this.bookRatings = value; }
+        }
+
+        public virtual ICollection<ShortStoryRating> ShortStoryRatings
+        {
+            get { return this.shortStoryRatings; }
+            set { this.shortStoryRatings = value; }
+        }
+
+        public virtual ICollection<TvShowRating> TvShowRatings
+        {
+            get { return this.tvShowRatings; }
+            set { this.tvShowRatings = value; }
+        }
+
         public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
         {
             var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);


Add AdditionalProperties property to FilePart

--- Source/HttpMultipartParser/FilePart.cs
+++ Source/HttpMultipartParser/FilePart.cs
@@ -24,6 +24,8 @@
 // </summary>
 // --------------------------------------------------------------------------------------------------------------------

+using System.Collections.Generic;
+using System.Collections.ObjectModel;
 using System.IO;
 using System.Linq;

@@ -50,7 +52,7 @@
         ///     The file data.
         /// </param>
         public FilePart(string name, string fileName, Stream data)
-            : this(name, fileName, data, "text/plain", "form-data")
+            : this(name, fileName, data, null)
         {
         }

@@ -73,12 +75,59 @@
         ///     The content disposition.
         /// </param>
         public FilePart(string name, string fileName, Stream data, string contentType, string contentDisposition)
+            : this(name, fileName, data, null, contentType, contentDisposition)
+        {
+        }
+
+        /// <summary>
+        ///     Initializes a new instance of the <see cref="FilePart" /> class.
+        /// </summary>
+        /// <param name="name">
+        ///     The name of the input field used for the upload.
+        /// </param>
+        /// <param name="fileName">
+        ///     The name of the file.
+        /// </param>
+        /// <param name="data">
+        ///     The file data.
+        /// </param>
+        /// <param name="additionalProperties">
+        ///     Additional properties associated with this file.
+        /// </param>
+        public FilePart(string name, string fileName, Stream data, IDictionary<string, string> additionalProperties)
+            : this(name, fileName, data, additionalProperties, "text/plain", "form-data")
+        {
+        }
+
+        /// <summary>
+        ///     Initializes a new instance of the <see cref="FilePart" /> class.
+        /// </summary>
+        /// <param name="name">
+        ///     The name of the input field used for the upload.
+        /// </param>
+        /// <param name="fileName">
+        ///     The name of the file.
+        /// </param>
+        /// <param name="data">
+        ///     The file data.
+        /// </param>
+        /// <param name="additionalProperties">
+        ///     Additional properties associated with this file.
+        /// </param>
+        /// <param name="contentType">
+        ///     The content type.
+        /// </param>
+        /// <param name="contentDisposition">
+        ///     The content disposition.
+        /// </param>
+        public FilePart(string name, string fileName, Stream data, IDictionary<string, string> additionalProperties, string contentType, string contentDisposition)
         {
             Name = name;
             FileName = fileName?.Split(Path.GetInvalidFileNameChars()).Last();
             Data = data;
             ContentType = contentType;
             ContentDisposition = contentDisposition;
+            AdditionalProperties = new ReadOnlyDictionary<string, string>(additionalProperties ?? new Dictionary<string, string>());
         }

         #endregion
@@ -110,6 +159,12 @@
         /// </summary>
         public string ContentDisposition { get; }

+        /// <summary>
+        /// Gets the additional properties associated with this file.
+        /// An additional property is any property other than the "well known" ones such as name, filename, content-type, etc.
+        /// </summary>
+        public IReadOnlyDictionary<string, string> AdditionalProperties { get; private set; }
+
         #endregion
     }
 }


Update ConsensusService.cs (#211)

Update ConsensusService.cs (#211)

--- neo/Consensus/ConsensusService.cs
+++ neo/Consensus/ConsensusService.cs
@@ -220,7 +220,7 @@

                         if (Blockchain.Default?.Height + 1 < payload.BlockIndex)
                         {
-                            Log($"chain sync: expected={payload.BlockIndex} current: {Blockchain.Default?.Height}");
+                            Log($"chain sync: expected={payload.BlockIndex} current: {Blockchain.Default?.Height} nodes={localNode.RemoteNodeCount}");

                             localNode.RequestGetBlocks();
                         }


Added one more sample

Added one more sample

--- ConsoleInteraction/Samples.cs
+++ ConsoleInteraction/Samples.cs
@@ -1,5 +1,5 @@
 using AngleSharp;
-using AngleSharp.DOM;
+using AngleSharp.DOM.Html;
 using System;
 using System.Linq;

@@ -9,12 +9,13 @@
     {
         public static void RunAll()
         {
-            First();
+            FirstExample();
             UsingLinq();
             SingleElements();
+            Construction();
         }

-        static void First()
+        static void FirstExample()
         {
             var document = DocumentBuilder.Html("
Some example source

This is a paragraph element");
             //Do something with document like the following
@@ -76,5 +77,26 @@
             Console.WriteLine(emphasize.OuterHtml);  // bold and italic
             Console.WriteLine(emphasize.TextContent);// bold and italic
         }
+
+        static void Construction()
+        {
+            var document = DocumentBuilder.Html(String.Empty);
+            document.Title = "My document";
+            var body = document.Body;
+            var p1 = document.CreateElement<IHtmlParagraphElement>();
+            p1.TextContent = "First paragraph";
+            body.AppendChild(p1);
+            var p2 = document.CreateElement<IHtmlParagraphElement>();
+            p2.TextContent = "Second paragraph";
+            body.AppendChild(p2);
+            var a = document.CreateElement<IHtmlAnchorElement>();
+            a.TextContent = "Some hyperlink";
+            a.Href = "http://www.myurl";
+            body.AppendChild(a);
+            var img = document.CreateElement<IHtmlImageElement>();
+            img.Source = "http://www.example.com/link";
+            body.AppendChild(img);
+            Console.WriteLine(document.DocumentElement.OuterHtml);
+        }
     }
 }


Added TODOs on System.Progress

Added TODOs on System.Progress

--- Core/System/Progress.net40.cs
+++ Core/System/Progress.net40.cs
@@ -11,6 +11,7 @@
         public Progress()
         {
             _context = SynchronizationContext.Current;
+            //TODO handle the case where SynchronizationContext.Current is null
         }

         public Progress(Action<T> handler)
@@ -23,7 +24,7 @@
             else
             {
                 _handler = handler;
-                _callback = new SendOrPostCallback(Callback);
+                _callback = Callback;
             }
         }

@@ -32,14 +33,14 @@

         public void Report(T value)
         {
-            this.OnReport(value);
+            OnReport(value);
         }

         protected virtual void OnReport(T value)
         {
             if (_callback != null || ProgressChanged != null)
             {
-                _context.Post(_callback, value);
+                _context.Post(_callback, value); //TODO: _context may be null
             }
         }


continue #5

continue #5

- получение DDL для field (типов)

--- ProcTree.Core/DbObject.cs
+++ ProcTree.Core/DbObject.cs
@@ -2,6 +2,7 @@
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
+using System.Xml;
 using Microsoft.SqlServer.Server;

 namespace ProcTree.Core
@@ -27,22 +28,20 @@
     public enum DbFirebirdBaseFieldType
     {
         Unknown = -1,
-        SmallInt = 7,
-        Integer = 8,
-        Int64 = 16,
+        Short = 7,
+        Long = 8,
         Quad = 9,
         Float = 10,
-        DFloat = 11,
-        Boolean = 17,
-        Double = 27,
         Date = 12,
         Time = 13,
+        Text = 14, // char
+        Int64 = 16,
+        Double = 27,
         Timestamp = 35,
-        Blob = 261,
-        Varchar = 37,
-        Char = 14,
+        Varying = 37, // varchar
         CString = 40,
-        BlobId = 45
+        BlobId = 45,
+        Blob = 261
     }

     public enum DbFirebirdBaseFieldSubType
@@ -71,7 +70,7 @@

     public enum ParameterMechanism
     {
-        Traditional = 0,
+        Normal = 0,
         TypeOf = 1
     }

@@ -128,7 +127,7 @@
     public class DbField : LinkedDbObject
     {
         public DbFirebirdBaseFieldType BaseType { get; set; }
-        public DbFirebirdBaseFieldSubType BasedSubType { get; set; }
+        public DbFirebirdBaseFieldSubType SubType { get; set; }
         public int Length { get; set; }
         public int Scale { get; set; }
         public int Precision { get; set; }
@@ -139,9 +138,41 @@
         public string DefaultSource { get; set; }
         public string ComputedSource { get; set; }

+        public static Dictionary<DbFirebirdBaseFieldType, string> TypeNames = new Dictionary
+            <DbFirebirdBaseFieldType, string>
+        {
+            {DbFirebirdBaseFieldType.Short, "SMALLINT"},
+            {DbFirebirdBaseFieldType.Long, "INTEGER"},
+            {DbFirebirdBaseFieldType.Quad, "BIGINT"},
+            {DbFirebirdBaseFieldType.Int64, "BIGINT"},
+            {DbFirebirdBaseFieldType.Varying, "VARCHAR"},
+            {DbFirebirdBaseFieldType.Text, "CHAR"}
+        };
+
         public override string GetDdl()
         {
-            return BaseType.ToString().ToUpper();
+            var res = BaseType.ToString().ToUpper();
+            if ((BaseType == DbFirebirdBaseFieldType.Short) ||
+                (BaseType == DbFirebirdBaseFieldType.Long) ||
+                (BaseType == DbFirebirdBaseFieldType.Quad) ||
+                (BaseType == DbFirebirdBaseFieldType.Int64))
+            {
+                if (SubType == DbFirebirdBaseFieldSubType.Unknown)
+                {
+                    res = TypeNames.ContainsKey(BaseType) ? TypeNames[BaseType] : BaseType.ToString();
+                }
+                else if ((SubType == DbFirebirdBaseFieldSubType.Numeric) || (SubType == DbFirebirdBaseFieldSubType.Decimal))
+                {
+                    res = string.Format("{0}({1},{2})", SubType, Precision, Scale);
+                }
+            }
+            else if ((BaseType == DbFirebirdBaseFieldType.Text) ||
+                     (BaseType == DbFirebirdBaseFieldType.Varying))
+            {
+                res = string.Format("{0}({1}) {2}", TypeNames[BaseType], CharacterLength,
+                    string.Format("CHARACTER SET {0}", CharacterSet.Name));
+            }
+            return res;
         }
     }

@@ -150,7 +181,6 @@
         public int OrderNumber { get; set; }
         public ParameterType ParameterType { get; set; }
         public DbField Field { get; set; }
-        public CharacterSet CharacterSet { get; set; }
         public Collation Collation { get; set; }
         public bool IsNull { get; set; }
         public ParameterMechanism ParameterMechanism { get; set; }
@@ -160,12 +190,13 @@

         public override string GetDdl()
         {
-            return string.Format("{0} {1} {2} {3} {4} {5}",
+            return string.Format("{0} {1} {2} {3} {4}",
                 Name,
                 GetSqlType(),
                 IsNull ? string.Empty : "NOT NULL",
-                CharacterSet == null ? string.Empty : string.Format("CHARACTER SET {0}", CharacterSet.Name),
-                Collation == null ? string.Empty : string.Format("COLLATE {0}", Collation.Name),
+                Collation == null
+                    ? Field.Collation == null ? string.Empty : Field.Collation.Name
+                    : string.Format("COLLATE {0}", Collation.Name),
                 GetDefaultSql());
         }

@@ -178,8 +209,8 @@

         private string GetSqlType()
         {
-            return ParameterMechanism == ParameterMechanism.Traditional
-                ? Field.Name
+            return ParameterMechanism == ParameterMechanism.Normal
+                ? Field.GetDdl()
                 : string.Format("TYPE OF COLUMN {0}.{1}", RelationName, FieldName);
         }
     }


Added Gamma / factorial function(s) to microj, only implemented for single y arg so far.


changed the error message for unhandled event in pt

--- Src/PTester/PRuntime/PrtBaseClasses.cs
+++ Src/PTester/PRuntime/PrtBaseClasses.cs
@@ -123,7 +123,7 @@
                 //TODO : Handle the spec machine case separately for the halt event
                 else if (!eventValue.Equals(PrtValue.halt))
                 {
-                    throw new PrtUnhandledEventException(string.Format("{0} failed to handle {1}", Name, eventValue.ToString()));
+                    throw new PrtUnhandledEventException(string.Format("{0} failed to handle event {1}", Name, eventValue.ToString()));
                 }
                 else
                 {


use automocking in service test

use automocking in service test

--- Src/playNET.Tests/PlayerModuleTests.cs
+++ Src/playNET.Tests/PlayerModuleTests.cs
@@ -5,26 +5,27 @@
 using playNET.App;
 using playNET.Tests.Helpers;
 using Ploeh.AutoFixture;
+using Ploeh.AutoFixture.AutoFakeItEasy;
 using Shouldly;

 namespace playNET.Tests
 {
     public class PlayerModuleTests
     {
-        private readonly IFixture fixture = new Fixture();
+        private readonly IFixture fixture = new Fixture().Customize(new AutoFakeItEasyCustomization());

-        private static Browser CreateDefaultBrowser(IPlayer player)
+        private Browser CreateDefaultBrowser()
         {
             return new Browser(with =>
                                {
                                    with.Module<PlayerModule>();
-                                   with.Dependency(player);
+                                   with.Dependency(fixture.Create<IPlayer>());
                                });
         }

         public void GetRoot_Always_ReturnsHttpOK()
         {
-            var sut = CreateDefaultBrowser(A.Fake<IPlayer>());
+            var sut = CreateDefaultBrowser();

             var actual = sut.Get("/").StatusCode;

@@ -33,11 +34,11 @@

         public void GetRoot_Always_ContainsTrackName()
         {
-            var player = A.Fake<IPlayer>();
+            var player = fixture.Freeze<IPlayer>();
             A.CallTo(() => player.Status).Returns(PlaybackStatus.Playing);
             var trackName = "panda rap";
             A.CallTo(() => player.NowPlaying).Returns(trackName);
-            var sut = CreateDefaultBrowser(player);
+            var sut = CreateDefaultBrowser();

             var actual = sut.Get("/").Body.AsString();

@@ -48,9 +49,9 @@
         [Input(PlaybackStatus.Stopped, "Stopped")]
         public void GetStatus_Always_RespondsWithPlaybackStatus(PlaybackStatus status, string expected)
         {
-            var player = A.Fake<IPlayer>();
+            var player = fixture.Freeze<IPlayer>();
             A.CallTo(() => player.Status).Returns(status);
-            var sut = CreateDefaultBrowser(player);
+            var sut = CreateDefaultBrowser();

             var actual = sut.Get("/status").Body.AsString();

@@ -59,10 +60,10 @@

         public void GetRoot_Always_ContainsPlaylist()
         {
-            var player = A.Fake<IPlayer>();
+            var player = fixture.Freeze<IPlayer>();
             var tracks = fixture.CreateMany<string>(2);
             A.CallTo(() => player.Playlist).Returns(tracks);
-            var sut = CreateDefaultBrowser(player);
+            var sut = CreateDefaultBrowser();

             var actual = sut.Get("/").Body.AsString();

@@ -72,40 +73,31 @@

         public void PostPlay_Always_StartsPlayback()
         {
-            var player = A.Fake<IPlayer>();
-            var sut = CreateDefaultBrowser(player);
+            var player = fixture.Freeze<IPlayer>();
+            var sut = CreateDefaultBrowser();

             sut.Post("/play");

             A.CallTo(() => player.Play()).MustHaveHappened();
         }

-        public void PostPlay_Always_ReturnsHttpOK()
-        {
-            var player = A.Fake<IPlayer>();
-            var sut = CreateDefaultBrowser(player);
-
-            var actual = sut.Post("/play").StatusCode;
-
-            actual.ShouldBe(HttpStatusCode.OK);
-        }
-
         public void PostStop_Always_StopsPlayback()
         {
-            var player = A.Fake<IPlayer>();
-            var sut = CreateDefaultBrowser(player);
+            var player = fixture.Freeze<IPlayer>();
+            var sut = CreateDefaultBrowser();

             sut.Post("/stop");

             A.CallTo(() => player.Stop()).MustHaveHappened();
         }

-        public void PostStop_Always_ReturnsHttpOK()
+        [Input("/play")]
+        [Input("/stop")]
+        public void Posts_Always_ReturnsHttpOK(string uri)
         {
-            var player = A.Fake<IPlayer>();
-            var sut = CreateDefaultBrowser(player);
+            var sut = CreateDefaultBrowser();

-            var actual = sut.Post("/stop").StatusCode;
+            var actual = sut.Post(uri).StatusCode;

             actual.ShouldBe(HttpStatusCode.OK);
         }


Be more permissive about method parameters.

Previously it was either a raw HttpRequest or a raw json body or querystring parameters. Now you can combine all three.

--- StatsHelix.Charizard/RoutingManager.cs
+++ StatsHelix.Charizard/RoutingManager.cs
@@ -15,6 +15,7 @@
     // aka google maps
     public class RoutingManager
     {
+        private const int VERSION = 2; // increment whenever codegen changes to update dynamic assemblies
         private const string CharizardDynamic = "StatsHelix.Charizard.Dynamic";
         private const string RequestDispatcher = CharizardDynamic + ".RequestDispatcher";
         private static readonly Type[] QuerystringPrimitives = new[] { typeof(string), typeof(string[]), typeof(int), typeof(long), typeof(bool), typeof(double) };
@@ -142,7 +143,7 @@
             // Of course you could still screw things up here but frankly, why would you (other than to shoot your own foot)?
             // The data here comes straight from attributes and class names - there is literally no way to hijack this.
             // Even then, all you get is a simple and obvious DoS.
-            var fullHash = String.Join("\n", byController.Select(x => x.Key))
+            var fullHash = VERSION + String.Join("\n", byController.Select(x => x.Key))
                 + "\n\nMiddleware:\n" + String.Join("\n", appMiddleware.Select(x => $"{x.DeclaringType.FullName}.{x.Name}"));

             var manager = new DynamicMsilManager(CharizardDynamic, CharizardDynamic);
@@ -311,122 +312,113 @@

         private static Expression BuildActionInvocation(ActionDefinition actionDef, Expression request, Expression controller)
         {
-            // Indentation preserved to avoid needlessly huge diffs.
-            // Welp, doesn't help much.
-            {
-                {
+            var method = actionDef.Method;
+
+            var args = new List<Expression>();
+            var parameters = method.GetParameters().ToList(); // enumerator with a sentinel null value
+            if (parameters.FirstOrDefault()?.ParameterType == typeof(HttpRequest))
+            {
+                // first optional parameter: HttpRequest
+                args.Add(request);
+                parameters.RemoveAt(0);
+            }
+            if (parameters.Any() && !QuerystringPrimitives.Contains(parameters.First().ParameterType))
+            {
+                // second optional parameter: HttpRequest
+
+                // JsonConvert.DeserializeObject<ParameterType>(request.StringBody)
+                args.Add(
+                    Expression.Call(typeof(JsonConvert).GetMethods().Single(x =>
                     {
-                        var method = actionDef.Method;
-
-                        Expression[] args = null;
-                        var parameters = method.GetParameters();
-                        if (parameters.Length == 1)
-                        {
-                            if (parameters[0].ParameterType == typeof(HttpRequest))
-                            {
-                                args = new[] { request };
-                            }
-                            else if (!QuerystringPrimitives.Contains(parameters[0].ParameterType))
-                            {
-                                // JsonConvert.DeserializeObject<ParameterType>(request.StringBody)
-                                args = new[]
-                                {
-                                    Expression.Call(typeof(JsonConvert).GetMethods().Single(x =>
-                                    {
-                                        var mParams = x.GetParameters();
-                                        return x.Name == nameof(JsonConvert.DeserializeObject) && x.IsGenericMethod
-                                        && mParams.Length == 1 && mParams[0].ParameterType == typeof(string);
-                                    }).MakeGenericMethod(parameters[0].ParameterType),
-                                    Expression.PropertyOrField(request, nameof(HttpRequest.StringBody)))
-                                };
-                            }
-                        }
-
-                        var earlyReturn = Expression.Label(typeof(Task<HttpResponse>));
-
-                        if (args == null)
-                        {
-                            // last resort: querystring parsing
-
-                            // System.Web.HttpUtility.ParseQueryString(request.QueryString)
-                            var querystring = Expression.Call(typeof(System.Web.HttpUtility).GetMethod(nameof(System.Web.HttpUtility.ParseQueryString),
-                                new[] { typeof(string) }),
-                                Expression.Call(
-                                    Expression.PropertyOrField(request, nameof(HttpRequest.Querystring)), typeof(object).GetMethod(nameof(ToString))));
-
-                            var indexer = GetIndexer(querystring.Type, typeof(string), typeof(string));
-
-                            // now for every parameter:
-                            // * retrieve the string value from the parsed query string
-                            // * try to convert it to the required type
-                            // * if conversion failed (or if there was no param to begin with):
-                            //     * fall back to the default value
-                            //     * if there is no default value, return an error message
-                            args = new Expression[parameters.Length];
-                            for (int i = 0; i < args.Length; i++)
-                            {
-                                var parameterName = parameters[i].Name;
-                                var stringVal = Expression.MakeIndex(querystring, indexer, new[] { Expression.Constant(parameterName) });
-                                var stringVar = Expression.Variable(typeof(string));
-
-                                var pt = parameters[i].ParameterType;
-
-                                // unwrap nullable
-                                var originalPt = pt;
-                                if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
-                                    pt = pt.GetGenericArguments()[0];
-
-                                var thingVar = Expression.Variable(pt);
-                                Expression success = Expression.ReferenceNotEqual(stringVar, Expression.Constant(null, typeof(string)));
-
-                                if (pt == typeof(string))
-                                {
-                                    success = Expression.Block(Expression.Assign(thingVar, stringVar), success);
-                                }
-                                else if (pt == typeof(string[]))
-                                {
-                                    success = Expression.Block(Expression.Assign(thingVar, Expression.Call(querystring,
-                                        nameof(System.Collections.Specialized.NameValueCollection.GetValues),
-                                        Type.EmptyTypes, Expression.Constant(parameterName))), success);
-                                }
-                                else if (QuerystringPrimitives.Contains(pt))
-                                {
-                                    success = Expression.AndAlso(success, Expression.Call(pt.GetMethod("TryParse", new[] { typeof(string), pt.MakeByRefType() }), stringVar, thingVar));
-                                }
-                                else
-                                    throw new NotImplementedException();
-
-
-                                // wrap nullable
-                                Expression thingVarResult = thingVar;
-                                if (pt != originalPt)
-                                    thingVarResult = Expression.Convert(thingVar, originalPt);
-
-                                Expression result;
-                                if (parameters[i].HasDefaultValue)
-                                    result = Expression.Condition(success, thingVarResult, Expression.Constant(parameters[i].DefaultValue, originalPt));
-                                else
-                                {
-                                    result = Expression.Block(Expression.IfThenElse(success, Expression.Constant(null), Expression.Return(earlyReturn,
-                                        Expression.Call(typeof(RoutingManager).GetMethod(nameof(InvalidOrMissingParameterHelper)), Expression.Constant(parameterName)))), thingVarResult);
-                                }
-
-                                args[i] = Expression.Block(new[] { thingVar, stringVar }, Expression.Assign(stringVar, stringVal), result);
-                            }
-                        }
-
-                        // TODO: regex support
-                        var path = $"/{actionDef.Controller.Info.Prefix}{method.Name}";
-
-                        var actionResult = Expression.Call(method.IsStatic ? null : controller, method, args);
-                        if (actionDef.IsSynchronous)
-                            actionResult = Expression.Call(typeof(Task).GetMethod(nameof(Task.FromResult)).MakeGenericMethod(typeof(HttpResponse)), actionResult);
-                        var lambda = Expression.Label(earlyReturn, actionResult);
-
-                        return Expression.Block(lambda);
-                    }
-                }
-            }
+                        var mParams = x.GetParameters();
+                        return x.Name == nameof(JsonConvert.DeserializeObject) && x.IsGenericMethod
+                        && mParams.Length == 1 && mParams[0].ParameterType == typeof(string);
+                    }).MakeGenericMethod(parameters.First().ParameterType),
+                    Expression.PropertyOrField(request, nameof(HttpRequest.StringBody)))
+                );
+                parameters.RemoveAt(0);
+            }
+
+            var earlyReturn = Expression.Label(typeof(Task<HttpResponse>));
+
+            // remaining parameters: querystring parsing
+
+            // System.Web.HttpUtility.ParseQueryString(request.QueryString)
+            var querystring = Expression.Call(typeof(System.Web.HttpUtility).GetMethod(nameof(System.Web.HttpUtility.ParseQueryString),
+                new[] { typeof(string) }),
+                Expression.Call(
+                    Expression.PropertyOrField(request, nameof(HttpRequest.Querystring)), typeof(object).GetMethod(nameof(ToString))));
+
+            args.AddRange(parameters.Select(p => BuildQuerystringParam(earlyReturn, querystring, p)));
+
+            // TODO: regex support
+            var path = $"/{actionDef.Controller.Info.Prefix}{method.Name}";
+
+            var actionResult = Expression.Call(method.IsStatic ? null : controller, method, args);
+            if (actionDef.IsSynchronous)
+                actionResult = Expression.Call(typeof(Task).GetMethod(nameof(Task.FromResult)).MakeGenericMethod(typeof(HttpResponse)), actionResult);
+            var lambda = Expression.Label(earlyReturn, actionResult);
+
+            return Expression.Block(lambda);
+        }
+
+        private static BlockExpression BuildQuerystringParam(LabelTarget earlyReturn, Expression querystring, ParameterInfo parameter)
+        {
+            // for every parameter:
+            // * retrieve the string value from the parsed query string
+            // * try to convert it to the required type
+            // * if conversion failed (or if there was no param to begin with):
+            //     * fall back to the default value
+            //     * if there is no default value, return an error message
+            var indexer = GetIndexer(querystring.Type, typeof(string), typeof(string));
+            var parameterName = parameter.Name;
+            var stringVal = Expression.MakeIndex(querystring, indexer, new[] { Expression.Constant(parameterName) });
+            var stringVar = Expression.Variable(typeof(string));
+
+            var pt = parameter.ParameterType;
+
+            // unwrap nullable
+            var originalPt = pt;
+            if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
+                pt = pt.GetGenericArguments()[0];
+
+            var thingVar = Expression.Variable(pt);
+            Expression success = Expression.ReferenceNotEqual(stringVar, Expression.Constant(null, typeof(string)));
+
+            if (pt == typeof(string))
+            {
+                success = Expression.Block(Expression.Assign(thingVar, stringVar), success);
+            }
+            else if (pt == typeof(string[]))
+            {
+                success = Expression.Block(Expression.Assign(thingVar, Expression.Call(querystring,
+                    nameof(System.Collections.Specialized.NameValueCollection.GetValues),
+                    Type.EmptyTypes, Expression.Constant(parameterName))), success);
+            }
+            else if (QuerystringPrimitives.Contains(pt))
+            {
+                success = Expression.AndAlso(success, Expression.Call(pt.GetMethod("TryParse", new[] { typeof(string), pt.MakeByRefType() }), stringVar, thingVar));
+            }
+            else
+                throw new NotImplementedException();
+
+
+            // wrap nullable
+            Expression thingVarResult = thingVar;
+            if (pt != originalPt)
+                thingVarResult = Expression.Convert(thingVar, originalPt);
+
+            Expression result;
+            if (parameter.HasDefaultValue)
+                result = Expression.Condition(success, thingVarResult, Expression.Constant(parameter.DefaultValue, originalPt));
+            else
+            {
+                result = Expression.Block(Expression.IfThenElse(success, Expression.Constant(null), Expression.Return(earlyReturn,
+                    Expression.Call(typeof(RoutingManager).GetMethod(nameof(InvalidOrMissingParameterHelper)), Expression.Constant(parameterName)))), thingVarResult);
+            }
+
+            BlockExpression item = Expression.Block(new[] { thingVar, stringVar }, Expression.Assign(stringVar, stringVal), result);
+            return item;
         }

         public static Task<HttpResponse> InvalidOrMissingParameterHelper(string parameterName)


Fix potential tray menu account items creation error

--- SteamAccountSwitcher/TrayIconHelper.cs
+++ SteamAccountSwitcher/TrayIconHelper.cs
@@ -61,22 +61,22 @@
             {
                 for (var i = 0; i < App.Accounts.Count; i++)
                 {
+                    var index = i;
                     var item = new MenuItem
                     {
                         Header =
-                            string.IsNullOrWhiteSpace(App.Accounts[i].DisplayName)
-                                ? App.Accounts[i].Username
-                                : App.Accounts[i].DisplayName
+                            string.IsNullOrWhiteSpace(App.Accounts[index].DisplayName)
+                                ? App.Accounts[index].Username
+                                : App.Accounts[index].DisplayName
                     };
-                    var i1 = i;

                     if (Settings.Default.ColorCodeAccountMenuItems)
                     {
-                        item.Background = new SolidColorBrush(App.Accounts[i1].Color);
-                        item.Foreground = new SolidColorBrush(App.Accounts[i1].TextColor);
+                        item.Background = new SolidColorBrush(App.Accounts[index].Color);
+                        item.Foreground = new SolidColorBrush(App.Accounts[index].TextColor);
                     }

-                    item.Click += delegate { App.Accounts[i1].SwitchTo(false); };
+                    item.Click += delegate { App.Accounts[index].SwitchTo(false); };
                     menuList.Add(item);
                 }
                 menuList.Add(new Separator());


Corrected message runner thread leakage. #28

The problem arises when you try to disconnect and reconnect within a messsage handler. The new connection starts a new runner thread, and the old thread sees the new valid state so it doesn't exit. Now we're blocking until the old thread is dead before we start a new one. I'd rather save the old thread, but it's going to be complicated and bug-prone to try to determine that it's not already shutting down. For now, if you want to disconnect/reconnect in a message handler, you'll need to use ClientBase.ConnectAsync instead of the blocking extension method or you'll deadlock.

--- Desktop/Tempest/ClientBase.cs
+++ Desktop/Tempest/ClientBase.cs
@@ -32,6 +32,10 @@
 using System.Threading;
 using Tempest.InternalProtocol;

+#if NET_4
+using System.Collections.Concurrent;
+#endif
+
 namespace Tempest
 {
 	/// <summary>
@@ -55,7 +59,11 @@
 				this.mode = MessagingModes.Inline;
 			else
 			{
+				#if NET_4
+				this.mqueue = new ConcurrentQueue<MessageEventArgs>();
+				#else
 				this.mqueue = new Queue<MessageEventArgs>();
+				#endif
 				this.connection.MessageReceived += ConnectionOnMessageReceived;
 				this.mode = MessagingModes.Async;
 			}
@@ -168,13 +176,19 @@
 			List<MessageEventArgs> messages;
 			if (this.mode == MessagingModes.Async)
 			{
-				messages = new List<MessageEventArgs> (mqueue.Count);
-
+				messages = new List<MessageEventArgs> (mqueue.Count * 2);
+
+				#if NET_4
+				MessageEventArgs e;
+				while (this.mqueue.TryDequeue (out e))
+					messages.Add (e);
+				#else
 				lock (this.mqueue)
 				{
 					while (this.mqueue.Count > 0)
 						messages.Add (this.mqueue.Dequeue());
 				}
+				#endif
 			}
 			else
 				messages = this.connection.Tick().ToList();
@@ -199,7 +213,12 @@
 		private readonly MessagingModes mode;
 		private readonly bool polling;

+		#if NET_4
+		private readonly ConcurrentQueue<MessageEventArgs> mqueue;
+		#else
 		private readonly Queue<MessageEventArgs> mqueue;
+		#endif
+
 		private AutoResetEvent mwait;
 		private Thread messageRunner;
 		protected volatile bool running;
@@ -224,11 +243,24 @@
 				if (wait != null)
 					wait.Set();

+				#if NET_4
+				MessageEventArgs e;
+				while (this.mqueue.TryDequeue (out e)) ;
+				#else
 				lock (this.mqueue)
 					this.mqueue.Clear();
-			}
-
-			this.messageRunner = null;
+				#endif
+			}
+
+			ThreadPool.QueueUserWorkItem (s =>
+			{
+				Thread runner = this.messageRunner;
+				if (runner != null)
+					runner.Join();
+
+				this.messageRunner = null;
+			});
+
 			this.disconnecting = false;
 		}

@@ -287,16 +319,21 @@

 		private void AsyncMessageRunner ()
 		{
+			#if NET_4
+			ConcurrentQueue<MessageEventArgs> q = this.mqueue;
+			#else
 			Queue<MessageEventArgs> q = this.mqueue;
+			#endif

 			while (this.running)
 			{
-				while (q.Count > 0)
+				while (q.Count > 0 && this.running)
 				{
-					if (!this.running)
-						break;
-
 					MessageEventArgs e;
+					#if NET_4
+					if (!q.TryDequeue (out e))
+						continue;
+					#else
 					lock (q)
 					{
 						if (q.Count == 0)
@@ -304,8 +341,9 @@

 						e = q.Dequeue();
 					}
-
-					var mhandlers = GetHandlers (e.Message);
+					#endif
+
+					List<Action<MessageEventArgs>> mhandlers = GetHandlers (e.Message);
 					if (mhandlers == null)
 						continue;

@@ -341,6 +379,9 @@

 			if (!this.polling)
 			{
+				while (this.messageRunner != null)
+					Thread.Sleep (0);
+
 				Thread runner = (this.mode == MessagingModes.Inline) ? new Thread (InlineMessageRunner) : new Thread (AsyncMessageRunner);
 				runner.Name = "Client Message Runner";
 				runner.IsBackground = true;


Correct order of code

Correct order of code

--- core/Piranha/App.cs
+++ core/Piranha/App.cs
@@ -361,9 +361,9 @@
                             module.Instance.Init();
                         }

+                        api.Media.Init();
+
                         _isInitialized = true;
-
-                        api.Media.Init();
                     }
                 }
             }


Formatting

Formatting

--- TMDbLib/Objects/Discover/DiscoverTv.cs
+++ TMDbLib/Objects/Discover/DiscoverTv.cs
@@ -149,7 +149,6 @@
         public DiscoverTv WhereRuntimeIsAtLeast(int runtime)
         {
             Parameters["with_runtime.gte"] = runtime.ToString();
-
             return this;
         }

@@ -159,7 +158,6 @@
         public DiscoverTv WhereRuntimeIsAtMost(int runtime)
         {
             Parameters["with_runtime.lte"] = runtime.ToString();
-
             return this;
         }

@@ -169,7 +167,6 @@
         public DiscoverTv IncludeNullFirstAirDates(bool include)
         {
             Parameters["include_null_first_air_dates"] = include.ToString();
-
             return this;
         }

@@ -204,7 +201,6 @@
         public DiscoverTv WhereCompaniesInclude(IEnumerable<int> companyIds)
         {
             Parameters["with_companies"] = string.Join(",", companyIds.Select(s => s.ToString()));
-
             return this;
         }

@@ -214,7 +210,6 @@
         public DiscoverTv WhereScreenedTheatrically(bool theatrical)
         {
             Parameters["screened_theatrically"] = theatrical.ToString();
-
             return this;
         }

@@ -251,8 +246,5 @@
             Parameters["without_keywords"] = string.Join("|", keywordIds.Select(s => s.ToString()));
             return this;
         }
-
-
-
     }
-}+}


OK, Issue #123 is fixed, so put things back to normal so everything passes.

--- Keen.NET.Test/QueryTest.cs
+++ Keen.NET.Test/QueryTest.cs
@@ -76,7 +76,7 @@
             }

             var response = await client.GetQueries();
-            Assert.False(response.Any(p => p.Key == "minimum"));
+            Assert.True(response.Any(p => p.Key == "minimum"));
             Assert.True(response.Any(p => p.Key == "average"));
             Assert.True(response.Any(p => p.Key == "maximum"));
             Assert.True(response.Any(p => p.Key == "count_url"));


Fixed Lens to duplicate record on set

Fixed Lens to duplicate record on set

--- KitchenSink/Purity/Lens.cs
+++ KitchenSink/Purity/Lens.cs
@@ -1,6 +1,9 @@
 using System;
+using System.Collections.Generic;
+using System.Linq;
 using System.Linq.Expressions;
 using System.Reflection;
+using KitchenSink.Extensions;
 using static KitchenSink.Operators;

 namespace KitchenSink.Purity
@@ -10,9 +13,6 @@
     /// </summary>
     public static class Lens
     {
-        // TODO: this mutates the object instead of creating a new one
-        //       need to generate call to constructor
-
         /// <summary>
         /// Builds a Lens for the given property.
         /// </summary>
@@ -37,12 +37,45 @@
                 throw new ArgumentException($"Property {property.Name} must be writeable.");
             }

-            Func<A, B, A> setter = (obj, val) =>
+            return new Lens<A, B>(getExpr.Compile(), Setter<A, B>(property.Name));
+        }
+
+        private static Func<A, B, A> Setter<A, B>(string name)
+        {
+            var ctor = typeof(A)
+                .GetConstructors()
+                .SingleOrDefault(c => c.GetParameters().Length > 0);
+
+            if (ctor == null)
             {
-                property.SetValue(obj, val);
-                return obj;
+                throw new InvalidOperationException(
+                    $"Type {typeof(A)} has more than one constructor");
+            }
+
+            var properties = typeof(A).GetProperties();
+            var paramz = ctor.GetParameters();
+            return (record, value) =>
+            {
+                var args = paramz
+                    .Select(p => p.Name.IsSimilar(name)
+                        ? value
+                        : Get<A>(record, properties, p))
+                    .ToArray();
+                return (A) ctor.Invoke(args);
             };
-            return new Lens<A, B>(getExpr.Compile(), setter);
+        }
+
+        private static object Get<A>(object target, IEnumerable<PropertyInfo> properties, ParameterInfo param)
+        {
+            var property = properties.FirstOrDefault(x => x.Name.IsSimilar(param.Name));
+
+            if (property == null)
+            {
+                throw new InvalidOperationException(
+                    $"Constructor for type {typeof(A)} has parameters that do not match properties");
+            }
+
+            return property.GetValue(target, null);
         }
     }


serie 2 finalizada

serie 2 finalizada

--- Lab1_compresion/Program.cs
+++ Lab1_compresion/Program.cs
@@ -87,14 +87,7 @@
                         anterior = bytes[i];
                     }
                 }
-                double ratio = sizeAfter / sizeBefore;
-                double factor = sizeBefore / sizeAfter;
-                Console.WriteLine("Tamaño antes: " + sizeBefore);
-                Console.WriteLine("Tamaño despues: " + sizeAfter);
-                Console.WriteLine("Ratio de compresion: " + ratio);
-                Console.WriteLine("Factor de compresion: " + factor);
-                double porcentaje = ((sizeBefore - sizeAfter) / sizeBefore)*100;
-                Console.WriteLine("Porcentaje de compresion: " + porcentaje);
+                mostrar();
                 RLE.Add(anterior);
                 RLE.Add(Convert.ToByte(contador));
                 File.WriteAllBytes(Path.GetFileNameWithoutExtension(archivo)+".comp", RLE.ToArray());
@@ -137,7 +130,9 @@
                         RLE.Add(caracter);
                     }
                 }
+                mostrar();
                 File.WriteAllBytes(file, RLE.ToArray());
+
             }
             catch (FileNotFoundException e)
             {
@@ -145,6 +140,17 @@
             }
         }

+        static void mostrar()
+        {
+            double ratio = sizeAfter / sizeBefore;
+            double factor = sizeBefore / sizeAfter;
+            Console.WriteLine("Tamaño antes: " + sizeBefore);
+            Console.WriteLine("Tamaño despues: " + sizeAfter);
+            Console.WriteLine("Ratio de compresion: " + Math.Round(ratio, 2));
+            Console.WriteLine("Factor de compresion: " + Math.Round(factor, 2));
+            double porcentaje = ((sizeBefore - sizeAfter) / sizeBefore) * 100;
+            Console.WriteLine("Porcentaje de compresion: " + Math.Round(porcentaje, 2));
+        }

     }
 }


quite el comentario de una prueba al inicio del proyecto

--- Lab1_compresion/Program.cs
+++ Lab1_compresion/Program.cs
@@ -11,7 +11,7 @@
     {
         static void Main(string[] args)
         {
-            args = new string[] { "-c","-f","test.txt" };
+            //args = new string[] { "-c","-f","test.txt" };
             if (args.Length == 1 && args[0].ToLower().Equals("help") )
             {
                 Console.WriteLine("Uso: .\\Lab1_compresion.exe [-d] [-c] [-f <archivo>]");


fix data type mappings for long string columns with netezza

--- TeslaSQL/DataUtils/NetezzaDataUtils.cs
+++ TeslaSQL/DataUtils/NetezzaDataUtils.cs
@@ -209,7 +209,11 @@
         public void AddColumn(TableConf t, string dbName, string schema, string table, string columnName, string dataType) {
             columnName = MapReservedWord(columnName);
             if (!CheckColumnExists(dbName, schema, table, columnName)) {
-                dataType = DataType.MapDataType(Config.RelayType, SqlFlavor.Netezza, dataType);
+                //The "max" string doesn't exist on netezza, we can just replace it with the NetezzaStringLength after mapping it.
+                //In practice this only impacts varchar and nvarchar, since other data types would be mapped to something else by the MapDataType
+                //function (i.e. varbinary). This is the only place we do this special string-based handling because we wanted to keep Netezza specific logic
+                //out of the DataType class. Outside of this case, the "max" is handled appropriately in the netezza data copy class.
+                dataType = DataType.MapDataType(Config.RelayType, SqlFlavor.Netezza, dataType).Replace("max", Config.NetezzaStringLength.ToString());
                 string sql = string.Format("ALTER TABLE {0} ADD {1} {2}; GROOM TABLE {0} VERSIONS;", table, columnName, dataType);
                 var cmd = new OleDbCommand(sql);
                 SqlNonQuery(dbName, cmd);


attempt to fix pipelines issue

attempt to fix pipelines issue

--- TesseractOCRPluginTester/frmOCRTest.cs
+++ TesseractOCRPluginTester/frmOCRTest.cs
@@ -1,5 +1,3 @@
-using TesseractOCRPlugin;
-
 namespace TesseractOCRPluginTester
 {
     public partial class frmOCRTest : Form
@@ -8,7 +6,7 @@

         public frmOCRTest()
         {
-            TessOCR = new TesseractOCRPlugin.TesseractOCR("eng", TesseractOCR.Quality.High);
+            TessOCR = new TesseractOCRPlugin.TesseractOCR("eng", TesseractOCRPlugin.TesseractOCR.Quality.High);
             InitializeComponent();
         }


tok bil

tok bil

--- TextDuck/Controllers/HomeController.cs
+++ TextDuck/Controllers/HomeController.cs
@@ -7,9 +7,7 @@
 namespace TextDuck.Controllers
 {
     public class HomeController : Controller
-    {
-        // this is a fucking comment
-
+    {
         public ActionResult Index()
         {
             return View();


Spurningarmerki part 2

Spurningarmerki part 2

--- TextDuck/Controllers/HomeController.cs
+++ TextDuck/Controllers/HomeController.cs
@@ -324,7 +324,7 @@
         }

         //A function that changes the status of the file from "Beiðni" to "Í vinnslu"
-        //Saves the changes to the database
+        //Saves the changes to the database!
         [Authorize]
         public ActionResult RequestMoved(int? Id)
         {


better document SpriteManager.CameraOffset

--- ThreeSheeps.Spritesse/SpriteManager.cs
+++ ThreeSheeps.Spritesse/SpriteManager.cs
@@ -15,7 +15,7 @@
         }

         /// <summary>
-        /// A camera offset for layers that make use of it
+        /// Camera offset: the position of the upper left pixel of the visible area
         /// </summary>
         public Vector2 CameraOffset { get; set; }


Made info and verbose messages from the factory get logged to the main log as verbose

--- FactoryLogger.cs
+++ FactoryLogger.cs
@@ -52,6 +52,7 @@
         public void LogInfo(string message, params object[] args)
         {
             factoryLogger.Information(message, args);
+            mainLogger.LogVerbose(message, args);
         }

         /// <summary>
@@ -60,6 +61,7 @@
         public void LogVerbose(string message, params object[] args)
         {
             factoryLogger.Verbose(message, args);
+            mainLogger.LogVerbose(message, args);
         }

         /// <summary>


Removed MimeType detection as the API does not require it and this makes it Mono compatible

--- Dropio.Core/ServiceAdapter.cs
+++ Dropio.Core/ServiceAdapter.cs
@@ -1212,7 +1212,6 @@
             // File
             sb.Append("--" + boundary + "\r\n");
             sb.Append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n");
-            sb.Append("Content-Type: " + this.GetMimeType(file) + "\r\n");
             sb.Append("\r\n");

             UTF8Encoding encoding = new UTF8Encoding();
@@ -1269,23 +1268,7 @@
             });

             return a;
-        }
-
-        /// <summary>
-        /// Gets the type of the MIME.
-        /// </summary>
-        /// <param name="fileName">Name of the file.</param>
-        /// <returns></returns>
-        protected string GetMimeType(string fileName)
-        {
-            string mime = "application/octetstream";
-            string ext = System.IO.Path.GetExtension(fileName).ToLower();
-            Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
-            if (rk != null && rk.GetValue("Content Type") != null)
-                mime = rk.GetValue("Content Type").ToString();
-            return mime;
-        }
-
+		}

         /// <summary>
         /// Handles the exception.


Filter out entries not from journal

Filter out entries not from journal

--- EDDiscovery/EDDN/EDDNClass.cs
+++ EDDiscovery/EDDN/EDDNClass.cs
@@ -43,7 +43,7 @@
             if (!journal.HasCoordinate)
                 return null;

-            if (journal.JumpDist <= 0.0)   //  Checkl for old ED 2.1. converted jump.
+            if (journal.FuelUsed <= 0.0)   //  Checkl for old ED 2.1. converted jump.
                 return null;

             JObject msg = new JObject();


Removed GetEDSM distance nightly dump function

--- EDDiscovery/EDSM/EDSMClass.cs
+++ EDDiscovery/EDSM/EDSMClass.cs
@@ -198,18 +198,6 @@
             return response.Body;
         }

-        public string GetEDSMDistances()            // download a file of distances..
-        {
-            if (File.Exists(EDSMDistancesFileName))
-                File.Delete(EDSMDistancesFileName);
-            if (File.Exists(EDSMDistancesFileName + ".etag"))
-                File.Delete(EDSMDistancesFileName + ".etag");
-
-            if (DownloadFileHandler.DownloadFile(_serverAddress + "dump/distances.json", EDSMDistancesFileName))
-                return EDSMDistancesFileName;
-            else
-                return null;
-        }

         internal long GetNewSystems(EDDiscoveryForm discoveryform, Func<bool> cancelRequested, Action<int, string> reportProgress)
         {


EDSM body name to  journal name for Rocky_ice_body

--- EDDiscovery/EDSM/EDSMClass.cs
+++ EDDiscovery/EDSM/EDSMClass.cs
@@ -811,7 +811,8 @@

         private static Dictionary<string, string> EDSM2PlanetNames = new Dictionary<string, string>()
         {
-            // EDSM name    (lower case)            Journal name
+            // EDSM name    (lower case)            Journal name
+            { "rocky ice world",                    "Rocky ice body" },
             { "high metal content world" ,          "High metal content body"},
             { "class i gas giant",                  "Sudarsky class IV gas giant"},
             { "class ii gas giant",                 "Sudarsky class II gas giant"},


IE8 Responsive fix

IE8 Responsive fix

--- BForms.Docs/Views/Shared/_Layout.cshtml
+++ BForms.Docs/Views/Shared/_Layout.cshtml
@@ -10,13 +10,14 @@

         <title>@ViewBag.Title - BForms</title>

-        @*For IE6-8 support of HTML5 elements and responsive*@
+        @Styles.Render("~/BForms/css")
+
+         @*For IE6-8 support of HTML5 elements and responsive*@
         <!--[if lt IE 9]>
-        <script src="~/Scripts/BForms/Components/Html5shiv/html5shiv.js"></script>
-        <script src="~/Scripts/BForms/Components/Respond/respond.js"></script>
+            <script src="@Url.Content("~/Scripts/BForms/Components/Html5shiv/html5shiv.js")"></script>
+            <script src="@Url.Content("~/Scripts/BForms/Components/Respond/respond.js")" type="text/javascript"></script>
         <![endif]-->

-        @Styles.Render("~/BForms/css")
     </head>
     <body>
         @Html.Partial("_Header")


Extension GetTimeSpanTillNow auch für Nullable-DateTimes.

--- dff.Extensions/DateTimeExtensions.cs
+++ dff.Extensions/DateTimeExtensions.cs
@@ -48,7 +48,20 @@
         /// <returns>TimeSpan seit dem DateTime</returns>
         public static TimeSpan GetTimeSpanTillNow(this DateTime date)
         {
-            return new TimeSpan(DateTime.Now.Ticks-date.Ticks);
+            return new TimeSpan(DateTime.Now.Ticks - date.Ticks);
+        }
+
+        /// <summary>
+        /// Gibt die Zeitspanne die seit dem DateTime vergangen ist zurück (Basis ist DateTime.Now).
+        /// Ist negativ, wenn das DateTime in der Zukunft liegt.
+        /// </summary>
+        /// <param name="date"></param>
+        /// <returns>TimeSpan seit dem DateTime</returns>
+        public static TimeSpan GetTimeSpanTillNow(this DateTime? date)
+        {
+            return new TimeSpan(DateTime.Now.Ticks - Convert.ToDateTime(date).Ticks);
         }
     }
+
+
 }


restore BuildTarget.StandaloneOSXUniversal

--- Editor/Builders/OSXBuilder.cs
+++ Editor/Builders/OSXBuilder.cs
@@ -85,7 +85,7 @@

                 pluginImporter.SetCompatibleWithAnyPlatform (false);
 				pluginImporter.SetCompatibleWithEditor (true);
-				pluginImporter.SetCompatibleWithPlatform (BuildTarget.StandaloneOSX, true);
+				pluginImporter.SetCompatibleWithPlatform (BuildTarget.StandaloneOSXUniversal, true);
 				pluginImporter.SetEditorData ("OS", "OSX");

                 pluginImporter.SaveAndReimport ();


Fix order history

Fix order history

--- RohlikAPI/OrderHistory.cs
+++ RohlikAPI/OrderHistory.cs
@@ -107,22 +107,23 @@

         private IEnumerable<Article> ParseOrderArticles(HtmlNode orderNode)
         {
-            var articleNodes = orderNode.SelectNodes(".//article");
+            var articleNodes = orderNode.SelectNodes(".//div[@class='products-table__product']");
             return articleNodes.Select(ParseSingleArticle);
         }

         private Article ParseSingleArticle(HtmlNode articleNode)
         {
-            var articleNameNode = articleNode.SelectSingleNode(".//h3/a") ?? articleNode.SelectSingleNode(".//h3");
+            var articleNameNode = articleNode.SelectSingleNode(".//a[@class='products-table__name']");
             string articleName = articleNameNode.InnerText.Trim();
-
-            var articleCountString = articleNode.SelectSingleNode(".//p").InnerText;

-            var cleanArticleCountString = Regex.Match(articleCountString, @"\d*").Value;
+            var articleCountNode = articleNode.SelectSingleNode(".//div[@class='products-table__quantity products-table__quantity--number']");
+            var articleCountString = articleCountNode.InnerText;
+
+            var cleanArticleCountString = Regex.Match(articleCountString, @"\d+").Value;
             int articleCount;
             int.TryParse(cleanArticleCountString, out articleCount);

-            var priceNode = articleNode.SelectSingleNode(".//h6/strong");
+            var priceNode = articleNode.SelectSingleNode(".//div[@class='products-table__price']");
             double price = priceParser.ParsePrice(priceNode.InnerText);

             return new Article


Added ProductRepository.Add()

Added ProductRepository.Add()

--- CSharp/Supermarket/ProductRepository.cs
+++ CSharp/Supermarket/ProductRepository.cs
@@ -9,6 +9,7 @@
     {
         Product GetProductByNumber(EAN number);
         Product GetProductByName(string name);
+        void Add(Product product);
         void AddRange(IEnumerable<Product> products);
     }

@@ -19,6 +20,11 @@
         public ProductRepository()
         {
             Products = new List<Product>();
+        }
+
+        public void Add(Product product)
+        {
+            Products.Add(product);
         }

         public void AddRange(IEnumerable<Product> products)


Organised environment commands.

Organised environment commands.

--- Rusty/Core/Environment.cs
+++ Rusty/Core/Environment.cs
@@ -8,15 +8,16 @@
         /// <summary>
         /// Waits until the clipboard contains data.
         /// </summary>
-        /// <param name="SecondsToWait">If omitted, the command will wait indefinitely. Otherwise, it will wait no longer than this many seconds</param>
-        /// <param name="AnyType"><c>false</c> to wait specifically for text or files to appear, otherwise wait for data of any kind.</param>
-        public static void ClipWait(double SecondsToWait, bool AnyType)
+        /// <param name="timeout">If omitted, the command will wait indefinitely.
+        /// Otherwise, it will wait no longer than this many seconds</param>
+        /// <param name="type"><c>false</c> to wait specifically for text or files to appear, otherwise wait for data of any kind.</param>
+        public static void ClipWait(double timeout, bool type)
         {
-            int frequency = 100, time = (int)(SecondsToWait * 1000);
+            int frequency = 100, time = (int)(timeout * 1000);

             for (int i = 0; i < time; i += frequency)
             {
-                if ((!AnyType && Clipboard.ContainsText()) || Clipboard.ContainsData(DataFormats.WaveAudio))
+                if ((!type && Clipboard.ContainsText()) || Clipboard.ContainsData(DataFormats.WaveAudio))
                 {
                     error = 0;
                     return;
@@ -30,21 +31,21 @@
         /// <summary>
         /// Retrieves an environment variable.
         /// </summary>
-        /// <param name="OutputVar">The name of the variable in which to store the string.</param>
+        /// <param name="output">The variable to store the result.</param>
         /// <param name="EnvVarName">The name of the environment variable to retrieve.</param>
-        public static void EnvGet(out string OutputVar, string EnvVarName)
+        public static void EnvGet(out string output, string name)
         {
-            OutputVar = Environment.GetEnvironmentVariable(EnvVarName);
+            output = Environment.GetEnvironmentVariable(name);
         }

         /// <summary>
         /// Writes a value to a variable contained in the environment.
         /// </summary>
-        /// <param name="EnvVar">Name of the environment variable to use, e.g. <c>PATH</c>.</param>
-        /// <param name="Value">Value to set the environment variable to.</param>
-        public static void EnvSet(string EnvVar, string Value)
+        /// <param name="name">Name of the environment variable to use, e.g. <c>PATH</c>.</param>
+        /// <param name="value">Value to set the environment variable to.</param>
+        public static void EnvSet(string name, string value)
         {
-            Environment.SetEnvironmentVariable(EnvVar, Value);
+            Environment.SetEnvironmentVariable(name, value);
         }

         /// <summary>
@@ -63,12 +64,14 @@
         /// <summary>
         /// Retrieves screen resolution, multi-monitor info, dimensions of system objects, and other system properties.
         /// </summary>
-        /// <param name="OutputVar">The variable in which to store the result.</param>
-        /// <param name="Command"></param>
-        /// <param name="Param"></param>
-        public static void SysGet(out string OutputVar, string Command, string Param)
+        /// <param name="output">The variable to store the result.</param>
+        /// <param name="command"></param>
+        /// <param name="param"></param>
+        public static void SysGet(out string output, string command, string param)
         {
-            OutputVar = null;
+            // TODO: sysget command
+
+            output = null;
         }
     }
-}+}


Make sure that base path is an entire segment of the URL

--- SampleApp.Owin/Program.cs
+++ SampleApp.Owin/Program.cs
@@ -39,7 +39,7 @@
             // A dummy calendar
             //scheduler.AddCalendar("myCalendar", new DummyCalendar { Description = "dummy calendar" }, false, false);

-            app.Use(QuartzNetWebConsole.Setup.Owin("/quartz", () => scheduler));
+            app.Use(QuartzNetWebConsole.Setup.Owin("/quartz/", () => scheduler));
         }

         private static void Main(string[] args) {