Tidy up Loader logic

Tidy up Loader logic

--- osu.Game/Screens/Loader.cs
+++ osu.Game/Screens/Loader.cs
@@ -1,7 +1,6 @@
 // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
 // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

-using System;
 using System.Collections.Generic;
 using System.Linq;
 using osu.Framework.Allocation;
@@ -46,30 +45,32 @@
             logo.FadeOut(logo.Alpha * 400);
         }

-        private OsuScreen loadScreen;
+        private OsuScreen loadableScreen;
         private ShaderPrecompiler precompiler;

         protected virtual OsuScreen CreateLoadableScreen() => showDisclaimer ? (OsuScreen)new Disclaimer() : new Intro();
+
+        protected virtual ShaderPrecompiler CreateShaderPrecompiler() => new ShaderPrecompiler();

         protected override void OnEntering(Screen last)
         {
             base.OnEntering(last);

-            LoadComponentAsync(precompiler = new ShaderPrecompiler(loadIfReady), Add);
-            LoadComponentAsync(loadScreen = CreateLoadableScreen(), s => loadIfReady());
+            LoadComponentAsync(precompiler = CreateShaderPrecompiler(), Add);
+            LoadComponentAsync(loadableScreen = CreateLoadableScreen());
+
+            checkIfLoaded();
         }

-        private void loadIfReady()
+        private void checkIfLoaded()
         {
-            if (ChildScreen == loadScreen) return;
+            if (loadableScreen.LoadState != LoadState.Ready || !precompiler.FinishedCompiling)
+            {
+                Schedule(checkIfLoaded);
+                return;
+            }

-            if (loadScreen.LoadState != LoadState.Ready)
-                return;
-
-            if (!precompiler.FinishedCompiling)
-                return;
-
-            Push(loadScreen);
+            Push(loadableScreen);
         }

         [BackgroundDependencyLoader]
@@ -83,15 +84,9 @@
         /// </summary>
         public class ShaderPrecompiler : Drawable
         {
-            private readonly Action onLoaded;
             private readonly List<Shader> loadTargets = new List<Shader>();

             public bool FinishedCompiling { get; private set; }
-
-            public ShaderPrecompiler(Action onLoaded)
-            {
-                this.onLoaded = onLoaded;
-            }

             [BackgroundDependencyLoader]
             private void load(ShaderManager manager)
@@ -106,16 +101,17 @@
                 loadTargets.Add(manager.Load(VertexShaderDescriptor.TEXTURE_3, FragmentShaderDescriptor.TEXTURE));
             }

+            protected virtual bool AllLoaded => loadTargets.All(s => s.Loaded);
+
             protected override void Update()
             {
                 base.Update();

                 // if our target is null we are done.
-                if (loadTargets.All(s => s.Loaded))
+                if (AllLoaded)
                 {
                     FinishedCompiling = true;
                     Expire();
-                    onLoaded?.Invoke();
                 }
             }
         }


show class namespace and assembly

show class namespace and assembly

--- HtmlWriter.cs
+++ HtmlWriter.cs
@@ -44,7 +44,10 @@
             writer.WriteLine("    vertical-align: top");
             writer.WriteLine("  }");
             writer.WriteLine("  th {");
-            writer.WriteLine("    background: lightgrey;");
+            writer.WriteLine("    background: lightgrey");
+            writer.WriteLine("  }  ");
+            writer.WriteLine("  dt {");
+            writer.WriteLine("    font-weight: bold");
             writer.WriteLine("  }  ");
             writer.WriteLine("  </style>");
             this.writer = new HtmlTextWriter(writer, "  ");
@@ -81,6 +84,23 @@
                 writer.WriteEndTag("ul");
             }

+            // namespace and assembly
+            writer.WriteFullBeginTag("dl");
+            writer.WriteFullBeginTag("dt");
+            writer.Write("Namespace");
+            writer.WriteEndTag("dt");
+            writer.WriteFullBeginTag("dd");
+            writer.Write(type.Namespace);
+            writer.WriteEndTag("dd");
+            writer.WriteFullBeginTag("dt");
+            writer.Write("Assembly");
+            writer.WriteEndTag("dt");
+            writer.WriteFullBeginTag("dd");
+            writer.Write(type.Assembly.GetName().Name + " (in" + Path.GetFileName(type.Assembly.Location) + ")");
+            writer.WriteEndTag("dd");
+            writer.WriteEndTag("dl");
+
+            // methods
             var methods = type.GetMethods();
             Array.Sort(methods, new MethodInfoComparer());

@@ -115,6 +135,7 @@
             }
             writer.WriteEndTag("table");

+            // fields
             var fields = type.GetFields();
             Array.Sort(fields, new FieldInfoComparer());


MainWindow: show talker status using event handler

--- p2pChat/MainWindow.xaml.cs
+++ p2pChat/MainWindow.xaml.cs
@@ -13,6 +13,7 @@
 using System.Windows.Media.Imaging;
 using System.Windows.Navigation;
 using System.Windows.Shapes;
+using System.Windows.Threading;
 using TakeAshUtility;

 namespace p2pChat {
@@ -59,11 +60,11 @@
         }

         private void Disconnect() {
+            if (_talker == null) {
+                return;
+            }
             _talker.Dispose();
             _talker = null;
-            button_Connect.IsEnabled = true;
-            button_Disconnect.IsEnabled = false;
-            button_Send.IsEnabled = false;
         }

         private void Window_Closing(object sender, CancelEventArgs e) {
@@ -81,12 +82,9 @@
                 var port = uri.Port > 0 ?
                     uri.Port :
                     _settings.Port;
-                _talker = new Talker(host, port, textBlock_Log);
+                _talker = new Talker(host, port, textBlock_Log, talker_ConnectedChanged);
                 _settings.Host = textBox_Host.Text;
                 _settings.Save();
-                button_Connect.IsEnabled = false;
-                button_Disconnect.IsEnabled = true;
-                button_Send.IsEnabled = true;
             }
             catch (Exception ex) {
                 ShowMessage(ex.GetAllMessages());
@@ -128,5 +126,28 @@
         private void button_ListeningStatus_Click(object sender, RoutedEventArgs e) {
             ToggleListener();
         }
+
+        private void talker_ConnectedChanged(object sender, PropertyChangedEventArgs e) {
+            var talker = sender as Talker;
+            if (talker == null) {
+                return;
+            }
+            Dispatcher.BeginInvoke(
+                DispatcherPriority.Background,
+                new Action(() => {
+                    if (talker.Connected) {
+                        ShowMessage("Connect: " + talker.Host + ":" + talker.Port);
+                        button_Connect.IsEnabled = false;
+                        button_Disconnect.IsEnabled = true;
+                        button_Send.IsEnabled = true;
+                    } else {
+                        ShowMessage("Disconnect: " + talker.Host + ":" + talker.Port);
+                        button_Connect.IsEnabled = true;
+                        button_Disconnect.IsEnabled = false;
+                        button_Send.IsEnabled = false;
+                    }
+                })
+            );
+        }
     }
 }


The bot will no longer store every single message in a anonomysed database, giving up on the neural network dream

--- JefBot/Bot.cs
+++ JefBot/Bot.cs
@@ -226,8 +226,6 @@
             var enabledPlugins = _plugins.Where(plug => plug.Loaded).ToArray();
             var command = "";

-            Storemessage(arg.Content);
-

             if (arg.Content[0] == '!') //TODO make option for this prefix :D
             {
@@ -271,26 +269,9 @@
             return Task.CompletedTask;
         }

-        /// <summary>
-        /// for collecting bot data
-        /// </summary>
-        /// <param name="msg"></param>
-        private void Storemessage(string msg)
-        {
-            using (MySqlConnection con = new MySqlConnection(Bot.SQLConnectionString))
-            {
-                con.Open();
-                MySqlCommand _cmd = con.CreateCommand();
-                _cmd.CommandText = "INSERT INTO `Chat` (`CHAT`, `ID`) VALUES (@chat, NULL)";
-                _cmd.Parameters.AddWithValue("@chat", msg);
-                _cmd.ExecuteNonQuery();
-            }
-        }
-
         //Don't remove this, it's critical to see the chat in the bot, it quickly tells me if it's absolutely broken...
         private void Chatmsg(object sender, OnMessageReceivedArgs e)
         {
-            Storemessage(e.ChatMessage.Message);
             Console.WriteLine($"{e.ChatMessage.Channel}-{e.ChatMessage.Username}: {e.ChatMessage.Message}");
         }


Methods for loading contracts

Methods for loading contracts

--- contractMission.cs
+++ contractMission.cs
@@ -10,6 +10,7 @@
 		private string name;
 		private string activeString;
 		private string hiddenString;
+		private Dictionary<Guid, contractUIObject> missionList;
 		private List<Guid> activeMissionList;
 		private List<Guid> hiddenMissionList;
 		private bool ascendingOrder;
@@ -25,11 +26,13 @@
 		public List<Guid> ActiveMissionList
 		{
 			get { return activeMissionList; }
+			internal set { activeMissionList = value; }
 		}

 		public List<Guid> HiddenMissionList
 		{
 			get { return hiddenMissionList; }
+			internal set { hiddenMissionList = value; }
 		}

 		public bool AscendingOrder
@@ -56,11 +59,16 @@
 			internal set { masterMission = value; }
 		}

-		internal contractMission(string n, string active, string hidden)
+		internal contractMission(string n, string active, string hidden, bool asc, bool showActive, int sMode, bool Master)
 		{
 			name = n;
 			activeString = active;
 			hiddenString = hidden;
+			ascendingOrder = asc;
+			showActiveMissions = showActive;
+			masterMission = Master;
+			orderMode = (sortClass)sMode;
+			missionList = new Dictionary<Guid, contractUIObject>();
 			activeMissionList = new List<Guid>();
 			hiddenMissionList = new List<Guid>();
 		}
@@ -68,18 +76,129 @@
 		internal contractMission(string n)
 		{
 			name = n;
+			missionList = new Dictionary<Guid, contractUIObject>();
 			activeMissionList = new List<Guid>();
 			hiddenMissionList = new List<Guid>();
 		}

+		internal contractUIObject getContract(Guid id)
+		{
+			if (missionList.ContainsKey(id))
+				return missionList[id];
+			else
+				return null;
+		}
+
+		internal void buildMissionList()
+		{
+			resetMasterList();
+			buildMissionList(activeString, activeMissionList);
+			buildMissionList(hiddenString, hiddenMissionList);
+		}
+
+		private void buildMissionList(string s, List<Guid> IDList)
+		{
+			if (string.IsNullOrEmpty(s))
+			{
+				IDList = new List<Guid>();
+			}
+			else
+			{
+				string[] sA = s.Split(',');
+				List<Guid> gID = new List<Guid>();
+				for (int i = 0; i < sA.Length; i++)
+				{
+					contractContainer c = null;
+					contractUIObject cUI = null;
+					string[] sB = sA[i].Split('|');
+					try
+					{
+						Guid g = new Guid(sB[0]);
+						c = contractScenario.Instance.getContract(g);
+						if (c != null)
+						{
+							addToMasterList(c);
+							cUI = getContract(g);
+							if (cUI == null)
+								continue;
+							gID.Add(g);
+						}
+						else
+							continue;
+					}
+					catch (Exception e)
+					{
+						DMC_MBW.LogFormatted("Guid invalid: {0}", e);
+						continue;
+					}
+
+					cUI.Order = stringIntParse(sB[1]);
+					cUI.ShowParams = stringBoolParse(sB[2]);
+				}
+
+				IDList = gID;
+			}
+		}
+
+		internal List<Guid> loadPinnedContracts(List<Guid> gID)
+		{
+			List<contractUIObject> temp = new List<contractUIObject>();
+			List<Guid> idTemp = new List<Guid>();
+			foreach (Guid id in gID)
+			{
+				contractUIObject c = getContract(id);
+				if (c != null)
+				{
+					if (c.Order != null)
+						temp.Add(c);
+				}
+			}
+			if (temp.Count > 0)
+			{
+				temp.Sort((a, b) =>
+				{
+					return Comparer<int?>.Default.Compare(a.Order, b.Order);
+				});
+				foreach (contractUIObject c in temp)
+				{
+					idTemp.Add(c.Container.Contract.ContractGuid);
+				}
+			}
+			return idTemp;
+		}
+
+		private bool stringBoolParse(string source)
+		{
+			bool b;
+			if (bool.TryParse(source, out b))
+				return b;
+			return true;
+		}
+
+		private int? stringIntParse(string s)
+		{
+			int i;
+			if (int.TryParse(s, out i)) return i;
+			return null;
+		}
+
 		internal void addMission(contractContainer c)
 		{
 			if (!activeMissionList.Contains(c.Contract.ContractGuid) || !hiddenMissionList.Contains(c.Contract.ContractGuid))
 			{
 				activeMissionList.Add(c.Contract.ContractGuid);
+				addToMasterList(c);
 			}
 			else
 				DMC_MBE.LogFormatted("Mission List Already Contains Contract: {0}", c.Title);
+		}
+
+		private void addToMasterList(contractContainer c)
+		{
+			if (!missionList.ContainsKey(c.Contract.ContractGuid))
+				missionList.Add(c.Contract.ContractGuid, new contractUIObject(c));
+			else
+				DMC_MBE.LogFormatted("Master Mission List For: [{0}] Already Contains Contract: [{1}]", name, c.Title);
 		}

 		internal void removeMission(contractContainer c)
@@ -95,6 +214,42 @@
 				if (g == c.Contract.ContractGuid)
 					hiddenMissionList.Remove(g);
 			}
+
+			removeFromMasterList(c);
+		}
+
+		private void removeFromMasterList(contractContainer c)
+		{
+			if (missionList.ContainsKey(c.Contract.ContractGuid))
+				missionList.Remove(c.Contract.ContractGuid);
+		}
+
+		private void resetMasterList()
+		{
+			missionList.Clear();
+		}
+
+		internal string stringConcat(List<Guid> source)
+		{
+			if (source.Count == 0)
+				return "";
+			List<string> s = new List<string>();
+			for (int j = 0; j < source.Count; j++)
+			{
+				contractUIObject c = getContract(source[j]);
+				if (c == null)
+					continue;
+				string i;
+				if (c.Order == null)
+					i = "N";
+				else
+					i = c.Order.ToString();
+				bool show = c.ShowParams;
+				string id = string.Format("{0}|{1}|{2}", source[j], i, show);
+				s.Add(id);
+			}
+
+			return string.Join(",", s.ToArray());
 		}
 	}
 }


even #more cleanup

even #more cleanup

--- Crypto/security/CipherUtilities.cs
+++ Crypto/security/CipherUtilities.cs
@@ -299,11 +299,14 @@
                 case CipherAlgorithm.HC256:
                     streamCipher = new HC256Engine();
                     break;
-#if INCLUDE_IDEA
-				case CipherAlgorithm.IDEA:
+
+                case CipherAlgorithm.IDEA:
+#if INCLUDE_IDEA
 					blockCipher = new IdeaEngine();
-					break;
-#endif
+                    break;
+#else
+                    throw new SecurityUtilityException("Cipher " + algorithm + " not included.");
+#endif
                 case CipherAlgorithm.NOEKEON:
                     blockCipher = new NoekeonEngine();
                     break;


Change back to longer sessions after testing.

--- ChalmersxTools/Sessions/SessionManager.cs
+++ ChalmersxTools/Sessions/SessionManager.cs
@@ -67,7 +67,7 @@

                 if (existingLtiSession != null)
                 {
-                    if (existingLtiSession.Timestamp < DateTime.Now.AddMinutes(-1))
+                    if (existingLtiSession.Timestamp < DateTime.Now.AddDays(-1))
                     {
                         // Remove the session if it is older than a day.
                         _dbContext.LtiSessions.Remove(existingLtiSession);
@@ -105,7 +105,7 @@
             {
                 res.DeserializeLtiRequest();

-                if (res.Timestamp < DateTime.Now.AddMinutes(-1))
+                if (res.Timestamp < DateTime.Now.AddDays(-1))
                 {
                     // Remove the session if it is older than a day.
                     _dbContext.LtiSessions.Remove(res);


- increase version to 1.0.1

- increase version to 1.0.1

--- CorsairLED.cs
+++ CorsairLED.cs
@@ -36,7 +36,7 @@
       _about.Type = PluginType.General;
       _about.VersionMajor = 1;  // your plugin version
       _about.VersionMinor = 0;
-      _about.Revision = 0;
+      _about.Revision = 1;
       _about.MinInterfaceVersion = MinInterfaceVersion;
       _about.MinApiRevision = MinApiRevision;
       _about.ReceiveNotifications = (ReceiveNotificationFlags.PlayerEvents | ReceiveNotificationFlags.TagEvents);


Fixed a typo in doc comments.

Fixed a typo in doc comments.

--- AutoUpdater.NET/AutoUpdater.cs
+++ AutoUpdater.NET/AutoUpdater.cs
@@ -98,7 +98,7 @@
         public static String AppCastURL;

         /// <summary>
-        ///     Opens the download url in default browser if true. Very usefull if you have portable application.
+        ///     Opens the download URL in default browser if true. Very usefull if you have portable application.
         /// </summary>
         public static bool OpenDownloadPage;

@@ -770,7 +770,7 @@
         private string Password { get; }

         /// <summary>
-        /// Intialize credentials for Basic Authentication.
+        /// Initializes credentials for Basic Authentication.
         /// </summary>
         /// <param name="username">Username to use for Basic Authentication</param>
         /// <param name="password">Password to use for Basic Authentication</param>


Now using HttpWebRequest for http and https uri scheme. This resolves #296.

--- AutoUpdater.NET/AutoUpdater.cs
+++ AutoUpdater.NET/AutoUpdater.cs
@@ -414,16 +414,22 @@

                     webResponse = ftpWebRequest.GetResponse();
                 }
+                else if(uri.Scheme.Equals(Uri.UriSchemeHttp) || uri.Scheme.Equals(Uri.UriSchemeHttps))
+                {
+                    HttpWebRequest httpWebRequest = (HttpWebRequest) webRequest;
+                    httpWebRequest.UserAgent = $"{AppTitle}/{InstalledVersion}";
+
+                    if (BasicAuthXML != null)
+                    {
+                        httpWebRequest.Headers[HttpRequestHeader.Authorization] = BasicAuthXML.ToString();
+                    }
+
+                    webResponse = httpWebRequest.GetResponse();
+                }
                 else
                 {
-                    if (BasicAuthXML != null)
-                    {
-                        webRequest.Headers[HttpRequestHeader.Authorization] = BasicAuthXML.ToString();
-                    }
-
-                    webResponse = webRequest.GetResponse();
-                }
-
+                    webResponse = webRequest.GetResponse();
+                }
             }
             catch (Exception exception)
             {


Renamed EmptyByteArray

Renamed EmptyByteArray

--- BencodeNET/IO/BencodeStream.cs
+++ BencodeNET/IO/BencodeStream.cs
@@ -12,7 +12,7 @@
     /// </summary>
     public class BencodeStream : IDisposable
     {
-        private static readonly byte[] _emptyByteArray = new byte[0];
+        private static readonly byte[] EmptyByteArray = new byte[0];

         private bool _hasPeeked;
         private int _peekedByte;
@@ -136,7 +136,7 @@
         public byte[] Read(int bytesToRead)
         {
             if (bytesToRead < 0) throw new ArgumentOutOfRangeException(nameof(bytesToRead));
-            if (bytesToRead == 0) return _emptyByteArray;
+            if (bytesToRead == 0) return EmptyByteArray;

             var bytes = new byte[bytesToRead];

@@ -145,7 +145,7 @@
             if (_hasPeeked)
             {
                 if (_peekedByte == -1)
-                    return _emptyByteArray;
+                    return EmptyByteArray;

                 bytes[0] = (byte)_peekedByte;
                 offset = 1;
@@ -234,7 +234,7 @@
         public async Task<byte[]> ReadAsync(int bytesToRead)
         {
             if (bytesToRead < 0) throw new ArgumentOutOfRangeException(nameof(bytesToRead));
-            if (bytesToRead == 0) return _emptyByteArray;
+            if (bytesToRead == 0) return EmptyByteArray;

             var bytes = new byte[bytesToRead];

@@ -243,7 +243,7 @@
             if (_hasPeeked)
             {
                 if (_peekedByte == -1)
-                    return _emptyByteArray;
+                    return EmptyByteArray;

                 bytes[0] = (byte)_peekedByte;
                 offset = 1;


Improve parsing performance (fixes #161)

--- src/HtmlSanitizer/HtmlSanitizer.cs
+++ src/HtmlSanitizer/HtmlSanitizer.cs
@@ -462,8 +462,7 @@
         public IHtmlDocument SanitizeDom(string html, string baseUrl = "")
         {
             var parser = HtmlParserFactory();
-            var dom = parser.Parse("");
-            dom.Body.InnerHtml = html;
+            var dom = parser.Parse("" + html);

             DoSanitize(dom, dom.Body, baseUrl);


Fix creation of stranded kerbals. Fix #123

--- Client/Systems/Scenario/ScenarioSystem.cs
+++ Client/Systems/Scenario/ScenarioSystem.cs
@@ -1,6 +1,4 @@
-using FinePrint.Utilities;
-using LunaClient.Base;
-using LunaClient.Systems.KerbalSys;
+using LunaClient.Base;
 using LunaClient.Systems.SettingsSys;
 using LunaClient.Utilities;
 using LunaCommon;
@@ -162,16 +160,6 @@
         {
             while (ScenarioQueue.TryDequeue(out var scenarioEntry))
             {
-                if (scenarioEntry.ScenarioModule == "ContractSystem")
-                {
-                    SpawnStrandedKerbalsForRescueMissions(scenarioEntry.ScenarioNode);
-                    CreateMissingTourists(scenarioEntry.ScenarioNode);
-                }
-                if (scenarioEntry.ScenarioModule == "ProgressTracking")
-                    CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(scenarioEntry.ScenarioNode);
-
-                CheckForBlankSceneSoTheGameDoesntBugOut(scenarioEntry);
-
                 var psm = new ProtoScenarioModule(scenarioEntry.ScenarioNode);
                 if (IsScenarioModuleAllowed(psm.moduleName) && !IgnoredScenarios.IgnoreReceive.Contains(psm.moduleName))
                 {
@@ -188,126 +176,7 @@
         #endregion

         #region Private methods
-
-        private static void CreateMissingTourists(ConfigNode contractSystemNode)
-        {
-            var contractsNode = contractSystemNode.GetNode("CONTRACTS");
-
-            var kerbalNames = contractsNode.GetNodes("CONTRACT")
-                .Where(c => c.GetValue("type") == "TourismContract" && c.GetValue("state") == "Active")
-                .SelectMany(c => c.GetNodes("PARAM"))
-                .SelectMany(p => p.GetValues("kerbalName"));
-
-            foreach (var kerbalName in kerbalNames)
-            {
-                LunaLog.Log($"[LMP]: Spawning missing tourist ({kerbalName}) for active tourism contract");
-                var pcm = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Tourist);
-                pcm.ChangeName(kerbalName);
-            }
-        }
-
-        private static void SpawnStrandedKerbalsForRescueMissions(ConfigNode contractSystemNode)
-        {
-            var rescueContracts = contractSystemNode.GetNode("CONTRACTS").GetNodes("CONTRACT").Where(c => c.GetValue("type") == "RecoverAsset");
-            foreach (var contractNode in rescueContracts)
-            {
-                if (contractNode.GetValue("state") == "Offered")
-                {
-                    var kerbalName = contractNode.GetValue("kerbalName");
-                    if (!HighLogic.CurrentGame.CrewRoster.Exists(kerbalName))
-                    {
-                        LunaLog.Log($"[LMP]: Spawning missing kerbal ({kerbalName}) for offered KerbalRescue contract");
-                        var pcm = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Unowned);
-                        pcm.ChangeName(kerbalName);
-                    }
-                }
-                if (contractNode.GetValue("state") == "Active")
-                {
-                    var kerbalName = contractNode.GetValue("kerbalName");
-                    LunaLog.Log($"[LMP]: Spawning stranded kerbal ({kerbalName}) for active KerbalRescue contract");
-                    var bodyId = int.Parse(contractNode.GetValue("body"));
-                    if (!HighLogic.CurrentGame.CrewRoster.Exists(kerbalName))
-                        GenerateStrandedKerbal(bodyId, kerbalName);
-                }
-            }
-        }
-
-        private static void GenerateStrandedKerbal(int bodyId, string kerbalName)
-        {
-            //Add kerbal to crew roster.
-            LunaLog.Log($"[LMP]: Spawning missing kerbal, Name: {kerbalName}");
-
-            var pcm = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Unowned);
-            pcm.ChangeName(kerbalName);
-            pcm.rosterStatus = ProtoCrewMember.RosterStatus.Assigned;
-
-            //Create protovessel
-            var newPartId = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);
-            var contractBody = FlightGlobals.Bodies[bodyId];
-
-            //Atmo: 10km above atmo, to half the planets radius out.
-            //Non-atmo: 30km above ground, to half the planets radius out.
-            var minAltitude = CelestialUtilities.GetMinimumOrbitalDistance(contractBody, 1.1f);
-            var maxAltitude = minAltitude + contractBody.Radius * 0.5;
-
-            var strandedOrbit = Orbit.CreateRandomOrbitAround(FlightGlobals.Bodies[bodyId], minAltitude, maxAltitude);
-
-            var kerbalPartNode = new[] { ProtoVessel.CreatePartNode("kerbalEVA", newPartId, pcm) };
-
-            var protoVesselNode = ProtoVessel.CreateVesselNode(kerbalName, VesselType.EVA, strandedOrbit, 0,
-                kerbalPartNode);
-
-            //It's not supposed to be infinite, but you're crazy if you think I'm going to decipher the values field of the rescue node.
-            var discoveryNode = ProtoVessel.CreateDiscoveryNode(DiscoveryLevels.Unowned, UntrackedObjectClass.A,
-                double.PositiveInfinity,
-                double.PositiveInfinity);
-
-            var protoVessel = new ProtoVessel(protoVesselNode, HighLogic.CurrentGame)
-            {
-                discoveryInfo = discoveryNode
-            };
-
-            HighLogic.CurrentGame.flightState.protoVessels.Add(protoVessel);
-        }
-
-        private static void CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(ConfigNode progressTrackingNode)
-        {
-            foreach (var possibleNode in progressTrackingNode.nodes)
-                CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(possibleNode as ConfigNode);
-
-            //The kerbals are kept in a ConfigNode named 'crew', with 'crews' as a comma space delimited array of names.
-            if (progressTrackingNode.name == "crew")
-            {
-                var kerbalNames = progressTrackingNode.GetValue("crews");
-                if (!string.IsNullOrEmpty(kerbalNames))
-                {
-                    var kerbalNamesSplit = kerbalNames.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
-                    foreach (var kerbalName in kerbalNamesSplit.Where(k => !HighLogic.CurrentGame.CrewRoster.Exists(k)))
-                    {
-                        LunaLog.Log($"[LMP]: Generating missing kerbal from ProgressTracking: {kerbalName}");
-                        var pcm = CrewGenerator.RandomCrewMemberPrototype();
-                        pcm.ChangeName(kerbalName);
-                        HighLogic.CurrentGame.CrewRoster.AddCrewMember(pcm);
-
-                        //Also send it off to the server
-                        KerbalSystem.Singleton.MessageSender.SendKerbal(pcm);
-                    }
-                }
-            }
-        }
-
-        //If the scene field is blank, KSP will throw an error while starting the game, meaning players will be unable to join the server.
-        private static void CheckForBlankSceneSoTheGameDoesntBugOut(ScenarioEntry scenarioEntry)
-        {
-            if (scenarioEntry.ScenarioNode.GetValue("scene") == string.Empty)
-            {
-                var nodeName = scenarioEntry.ScenarioModule;
-                LunaScreenMsg.PostScreenMessage($"{nodeName} is badly behaved!", 3, ScreenMessageStyle.UPPER_CENTER);
-                LunaLog.Log($"[LMP]: {nodeName} is badly behaved!");
-                scenarioEntry.ScenarioNode.SetValue("scene", "7, 8, 5, 6, 9");
-            }
-        }
-
+
         private static bool LoadModuleByGameMode(KSPScenarioType validScenario)
         {
             switch (HighLogic.CurrentGame.Mode)
@@ -322,7 +191,7 @@
             return false;
         }

-        private bool IsScenarioModuleAllowed(string scenarioName)
+        private static bool IsScenarioModuleAllowed(string scenarioName)
         {
             if (string.IsNullOrEmpty(scenarioName)) return false;


- added SSL support for NET_2_0 build.

- added SSL support for NET_2_0 build.

--- src/IrcConnection/IrcConnection.cs
+++ src/IrcConnection/IrcConnection.cs
@@ -33,6 +33,9 @@
 using System.Threading;
 using System.Reflection;
 using System.Net.Sockets;
+#if NET_2_0
+using System.Net.Security;
+#endif

 namespace Meebey.SmartIrc4net
 {
@@ -47,6 +50,9 @@
         private string[]         _AddressList = {"localhost"};
         private int              _CurrentAddress;
         private int              _Port = 6667;
+#if NET_2_0
+        private bool             _UseSsl;
+#endif
         private StreamReader     _Reader;
         private StreamWriter     _Writer;
         private ReadThread       _ReadThread;
@@ -287,6 +293,26 @@
             }
         }

+#if NET_2_0
+        /// <summary>
+        /// Enables/disables using SSL for the connection
+        /// Default: false
+        /// </summary>
+        public bool UseSsl {
+            get {
+                return _UseSsl;
+            }
+            set {
+                _UseSsl = value;
+                if (value) {
+                    _Port = 6697;
+                } else {
+                    _Port = 6667;
+                }
+            }
+        }
+#endif
+
         /// <summary>
         /// Timeout in seconds for receiving data from the socket
         /// Default: 600
@@ -412,7 +438,7 @@
         public void Connect(string[] addresslist, int port)
         {
             if (_IsConnected) {
-                throw new AlreadyConnectedException("Already connected to: "+Address+":"+Port);
+                throw new AlreadyConnectedException("Already connected to: " + Address + ":" + Port);
             }

 #if LOG4NET
@@ -435,8 +461,18 @@
                 _TcpClient.SendTimeout = _SocketSendTimeout*1000;
                 _TcpClient.Connect(ip, port);

-                _Reader = new StreamReader(_TcpClient.GetStream(), _Encoding);
-                _Writer = new StreamWriter(_TcpClient.GetStream(), _Encoding);
+                Stream stream = _TcpClient.GetStream();
+#if NET_2_0
+                if (_UseSsl) {
+                    SslStream sslStream = new SslStream(stream, false, delegate {
+                        return true;
+                    });
+                    sslStream.AuthenticateAsClient(Address);
+                    stream = sslStream;
+                }
+#endif
+                _Reader = new StreamReader(stream, _Encoding);
+                _Writer = new StreamWriter(stream, _Encoding);

                 if (_Encoding.GetPreamble().Length > 0) {
                     // HACK: we have an encoding that has some kind of preamble
@@ -510,7 +546,7 @@
         /// <param name="port">Port number to connect to</param>
         public void Connect(string address, int port)
         {
-            Connect(new string[] {address}, port);
+            Connect(new string[] { address }, port);
         }

         /// <summary>
@@ -861,6 +897,10 @@
                     Thread.ResetAbort();
 #if LOG4NET
                     Logger.Socket.Debug("ReadThread aborted");
+#endif
+                } catch (Exception ex) {
+#if LOG4NET
+                    Logger.Socket.Error(ex);
 #endif
                 }
             }
@@ -943,6 +983,10 @@
                     Thread.ResetAbort();
 #if LOG4NET
                     Logger.Socket.Debug("WriteThread aborted");
+#endif
+                } catch (Exception ex) {
+#if LOG4NET
+                    Logger.Socket.Error(ex);
 #endif
                 }
             }
@@ -1166,8 +1210,11 @@
 #if LOG4NET
                     Logger.Socket.Debug("IdleWorkerThread aborted");
 #endif
-                }
-            }
+                } catch (Exception ex) {
+#if LOG4NET
+                    Logger.Socket.Error(ex);
+#endif
+                }
         }
     }
 }


Rearranged Task.net35.cs

Rearranged Task.net35.cs

--- Core/System/Threading/Tasks/Task.net35.cs
+++ Core/System/Threading/Tasks/Task.net35.cs
@@ -8,19 +8,20 @@
 {
     public partial class Task : IDisposable, IAsyncResult
     {
+        internal CancellationToken _cancellationToken;
+
         [ThreadStatic]
         private static Task _current;

         private static int _lastId;
-        private object _action;
         private readonly TaskCreationOptions _creationOptions;
         private readonly int _id;
         private readonly Task _parent;
-        private TaskScheduler _scheduler;
-        internal CancellationToken _cancellationToken;
+        private object _action;
         private ExecutionContext _capturedContext;
         private AggregateException _exception;
         private int _isDisposed = 0;
+        private TaskScheduler _scheduler;
         private object _state;
         private int _status;
         private StructNeedle<ManualResetEventSlim> _waitHandle;
@@ -131,6 +132,28 @@
             }
         }

+        [Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Microsoft's Design")]
+        WaitHandle IAsyncResult.AsyncWaitHandle
+        {
+            get
+            {
+                if (Thread.VolatileRead(ref _isDisposed) == 1)
+                {
+                    throw new ObjectDisposedException(GetType().FullName);
+                }
+                return _waitHandle.Value.WaitHandle;
+            }
+        }
+
+        [Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Returns false")]
+        bool IAsyncResult.CompletedSynchronously
+        {
+            get
+            {
+                return false;
+            }
+        }
+
         public int Id
         {
             get
@@ -173,29 +196,6 @@
                 return (TaskStatus)Thread.VolatileRead(ref _status);
             }
         }
-
-        [Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Microsoft's Design")]
-        WaitHandle IAsyncResult.AsyncWaitHandle
-        {
-            get
-            {
-                if (Thread.VolatileRead(ref _isDisposed) == 1)
-                {
-                    throw new ObjectDisposedException(GetType().FullName);
-                }
-                return _waitHandle.Value.WaitHandle;
-            }
-        }
-
-        [Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Returns false")]
-        bool IAsyncResult.CompletedSynchronously
-        {
-            get
-            {
-                return false;
-            }
-        }
-
         internal static Task Current
         {
             get
@@ -396,6 +396,28 @@
                     GC.KeepAlive(cancellationToken.WaitHandle);
                 }
             }
+        }
+
+        internal bool ExecuteEntry(bool preventDoubleExecution)
+        {
+            if (!SetRunning(preventDoubleExecution))
+            {
+                return false;
+            }
+            if (!IsCanceled)
+            {
+                if (_cancellationToken.IsCancellationRequested)
+                {
+                    Thread.VolatileWrite(ref _status, (int)TaskStatus.Canceled);
+                    SetCompleted();
+                    FinishStageThree();
+                }
+                else
+                {
+                    ExecuteWithThreadLocal(ref _current);
+                }
+            }
+            return true;
         }

         internal bool InternalCancel(bool cancelNonExecutingOnly)
@@ -459,29 +481,6 @@
                 return cancelSucceeded;
             }
         }
-
-        internal bool ExecuteEntry(bool preventDoubleExecution)
-        {
-            if (!SetRunning(preventDoubleExecution))
-            {
-                return false;
-            }
-            if (!IsCanceled)
-            {
-                if (_cancellationToken.IsCancellationRequested)
-                {
-                    Thread.VolatileWrite(ref _status, (int)TaskStatus.Canceled);
-                    SetCompleted();
-                    FinishStageThree();
-                }
-                else
-                {
-                    ExecuteWithThreadLocal(ref _current);
-                }
-            }
-            return true;
-        }
-
         internal void InternalStart(TaskScheduler scheduler)
         {
             if (Thread.VolatileRead(ref _isDisposed) == 1)


Validate metric binding type. ref #8

Validate metric binding type. ref #8

--- BosunReporter/BosunReporter.cs
+++ BosunReporter/BosunReporter.cs
@@ -91,7 +91,10 @@
                             name, type.FullName, _rootNameToType[name].FullName));
                 }

-//                if (type)
+                if (!type.IsSubclassOf(typeof (BosunMetric)))
+                {
+                    throw new Exception(String.Format("Cannot bind metric \"{0}\" to Type {1}. It does not inherit from BosunMetric.", name, type.FullName));
+                }

                 _rootNameToType[name] = type;
             }


consistency

consistency

--- DIP/After/InsuranceApplicantRepository.cs
+++ DIP/After/InsuranceApplicantRepository.cs
@@ -4,12 +4,7 @@
 {
     public class ApplicantRepository : IInsuranceApplicantRepository
     {
-        public ApplicantRepository()
-        {
-            Applicants = new HashSet<InsuranceApplicant>();
-        }
-
-        private HashSet<InsuranceApplicant> Applicants { get; set; }
+        private static readonly HashSet<InsuranceApplicant> Applicants = new HashSet<InsuranceApplicant>();

         public void Save(InsuranceApplicant applicant)
         {


LUCENENET-364 Workaround for a Mono float/Single parsing issue

git-svn-id: b2dcba4c53c5fa0a86ccceee81d7e0ce197ae049@940116 13f79535-47bb-0310-9956-ffa450edef68


added documentation (thanks Louie for the feedback)

--- cs/Serializer/VowpalWabbitSerializerCompiled.cs
+++ cs/Serializer/VowpalWabbitSerializerCompiled.cs
@@ -29,42 +29,102 @@
     /// <returns>A serializer for the given user example type.</returns>
     public sealed class VowpalWabbitSerializerCompiled<TExample>
     {
+        /// <summary>
+        /// Internal structure collecting all itmes required to marshal a single feature.
+        /// </summary>
         internal sealed class FeatureExpressionInternal
         {
+            /// <summary>
+            /// The supplied feature expression.
+            /// </summary>
             internal FeatureExpression Source;

-            internal readonly List<ParameterExpression> Additional = new List<ParameterExpression>();
-
+            /// <summary>
+            /// The resolved mrarshalling method.
+            /// </summary>
             internal MarshalMethod MarshalMethod;
-
-            internal Expression<Action> Visit;
-        }
-
+        }
+
+        /// <summary>
+        /// Describes the actual marshalling method and the feature type (e.g. <see cref="PreHashedFeature"/>).
+        /// </summary>
         internal sealed class MarshalMethod
         {
+            /// <summary>
+            /// The actual marshalling method.
+            /// </summary>
             internal MethodInfo Method;

+            /// <summary>
+            /// The feature type (e.g. <see cref="PreHashedFeature"/>).
+            /// </summary>
             internal Type MetaFeatureType;
         }

-        private static readonly string SerializeMethodName = "Serialize";
-
-        private static readonly ConstructorInfo ArgumentNullExceptionConstructorInfo = (ConstructorInfo)ReflectionHelper.GetInfo((ArgumentNullException t) => new ArgumentNullException(""));
-
+        /// <summary>
+        /// All discovered features.
+        /// </summary>
         private readonly FeatureExpressionInternal[] allFeatures;
-        private readonly List<Type> featurizerTypes;
+
+        /// <summary>
+        /// Ordered list of featurizer types. Marshalling methods are resolved in order of this list.
+        /// <see cref="VowpalWabbitDefaultMarshaller"/> is added last as  default.
+        /// </summary>
+        private readonly List<Type> marshallerTypes;
+
+        /// <summary>
+        /// The main body of the serializer holding preemptive calcutions (e.g. <see cref="PreHashedFeature"/>.
+        /// </summary>
         private readonly List<Expression> body;
+
+        /// <summary>
+        /// The body executed for example.
+        /// </summary>
         private readonly List<Expression> perExampleBody;
+
+        /// <summary>
+        /// Local variables.
+        /// </summary>
         private readonly List<ParameterExpression> variables;
+
+        /// <summary>
+        /// Local variables holding namespaces.
+        /// </summary>
         private readonly List<ParameterExpression> namespaceVariables;

+        /// <summary>
+        /// The parameter of the main lambda to <see cref="VowpalWabbit"/>.
+        /// </summary>
         private ParameterExpression vwParameter;
+
+        /// <summary>
+        /// The parameter of the main lambda to <see cref="VowpalWabbitMarshalContext"/>.
+        /// </summary>
         private ParameterExpression contextParameter;
+
+        /// <summary>
+        /// The parameter of the per example lambda to <see cref="VowpalWabbitExample"/>.
+        /// </summary>
         private ParameterExpression exampleParameter;
+
+        /// <summary>
+        /// The parameter of the per example lambda to <see cref="ILabel"/>
+        /// </summary>
         private ParameterExpression labelParameter;

-        private readonly List<ParameterExpression> featurizers;
+        /// <summary>
+        /// The list of featurizers.
+        /// </summary>
+        private readonly List<ParameterExpression> marshallers;
+
+        /// <summary>
+        /// The list of meta features such as <see cref="PreHashedFeature"/>.
+        /// </summary>
         private readonly List<ParameterExpression> metaFeatures;
+
+        /// <summary>
+        /// If true, VowpalWabbit string generation is disabled.
+        /// </summary>
         private readonly bool disableStringExampleGeneration;

         internal VowpalWabbitSerializerCompiled(IReadOnlyList<FeatureExpression> allFeatures, IReadOnlyList<Type> featurizerTypes, bool disableStringExampleGeneration)
@@ -77,35 +137,37 @@

             this.allFeatures = allFeatures.Select(f => new FeatureExpressionInternal { Source = f }).ToArray();

-            this.featurizerTypes = featurizerTypes == null ? new List<Type>() : new List<Type>(featurizerTypes);
-
+            // collect the types used for marshalling
+            this.marshallerTypes = featurizerTypes == null ? new List<Type>() : new List<Type>(featurizerTypes);
+
+            // extract types from overrides defined on particular features
             var overrideFeaturizerTypes = allFeatures
                 .Select(f => f.OverrideSerializeMethod)
                 .Where(o => o != null)
                 .Select(o => o.DeclaringType);
-            this.featurizerTypes.AddRange(overrideFeaturizerTypes);
+            this.marshallerTypes.AddRange(overrideFeaturizerTypes);

             // add as last
-            this.featurizerTypes.Add(typeof(VowpalWabbitDefaultMarshaller));
+            this.marshallerTypes.Add(typeof(VowpalWabbitDefaultMarshaller));

             this.body = new List<Expression>();
             this.perExampleBody = new List<Expression>();
             this.variables = new List<ParameterExpression>();
             this.namespaceVariables = new List<ParameterExpression>();
-            this.featurizers = new List<ParameterExpression>();
+            this.marshallers = new List<ParameterExpression>();
             this.metaFeatures = new List<ParameterExpression>();

-            this.CreateVisitors();
+            this.CreateMarshallers();

             this.ResolveFeatureMarshallingMethods();
             this.CreateParameters();

             // CODE MarshalLabel(...)
-            this.CreateFeaturizerCall("MarshalLabel", this.contextParameter, this.labelParameter);
+            this.CreateMarshallerCall("MarshalLabel", this.contextParameter, this.labelParameter);

             this.CreateNamespacesAndFeatures();

-            this.CreateLambda();
+            this.CreateLambdas();
             // this.CreateLambda();
             this.Compile();
         }
@@ -122,25 +184,28 @@
             return new VowpalWabbitSerializer<TExample>(this, vw);
         }

-        private void CreateVisitors()
-        {
-            foreach (var featurizerType in this.featurizerTypes)
-            {
-                var featurizer = Expression.Parameter(featurizerType, "featurizer_" + featurizerType.Name);
-
-                this.featurizers.Add(featurizer);
-                this.variables.Add(featurizer);
+        /// <summary>
+        /// Define variables and instantiate marshaller types.
+        /// </summary>
+        private void CreateMarshallers()
+        {
+            foreach (var marshallerType in this.marshallerTypes)
+            {
+                var marshaller = Expression.Parameter(marshallerType, "marshaller_" + marshallerType.Name);
+
+                this.marshallers.Add(marshaller);
+                this.variables.Add(marshaller);

                 // CODE new FeaturizerType(disableStringExampleGeneration)
-                var newExpr = CreateNew(featurizerType, Expression.Constant(disableStringExampleGeneration));
+                var newExpr = CreateNew(marshallerType, Expression.Constant(disableStringExampleGeneration));
                 if (newExpr == null)
                 {
-                    // CODE new FeaturizerType()
-                    newExpr = Expression.New(featurizerType);
+                    // CODE new MarshallerType()
+                    newExpr = Expression.New(marshallerType);
                 }

-                // featurizer = new ...
-                this.body.Add(Expression.Assign(featurizer, newExpr));
+                // marshaller = new ...
+                this.body.Add(Expression.Assign(marshaller, newExpr));
             }
         }

@@ -194,7 +259,7 @@
             foreach (var metaFeatureType in metaFeatureTypeCandidates)
             {
                 // find visitor.MarshalFeature(VowpalWabbitMarshallingContext context, Namespace ns, <PreHashedFeature|Feature> feature, <valueType> value)
-                var method = this.featurizerTypes.Select(visitor =>
+                var method = this.marshallerTypes.Select(visitor =>
                     ReflectionHelper.FindMethod(
                             visitor,
                             methodName,
@@ -218,6 +283,9 @@
             throw new ArgumentException("Unable to find featurize method for " + feature);
         }

+        /// <summary>
+        /// Resolve methods for each feature base on feature type and configuration.
+        /// </summary>
         private void ResolveFeatureMarshallingMethods()
         {
             foreach (var feature in this.allFeatures)
@@ -226,6 +294,24 @@
             }
         }

+        /// <summary>
+        /// define functions input parameter
+        /// </summary>
+        private void CreateParameters()
+        {
+            this.vwParameter = Expression.Parameter(typeof(VowpalWabbit), "vw");
+            this.contextParameter = Expression.Parameter(typeof(VowpalWabbitMarshalContext), "context");
+            this.exampleParameter = Expression.Parameter(typeof(TExample), "example");
+            this.labelParameter = Expression.Parameter(typeof(ILabel), "label");
+        }
+
+        /// <summary>
+        /// Instantiate the meta information object such as <see cref="PreHashedFeature"/>
+        /// for a given feature.
+        /// </summary>
+        /// <param name="featureInternal">The feature.</param>
+        /// <param name="namespace">The namespace.</param>
+        /// <returns>The "new" expression for the meta information object.</returns>
         private Expression CreateFeature(FeatureExpressionInternal featureInternal, Expression @namespace)
         {
             FeatureExpression feature = featureInternal.Source;
@@ -233,6 +319,7 @@

             if (metaFeatureType.IsGenericType && metaFeatureType.GetGenericTypeDefinition() == typeof(EnumerizedFeature<>))
             {
+                // preemptively calculate all hashes for each enum value
                 var featureParameter = Expression.Parameter(metaFeatureType);
                 var valueParameter = Expression.Parameter(feature.FeatureType);

@@ -251,7 +338,7 @@
                             Expression.Constant(value))));
                 }

-                var cases =  Enum.GetValues(feature.FeatureType)
+                var cases = Enum.GetValues(feature.FeatureType)
                         .Cast<object>()
                         .Zip(hashVariables, (value, hash) => Expression.SwitchCase(
                             hash,
@@ -277,7 +364,7 @@
             }
             else if (metaFeatureType == typeof(PreHashedFeature))
             {
-                // CODE: new PreHashedFeature(vw, namespace, "Name", "AddAnchor");
+                // CODE new PreHashedFeature(vw, namespace, "Name", "AddAnchor");
                 return CreateNew(
                         typeof(PreHashedFeature),
                         this.vwParameter,
@@ -287,6 +374,7 @@
                         Expression.Constant(feature.Dictify));
             }
             else
+                // CODE new Feature("Name", ...)
                 return CreateNew(
                     metaFeatureType,
                     Expression.Constant(feature.Name, typeof(string)),
@@ -294,6 +382,12 @@
                     Expression.Constant(feature.Dictify));
         }

+        /// <summary>
+        /// Helper to create the "new" expression using a matching constructor.
+        /// </summary>
+        /// <param name="type">The type of the new object.</param>
+        /// <param name="constructorParameters">The actual parameters for the constructor.</param>
+        /// <returns>The "new" expression bound to <paramref name="constructorParameters"/>.</returns>
         private static Expression CreateNew(Type type, params Expression[] constructorParameters)
         {
             var ctor = type.GetConstructor(constructorParameters.Select(e => e.Type).ToArray());
@@ -341,7 +435,7 @@
                     this.body.Add(Expression.Assign(featureVariable, newFeature));

                     // TODO: optimize
-                    var featurizer = this.featurizers.First(f => f.Type == feature.MarshalMethod.Method.ReflectedType);
+                    var marshaller = this.marshallers.First(f => f.Type == feature.MarshalMethod.Method.ReflectedType);

                     var valueVariable = feature.Source.ValueExpressionFactory(this.exampleParameter);
                     Expression featureVisit;
@@ -351,7 +445,7 @@
                         featureVisit = Expression.IfThen(
                             Expression.NotEqual(valueVariable, Expression.Constant(null)),
                                 Expression.Call(
-                                     featurizer,
+                                     marshaller,
                                      feature.MarshalMethod.Method,
                                      this.contextParameter,
                                      namespaceVariable,
@@ -362,7 +456,7 @@
                     {
                         // featurzier.MarshalXXX(vw, context, ns, feature, value);
                         featureVisit = Expression.Call(
-                            featurizer,
+                            marshaller,
                             feature.MarshalMethod.Method,
                             this.contextParameter,
                             namespaceVariable,
@@ -388,20 +482,25 @@
                 var featureVisitLambda = Expression.Lambda(Expression.Block(featureVisits));

                 // CODE: featurizer.MarshalNamespace(context, namespace, { ... })
-                this.CreateFeaturizerCall("MarshalNamespace", this.contextParameter, namespaceVariable, featureVisitLambda);
-            }
-        }
-
-        private void CreateFeaturizerCall(string methodName, params Expression[] parameters)
+                this.CreateMarshallerCall("MarshalNamespace", this.contextParameter, namespaceVariable, featureVisitLambda);
+            }
+        }
+
+        /// <summary>
+        /// Create the invocation expression of a marshalling method.
+        /// </summary>
+        /// <param name="methodName">The marshalling method to invoke.</param>
+        /// <param name="parameters">The parameters for this method.</param>
+        private void CreateMarshallerCall(string methodName, params Expression[] parameters)
         {
             var parameterTypes = parameters.Select(p => p.Type).ToArray();
-            foreach (var featurizer in this.featurizers)
+            foreach (var marshaller in this.marshallers)
 	        {
-                var method = featurizer.Type.GetMethod(methodName, parameterTypes);
+                var method = marshaller.Type.GetMethod(methodName, parameterTypes);

                 if (method != null)
                 {
-                    this.perExampleBody.Add(Expression.Call(featurizer, method, parameters));
+                    this.perExampleBody.Add(Expression.Call(marshaller, method, parameters));
                     return;
                 }
 	        }
@@ -409,7 +508,10 @@
             throw new ArgumentException("Unable to find MarshalNamespace(VowpalWabbitMarshallingContext, Namespace, Action) on any featurizer");
         }

-        private void CreateLambda()
+        /// <summary>
+        /// Creates the main lambda and the per example lambda.
+        /// </summary>
+        private void CreateLambdas()
         {
             // CODE (TExample, Label) => { ... }
             this.body.Add(
@@ -441,6 +543,9 @@
             private set;
         }

+        /// <summary>
+        /// Compiles the <see cref="SourceExpression"/> into an executable assembly.
+        /// </summary>
         private void Compile()
         {
             var asmName = new AssemblyName("VowpalWabbitSerializer." + typeof(TExample).Name);
@@ -455,8 +560,9 @@
             var typeBuilder = moduleBuilder.DefineType("VowpalWabbitSerializer" + Guid.NewGuid().ToString().Replace('-', '_'));

             // Create our method builder for this type builder
+            const string serializeMethodName = "Serialize";
             var methodBuilder = typeBuilder.DefineMethod(
-                SerializeMethodName,
+                serializeMethodName,
                 MethodAttributes.Public | MethodAttributes.Static,
                 typeof(Action<VowpalWabbitMarshalContext, TExample, ILabel>),
                 new[] { typeof(VowpalWabbit) });
@@ -474,19 +580,7 @@

             this.Func = (Func<VowpalWabbit, Action<VowpalWabbitMarshalContext, TExample, ILabel>>)Delegate.CreateDelegate(
                 typeof(Func<VowpalWabbit, Action<VowpalWabbitMarshalContext, TExample, ILabel>>),
-                dynType.GetMethod(SerializeMethodName));
-        }
-
-        /// <summary>
-        /// define functions input parameter
-        /// </summary>
-        private void CreateParameters()
-        {
-            this.vwParameter = Expression.Parameter(typeof(VowpalWabbit), "vw");
-            this.contextParameter = Expression.Parameter(typeof(VowpalWabbitMarshalContext), "context");
-            this.exampleParameter = Expression.Parameter(typeof(TExample), "example");
-            this.labelParameter = Expression.Parameter(typeof(ILabel), "label");
-
+                dynType.GetMethod(serializeMethodName));
         }
     }
 }


Cascade parameters during child update.

Cascade parameters during child update.

--- cslatest/Csla.Test/DataPortalChild/ChildList.cs
+++ cslatest/Csla.Test/DataPortalChild/ChildList.cs
@@ -29,7 +29,7 @@
       _status = "Fetched";
     }

-    protected override void Child_Update()
+    protected override void Child_Update(params object[] p)
     {
       base.Child_Update();
       _status = "Updated";


Fix for failing test Components/Basic/TestMergeComponent. Refinement of contributed patch (see NH-2011 and NH-2061)

SVN: 488784591515bd4cdaa016be4ec9b172dc4e7caf@5015

--- src/NHibernate/Type/TypeFactory.cs
+++ src/NHibernate/Type/TypeFactory.cs
@@ -1121,14 +1121,14 @@
 					// need to extract the component values and check for subtype replacements...
 					IAbstractComponentType componentType = (IAbstractComponentType)types[i];
 					IType[] subtypes = componentType.Subtypes;
-					object[] origComponentValues = original[i] == null
-																					? new object[subtypes.Length]
-																					: componentType.GetPropertyValues(original[i], session);
-					object[] targetComponentValues = componentType.GetPropertyValues(target[i], session);
-					object[] componentCopy = ReplaceAssociations(origComponentValues, targetComponentValues, subtypes, session, null, copyCache,
-															foreignKeyDirection);
-					if (!componentType.IsAnyType)
+					object[] origComponentValues = original[i] == null ? new object[subtypes.Length] : componentType.GetPropertyValues(original[i], session);
+					object[] targetComponentValues = target[i] == null ? new object[subtypes.Length] : componentType.GetPropertyValues(target[i], session);
+
+					object[] componentCopy = ReplaceAssociations(origComponentValues, targetComponentValues, subtypes, session, null, copyCache, foreignKeyDirection);
+
+					if (!componentType.IsAnyType && target[i] != null)
 						componentType.SetPropertyValues(target[i], componentCopy, session.EntityMode);
+
 					copied[i] = target[i];
 				}
 				else if (!types[i].IsAssociationType)


(GH-85) Delete nupkg files

(GH-85) Delete nupkg files

- This time with the correct globbing pattern
- Not, this is hard-coded to a top level tools folder, which doesn't take into account any cake.config configurations

--- Cake.Recipe/Content/build.cake
+++ Cake.Recipe/Content/build.cake
@@ -70,6 +70,14 @@
                 SendMessageToSlackChannel("Continuous Integration Build of " + BuildParameters.Title + " just failed :-(");
             }
         }
+    }
+
+    // Clear nupkg files from tools directory
+    if(DirectoryExists(Context.Environment.WorkingDirectory.Combine("tools")))
+    {
+        Information("Deleting nupkg files...");
+        var nupkgFiles = GetFiles(Context.Environment.WorkingDirectory.Combine("tools") + "/**/*.nupkg");
+        DeleteFiles(nupkgFiles);
     }

     Information("Finished running tasks.");


Removing FindUser hackery

Removing FindUser hackery

--- Extensions.cs
+++ Extensions.cs
@@ -18,27 +18,6 @@
 		public static bool SendFakePrivMessage(this IServer server, IUser source, string msg) {
 			string line = string.Format(":{0}!{1}@{2} PRIVMSG {3} :{4}", source.Nick, source.Ident, source.Host, server.UserNick, msg);
 			return server.SendFakeRaw(line);
-		}
-		//TODO: remove this bit of hackery when the API is updated.
-		private static Assembly GetAdiIRCAssembly() {
-			if (adiIRC == null) {
-				Assembly[] allAssemblies = AppDomain.CurrentDomain.GetAssemblies();
-				for (int i = 0; i < allAssemblies.Length; i++) {
-					if (allAssemblies[i].GetName().Name == "AdiIRC") {
-						adiIRC = allAssemblies[i];
-						break;
-					}
-				}
-			}
-			return adiIRC;
-		}
-		public static IUser FindUser(this IServer server, string prefix) {
-			if (prefix.Contains("!")) {
-				prefix = prefix.Substring(0, prefix.IndexOf('!'));
-			}
-			Type serverT = GetAdiIRCAssembly().GetType("AdiIRC.IRC.Core.Server");
-			MethodInfo mi = serverT.GetMethod("FindUser", BindingFlags.NonPublic | BindingFlags.Instance);
-			return mi.Invoke(server, new object[]{ prefix }) as IUser;
 		}

 		// Extending byte[]


v1.3.1 - Removed ability to adjust text size. Hard coded now. I could not get the banner+text sizes to properly adjust after saving it. Additionally, existing Chirps couldn't be adjusted on-the-fly, making it really awkward.

--- ChirpBanner/ChirpyBannerMod.cs
+++ ChirpBanner/ChirpyBannerMod.cs
@@ -43,7 +43,7 @@
 			colors.AddTextfield ("Name Color", ChirpyBanner.CurrentConfig.NameColor, CheckChirpNameColor, CheckChirpNameColor);
 			colors.AddTextfield ("Chirp Color", ChirpyBanner.CurrentConfig.MessageColor, CheckChirpMsgColor, CheckChirpMsgColor);

-			UIHelperBase version = helper.AddGroup ("v1.3");
+			UIHelperBase version = helper.AddGroup ("v1.3.1");

 			//group.AddSlider("My Slider", 0, 1, 0.01f, 0.5f, EventSlide);
 			//group.AddDropdown("My Dropdown", new string[] { "First Entry", "Second Entry", "Third Entry" }, -1, EventSel);
@@ -498,8 +498,8 @@
 			int viewWidth = (int)uiv.GetScreenResolution ().x;
 			int viewHeight = (int)uiv.GetScreenResolution ().y;

-			//this.height = 25;
-			this.height = (float)ChirpyBanner.CurrentConfig.TextSize + 20;
+			this.height = 25.0f;
+			//this.height = (float)ChirpyBanner.CurrentConfig.TextSize + 20;
 			this.position = new Vector3 ((-viewWidth / 2) + banner_inset, (viewHeight / 2));
 			this.opacity = ChirpyBanner.CurrentConfig.BackgroundAlpha;
 			this.width = (viewWidth * ChirpyBanner.CurrentConfig.BannerWidth) - (banner_inset * 2);
@@ -525,18 +525,18 @@
 			hasChirps = true;
 			ChirpLabel = this.AddUIComponent<UILabel> ();
 			if (ChirpLabel != null) {
-				//newLabel.autoSize = true;
-				//newLabel.autoHeight = true;
-				ChirpLabel.autoHeight = true;
-				ChirpLabel.autoSize = true;
+				//ChirpLabel.autoHeight = true;
+				//ChirpLabel.autoSize = true;
 				ChirpLabel.verticalAlignment = UIVerticalAlignment.Middle;
 				ChirpLabel.textAlignment = UIHorizontalAlignment.Left;
 				ChirpLabel.relativePosition = new Vector3 ((this.width), 0);
 				//ChirpLabel.height = (float)ChirpyBanner.CurrentConfig.TextSize;
+				ChirpLabel.height = 10.0f;
 				ChirpLabel.padding = new RectOffset (0, 0, 2, 2);

-				ChirpLabel.textScaleMode = UITextScaleMode.ScreenResolution;
-				ChirpLabel.textScale = (float)ChirpyBanner.CurrentConfig.TextSize / 15f;
+				ChirpLabel.textScaleMode = UITextScaleMode.None;
+				ChirpLabel.textScale = 1.0f;
+				ChirpLabel.autoHeight = false;
 				ChirpLabel.opacity = 1.0f;
 				ChirpLabel.processMarkup = true;
 				ChirpLabel.text = chirpStr;


ClientStarter.cs: Timeout option is introduced.

--- ClientStarter/ClientStarter.cs
+++ ClientStarter/ClientStarter.cs
@@ -10,7 +10,7 @@
     /// AIWolf client starter.
     /// </summary>
     /// <remarks>
-    /// Usage: -h host -p port -c clientClass dllName [roleRequest] [-n name]
+    /// Usage: [-h host] [-p port] -c clientClass dllName [roleRequest] [-n name]
     /// </remarks>
     public class ClientStarter
     {
@@ -27,12 +27,13 @@
         /// <remarks></remarks>
         public static void Main(string[] args)
         {
-            string host = null;
-            int port = -1;
+            string host = "localhost";
+            int port = 10000;
             string clsName = null;
             string dllName = null;
             Role? roleRequest = null;
             string playerName = null;
+            int timeout = 100; // ms

             for (int i = 0; i < args.Length; i++)
             {
@@ -76,11 +77,16 @@
                         i++;
                         playerName = args[i];
                     }
+                    else if (args[i].Equals("-t"))
+                    {
+                        i++;
+                        timeout = int.Parse(args[i]);
+                    }
                 }
             }
-            if (port < 0 || host == null || clsName == null)
+            if (port < 0 || clsName == null)
             {
-                Console.Error.WriteLine("Usage:" + typeof(ClientStarter).Name + " -h host -p port -c clientClass dllName [roleRequest] [-n name]");
+                Console.Error.WriteLine("Usage:" + typeof(ClientStarter).Name + " [-h host] [-p port] -c clientClass dllName [roleRequest] [-n name] [-t timeout]");
                 return;
             }

@@ -112,11 +118,19 @@
             }

             TcpipClient client = new TcpipClient(host, port, roleRequest);
+            client.Timeout = timeout;
             if (playerName != null)
             {
                 client.PlayerName = playerName;
             }
-            client.Connect(player);
+            try
+            {
+                client.Connect(player);
+            }
+            catch (Exception e)
+            {
+                Console.Error.WriteLine(e.StackTrace);
+            }
         }
     }
 }


Fix warning

Fix warning

--- Tests/Boxed.Templates.Test/Framework/DirectoryExtended.cs
+++ Tests/Boxed.Templates.Test/Framework/DirectoryExtended.cs
@@ -67,7 +67,7 @@
                 throw new ArgumentOutOfRangeException(nameof(millisecondsDelay));
             }

-            for (int i = 0; i < maxRetries; ++i)
+            for (var i = 0; i < maxRetries; ++i)
             {
                 try
                 {


Delete RmDir.cs

Delete RmDir.cs

--- TextEditor/TestConsole/CommandProcessor/Commands/RmDir.cs
+++ TextEditor/TestConsole/CommandProcessor/Commands/RmDir.cs
@@ -1,42 +0,0 @@
-using System;
-
-namespace Kernel.CommandProcessor.Commands
-{
-    public class RmDir : BaseCommand
-    {
-        public RmDir()
-        {
-            name = "rmdir";
-            description = "Remove an existing directory.";
-            parameterCount = 2;
-        }
-
-        public override void Do(params string[] args)
-        {
-            try
-            {
-                //DirectoryEntry de = fs.GetDirectory(Global.CurrentPath + args[1]);
-                //if (de != null)
-                //{
-                //    fs.DeleteDirectory(de);
-                //    Console.WriteLine("Directory removed: " + de.mFullPath);
-                //    Console.WriteLine("");
-                //}
-                //else
-                //{
-                //    Console.WriteLine("Directory '" + Global.CurrentPath + args[1] + "' does not exist.");
-                //}
-            }
-            catch(Exception ex)
-            {
-                CommandResult.AddErrorMessage("Unable to remove directory: " + ex.Message);
-                CommandResult.Exception = ex;
-            }
-        }
-
-        public override BaseCommand Create()
-        {
-            return new RmDir();
-        }
-    }
-}


HttpDriver sample updated

HttpDriver sample updated

--- Cycle.Net.Sample/HttpDriver.cs
+++ Cycle.Net.Sample/HttpDriver.cs
@@ -52,9 +52,8 @@
             {
                 case HttpRequest httpRequest:
                     var client = new System.Net.Http.HttpClient();
-                    Observable.FromAsync(() => client.GetStringAsync(httpRequest.Url))
+                    Observable.FromAsync(() => client.GetStringAsync(httpRequest.Url), m_scheduler)
                         .Select(content => new HttpResponse(httpRequest, content))
-                        .ObserveOn(m_scheduler)
                         .Subscribe(this);
                     break;
             }


The try/catch around PrimaryLogic.Run now logs to a text file.

--- Dbot.Service/PrimaryService.cs
+++ Dbot.Service/PrimaryService.cs
@@ -1,5 +1,7 @@
 using System;
+using System.Collections;
 using System.Collections.Generic;
+using System.IO;
 using System.Linq;
 using System.ServiceProcess;
 using System.Text;
@@ -44,12 +46,56 @@
     /// </summary>
     /// <param name="args"></param>
     protected override void OnStart(string[] args) {
-      try {
-        new PrimaryLogic().Run();
-      } catch (Exception e) {
-        Logger.ErrorLog(e);
+      const string folderName = "Logs";
+      var fileNamePath = $"{folderName}//{DateTime.UtcNow.Date.ToString("yyyy-MM-dd")}error.txt";
+
+      var exists = Directory.Exists(folderName);
+      if (!exists) Directory.CreateDirectory(folderName);
+
+      using (var writer = new StreamWriter(fileNamePath)) {
+        writer.AutoFlush = true;
+        try {
+          new PrimaryLogic().Run();
+        } catch (Exception e) {
+          var sb = new StringBuilder();
+          WriteExceptionDetails(e, sb, 0);
+          writer.WriteLine(sb.ToString());
+          Logger.ErrorLog(e);
+        }
       }
       base.OnStart(args);
+    }
+
+    public static void WriteExceptionDetails(Exception exception, StringBuilder builderToFill, int level) {
+      var indent = new string(' ', level);
+
+      if (level > 0) {
+        builderToFill.AppendLine(indent + "=== INNER EXCEPTION ===");
+      }
+
+      Action<string> append = (prop) => {
+        var propInfo = exception.GetType().GetProperty(prop);
+        var val = propInfo.GetValue(exception);
+
+        if (val != null) {
+          builderToFill.AppendFormat("{0}{1}: {2}{3}", indent, prop, val.ToString(), Environment.NewLine);
+        }
+      };
+
+      append("Message");
+      append("HResult");
+      append("HelpLink");
+      append("Source");
+      append("StackTrace");
+      append("TargetSite");
+
+      foreach (DictionaryEntry de in exception.Data) {
+        builderToFill.AppendFormat("{0} {1} = {2}{3}", indent, de.Key, de.Value, Environment.NewLine);
+      }
+
+      if (exception.InnerException != null) {
+        WriteExceptionDetails(exception.InnerException, builderToFill, ++level);
+      }
     }

     /// <summary>


Reacted to the addition of the greeting service

--- src/configuration/Startup.cs
+++ src/configuration/Startup.cs
@@ -1,41 +1,20 @@
 using System.IO;
-using System.Linq;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Routing;
 using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;

 public class Startup
 {
-    public IConfiguration Configuration { get; set; }
-    public Startup (IHostingEnvironment environment)
-    {
-        var configurationBuilder = new ConfigurationBuilder()
-            .SetBasePath(Directory.GetCurrentDirectory())
-            .AddJsonFile("greetings.json", optional: false, reloadOnChange: true);
-
-        Configuration = configurationBuilder.Build();
-    }
-
-    public void Configure(IApplicationBuilder app)
+    public void Configure(IApplicationBuilder app, IGreetingService greetingService)
     {
         var routeBuilder = new RouteBuilder(app);

-        routeBuilder.MapGet("{route}", context =>
+        routeBuilder.MapGet("{route}", context =>
         {
-            var routeMessage = Configuration.AsEnumerable()
-                .FirstOrDefault(r => r.Key == context.GetRouteValue("route")
-                .ToString())
-                .Value;
-
-            var defaultMessage = Configuration.AsEnumerable()
-                .FirstOrDefault(r => r.Key == "default")
-                .Value;
-
-            var response = (routeMessage != null) ? routeMessage : defaultMessage;
-            return context.Response.WriteAsync(response);
+            var route = context.GetRouteValue("route").ToString();
+            return context.Response.WriteAsync(greetingService.Greet(route));
         });

         app.UseRouter(routeBuilder.Build());
@@ -44,5 +23,16 @@
     public void ConfigureServices(IServiceCollection services)
     {
         services.AddRouting();
+
+        services.Add(new ServiceDescriptor(typeof(IConfiguration),
+                     provider => new ConfigurationBuilder()
+                                    .SetBasePath(Directory.GetCurrentDirectory())
+                                    .AddJsonFile("greetings.json",
+                                                 optional: false,
+                                                 reloadOnChange: true)
+                                    .Build(),
+                     ServiceLifetime.Singleton));
+
+        services.AddTransient<IGreetingService, GreeringService>();
     }
 }


About page for iOS added.

About page for iOS added.

--- iOS/Source/About/AboutViewController.cs
+++ iOS/Source/About/AboutViewController.cs
@@ -8,9 +8,6 @@
 	{
 		public AboutViewController (IntPtr handle) : base (handle)
 		{
-			// @{UITextAttributeTextColor: [UIColor whiteColor]}
-
-//			UINavigationItem.Appearance.SetTitleTextAttributes ();
 		}
 	}
 }


Pressing Enter will stop web application trace

--- dotnet-tracer/main/CodePulse.Console/Program.cs
+++ dotnet-tracer/main/CodePulse.Console/Program.cs
@@ -348,6 +348,18 @@
                 LogMandatoryInfo($"Trace will stop when either '{WorldWideWebPublishingServiceDisplayName}' stops or Code Pulse ends the trace.");

                 var service = w3SvcService;
+                Task.Run(() =>
+                {
+                    System.Console.WriteLine();
+                    System.Console.WriteLine();
+                    System.Console.WriteLine("Press Enter to end web application and tracing...");
+                    System.Console.ReadLine();
+
+                    Logger.Info("Stopping service...");
+                    service.StopService(TimeSpan.MaxValue);
+                    Logger.Info("Service stopped");
+                });
+
                 Task.WaitAny(
                     Task.Run(() => service.WaitForStatus(ServiceControllerStatus.Stopped)),
                     Task.Run(() => _persistence.WaitForShutdown()));


Fix Crabrawler gender

Fix Crabrawler gender

--- 3DSRNGTool/Gen7/Wild7.cs
+++ 3DSRNGTool/Gen7/Wild7.cs
@@ -91,7 +91,7 @@
             else if (Crabrawler)
             {
                 CheckLeadAbility(getrand % 100);
-                rt.Slot = 1;
+                rt.Slot = slot = 1;
                 rt.Level = ModifiedLevel;
             }
             else if (NormalSlot) // Normal wild


add ulong IsEven() and IsOdd() extensions

--- punku/Extensions/ULongExtensions.cs
+++ punku/Extensions/ULongExtensions.cs
@@ -23,6 +23,7 @@
 	 */
 	public static byte[] Digits (this ulong n, uint numberBase = 10)
 	{
+		// TODO this method should be in NaturalNumber class
 		int count = (int)n.CountDigits (numberBase);
 		byte[] digits = new byte[count];

@@ -97,6 +98,9 @@
 		return true;
 	}

+	/**
+	 * @return true if n is a prime
+	 */
 	public static bool IsPrime (this ulong n)
 	{
 		for (ulong j = 2; j < n; j++)
@@ -105,6 +109,25 @@

 		return true;
 	}
+
+	/**
+	 * @return true if n is a even number
+	 */
+	public static bool IsEven (this ulong n)
+	{
+		if (n % 2 == 0)
+			return true;
+
+		return false;
+	}
+
+	/**
+	 * @return true if n is a odd number
+	 */
+	public static bool IsOdd (this ulong n)
+	{
+		return !n.IsEven ();
+	}
 }


Fix GetFieldMapping integration tests

Fix GetFieldMapping integration tests

--- src/Nest/CommonAbstractions/Response/ResolvableDictionaryProxy.cs
+++ src/Nest/CommonAbstractions/Response/ResolvableDictionaryProxy.cs
@@ -68,10 +68,10 @@
 	}

 	internal class ResolvableDictionaryFormatter<TKey, TValue>
-		: ResolvableDictionaryFormatterBase<ResolvableDictionaryProxy<TKey, TValue>, TKey, TValue>
+		: ResolvableDictionaryFormatterBase<IReadOnlyDictionary<TKey, TValue>, TKey, TValue>
 		where TKey : IUrlParameter
 	{
-		protected override ResolvableDictionaryProxy<TKey, TValue> Create(IConnectionSettingsValues settings, Dictionary<TKey, TValue> dictionary) =>
+		protected override IReadOnlyDictionary<TKey, TValue> Create(IConnectionSettingsValues settings, Dictionary<TKey, TValue> dictionary) =>
 			new ResolvableDictionaryProxy<TKey, TValue>(settings, dictionary);
 	}


fixing my own fuckup

fixing my own fuckup

--- src/Sandra.Snow.PreCompiler/StaticFileProcessors/BaseProcessor.cs
+++ src/Sandra.Snow.PreCompiler/StaticFileProcessors/BaseProcessor.cs
@@ -29,7 +29,7 @@
     {
         public override string ProcessorName
         {
-            get { return "PagedPost" }
+            get { return "PagedPost"; }
         }

         public override void Process(SnowyData snowyData)


#3 - Added base interface for IUserManager

--- src/Security/Frontend.Security.Web/App_Start/Base/IUserManager.cs
+++ src/Security/Frontend.Security.Web/App_Start/Base/IUserManager.cs
@@ -1,5 +1,4 @@
 using System;
-using System.Collections;
 using System.Collections.Generic;
 using System.Linq;
 using System.Security.Claims;
@@ -8,7 +7,12 @@

 namespace GoldenEye.Frontend.Security.Web.Base
 {
-    public interface IUserManager<T> where T : class, IUser<int>, new()
+    public interface IUserManager<TUser> : IUserManager<TUser, int> where TUser : class, IUser<int>, new()
+    {
+
+    }
+
+    public interface IUserManager<TUser, TKey> where TUser : class, IUser<TKey>, new() where TKey : IEquatable<TKey>
     {
         /// <summary>
         /// Finds existing username with password, if not exists checks if external authorization service
@@ -17,78 +21,78 @@
         /// <param name="userName"></param>
         /// <param name="password"></param>
         /// <returns></returns>
-        Task<T> FindAsync(string userName, string password);
+        Task<TUser> FindAsync(string userName, string password);

         void Dispose();
-        Task<ClaimsIdentity> CreateIdentityAsync(T user, string authenticationType);
-        Task<IdentityResult> CreateAsync(T user);
-        Task<IdentityResult> UpdateAsync(T user);
-        Task<IdentityResult> DeleteAsync(T user);
-        Task<T> FindByIdAsync(int userId);
-        Task<T> FindByNameAsync(string userName);
-        Task<IdentityResult> CreateAsync(T user, string password);
-        Task<bool> CheckPasswordAsync(T user, string password);
-        Task<bool> HasPasswordAsync(int userId);
-        Task<IdentityResult> AddPasswordAsync(int userId, string password);
-        Task<IdentityResult> ChangePasswordAsync(int userId, string currentPassword, string newPassword);
-        Task<IdentityResult> RemovePasswordAsync(int userId);
-        Task<string> GetSecurityStampAsync(int userId);
-        Task<IdentityResult> UpdateSecurityStampAsync(int userId);
-        Task<string> GeneratePasswordResetTokenAsync(int userId);
-        Task<IdentityResult> ResetPasswordAsync(int userId, string token, string newPassword);
-        Task<T> FindAsync(UserLoginInfo login);
-        Task<IdentityResult> RemoveLoginAsync(int userId, UserLoginInfo login);
-        Task<IdentityResult> AddLoginAsync(int userId, UserLoginInfo login);
-        Task<IList<UserLoginInfo>> GetLoginsAsync(int userId);
-        Task<IdentityResult> AddClaimAsync(int userId, Claim claim);
-        Task<IdentityResult> RemoveClaimAsync(int userId, Claim claim);
-        Task<IList<Claim>> GetClaimsAsync(int userId);
-        Task<IdentityResult> AddToRoleAsync(int userId, string role);
-        Task<IdentityResult> AddToRolesAsync(int userId, params string[] roles);
-        Task<IdentityResult> RemoveFromRolesAsync(int userId, params string[] roles);
-        Task<IdentityResult> RemoveFromRoleAsync(int userId, string role);
-        Task<IList<string>> GetRolesAsync(int userId);
-        Task<bool> IsInRoleAsync(int userId, string role);
-        Task<string> GetEmailAsync(int userId);
-        Task<IdentityResult> SetEmailAsync(int userId, string email);
-        Task<T> FindByEmailAsync(string email);
-        Task<string> GenerateEmailConfirmationTokenAsync(int userId);
-        Task<IdentityResult> ConfirmEmailAsync(int userId, string token);
-        Task<bool> IsEmailConfirmedAsync(int userId);
-        Task<string> GetPhoneNumberAsync(int userId);
-        Task<IdentityResult> SetPhoneNumberAsync(int userId, string phoneNumber);
-        Task<IdentityResult> ChangePhoneNumberAsync(int userId, string phoneNumber, string token);
-        Task<bool> IsPhoneNumberConfirmedAsync(int userId);
-        Task<string> GenerateChangePhoneNumberTokenAsync(int userId, string phoneNumber);
-        Task<bool> VerifyChangePhoneNumberTokenAsync(int userId, string token, string phoneNumber);
-        Task<bool> VerifyUserTokenAsync(int userId, string purpose, string token);
-        Task<string> GenerateUserTokenAsync(string purpose, int userId);
-        void RegisterTwoFactorProvider(string twoFactorProvider, IUserTokenProvider<T,int> provider);
-        Task<IList<string>> GetValidTwoFactorProvidersAsync(int userId);
-        Task<bool> VerifyTwoFactorTokenAsync(int userId, string twoFactorProvider, string token);
-        Task<string> GenerateTwoFactorTokenAsync(int userId, string twoFactorProvider);
-        Task<IdentityResult> NotifyTwoFactorTokenAsync(int userId, string twoFactorProvider, string token);
-        Task<bool> GetTwoFactorEnabledAsync(int userId);
-        Task<IdentityResult> SetTwoFactorEnabledAsync(int userId, bool enabled);
-        Task SendEmailAsync(int userId, string subject, string body);
-        Task SendSmsAsync(int userId, string message);
-        Task<bool> IsLockedOutAsync(int userId);
-        Task<IdentityResult> SetLockoutEnabledAsync(int userId, bool enabled);
-        Task<bool> GetLockoutEnabledAsync(int userId);
-        Task<DateTimeOffset> GetLockoutEndDateAsync(int userId);
-        Task<IdentityResult> SetLockoutEndDateAsync(int userId, DateTimeOffset lockoutEnd);
-        Task<IdentityResult> AccessFailedAsync(int userId);
-        Task<IdentityResult> ResetAccessFailedCountAsync(int userId);
-        Task<int> GetAccessFailedCountAsync(int userId);
+        Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType);
+        Task<IdentityResult> CreateAsync(TUser user);
+        Task<IdentityResult> UpdateAsync(TUser user);
+        Task<IdentityResult> DeleteAsync(TUser user);
+        Task<TUser> FindByIdAsync(TKey userId);
+        Task<TUser> FindByNameAsync(string userName);
+        Task<IdentityResult> CreateAsync(TUser user, string password);
+        Task<bool> CheckPasswordAsync(TUser user, string password);
+        Task<bool> HasPasswordAsync(TKey userId);
+        Task<IdentityResult> AddPasswordAsync(TKey userId, string password);
+        Task<IdentityResult> ChangePasswordAsync(TKey userId, string currentPassword, string newPassword);
+        Task<IdentityResult> RemovePasswordAsync(TKey userId);
+        Task<string> GetSecurityStampAsync(TKey userId);
+        Task<IdentityResult> UpdateSecurityStampAsync(TKey userId);
+        Task<string> GeneratePasswordResetTokenAsync(TKey userId);
+        Task<IdentityResult> ResetPasswordAsync(TKey userId, string token, string newPassword);
+        Task<TUser> FindAsync(UserLoginInfo login);
+        Task<IdentityResult> RemoveLoginAsync(TKey userId, UserLoginInfo login);
+        Task<IdentityResult> AddLoginAsync(TKey userId, UserLoginInfo login);
+        Task<IList<UserLoginInfo>> GetLoginsAsync(TKey userId);
+        Task<IdentityResult> AddClaimAsync(TKey userId, Claim claim);
+        Task<IdentityResult> RemoveClaimAsync(TKey userId, Claim claim);
+        Task<IList<Claim>> GetClaimsAsync(TKey userId);
+        Task<IdentityResult> AddToRoleAsync(TKey userId, string role);
+        Task<IdentityResult> AddToRolesAsync(TKey userId, params string[] roles);
+        Task<IdentityResult> RemoveFromRolesAsync(TKey userId, params string[] roles);
+        Task<IdentityResult> RemoveFromRoleAsync(TKey userId, string role);
+        Task<IList<string>> GetRolesAsync(TKey userId);
+        Task<bool> IsInRoleAsync(TKey userId, string role);
+        Task<string> GetEmailAsync(TKey userId);
+        Task<IdentityResult> SetEmailAsync(TKey userId, string email);
+        Task<TUser> FindByEmailAsync(string email);
+        Task<string> GenerateEmailConfirmationTokenAsync(TKey userId);
+        Task<IdentityResult> ConfirmEmailAsync(TKey userId, string token);
+        Task<bool> IsEmailConfirmedAsync(TKey userId);
+        Task<string> GetPhoneNumberAsync(TKey userId);
+        Task<IdentityResult> SetPhoneNumberAsync(TKey userId, string phoneNumber);
+        Task<IdentityResult> ChangePhoneNumberAsync(TKey userId, string phoneNumber, string token);
+        Task<bool> IsPhoneNumberConfirmedAsync(TKey userId);
+        Task<string> GenerateChangePhoneNumberTokenAsync(TKey userId, string phoneNumber);
+        Task<bool> VerifyChangePhoneNumberTokenAsync(TKey userId, string token, string phoneNumber);
+        Task<bool> VerifyUserTokenAsync(TKey userId, string purpose, string token);
+        Task<string> GenerateUserTokenAsync(string purpose, TKey userId);
+        void RegisterTwoFactorProvider(string twoFactorProvider, IUserTokenProvider<TUser,TKey> provider);
+        Task<IList<string>> GetValidTwoFactorProvidersAsync(TKey userId);
+        Task<bool> VerifyTwoFactorTokenAsync(TKey userId, string twoFactorProvider, string token);
+        Task<string> GenerateTwoFactorTokenAsync(TKey userId, string twoFactorProvider);
+        Task<IdentityResult> NotifyTwoFactorTokenAsync(TKey userId, string twoFactorProvider, string token);
+        Task<bool> GetTwoFactorEnabledAsync(TKey userId);
+        Task<IdentityResult> SetTwoFactorEnabledAsync(TKey userId, bool enabled);
+        Task SendEmailAsync(TKey userId, string subject, string body);
+        Task SendSmsAsync(TKey userId, string message);
+        Task<bool> IsLockedOutAsync(TKey userId);
+        Task<IdentityResult> SetLockoutEnabledAsync(TKey userId, bool enabled);
+        Task<bool> GetLockoutEnabledAsync(TKey userId);
+        Task<DateTimeOffset> GetLockoutEndDateAsync(TKey userId);
+        Task<IdentityResult> SetLockoutEndDateAsync(TKey userId, DateTimeOffset lockoutEnd);
+        Task<IdentityResult> AccessFailedAsync(TKey userId);
+        Task<IdentityResult> ResetAccessFailedCountAsync(TKey userId);
+        Task<TKey> GetAccessFailedCountAsync(TKey userId);
         IPasswordHasher PasswordHasher { get; set; }
-        IIdentityValidator<T> UserValidator { get; set; }
+        IIdentityValidator<TUser> UserValidator { get; set; }
         IIdentityValidator<string> PasswordValidator { get; set; }
-        IClaimsIdentityFactory<T, int> ClaimsIdentityFactory { get; set; }
+        IClaimsIdentityFactory<TUser, TKey> ClaimsIdentityFactory { get; set; }
         IIdentityMessageService EmailService { get; set; }
         IIdentityMessageService SmsService { get; set; }
-        IUserTokenProvider<T, int> UserTokenProvider { get; set; }
+        IUserTokenProvider<TUser, TKey> UserTokenProvider { get; set; }
         bool UserLockoutEnabledByDefault { get; set; }
-        int MaxFailedAccessAttemptsBeforeLockout { get; set; }
+        TKey MaxFailedAccessAttemptsBeforeLockout { get; set; }
         TimeSpan DefaultAccountLockoutTimeSpan { get; set; }
         bool SupportsUserTwoFactor { get; }
         bool SupportsUserPassword { get; }
@@ -100,7 +104,7 @@
         bool SupportsUserClaim { get; }
         bool SupportsUserLockout { get; }
         bool SupportsQueryableUsers { get; }
-        IQueryable<T> Users { get; }
-        IDictionary<string, IUserTokenProvider<T, int>> TwoFactorProviders { get; }
+        IQueryable<TUser> Users { get; }
+        IDictionary<string, IUserTokenProvider<TUser, TKey>> TwoFactorProviders { get; }
     }
 }


deleting through the recycle bin also deletes redirect urls.

--- src/Umbraco.Core/Persistence/Repositories/RecycleBinRepository.cs
+++ src/Umbraco.Core/Persistence/Repositories/RecycleBinRepository.cs
@@ -49,6 +49,10 @@
                     INNER JOIN umbracoNode as TB2 ON TB1.nodeId = TB2.id
                     WHERE TB2.trashed = '1' AND TB2.nodeObjectType = @NodeObjectType)",
                 FormatDeleteStatement("umbracoAccess", "nodeId"),
+                @"DELETE FROM umbracoRedirectUrl WHERE umbracoRedirectUrl.id IN(
+                    SELECT TB1.id FROM umbracoRedirectUrl as TB1
+                    INNER JOIN umbracoNode as TB2 ON TB1.contentKey = TB2.uniqueId
+                    WHERE TB2.trashed = '1' AND TB2.nodeObjectType = @NodeObjectType)",
                 FormatDeleteStatement("umbracoRelation", "parentId"),
                 FormatDeleteStatement("umbracoRelation", "childId"),
                 FormatDeleteStatement("cmsTagRelationship", "nodeId"),


Fixing determine resolutions

Fixing determine resolutions

--- Mapsui/Map.cs
+++ Mapsui/Map.cs
@@ -285,7 +285,7 @@
                     // to determine if another resolution adds value. If a resolution
                     // is a factor of 2 of another resolution. The normalized distance
                     // is one.
-                    var normalized = Math.Pow(resolution, 2);
+                    var normalized = Math.Log(resolution, 2);
                     if (items.Count == 0)
                     {
                         items[normalized] = resolution;


改行コードの修正。

改行コードの修正。

--- Grabacr07.KanColleWrapper/Models/SlotItemInfo.cs
+++ Grabacr07.KanColleWrapper/Models/SlotItemInfo.cs
@@ -1,34 +1,34 @@
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using Grabacr07.KanColleWrapper.Internal;
-using Grabacr07.KanColleWrapper.Models.Raw;
-
-namespace Grabacr07.KanColleWrapper.Models
-{
-	/// <summary>
-	/// 装備アイテムの種類に基づく情報を表します。
-	/// </summary>
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Grabacr07.KanColleWrapper.Internal;
+using Grabacr07.KanColleWrapper.Models.Raw;
+
+namespace Grabacr07.KanColleWrapper.Models
+{
+	/// <summary>
+	/// 装備アイテムの種類に基づく情報を表します。
+	/// </summary>
 	public class SlotItemInfo : RawDataWrapper<kcsapi_master_slotitem>, IIdentifiable
 	{
-		private SlotItemIconType? iconType;
-
-		public int Id
-		{
-			get { return this.RawData.api_id; }
-		}
-
-		public string Name
-		{
-			get { return this.RawData.api_name; }
-		}
-
-		public SlotItemIconType IconType
-		{
-			get { return this.iconType ?? (this.iconType = this.RawData.api_type.Length == 4 ? (SlotItemIconType)this.RawData.api_type[3] : SlotItemIconType.Unknown).Value; }
+		private SlotItemIconType? iconType;
+
+		public int Id
+		{
+			get { return this.RawData.api_id; }
+		}
+
+		public string Name
+		{
+			get { return this.RawData.api_name; }
+		}
+
+		public SlotItemIconType IconType
+		{
+			get { return this.iconType ?? (this.iconType = this.RawData.api_type.Length == 4 ? (SlotItemIconType)this.RawData.api_type[3] : SlotItemIconType.Unknown).Value; }
 		}

 		/// <summary>
@@ -39,9 +39,9 @@
 			get
 			{
 				return this.IconType == SlotItemIconType.Fighter ||
-				       this.IconType == SlotItemIconType.TorpedoBomber ||
-				       this.IconType == SlotItemIconType.DiveBomber ||
-				       this.IconType == SlotItemIconType.ReconPlane;
+					   this.IconType == SlotItemIconType.TorpedoBomber ||
+					   this.IconType == SlotItemIconType.DiveBomber ||
+					   this.IconType == SlotItemIconType.ReconPlane;
 			}
 		}

@@ -51,28 +51,28 @@
 		public bool IsSeaplane
 		{
 			get { return this.IconType == SlotItemIconType.ReconSeaplane; }
-		}
-
-		internal SlotItemInfo(kcsapi_master_slotitem rawData) : base(rawData) { }
-
-		public override string ToString()
-		{
-			return string.Format("ID = {0}, Name = \"{1}\", Type = {{{2}}}", this.Id, this.Name, this.RawData.api_type.ToString(", "));
-		}
-
-		#region static members
-
-		private static readonly SlotItemInfo dummy = new SlotItemInfo(new kcsapi_master_slotitem()
-		{
-			api_id = 0,
-			api_name = "？？？",
-		});
-
-		public static SlotItemInfo Dummy
-		{
-			get { return dummy; }
-		}
-
-		#endregion
-	}
-}
+		}
+
+		internal SlotItemInfo(kcsapi_master_slotitem rawData) : base(rawData) { }
+
+		public override string ToString()
+		{
+			return string.Format("ID = {0}, Name = \"{1}\", Type = {{{2}}}", this.Id, this.Name, this.RawData.api_type.ToString(", "));
+		}
+
+		#region static members
+
+		private static readonly SlotItemInfo dummy = new SlotItemInfo(new kcsapi_master_slotitem()
+		{
+			api_id = 0,
+			api_name = "？？？",
+		});
+
+		public static SlotItemInfo Dummy
+		{
+			get { return dummy; }
+		}
+
+		#endregion
+	}
+}


Enabled test paralezation

Enabled test paralezation

--- GridDomain.Tests.Unit/Properties/AssemblyInfo.cs
+++ GridDomain.Tests.Unit/Properties/AssemblyInfo.cs
@@ -41,4 +41,4 @@
 [assembly: AssemblyFileVersion("1.0.0.0")]
 [assembly: InternalsVisibleTo("GridDomain.Tests.Acceptance")]
 [assembly: InternalsVisibleTo("GridDomain.Tests.Acceptance")]
-[assembly: CollectionBehavior(DisableTestParallelization = true)]
+


Apparently, errors don't always have a string message

--- src/Dbus/Connection.SendMethodCall.cs
+++ src/Dbus/Connection.SendMethodCall.cs
@@ -81,13 +81,14 @@
                 {
                     if (header.ReplySerial == 0)
                         throw new InvalidOperationException("Only errors for method calls are supported");
-                    if (!header.BodySignature.ToString().StartsWith("s"))
-                        throw new InvalidOperationException("Errors are expected to start their body with a string");

                     if (!expectedMessages.TryRemove(header.ReplySerial, out var tcs))
                         throw new InvalidOperationException("Couldn't find the method call for the error");

-                    var message = decoder.GetString();
+                    var message = "";
+                    if (header.BodySignature.ToString().StartsWith("s"))
+                        message = decoder.GetString();
+
                     var exception = new DbusException(header.ErrorName, message);
                     tcs.SetException(exception);
                 }