[WIN-6232] Windows: Various errors related to clipboard access

--- Xwt.WPF/Xwt.WPFBackend/ClipboardBackend.cs
+++ Xwt.WPF/Xwt.WPFBackend/ClipboardBackend.cs
@@ -38,8 +38,37 @@
 	public class WpfClipboardBackend
 		: ClipboardBackend {

+		// Clipboard may be locked by another process. In order to overcome this, it can be queried repeatedly.
+		// See https://stackoverflow.com/questions/12769264/openclipboard-failed-when-copy-pasting-data-from-wpf-datagrid
+		// And https://www.infragistics.com/community/forums/f/ultimate-ui-for-wpf/35379/failed-to-copy-clipbrd_e_cant_open
+		// The wrapper below implements retry logic that should make it more reliable.
+		const int MaxRetries = 10;
+		const int SleepTime = 10;
+		private static void CatchExceptionsAndRetry(Action action) {
+			int retryCount = 0;
+			Exception exception = null;
+			while(retryCount < MaxRetries) {
+				try {
+					action.Invoke();
+					return;
+				} catch(Exception e) {
+					exception = e;
+					if(exception.Message.Contains("CLIPBRD_E_BAD_DATA")) {
+						// do not retry
+						break;
+					}
+					System.Threading.Thread.Sleep(SleepTime);
+					retryCount++;
+				}
+			}
+
+			throw exception;
+		}
+
 		public override void Clear() {
-			WindowsClipboard.Clear();
+			CatchExceptionsAndRetry(() => {
+				WindowsClipboard.Clear();
+			});
 		}

 		public override void SetData(TransferDataType type, Func<object> dataSource, bool cleanClipboardFirst = true) {
@@ -49,22 +78,30 @@
 				throw new ArgumentNullException("dataSource");

 			if(cleanClipboardFirst) {
-				WindowsClipboard.Clear();
+				Clear();
 			}

 			if (type == TransferDataType.Html) {
-				WindowsClipboard.SetData (type.ToWpfDataFormat (), GenerateCFHtml (dataSource ().ToString ()));
+				CatchExceptionsAndRetry(() => {
+					WindowsClipboard.SetData(type.ToWpfDataFormat(), GenerateCFHtml(dataSource().ToString()));
+				});
 			} else if (type == TransferDataType.Image) {
 				var img = dataSource() as Xwt.Drawing.Image;
 				if (img != null)
 				{
 					var src = img.ToBitmap().GetBackend() as WpfImage;
-					WindowsClipboard.SetData (type.ToWpfDataFormat (), src.MainFrame);
+					CatchExceptionsAndRetry(() => {
+						WindowsClipboard.SetData(type.ToWpfDataFormat(), src.MainFrame);
+					});
 				}
 			} else if(type == TransferDataType.Uri) {
-				WindowsClipboard.SetFileDropList((StringCollection)(dataSource()));
+				CatchExceptionsAndRetry(() => {
+					WindowsClipboard.SetFileDropList((StringCollection)(dataSource()));
+				});
 			} else {
-				WindowsClipboard.SetData(type.ToWpfDataFormat(), dataSource());
+				CatchExceptionsAndRetry(() => {
+					WindowsClipboard.SetData(type.ToWpfDataFormat(), dataSource());
+				});
 			}
 		}

@@ -101,14 +138,26 @@
 				throw new ArgumentNullException ("type");

 			if (type == TransferDataType.Text) {
-				if (WindowsClipboard.ContainsFileDropList()) {
-					foreach (string s in WindowsClipboard.GetFileDropList()) {
+				bool containsFileDropList = false;
+				CatchExceptionsAndRetry(() => {
+					containsFileDropList = WindowsClipboard.ContainsFileDropList();
+				});
+				if(containsFileDropList) {
+					StringCollection stringCollection = null;
+					CatchExceptionsAndRetry(() => {
+						stringCollection = WindowsClipboard.GetFileDropList();
+					});
+					foreach(string s in stringCollection) {
 						return true;
 					}
 				}
 			}

-			return WindowsClipboard.ContainsData (type.ToWpfDataFormat ());
+			bool val = false;
+			CatchExceptionsAndRetry(() => {
+				val = WindowsClipboard.ContainsData(type.ToWpfDataFormat());
+			});
+			return val;
 		}

@@ -186,7 +235,9 @@
 			}

 			if (bmp == null) {
-				bmp = WindowsClipboard.GetImage();
+				CatchExceptionsAndRetry(() => {
+					bmp = WindowsClipboard.GetImage();
+				});
 			}
 			bmp = TryFixAlphaChannel(bmp);
 			return bmp;
@@ -201,20 +252,35 @@
 				return null;

 			if (type == TransferDataType.Text) {
-				if (WindowsClipboard.ContainsFileDropList()) {
-					foreach (string s in WindowsClipboard.GetFileDropList()) {
+				bool containsFileDropList = false;
+				CatchExceptionsAndRetry(() => {
+					containsFileDropList = WindowsClipboard.ContainsFileDropList();
+				});
+				if(containsFileDropList) {
+					StringCollection stringCollection = null;
+					CatchExceptionsAndRetry(() => {
+						stringCollection = WindowsClipboard.GetFileDropList();
+					});
+					foreach(string s in stringCollection) {
 						return "file://" + s;
 					}
 				}
 			}

 			if(type == TransferDataType.Image) {
-				var ob = WindowsClipboard.GetDataObject();
+				IDataObject ob = null;
+				CatchExceptionsAndRetry(() => {
+					ob = WindowsClipboard.GetDataObject();
+				});
 				var bmp = GetBestPossibletAlphaBitmapFromDataObject(ob);
 				return ApplicationContext.Toolkit.WrapImage(bmp);
 			}

-			return WindowsClipboard.GetData (type.ToWpfDataFormat ());
+			object result = null;
+			CatchExceptionsAndRetry(() => {
+				result = WindowsClipboard.GetData(type.ToWpfDataFormat());
+			});
+			return result;
 		}

 		public override IAsyncResult BeginGetData (TransferDataType type, AsyncCallback callback, object state)


fix copy paste error for rsa key creation

--- NTumbleBit.TumblerServer/Extensions.cs
+++ NTumbleBit.TumblerServer/Extensions.cs
@@ -84,8 +84,8 @@
 					var factory = provider.GetRequiredService<ILoggerFactory>();
 					var logger = factory.CreateLogger<TumblerConfiguration>();
 					conf.DataDirectory = conf.DataDirectory ?? GetDefaultDirectory(logger);
-
-					var rsaFile = Path.Combine(Directory.GetCurrentDirectory(), "Tumbler.pem");
+
+					var rsaFile = Path.Combine(conf.DataDirectory, "Tumbler.pem");

 					if(conf.TumblerKey == null)
 					{
@@ -105,24 +105,30 @@

 					if(conf.VoucherKey == null)
 					{
-						var voucherFile = Path.Combine(Directory.GetCurrentDirectory(), "Voucher.pem");
-						if(!File.Exists(rsaFile))
+						var voucherFile = Path.Combine(conf.DataDirectory, "Voucher.pem");
+						if(!File.Exists(voucherFile))
 						{
 							logger.LogWarning("Creation of Voucher Key");
 							conf.VoucherKey = new RsaKey();
-							File.WriteAllBytes(rsaFile, conf.VoucherKey.ToBytes());
+							File.WriteAllBytes(voucherFile, conf.VoucherKey.ToBytes());
 							logger.LogInformation("RSA key saved (" + voucherFile + ")");
 						}
 						else
 						{
 							logger.LogInformation("Voucher key found (" + voucherFile + ")");
-							conf.VoucherKey = new RsaKey(File.ReadAllBytes(rsaFile));
+							conf.VoucherKey = new RsaKey(File.ReadAllBytes(voucherFile));
 						}
 					}

 					Debug.Assert(conf.TumblerKey != null);
 					Debug.Assert(conf.VoucherKey != null);

+					if(conf.RPCClient == null)
+					{
+						var error = "RPC connection settings not configured";
+						logger.LogError(error);
+						throw new InvalidOperationException(error);
+					}
 					logger.LogInformation("Testing RPC connection to " + conf.RPCClient.Address.AbsoluteUri);
 					try
 					{
@@ -160,7 +166,7 @@
 			else
 			{
 				var localAppData = Environment.GetEnvironmentVariable("LOCALAPPDATA");
-				if(!string.IsNullOrEmpty(home))
+				if(!string.IsNullOrEmpty(localAppData))
 				{
 					logger.LogInformation("Using LOCALAPPDATA environment variable for initializing application data");
 					directory = localAppData;
@@ -172,6 +178,11 @@
 			}
 			directory = Path.Combine(directory, ".ntumblebitserver");
 			logger.LogInformation("Data directory set to " + directory);
+			if(!Directory.Exists(directory))
+			{
+				logger.LogInformation("Creating data directory");
+				Directory.CreateDirectory(directory);
+			}
 			return directory;
 		}
 	}


Add: search implementation

Add: search implementation

--- PhoneBook.Domain/Infrastructure/MainUserManager.cs
+++ PhoneBook.Domain/Infrastructure/MainUserManager.cs
@@ -1,6 +1,7 @@
 using System;
 using System.Collections.Generic;
 using System.Data.Entity;
+using System.Linq;
 using System.Security.Claims;
 using System.Threading.Tasks;
 using Microsoft.AspNet.Identity;
@@ -67,6 +68,11 @@
             return await _applicationUserManager.FindAsync(userLoginInfo);
         }

+        public IQueryable<User> FindByFirstName(string firstName)
+        {
+            return _applicationUserManager.Users.Where(u => u.FirstName.Contains(firstName)).Select(u=> u);
+        }
+
         public async Task<ClaimsIdentity> CreateIdentityAsync(User user, string authenticationType)
         {
             return await _applicationUserManager.CreateIdentityAsync(user, authenticationType);


Added more tests to Reduce

Added more tests to Reduce

--- NetFabric.Angle.UnitTests/AngleTest.cs
+++ NetFabric.Angle.UnitTests/AngleTest.cs
@@ -354,6 +354,12 @@
             Assert.AreEqual(Angle.Right, Angle.Reduce(Angle.Right + Angle.Full));
             Assert.AreEqual(Angle.FromDegrees(135).ToRadians(), Angle.Reduce(Angle.FromDegrees(135) + Angle.Full).ToRadians(), 0.000001);
             Assert.AreEqual(Angle.Straight, Angle.Reduce(Angle.Straight + Angle.Full));
+
+            Assert.AreEqual(Angle.Zero, Angle.Reduce(-Angle.Full));
+            Assert.AreEqual(Angle.FromDegrees(315), Angle.Reduce(-Angle.FromDegrees(45)));
+            Assert.AreEqual(Angle.FromDegrees(270), Angle.Reduce(-Angle.Right));
+            Assert.AreEqual(Angle.Straight, Angle.Reduce(-Angle.Straight));
+            Assert.AreEqual(Angle.Right, Angle.Reduce(-Angle.FromDegrees(270)));

         }


Remove optimization to only clear ToolLayer when it has been changed by the edit engine, because it might have been changed by another tool.  Fortunately Clear should be a relatively cheap operation.

--- Pinta.Tools/Editable/EditEngines/BaseEditEngine.cs
+++ Pinta.Tools/Editable/EditEngines/BaseEditEngine.cs
@@ -246,8 +246,6 @@
         //Stores the editable shape data.
 		public static ShapeEngineCollection SEngines = new ShapeEngineCollection();

-		protected static bool usedToolLayer = false;
-

         #region ToolbarEventHandlers

@@ -1213,12 +1211,7 @@
 		private void beforeDraw()
 		{
 			//Clear the ToolLayer if it was used previously (e.g. for hover points when there was no active shape).
-			if (usedToolLayer)
-			{
-				PintaCore.Workspace.ActiveDocument.ToolLayer.Clear();
-
-				usedToolLayer = false;
-			}
+			PintaCore.Workspace.ActiveDocument.ToolLayer.Clear();

 			//Invalidate the old hover point bounds, if any.
 			if (lastHover != null)
@@ -1256,8 +1249,6 @@

 				//Draw the hover point. Note: the hover point has its own invalidation.
 				drawHoverPoint(g);
-
-				usedToolLayer = true;
 			}

 			doc.ToolLayer.Hidden = false;


Refactor to simplify how the hovered point is tracked in the shape tools

- Use a nullable type to indicate whether there is a hovered point
- Remove the hovered_pt_as_control_pt flag. This wasn't really necessary and it's fine to just skip drawing the control point if the hovered position is on top of it

--- Pinta.Tools/Editable/EditEngines/BaseEditEngine.cs
+++ Pinta.Tools/Editable/EditEngines/BaseEditEngine.cs
@@ -177,8 +177,7 @@
 			}
 		}

-		protected PointD hover_point = new PointD (-1d, -1d);
-		protected int hovered_pt_as_control_pt = -1;
+		protected PointD? hover_point;

 		protected bool changing_tension = false;
 		protected PointD last_mouse_pos = new PointD (0d, 0d);
@@ -502,7 +501,7 @@
 						SelectedShapeIndex = -1;
 					}

-					hover_point = new PointD (-1d, -1d);
+					hover_point = null;

 					DrawActiveShape (true, false, true, false, false);
 				}
@@ -1124,16 +1123,14 @@
 			} else {
 				//Do not draw the hover point. Instead, reset the hover point. NOTE: this is necessary even though the hover point
 				//is reset later. It affects the DrawShape call.
-				hover_point = new PointD (-1d, -1d);
-				hovered_pt_as_control_pt = -1;
+				hover_point = null;
 			}

 			//Draw the shape onto the temporary DrawingLayer.
 			Rectangle dirty = DrawShape (engine, engine.DrawingLayer.Layer, true, drawHoverSelection);

 			//Reset the hover point after each drawing.
-			hover_point = new PointD (-1d, -1d);
-			hovered_pt_as_control_pt = -1;
+			hover_point = null;

 			return dirty;
 		}
@@ -1143,9 +1140,8 @@
 		/// </summary>
 		private void CalculateHoverPoint ()
 		{
+			hover_point = null;
 			if (SEngines.Count > 0) {
-				hover_point = new PointD (-1d, -1d);
-
 				int closestCPIndex, closestCPShapeIndex;
 				ControlPoint? closestControlPoint;
 				double closestCPDistance;
@@ -1167,10 +1163,7 @@
 				//Determine if the closest ControlPoint is within the expected click range.
 				if (closestControlPoint != null && closestCPDistance < currentClickRange) {
 					//User clicked directly on a ControlPoint on a shape.
-
-					hover_point.X = closestControlPoint.Position.X;
-					hover_point.Y = closestControlPoint.Position.Y;
-					hovered_pt_as_control_pt = closestCPIndex;
+					hover_point = closestControlPoint.Position;
 				} else if (closestDistance < currentClickRange) //Determine if the user is hovering the mouse close enough to a shape.
 				  {
 					//User is hovering over a generated point on a shape.
@@ -1179,31 +1172,20 @@
 						//Note: compare the currentPoint's distance here because it's the actual mouse position.
 						if (current_point.Distance (controlPoints[closestPointIndex].Position) < currentClickRange) {
 							//Mouse hovering over a control point (on the "previous order" side of the point).
-
-							hover_point.X = controlPoints[closestPointIndex].Position.X;
-							hover_point.Y = controlPoints[closestPointIndex].Position.Y;
-							hovered_pt_as_control_pt = closestPointIndex;
+							hover_point = controlPoints[closestPointIndex].Position;
 						} else if (closestPointIndex > 0) {
 							if (current_point.Distance (controlPoints[closestPointIndex - 1].Position) < currentClickRange) {
 								//Mouse hovering over a control point (on the "following order" side of the point).
-
-								hover_point.X = controlPoints[closestPointIndex - 1].Position.X;
-								hover_point.Y = controlPoints[closestPointIndex - 1].Position.Y;
-								hovered_pt_as_control_pt = closestPointIndex - 1;
+								hover_point = controlPoints[closestPointIndex - 1].Position;
 							}
 						} else if (controlPoints.Count > 0 && current_point.Distance (controlPoints[controlPoints.Count - 1].Position) < currentClickRange) {
 							//Mouse hovering over a control point (on the "following order" side of the point).
-
-							hovered_pt_as_control_pt = controlPoints.Count - 1;
-							hover_point.X = controlPoints[hovered_pt_as_control_pt].Position.X;
-							hover_point.Y = controlPoints[hovered_pt_as_control_pt].Position.Y;
+							hover_point = controlPoints[controlPoints.Count - 1].Position;
 						}
 					}

-					if (hover_point.X < 0d) {
-						hover_point.X = closestPoint.X;
-						hover_point.Y = closestPoint.Y;
-					}
+					if (hover_point is null)
+						hover_point = closestPoint;
 				}
 			}
 		}
@@ -1340,8 +1322,8 @@
 				if (controlPoints.Count > 0) {
 					//Draw the control points for the shape.
 					for (int i = 0; i < controlPoints.Count; ++i) {
-						//Skip drawing the hovered control point.
-						if (drawHoverSelection && hovered_pt_as_control_pt > -1 && hover_point.Distance (controlPoints[i].Position) < 1d) {
+						//Skip drawing the control point if it is being hovered over.
+						if (drawHoverSelection && hover_point is PointD pos && pos.Distance (controlPoints[i].Position) < 1d) {
 							continue;
 						}

@@ -1379,15 +1361,15 @@
 			double controlPointOffset = (double) last_control_pt_size / 2d;

 			//Verify that the user isn't changing the tension of a control point and that there is a hover point to draw.
-			if (!changing_tension && hover_point.X > -1d) {
+			if (!changing_tension && hover_point is PointD pos) {
 				Rectangle hoverOuterEllipseRect = new Rectangle (
-					hover_point.X - controlPointOffset * 3d, hover_point.Y - controlPointOffset * 3d,
+					pos.X - controlPointOffset * 3d, pos.Y - controlPointOffset * 3d,
 					controlPointOffset * 6d, controlPointOffset * 6d);

 				g.FillStrokedEllipse (hoverOuterEllipseRect, hover_color, hover_color, 1);

 				g.FillStrokedEllipse (new Rectangle (
-					hover_point.X - controlPointOffset, hover_point.Y - controlPointOffset,
+					pos.X - controlPointOffset, pos.Y - controlPointOffset,
 					last_control_pt_size, last_control_pt_size), hover_color, hover_color, (int) last_control_pt_size);


Add xmldoc to HitWindows.cs.

Add xmldoc to HitWindows.cs.

--- osu.Game.Rulesets.Mania/Judgements/HitWindows.cs
+++ osu.Game.Rulesets.Mania/Judgements/HitWindows.cs
@@ -119,10 +119,17 @@
         /// </summary>
         public double Miss = miss_mid;

+        /// <summary>
+        /// Constructs default hit windows.
+        /// </summary>
         public HitWindows()
         {
         }

+        /// <summary>
+        /// Constructs hit windows by fitting a parameter to a 2-part piecewise linear function for each hit window.
+        /// </summary>
+        /// <param name="difficulty">The parameter.</param>
         public HitWindows(double difficulty)
         {
             Perfect = BeatmapDifficulty.DifficultyRange(difficulty, perfect_max, perfect_mid, perfect_min);
@@ -133,6 +140,11 @@
             Miss = BeatmapDifficulty.DifficultyRange(difficulty, miss_max, miss_mid, miss_min);
         }

+        /// <summary>
+        /// Constructs new hit windows which have been multiplied by a value.
+        /// </summary>
+        /// <param name="windows">The original hit windows.</param>
+        /// <param name="value">The value to multiply each hit window by.</param>
         public static HitWindows operator *(HitWindows windows, double value)
         {
             return new HitWindows
@@ -146,6 +158,11 @@
             };
         }

+        /// <summary>
+        /// Constructs new hit windows which have been divided by a value.
+        /// </summary>
+        /// <param name="windows">The original hit windows.</param>
+        /// <param name="value">The value to divide each hit window by.</param>
         public static HitWindows operator /(HitWindows windows, double value)
         {
             return new HitWindows


Bring database snapshot in line with specs

--- osu.Game/Migrations/OsuDbContextModelSnapshot.cs
+++ osu.Game/Migrations/OsuDbContextModelSnapshot.cs
@@ -43,7 +43,7 @@
                     b.Property<int>("ID")
                         .ValueGeneratedOnAdd();

-                    b.Property<int>("AudioLeadIn");
+                    b.Property<double>("AudioLeadIn");

                     b.Property<double>("BPM");


WebPlayer show/hide command should apply to entire command bar

--- WebPlayer/PlayerHandler.cs
+++ WebPlayer/PlayerHandler.cs
@@ -415,7 +415,7 @@
         {
             { "Panes", "#gamePanes" },
             { "Location", "#location" },
-            { "Command", "#txtCommand" }
+            { "Command", "#txtCommandDiv" }
         };

         private string GetElementId(string code)


More extensions to Moq Any

More extensions to Moq Any

--- Repo2.UnitTests.Lib/TestTools/MoqExtensions/Any.cs
+++ Repo2.UnitTests.Lib/TestTools/MoqExtensions/Any.cs
@@ -7,10 +7,12 @@
 {
     public class Any
     {
-        public static string            Text => It.IsAny<string>();
-        public static object            Obj  => It.IsAny<object>();
-        public static D8NodeBase        Node => It.IsAny<D8NodeBase>();
-        public static R2Package         Pkg  => It.IsAny<R2Package>();
-        public static CancellationToken Tkn  => It.IsAny<CancellationToken>();
+        public static ulong             ULong => It.IsAny<ulong>();
+        public static uint              UInt  => It.IsAny<uint>();
+        public static string            Text  => It.IsAny<string>();
+        public static object            Obj   => It.IsAny<object>();
+        public static D8NodeBase        Node  => It.IsAny<D8NodeBase>();
+        public static R2Package         Pkg   => It.IsAny<R2Package>();
+        public static CancellationToken Tkn   => It.IsAny<CancellationToken>();
     }
 }


S2239

--- RoslynProofs/RoslynProofsConsole/animals/People.cs
+++ RoslynProofs/RoslynProofsConsole/animals/People.cs
@@ -25,5 +25,9 @@
                 targetValue = targetValue.ToLower();
             }
         }
+
+        // S2239
+        public const string CHECKBOX_STRING = "<input type=\"checkbox\" id=\"{7}\" name=\"{1}\" checked=\"{2}\"  tablename=\"{4}\" value=\"{5}\" tabindex=\"{6}\" /> {3}";
+        public const string CHECKBOX_UNCHECK_STRING = "<input type=\"checkbox\" id=\"{6}\" name=\"{1}\" tablename=\"{3}\" value=\"{4}\" tabindex=\"{5}\" /> {2}";
     }
 }


added test for line comments

added test for line comments

--- ZUGFeRD-Test/BasicTests.cs
+++ ZUGFeRD-Test/BasicTests.cs
@@ -46,7 +46,7 @@

         [TestMethod]
-        void TestManualLineIds()
+        public void TestManualLineIds()
         {
             InvoiceDescriptor desc = this.InvoiceProvider.CreateInvoice();
             desc.TradeLineItems.Clear();
@@ -56,5 +56,38 @@
             Assert.AreEqual(desc.TradeLineItems[0].AssociatedDocument.LineID, "item-01");
             Assert.AreEqual(desc.TradeLineItems[1].AssociatedDocument.LineID, "item-02");
         } // !TestManualLineIds()
+
+
+        [TestMethod]
+        public void TestCommentLine()
+        {
+            string COMMENT = System.Guid.NewGuid().ToString();
+            string CUSTOM_LINE_ID = System.Guid.NewGuid().ToString();
+
+            // test with automatic line id
+            InvoiceDescriptor desc = this.InvoiceProvider.CreateInvoice();
+            int numberOfTradeLineItems = desc.TradeLineItems.Count;
+            desc.AddTradeLineCommentItem(COMMENT);
+
+            Assert.AreEqual(numberOfTradeLineItems + 1, desc.TradeLineItems.Count);
+            Assert.IsNotNull(desc.TradeLineItems[desc.TradeLineItems.Count - 1].AssociatedDocument);
+            Assert.IsNotNull(desc.TradeLineItems[desc.TradeLineItems.Count - 1].AssociatedDocument.Notes);
+            Assert.AreEqual(desc.TradeLineItems[desc.TradeLineItems.Count - 1].AssociatedDocument.Notes.Count, 1);
+            Assert.AreEqual(desc.TradeLineItems[desc.TradeLineItems.Count - 1].AssociatedDocument.Notes[0].Content, COMMENT);
+
+
+            // test with manual line id
+            desc = this.InvoiceProvider.CreateInvoice();
+            numberOfTradeLineItems = desc.TradeLineItems.Count;
+            desc.AddTradeLineCommentItem(CUSTOM_LINE_ID, COMMENT);
+
+            Assert.AreEqual(numberOfTradeLineItems + 1, desc.TradeLineItems.Count);
+            Assert.IsNotNull(desc.TradeLineItems[desc.TradeLineItems.Count - 1].LineID, CUSTOM_LINE_ID);
+            Assert.IsNotNull(desc.TradeLineItems[desc.TradeLineItems.Count - 1].AssociatedDocument);
+            Assert.IsNotNull(desc.TradeLineItems[desc.TradeLineItems.Count - 1].AssociatedDocument.Notes);
+            Assert.AreEqual(desc.TradeLineItems[desc.TradeLineItems.Count - 1].AssociatedDocument.Notes.Count, 1);
+            Assert.AreEqual(desc.TradeLineItems[desc.TradeLineItems.Count - 1].AssociatedDocument.Notes[0].Content, COMMENT);
+        }
+
     }
 }


multi-threading test

multi-threading test

--- src/tests/IntegrationTests/Memory/SafeString/SafeStringTests.cs
+++ src/tests/IntegrationTests/Memory/SafeString/SafeStringTests.cs
@@ -1,4 +1,5 @@
-using NUnit.Framework;
+using System.Threading;
+using NUnit.Framework;

 namespace SafeOrbit.Memory
 {
@@ -21,5 +22,25 @@
                 Assert.That(actual, Is.EqualTo(expected));
             }
         }
+
+        [Test]
+        public void SafeString_ModifiedByAnotherThread_ReturnsAppendedText()
+        {
+            var expected = "test";
+            var sut = new SafeString();
+            sut.Append("t");
+            var thread = new Thread(() =>
+            {
+                sut.Append("es");
+                sut.Append('t');
+            });
+            thread.Start();
+            thread.Join();
+            using (var sm = new SafeStringToStringMarshaler(sut))
+            {
+                var actual = sm.String;
+                Assert.That(actual, Is.EqualTo(expected));
+            }
+        }
     }
 }


fix failing tests

fix failing tests

--- SS.Integration.Adapter.Specs/MarketFiltersSteps.cs
+++ SS.Integration.Adapter.Specs/MarketFiltersSteps.cs
@@ -278,7 +278,7 @@
                 if (Convert.ToBoolean (row["Exists"]))
                 {
                     Market mkt = fixture.Markets.First(x => x.Id == mkt_name);
-                    var n = row["Name"];
+                    var n = row["Name"].ToLower();
                     mkt.Name.Should().Be(n);
                 }
             }
@@ -296,7 +296,7 @@
                 var mkt_name = row["Market"];

                 Market mkt = fixture.Markets.First(x => x.Id == mkt_name);
-                var n = row["Name"];
+                var n = row["Name"].ToLower();
                 mkt.Name.Should().Be(n);

                 var n_seln = Convert.ToInt32(row["NumberOfSelections"]);
@@ -308,7 +308,7 @@

                     foreach (var name in names.Split(','))
                     {
-                        mkt.Selections.FirstOrDefault(x => x.Name == name.Trim()).Should().NotBeNull();
+                        mkt.Selections.FirstOrDefault(x => x.Name.ToLower() == name.Trim().ToLower()).Should().NotBeNull();
                     }
                 }
             }


TSI-1265 Handle unresolved Component Links in GetFieldValuesAsStrings instead of in the standard model mapping logic.

--- Sdl.Web.Tridion/R2Mapping/DefaultModelBuilderR2.cs
+++ Sdl.Web.Tridion/R2Mapping/DefaultModelBuilderR2.cs
@@ -310,7 +310,7 @@
             return fieldValue;
         }

-        private static object MapField(object fieldValues, Type modelPropertyType, SemanticSchemaField semanticSchemaField, MappingData mappingData, bool resolveComponentLinks = true)
+        private static object MapField(object fieldValues, Type modelPropertyType, SemanticSchemaField semanticSchemaField, MappingData mappingData)
         {
             Type sourceType = fieldValues.GetType();
             bool isArray = sourceType.IsArray;
@@ -394,12 +394,12 @@
                     {
                         foreach (EntityModelData entityModelData in (EntityModelData[]) fieldValues)
                         {
-                            mappedValues.Add(MapComponentLink(entityModelData, targetType, mappingData.Localization, resolveComponentLinks));
+                            mappedValues.Add(MapComponentLink(entityModelData, targetType, mappingData.Localization));
                         }
                     }
                     else
                     {
-                        mappedValues.Add(MapComponentLink((EntityModelData) fieldValues, targetType, mappingData.Localization, resolveComponentLinks));
+                        mappedValues.Add(MapComponentLink((EntityModelData) fieldValues, targetType, mappingData.Localization));
                     }
                     break;

@@ -439,32 +439,25 @@
             return Convert.ChangeType(stringValue, targetType, CultureInfo.InvariantCulture.NumberFormat);
         }

-        private static object MapComponentLink(EntityModelData entityModelData, Type targetType, Localization localization, bool resolveComponentLink = true)
-        {
-            if (resolveComponentLink)
-            {
-                // TODO TSI-878: Use EntityModelData.LinkUrl (resolved by Model Service)
-                if (targetType == typeof(Link))
-                {
-                    return new Link { Url = ResolveLinkUrl(entityModelData, localization) };
-                }
-
-                if (targetType == typeof(string))
-                {
-                    return ResolveLinkUrl(entityModelData, localization);
-                }
-
-                if (!typeof(EntityModel).IsAssignableFrom(targetType))
-                {
-                    throw new DxaException($"Cannot map Component Link to property of type '{targetType.Name}'.");
-                }
-
-                return ModelBuilderPipelineR2.CreateEntityModel(entityModelData, targetType, localization);
-            }
-            else
-            {
-                return localization.GetCmUri(entityModelData.Id);
-            }
+        private static object MapComponentLink(EntityModelData entityModelData, Type targetType, Localization localization)
+        {
+            // TODO TSI-878: Use EntityModelData.LinkUrl (resolved by Model Service)
+            if (targetType == typeof(Link))
+            {
+                return new Link { Url = ResolveLinkUrl(entityModelData, localization) };
+            }
+
+            if (targetType == typeof(string))
+            {
+                return ResolveLinkUrl(entityModelData, localization);
+            }
+
+            if (!typeof(EntityModel).IsAssignableFrom(targetType))
+            {
+                throw new DxaException($"Cannot map Component Link to property of type '{targetType.Name}'.");
+            }
+
+            return ModelBuilderPipelineR2.CreateEntityModel(entityModelData, targetType, localization);
         }

         private static object MapKeyword(KeywordModelData keywordModelData, Type targetType, Localization localization)
@@ -650,22 +643,39 @@
                     {
                         throw new NotImplementedException("'settings' field handling"); // TODO
                     }
-                    result[field.Key] = GetFieldValuesAsStrings(field.Value, mappingData, false).FirstOrDefault();
+                    result[field.Key] = GetFieldValuesAsStrings(field.Value, mappingData,  resolveComponentLinks: false).FirstOrDefault();
                 }
             }
             if (mappingData.MetadataFields != null)
             {
                 foreach (KeyValuePair<string, object> field in mappingData.MetadataFields)
                 {
-                    result[field.Key] = GetFieldValuesAsStrings(field.Value, mappingData, false).FirstOrDefault();
+                    result[field.Key] = GetFieldValuesAsStrings(field.Value, mappingData, resolveComponentLinks: false).FirstOrDefault();
                 }
             }
             return result;
         }

-        private static IEnumerable<string> GetFieldValuesAsStrings(object fieldValues, MappingData mappingData, bool resolveComponentLinks = true)
-            => (IEnumerable<string>) MapField(fieldValues, typeof(List<string>), null, mappingData, resolveComponentLinks);
-
+        private static IEnumerable<string> GetFieldValuesAsStrings(object fieldValues, MappingData mappingData, bool resolveComponentLinks)
+        {
+            if (!resolveComponentLinks)
+            {
+                // Handle Component Links here, because standard model mapping will resolve them.
+                Localization localization = mappingData.Localization;
+                if (fieldValues is EntityModelData)
+                {
+                    return new[] { localization.GetCmUri(((EntityModelData) fieldValues).Id) };
+                }
+                if (fieldValues is EntityModelData[])
+                {
+                    return ((EntityModelData[]) fieldValues).Select(emd => localization.GetCmUri(emd.Id));
+                }
+            }
+
+            // Use standard model mapping to map the field to a list of strings.
+            return (IEnumerable<string>) MapField(fieldValues, typeof(List<string>), null, mappingData);
+        }
+
         private static IDictionary<string, string> ResolveMetaLinks(IDictionary<string, string> meta)
         {
             if (meta == null)


Add test fixture, clean up background/foreground test

--- ShopifySharp.Tests/RetryExecutionPolicies_Tests.cs
+++ ShopifySharp.Tests/RetryExecutionPolicies_Tests.cs
@@ -8,12 +8,9 @@
 namespace ShopifySharp.Tests
 {
     [Trait("Category", "Retry policies"), Trait("Category", "DotNetFramework"), Collection("DotNetFramework tests")]
-    public class RetryExecutionPolicies_Tests
+    public class RetryExecutionPolicies_Tests : IClassFixture<RetryExecutionPolicies_Tests_Fixture>
     {
-        private OrderService OrderService { get; } = new OrderService(Utils.MyShopifyUrl, Utils.AccessToken);
-        private GraphService GraphService { get; } = new GraphService(Utils.MyShopifyUrl, Utils.AccessToken);
-
-        private Order Order = new Order()
+        private readonly Order Order = new Order()
         {
             LineItems = new List<LineItem>()
             {
@@ -28,17 +25,24 @@
             TotalPrice = 5.00m,
         };

+        private readonly RetryExecutionPolicies_Tests_Fixture Fixture;
+
+        public RetryExecutionPolicies_Tests(RetryExecutionPolicies_Tests_Fixture fixture)
+        {
+            Fixture = fixture;
+        }
+
         [Fact]
         public async Task NonFullLeakyBucketBreachShouldNotAttemptRetry()
         {
-            OrderService.SetExecutionPolicy(new LeakyBucketExecutionPolicy());
+            Fixture.OrderService.SetExecutionPolicy(new LeakyBucketExecutionPolicy());
             bool caught = false;
             try
             {
                 //trip the 5 orders per minute limit on dev stores
                 foreach (var i in Enumerable.Range(0, 10))
                 {
-                    await OrderService.CreateAsync(this.Order);
+                    await Fixture.OrderService.CreateAsync(this.Order);
                 }
             }
             catch (ShopifyRateLimitException ex)
@@ -52,7 +56,7 @@
         [Fact]
         public async Task NonFullLeakyBucketBreachShouldRetryWhenConstructorBoolIsFalse()
         {
-            OrderService.SetExecutionPolicy(new LeakyBucketExecutionPolicy(false));
+            Fixture.OrderService.SetExecutionPolicy(new LeakyBucketExecutionPolicy(false));

             bool caught = false;

@@ -61,7 +65,7 @@
                 //trip the 5 orders per minute limit on dev stores
                 foreach (var i in Enumerable.Range(0, 6))
                 {
-                    await OrderService.CreateAsync(this.Order);
+                    await Fixture.OrderService.CreateAsync(this.Order);
                 }
             }
             catch (ShopifyRateLimitException)
@@ -75,14 +79,14 @@
         [Fact]
         public async Task LeakyBucketRESTBreachShouldAttemptRetry()
         {
-            OrderService.SetExecutionPolicy(new LeakyBucketExecutionPolicy());
+            Fixture.OrderService.SetExecutionPolicy(new LeakyBucketExecutionPolicy());

             bool caught = false;

             try
             {
                 //trip the 40/seconds bucket limit
-                await Task.WhenAll(Enumerable.Range(0, 45).Select(async _ => await OrderService.ListAsync()));
+                await Task.WhenAll(Enumerable.Range(0, 45).Select(async _ => await Fixture.OrderService.ListAsync()));
             }
             catch (ShopifyRateLimitException)
             {
@@ -95,7 +99,7 @@
         [Fact]
         public async Task LeakyBucketGraphQLBreachShouldAttemptRetry()
         {
-            GraphService.SetExecutionPolicy(new LeakyBucketExecutionPolicy());
+            Fixture.GraphService.SetExecutionPolicy(new LeakyBucketExecutionPolicy());

             bool caught = false;

@@ -122,7 +126,7 @@
   }
 }
 ";
-                await Task.WhenAll(Enumerable.Range(0, 10).Select(async _ => await GraphService.PostAsync(query, queryCost)));
+                await Task.WhenAll(Enumerable.Range(0, 10).Select(async _ => await Fixture.GraphService.PostAsync(query, queryCost)));
             }
             catch (ShopifyRateLimitException)
             {
@@ -137,22 +141,32 @@
         public async Task ForegroundRequestsMustRunBeforeBackgroundRequests()
         {
             var context = RequestContext.Background;
+            var policy = new LeakyBucketExecutionPolicy(getRequestContext: () => context);
+            var filter = new Filters.OrderListFilter
+            {
+                Status = "any",
+                Limit = 1,
+                Fields = "id"
+            };
+
             DateTime? backgroundCompletedAt = null;
             DateTime? foregroundCompletedAt = null;

-
-            OrderService.SetExecutionPolicy(new LeakyBucketExecutionPolicy(getRequestContext: () => context));
+            Fixture.OrderService.SetExecutionPolicy(policy);

             //kick off background requests, which will trigger a throttle
-            var bgTask = Task.WhenAll(Enumerable.Range(0, 50).Select(async _ => await OrderService.ListAsync()))
-                             .ContinueWith(_ => backgroundCompletedAt = DateTime.UtcNow);
+            var bgTask = Task.WhenAll(Enumerable.Range(0, 50).Select(async _ => await Fixture.OrderService.ListAsync(filter)))
+                .ContinueWith(_ => backgroundCompletedAt = DateTime.UtcNow);

             context = RequestContext.Foreground;
-            var fgTask = Task.WhenAll(Enumerable.Range(0, 10).Select(async _ => await OrderService.ListAsync(new Filters.OrderListFilter { Status = "any" })))
-                             .ContinueWith(_ => foregroundCompletedAt = DateTime.UtcNow);
+
+            var fgTask = Task.WhenAll(Enumerable.Range(0, 10).Select(async _ => await Fixture.OrderService.ListAsync(filter)))
+                .ContinueWith(_ => foregroundCompletedAt = DateTime.UtcNow);

             await Task.WhenAll(bgTask, fgTask);

+            Assert.NotNull(backgroundCompletedAt);
+            Assert.NotNull(foregroundCompletedAt);
             Assert.True(foregroundCompletedAt < backgroundCompletedAt);
         }

@@ -161,9 +175,9 @@
         {
             await Assert.ThrowsAnyAsync<Exception>(async () =>
             {
-                GraphService.SetExecutionPolicy(new LeakyBucketExecutionPolicy());
+                Fixture.GraphService.SetExecutionPolicy(new LeakyBucketExecutionPolicy());
                 string query = "!#@$%$#%";
-                await GraphService.PostAsync(query, 1);
+                await Fixture.GraphService.PostAsync(query, 1);
             });
         }

@@ -172,7 +186,7 @@
         {
             await Assert.ThrowsAnyAsync<Exception>(async () =>
             {
-                GraphService.SetExecutionPolicy(new LeakyBucketExecutionPolicy());
+                Fixture.GraphService.SetExecutionPolicy(new LeakyBucketExecutionPolicy());
                 string query = @"{
   products(first: 20) {
     edges {
@@ -194,8 +208,25 @@
   }
 }
 ";
-                await GraphService.PostAsync(query, 1);
+                await Fixture.GraphService.PostAsync(query, 1);
             });
         }
     }
+
+    public class RetryExecutionPolicies_Tests_Fixture : IAsyncLifetime
+    {
+        public readonly OrderService OrderService = new OrderService(Utils.MyShopifyUrl, Utils.AccessToken);
+
+        public GraphService GraphService = new GraphService(Utils.MyShopifyUrl, Utils.AccessToken);
+
+        public Task InitializeAsync()
+        {
+            return Task.CompletedTask;
+        }
+
+        public Task DisposeAsync()
+        {
+            return Task.CompletedTask;
+        }
+    }
 }


clean liens with DeclareNode only

clean liens with DeclareNode only

--- Signum.Engine.Extensions/Word/WordTemplateNodes.cs
+++ Signum.Engine.Extensions/Word/WordTemplateNodes.cs
@@ -186,7 +186,10 @@

         protected internal override void RenderNode(WordTemplateParameters p)
         {
-            this.Remove();
+            if (this.Parent is Paragraph && !this.Parent.ChildElements.Any(a => BlockContainerNode.IsImportant (a) && a != this))
+                this.Parent.Remove();
+            else
+                this.Remove();
         }

         protected internal override void RenderTemplate(ScopedDictionary<string, ValueProviderBase> variables)
@@ -317,7 +320,7 @@
             }
         }

-        private bool IsImportant(OpenXmlElement c)
+        public static bool IsImportant(OpenXmlElement c)
         {
             if (c is Paragraph)
                 return true;
@@ -331,6 +334,9 @@

                 return true;
             }
+
+            if (c is BaseNode)
+                return true;

             return false;
         }


ReadIdentityInfo fix

ReadIdentityInfo fix

--- Signum.React/JsonConverters/EntityJsonConverter.cs
+++ Signum.React/JsonConverters/EntityJsonConverter.cs
@@ -501,12 +501,13 @@
                     case "Type": info.Type = reader.ReadAsString()!; break;
                     case "ticks": info.Ticks = long.Parse(reader.ReadAsString()!); break;
                     case "modified": info.Modified = bool.Parse(reader.ReadAsString()!); break;
-                    default: return info;
+                    default: goto finish;
                 }

                 reader.Read();
             }

+            finish:
             if (info.Type == null)
                 throw new JsonSerializationException($"Expected member 'Type' not found in {reader.Path}");


Fixed ugly spacing somewhat

Fixed ugly spacing somewhat

--- SimpleYetSoSharpBot/SimpleYetSoSharpBot/Program.cs
+++ SimpleYetSoSharpBot/SimpleYetSoSharpBot/Program.cs
@@ -15,7 +15,7 @@
 {
     internal class Program
     {
-		//edit this if you feel like it
+        //edit this if you feel like it
         private static string[] shityousaywhenyoudead = { "lulz", "lol", "omg", "noooooob", "help me", "fkin nooooobs", "TEAM WHERE YOU AT???", "WILL YOU HELP?", "HEEEEEEEEEEEELP", "OMG REPORT MY NOOB TEAM", "OMG MY TEAM SHOULD UNINSTALL", "MATCHMAKING SO UNFAIR", "gg", "I just want this game to end fking noobs" };
         private static Spell Q;
         private static Spell W;
@@ -23,7 +23,7 @@
         private static Spell R;
         private static TargetSelector ts;
         private static Menu menu;
-		private static int deathcounter = 0;
+        private static int deathcounter = 0;
         private static double timedead;
         private static List<Obj_AI_Hero> allies;
         private static int i = 0;
@@ -63,7 +63,7 @@

         private static void Game_OnGameLoad(EventArgs args)
         {
-             if (player.Level == 1)
+            if (player.Level == 1)
             {
                 SpellSlot abilitySlot;
                 if (abilityOrder[0] == 1)
@@ -92,14 +92,14 @@

             allies = new List<Obj_AI_Hero>();

-
-			if (ObjectManager.Player.ChampionName == "Soraka")
-			{
-				Q = new Spell(SpellSlot.Q, 970);
-				W = new Spell(SpellSlot.W, 550);
-				E = new Spell(SpellSlot.E, 925);
-				R = new Spell(SpellSlot.R);
-			}
+
+            if (ObjectManager.Player.ChampionName == "Soraka")
+            {
+                Q = new Spell(SpellSlot.Q, 970);
+                W = new Spell(SpellSlot.W, 550);
+                E = new Spell(SpellSlot.E, 925);
+                R = new Spell(SpellSlot.R);
+            }
             else if (ObjectManager.Player.ChampionName == "Annie")
             {
                 Q = new Spell(SpellSlot.Q, 650);
@@ -119,14 +119,14 @@
             menu = new Menu("AutoPlay Bot", "syssb", true);
             menu.AddSubMenu(new Menu("Follow:", "follower"));
             menu.AddItem(new MenuItem("quiet", "Quiet mode").SetValue(quietm));
-			if (ObjectManager.Player.ChampionName == "Soraka")
-			{
-				menu.AddItem(new MenuItem("user", "Use R?").SetValue(true));
-				menu.AddItem(new MenuItem("usew", "Use W?").SetValue(true));
-				menu.AddItem(new MenuItem("allyhpw", "Ally % HP for W").SetValue(new Slider(30, 0, 93)));
-				menu.AddItem(new MenuItem("wabovehp", "Use W when my hp > x%").SetValue(new Slider(20, 0, 99)));
-				menu.AddItem(new MenuItem("allyhpr", "Ally % HP for R").SetValue(new Slider(30, 0, 50)));
-			}
+            if (ObjectManager.Player.ChampionName == "Soraka")
+            {
+                menu.AddItem(new MenuItem("user", "Use R?").SetValue(true));
+                menu.AddItem(new MenuItem("usew", "Use W?").SetValue(true));
+                menu.AddItem(new MenuItem("allyhpw", "Ally % HP for W").SetValue(new Slider(30, 0, 93)));
+                menu.AddItem(new MenuItem("wabovehp", "Use W when my hp > x%").SetValue(new Slider(20, 0, 99)));
+                menu.AddItem(new MenuItem("allyhpr", "Ally % HP for R").SetValue(new Slider(30, 0, 50)));
+            }
             foreach (var ally in ObjectManager.Get<Obj_AI_Hero>().Where(x => x.IsAlly && !x.IsMe))
             {
                 allies.Add(ally);
@@ -152,7 +152,7 @@
             menu.AddToMainMenu();
             Game.OnGameProcessPacket += Game_OnGameProcessPacket;
             Game.OnGameUpdate += Game_OnGameUpdate;
-			Game.OnGameEnd += OnGameEnd;
+            Game.OnGameEnd += OnGameEnd;
             BuyItems();
         }

@@ -164,14 +164,7 @@
             if (p.Header != Packet.S2C.TowerAggro.Header) return;
             if (Packet.S2C.TowerAggro.Decoded(args.PacketData).TargetNetworkId != ObjectManager.Player.NetworkId)
                 return;
-
-
-        }
-
-
-
-
-
+        }

         private static void Game_OnGameUpdate(EventArgs args)
@@ -191,7 +184,7 @@
             BuyItems();
             doFollow();

-
+

             if (ObjectManager.Player.IsDead && Game.Time - timedead > 80 && !quietm)
             {
@@ -208,9 +201,6 @@

             Console.WriteLine(follow.IsDead);

-
-
-
         }
         public static void OnLevelUp(Obj_AI_Base sender, CustomEvents.Unit.OnLevelUpEventArgs args)
         {
@@ -244,7 +234,7 @@

-
+
         public static void doFollow()
         {
             if (adcs == 0 && !menuHacked)
@@ -253,91 +243,91 @@
                 menu.SubMenu("follower").Item(tempfollow).SetValue(true);
                 menuHacked = true;
             }
-			if (follow == null)
+            if (follow == null)
             {
                 follow = ObjectManager.Get<Obj_AI_Hero>().First(x => !x.IsMe && x.IsAlly);
             }
-                if (follow.Distance(ObjectManager.Player.Position) > 600)
-                {
-                    ObjectManager.Player.IssueOrder(GameObjectOrder.MoveTo, follow.Position);
-                }
-
-
-				if (ObjectManager.Player.ChampionName == "Soraka")
-				{
-						if (W.IsReady() && menu.Item("usew").GetValue<bool>() &&
-						ObjectManager.Player.Health / ObjectManager.Player.MaxHealth * 100 >
-						menu.Item("wabovehp").GetValue<Slider>().Value)
-						{
-						if (follow.Health / follow.MaxHealth * 100 < menu.Item("allyhpw").GetValue<Slider>().Value &&
-						follow.Distance(ObjectManager.Player.Position) < 550 &&
-						ObjectManager.Player.Health / ObjectManager.Player.MaxHealth * 100 >
-						menu.Item("wabovehp").GetValue<Slider>().Value)
-						{
-						W.Cast(follow);
-							if (R.IsReady())
-								{
-									R.Cast();
-								}
-						}
-						else if (follow.Health / follow.MaxHealth * 100 < menu.Item("allyhpw").GetValue<Slider>().Value &&
-						follow.Distance(ObjectManager.Player.Position) > 550)
-						{
-						ObjectManager.Player.IssueOrder(GameObjectOrder.MoveTo, follow.Position);
-						}
-						}
-						if (ts.Target.Distance(ObjectManager.Player) < Q.Range && Q.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
-						{
-						Q.Cast(ts.Target);
-						}
-						if (ts.Target.Distance(ObjectManager.Player) < E.Range && E.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
-						{
-						E.Cast(ts.Target);
-						}
-				}
-                else if (ObjectManager.Player.ChampionName == "Annie")
-                {
-                    if (ts.Target.Distance(ObjectManager.Player) < Q.Range && Q.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
+            if (follow.Distance(ObjectManager.Player.Position) > 600)
+            {
+                ObjectManager.Player.IssueOrder(GameObjectOrder.MoveTo, follow.Position);
+            }
+
+
+            if (ObjectManager.Player.ChampionName == "Soraka")
+            {
+                if (W.IsReady() && menu.Item("usew").GetValue<bool>() &&
+                ObjectManager.Player.Health / ObjectManager.Player.MaxHealth * 100 >
+                menu.Item("wabovehp").GetValue<Slider>().Value)
+                {
+                    if (follow.Health / follow.MaxHealth * 100 < menu.Item("allyhpw").GetValue<Slider>().Value &&
+                    follow.Distance(ObjectManager.Player.Position) < 550 &&
+                    ObjectManager.Player.Health / ObjectManager.Player.MaxHealth * 100 >
+                    menu.Item("wabovehp").GetValue<Slider>().Value)
                     {
-                        Q.Cast(ts.Target);
+                        W.Cast(follow);
+                        if (R.IsReady())
+                        {
+                            R.Cast();
+                        }
                     }
-
-                    if (ts.Target.Distance(ObjectManager.Player) < W.Range && W.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
+                    else if (follow.Health / follow.MaxHealth * 100 < menu.Item("allyhpw").GetValue<Slider>().Value &&
+                    follow.Distance(ObjectManager.Player.Position) > 550)
                     {
-                        W.Cast(ts.Target);
+                        ObjectManager.Player.IssueOrder(GameObjectOrder.MoveTo, follow.Position);
                     }
-
-                    if (ts.Target.Distance(ObjectManager.Player) < R.Range && R.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
-                    {
-                        R.Cast(ts.Target);
-                    }
-                    if (E.IsReady())
-                    {
-                        E.Cast();
-                    }
-                }
-                else
-                {
-                    //if spells available, cast them.
-                    if (ts.Target.Distance(follow.Position) < 600 && follow.Distance(ObjectManager.Player.Position) < 700 && Q.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
-                    {
-                        Q.Cast(ts.Target);
-                    }
-
-                    if (ts.Target.Distance(follow.Position) < 600 && follow.Distance(ObjectManager.Player.Position) < 700 && W.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
-                    {
-                        W.Cast(ts.Target);
-                    }
-
-                    if (ts.Target.Distance(follow.Position) < 600 && follow.Distance(ObjectManager.Player.Position) < 700 && R.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
-                    {
-                        R.Cast(ts.Target);
-                    }
-                    if (ts.Target.Distance(follow.Position) < 600 && follow.Distance(ObjectManager.Player.Position) < 700 && E.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
-                    {
-                        E.Cast(ts.Target);
-                    }
-                }
+                }
+                if (ts.Target.Distance(ObjectManager.Player) < Q.Range && Q.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
+                {
+                    Q.Cast(ts.Target);
+                }
+                if (ts.Target.Distance(ObjectManager.Player) < E.Range && E.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
+                {
+                    E.Cast(ts.Target);
+                }
+            }
+            else if (ObjectManager.Player.ChampionName == "Annie")
+            {
+                if (ts.Target.Distance(ObjectManager.Player) < Q.Range && Q.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
+                {
+                    Q.Cast(ts.Target);
+                }
+
+                if (ts.Target.Distance(ObjectManager.Player) < W.Range && W.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
+                {
+                    W.Cast(ts.Target);
+                }
+
+                if (ts.Target.Distance(ObjectManager.Player) < R.Range && R.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
+                {
+                    R.Cast(ts.Target);
+                }
+                if (E.IsReady())
+                {
+                    E.Cast();
+                }
+            }
+            else
+            {
+                //if spells available, cast them.
+                if (ts.Target.Distance(follow.Position) < 600 && follow.Distance(ObjectManager.Player.Position) < 700 && Q.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
+                {
+                    Q.Cast(ts.Target);
+                }
+
+                if (ts.Target.Distance(follow.Position) < 600 && follow.Distance(ObjectManager.Player.Position) < 700 && W.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
+                {
+                    W.Cast(ts.Target);
+                }
+
+                if (ts.Target.Distance(follow.Position) < 600 && follow.Distance(ObjectManager.Player.Position) < 700 && R.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
+                {
+                    R.Cast(ts.Target);
+                }
+                if (ts.Target.Distance(follow.Position) < 600 && follow.Distance(ObjectManager.Player.Position) < 700 && E.IsReady() && !Utility.UnderTurret(ObjectManager.Player, true))
+                {
+                    E.Cast(ts.Target);
+                }
+            }
         }

         public static void BuyItems()
@@ -376,32 +366,32 @@
             }
             else
             {
-                    if (Utility.InFountain() && ObjectManager.Player.Gold == 475 && !boughtItemOne)
-                    {
-                        Packet.C2S.BuyItem.Encoded(new Packet.C2S.BuyItem.Struct(1001)).Send();
-                        Packet.C2S.BuyItem.Encoded(new Packet.C2S.BuyItem.Struct(2003)).Send();
-                        Packet.C2S.BuyItem.Encoded(new Packet.C2S.BuyItem.Struct(3340)).Send();
-                        Game.PrintChat("BOUGHT BOTS");
-                        boughtItemOne = true;
-                    }
-                    if (Utility.InShopRange() && ObjectManager.Player.Gold > 1900 && ObjectManager.Player.Gold < 2550 && !boughtItemTwo)
-                    {
-                        Packet.C2S.BuyItem.Encoded(new Packet.C2S.BuyItem.Struct(3105)).Send();
-                        Game.PrintChat("BOUGHT AEGIS");
-                        boughtItemTwo = true;
-                    }
-                    else if (Utility.InShopRange() && ObjectManager.Player.Gold > 2550 && !boughtItemThree)
-                    {
-                        Packet.C2S.BuyItem.Encoded(new Packet.C2S.BuyItem.Struct(3050)).Send();
-                        Game.PrintChat("BOUGHT ZEKES");
-                        boughtItemThree = true;
-                    }
-            }
-
-        }
-		private static void OnGameEnd(EventArgs args)
-		{
-		Game.Say("gg");
-		}
+                if (Utility.InFountain() && ObjectManager.Player.Gold == 475 && !boughtItemOne)
+                {
+                    Packet.C2S.BuyItem.Encoded(new Packet.C2S.BuyItem.Struct(1001)).Send();
+                    Packet.C2S.BuyItem.Encoded(new Packet.C2S.BuyItem.Struct(2003)).Send();
+                    Packet.C2S.BuyItem.Encoded(new Packet.C2S.BuyItem.Struct(3340)).Send();
+                    Game.PrintChat("BOUGHT BOTS");
+                    boughtItemOne = true;
+                }
+                if (Utility.InShopRange() && ObjectManager.Player.Gold > 1900 && ObjectManager.Player.Gold < 2550 && !boughtItemTwo)
+                {
+                    Packet.C2S.BuyItem.Encoded(new Packet.C2S.BuyItem.Struct(3105)).Send();
+                    Game.PrintChat("BOUGHT AEGIS");
+                    boughtItemTwo = true;
+                }
+                else if (Utility.InShopRange() && ObjectManager.Player.Gold > 2550 && !boughtItemThree)
+                {
+                    Packet.C2S.BuyItem.Encoded(new Packet.C2S.BuyItem.Struct(3050)).Send();
+                    Game.PrintChat("BOUGHT ZEKES");
+                    boughtItemThree = true;
+                }
+            }
+
+        }
+        private static void OnGameEnd(EventArgs args)
+        {
+            Game.Say("gg");
+        }
     }
 }


Update to line endings from CRLF to LF

Update to line endings from CRLF to LF

--- Raccoon/Core/Input/Input.cs
+++ Raccoon/Core/Input/Input.cs
@@ -1,198 +1,198 @@
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using Microsoft.Xna.Framework.Input;
-
-namespace Raccoon.Input {
-    public enum MouseButton {
-        None = 0,
-        Left,
-        Middle,
-        Right,
-        M4,
-        M5
-    }
-
-    public enum InputButtonState {
-        None,
-        Up,
-        Released,
-        Pressed,
-        Down
-    }
-
-    public class Input {
-        #region Public Members
-
-        public static System.Action<char, Key> OnTextInput = delegate { };
-
-        #endregion Public Members
-
-        #region Private Members
-
-        private static readonly System.Lazy<Input> _lazy = new System.Lazy<Input>(() => new Input());
-
-        private bool _activated;
-
-        // keyboard
-        private KeyboardState _keyboardState, _keyboardPreviousState;
-        private List<Key> _pressedKeys = new List<Key>();
-        private readonly Dictionary<Key, char> _specialKeysToChar = new Dictionary<Key, char>();
-
-        // mouse
-        private Dictionary<MouseButton, ButtonState> _mouseButtonsState = new Dictionary<MouseButton, ButtonState>(), _mouseButtonsLastState = new Dictionary<MouseButton, ButtonState>();
-        private Vector2 _mousePosition;
-
-        // joystick
-        //private Dictionary<int, JoystickState> _joysticksState = new Dictionary<int, JoystickState>(), _joysticksPreviousState = new Dictionary<int, JoystickState>();
-
-        #endregion Private Members
-
-        #region Constructors
-
-        private Input() {
-            // mouse
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using Microsoft.Xna.Framework.Input;
+
+namespace Raccoon.Input {
+    public enum MouseButton {
+        None = 0,
+        Left,
+        Middle,
+        Right,
+        M4,
+        M5
+    }
+
+    public enum InputButtonState {
+        None,
+        Up,
+        Released,
+        Pressed,
+        Down
+    }
+
+    public class Input {
+        #region Public Members
+
+        public static System.Action<char, Key> OnTextInput = delegate { };
+
+        #endregion Public Members
+
+        #region Private Members
+
+        private static readonly System.Lazy<Input> _lazy = new System.Lazy<Input>(() => new Input());
+
+        private bool _activated;
+
+        // keyboard
+        private KeyboardState _keyboardState, _keyboardPreviousState;
+        private List<Key> _pressedKeys = new List<Key>();
+        private readonly Dictionary<Key, char> _specialKeysToChar = new Dictionary<Key, char>();
+
+        // mouse
+        private Dictionary<MouseButton, ButtonState> _mouseButtonsState = new Dictionary<MouseButton, ButtonState>(), _mouseButtonsLastState = new Dictionary<MouseButton, ButtonState>();
+        private Vector2 _mousePosition;
+
+        // joystick
+        //private Dictionary<int, JoystickState> _joysticksState = new Dictionary<int, JoystickState>(), _joysticksPreviousState = new Dictionary<int, JoystickState>();
+
+        #endregion Private Members
+
+        #region Constructors
+
+        private Input() {
+            // mouse
             foreach (MouseButton id in System.Enum.GetValues(typeof(MouseButton))) {
                 _mouseButtonsState[id] = ButtonState.Released;
                 _mouseButtonsLastState[id] = ButtonState.Released;
-            }
-
-            PressedKeys = _pressedKeys.AsReadOnly();
-
-            // keys to string
-            _specialKeysToChar[Key.Space] = ' ';
-            _specialKeysToChar[Key.Period] = '.';
-            _specialKeysToChar[Key.Comma] = ',';
-
-            //! Game.Instance.XNAGameWrapper.Window.TextInput += ProcessTextInput;
-            Game.Instance.XNAGameWrapper.Activated += (object sender, System.EventArgs e) => {
-                _activated = true;
-            };
-        }
-
-        #endregion Constructors
-
-        #region Public Properties
-
-        public static Input Instance { get { return _lazy.Value; } }
-        public static int JoysticksConnected { get; private set; }
+            }
+
+            PressedKeys = _pressedKeys.AsReadOnly();
+
+            // keys to string
+            _specialKeysToChar[Key.Space] = ' ';
+            _specialKeysToChar[Key.Period] = '.';
+            _specialKeysToChar[Key.Comma] = ',';
+
+            //! Game.Instance.XNAGameWrapper.Window.TextInput += ProcessTextInput;
+            Game.Instance.XNAGameWrapper.Activated += (object sender, System.EventArgs e) => {
+                _activated = true;
+            };
+        }
+
+        #endregion Constructors
+
+        #region Public Properties
+
+        public static Input Instance { get { return _lazy.Value; } }
+        public static int JoysticksConnected { get; private set; }
         public static Vector2 MouseMovement { get; private set; }
         public static int MouseScrollWheel { get; private set; }
-        public static int MouseScrollWheelDelta { get; private set; }
-        public static bool LockMouseOnWindow { get; set; }
-        public static bool LockMouseOnCenter { get; set; }
-        public static ReadOnlyCollection<Key> PressedKeys { get; private set; }
-
-        public static Vector2 MousePosition {
-            get {
-                return Instance._mousePosition;
-            }
-
-            set {
-                Instance._mousePosition = new Vector2(
-                    Util.Math.Clamp(value.X, 0, Game.Instance.WindowWidth) / (Game.Instance.PixelScale * Game.Instance.KeepProportionsScale),
-                    Util.Math.Clamp(value.Y, 0, Game.Instance.WindowHeight) / (Game.Instance.PixelScale * Game.Instance.KeepProportionsScale)
-                );
-
-                Mouse.SetPosition((int) Util.Math.Clamp(value.X, 0, Game.Instance.WindowWidth), (int) Util.Math.Clamp(value.Y, 0, Game.Instance.WindowHeight));
-            }
-        }
-
-        #endregion Public Properties
-
-        #region Public Methods
-
-        public static bool IsKeyPressed(Key key) {
-            return Instance._keyboardPreviousState[(Keys) key] == KeyState.Up && Instance._keyboardState[(Keys) key] == KeyState.Down;
-        }
-
-        public static bool IsKeyDown(Key key) {
-            return Instance._keyboardState[(Keys) key] == KeyState.Down;
-        }
-
-        public static bool IsKeyReleased(Key key) {
-            return Instance._keyboardPreviousState[(Keys) key] == KeyState.Down && Instance._keyboardState[(Keys) key] == KeyState.Up;
-        }
-
-        public static bool IsKeyUp(Key key) {
-            return Instance._keyboardState[(Keys) key] == KeyState.Up;
-        }
-
-        public static bool IsAnyKeyPressed() {
-            return PressedKeys.Count > 0;
-        }
-
-        public static InputButtonState KeyboardState(Key key) {
-            KeyState previousState = Instance._keyboardPreviousState[(Keys) key],
-                     currentState = Instance._keyboardState[(Keys) key];
-
-            if (previousState == KeyState.Up) {
-                if (currentState == KeyState.Down) {
-                    return InputButtonState.Pressed;
-                }
-
-                return InputButtonState.Up;
-            }
-
-            if (currentState == KeyState.Up) {
-                return InputButtonState.Released;
-            }
-
-            return InputButtonState.Down;
-        }
-
-        public static bool IsJoyButtonPressed(int joystickId, int buttonId) {
-            //return (!Instance._joysticksPreviousState.ContainsKey(joystickId) || Instance._joysticksPreviousState[joystickId].Buttons[buttonId] == ButtonState.Released) && Instance._joysticksState[joystickId].Buttons[buttonId] == ButtonState.Pressed;
-            return false;
-        }
-
-        public static bool IsJoyButtonDown(int joystickId, int buttonId) {
-            //return Instance._joysticksState[joystickId].Buttons[buttonId] == ButtonState.Pressed;
-            return false;
-        }
-
-        public static bool IsJoyButtonReleased(int joystickId, int buttonId) {
-            //return Instance._joysticksPreviousState[joystickId].Buttons[buttonId] == ButtonState.Pressed && (!Instance._joysticksState.ContainsKey(joystickId) || Instance._joysticksState[joystickId].Buttons[buttonId] == ButtonState.Released);
-            return false;
-        }
-
-        public static bool IsJoyButtonUp(int joystickId, int buttonId) {
-            //return Instance._joysticksState[joystickId].Buttons[buttonId] == ButtonState.Released;
-            return true;
-        }
-
-        public static InputButtonState JoyButtonState(int joystickId, int buttonId) {
-            /*
-            ButtonState previousState = Instance._joysticksState[joystickId].Buttons[buttonId],
-                        currentState = Instance._joysticksPreviousState[joystickId].Buttons[buttonId];
-
-            if (previousState == ButtonState.Released) {
-                if (currentState == ButtonState.Pressed) {
-                    return InputButtonState.Pressed;
-                }
-
-                return InputButtonState.Up;
-            }
-
-            if (currentState == ButtonState.Released) {
-                return InputButtonState.Released;
-            }
-
-            return InputButtonState.Down;
-            */
-
-            return InputButtonState.Up;
-        }
-
-        public static float JoyAxisValue(int joystickId, int axisId) {
-            //return Instance._joysticksState[joystickId].Axes[axisId];
-            return 0f;
-        }
-
-        public static bool IsJoystickConnected(int joystickId) {
-        //return Instance._joysticksState.ContainsKey(joystickId) && Instance._joysticksState[joystickId].IsConnected;
-            return false;
-        }
-
+        public static int MouseScrollWheelDelta { get; private set; }
+        public static bool LockMouseOnWindow { get; set; }
+        public static bool LockMouseOnCenter { get; set; }
+        public static ReadOnlyCollection<Key> PressedKeys { get; private set; }
+
+        public static Vector2 MousePosition {
+            get {
+                return Instance._mousePosition;
+            }
+
+            set {
+                Instance._mousePosition = new Vector2(
+                    Util.Math.Clamp(value.X, 0, Game.Instance.WindowWidth) / (Game.Instance.PixelScale * Game.Instance.KeepProportionsScale),
+                    Util.Math.Clamp(value.Y, 0, Game.Instance.WindowHeight) / (Game.Instance.PixelScale * Game.Instance.KeepProportionsScale)
+                );
+
+                Mouse.SetPosition((int) Util.Math.Clamp(value.X, 0, Game.Instance.WindowWidth), (int) Util.Math.Clamp(value.Y, 0, Game.Instance.WindowHeight));
+            }
+        }
+
+        #endregion Public Properties
+
+        #region Public Methods
+
+        public static bool IsKeyPressed(Key key) {
+            return Instance._keyboardPreviousState[(Keys) key] == KeyState.Up && Instance._keyboardState[(Keys) key] == KeyState.Down;
+        }
+
+        public static bool IsKeyDown(Key key) {
+            return Instance._keyboardState[(Keys) key] == KeyState.Down;
+        }
+
+        public static bool IsKeyReleased(Key key) {
+            return Instance._keyboardPreviousState[(Keys) key] == KeyState.Down && Instance._keyboardState[(Keys) key] == KeyState.Up;
+        }
+
+        public static bool IsKeyUp(Key key) {
+            return Instance._keyboardState[(Keys) key] == KeyState.Up;
+        }
+
+        public static bool IsAnyKeyPressed() {
+            return PressedKeys.Count > 0;
+        }
+
+        public static InputButtonState KeyboardState(Key key) {
+            KeyState previousState = Instance._keyboardPreviousState[(Keys) key],
+                     currentState = Instance._keyboardState[(Keys) key];
+
+            if (previousState == KeyState.Up) {
+                if (currentState == KeyState.Down) {
+                    return InputButtonState.Pressed;
+                }
+
+                return InputButtonState.Up;
+            }
+
+            if (currentState == KeyState.Up) {
+                return InputButtonState.Released;
+            }
+
+            return InputButtonState.Down;
+        }
+
+        public static bool IsJoyButtonPressed(int joystickId, int buttonId) {
+            //return (!Instance._joysticksPreviousState.ContainsKey(joystickId) || Instance._joysticksPreviousState[joystickId].Buttons[buttonId] == ButtonState.Released) && Instance._joysticksState[joystickId].Buttons[buttonId] == ButtonState.Pressed;
+            return false;
+        }
+
+        public static bool IsJoyButtonDown(int joystickId, int buttonId) {
+            //return Instance._joysticksState[joystickId].Buttons[buttonId] == ButtonState.Pressed;
+            return false;
+        }
+
+        public static bool IsJoyButtonReleased(int joystickId, int buttonId) {
+            //return Instance._joysticksPreviousState[joystickId].Buttons[buttonId] == ButtonState.Pressed && (!Instance._joysticksState.ContainsKey(joystickId) || Instance._joysticksState[joystickId].Buttons[buttonId] == ButtonState.Released);
+            return false;
+        }
+
+        public static bool IsJoyButtonUp(int joystickId, int buttonId) {
+            //return Instance._joysticksState[joystickId].Buttons[buttonId] == ButtonState.Released;
+            return true;
+        }
+
+        public static InputButtonState JoyButtonState(int joystickId, int buttonId) {
+            /*
+            ButtonState previousState = Instance._joysticksState[joystickId].Buttons[buttonId],
+                        currentState = Instance._joysticksPreviousState[joystickId].Buttons[buttonId];
+
+            if (previousState == ButtonState.Released) {
+                if (currentState == ButtonState.Pressed) {
+                    return InputButtonState.Pressed;
+                }
+
+                return InputButtonState.Up;
+            }
+
+            if (currentState == ButtonState.Released) {
+                return InputButtonState.Released;
+            }
+
+            return InputButtonState.Down;
+            */
+
+            return InputButtonState.Up;
+        }
+
+        public static float JoyAxisValue(int joystickId, int axisId) {
+            //return Instance._joysticksState[joystickId].Axes[axisId];
+            return 0f;
+        }
+
+        public static bool IsJoystickConnected(int joystickId) {
+        //return Instance._joysticksState.ContainsKey(joystickId) && Instance._joysticksState[joystickId].IsConnected;
+            return false;
+        }
+
         public static bool IsMouseButtonPressed(MouseButton button) {
             return Instance._mouseButtonsLastState[button] == ButtonState.Released && Instance._mouseButtonsState[button] == ButtonState.Pressed;
         }
@@ -207,67 +207,67 @@

         public static bool IsMouseButtonUp(MouseButton button) {
             return Instance._mouseButtonsState[button] == ButtonState.Released;
-        }
-
-        public static InputButtonState MouseButtonState(MouseButton button) {
-            ButtonState previousState = Instance._mouseButtonsLastState[button],
-                        currentState = Instance._mouseButtonsState[button];
-
-            if (previousState == ButtonState.Released) {
-                if (currentState == ButtonState.Pressed) {
-                    return InputButtonState.Pressed;
-                }
-
-                return InputButtonState.Up;
-            }
-
-            if (currentState == ButtonState.Released) {
-                return InputButtonState.Released;
-            }
-
-            return InputButtonState.Down;
-        }
-
-        public void Update(int delta) {
-            if (!Game.Instance.HasFocus) {
-                return;
-            }
-
-            // joystick states
-            /*
-            _joysticksPreviousState.Clear();
-            int id = 0;
-            JoysticksConnected = 0;
-            JoystickState joystickState = Joystick.GetState(id);
-            while (joystickState.IsConnected) {
-                if (_joysticksState.ContainsKey(id)) {
-                    _joysticksPreviousState[id] = _joysticksState[id];
-                }
-
-                _joysticksState[id] = joystickState;
-                joystickState = Joystick.GetState(++id);
-                JoysticksConnected++;
-            }
-
-            // clean unused states
-            if (id < _joysticksState.Count) {
-                for (int i = id; i < _joysticksState.Count; i++) {
-                    _joysticksState.Remove(i);
-                }
-            }
-            */
-
-            // keyboard state
-            _keyboardPreviousState = _keyboardState;
-            _keyboardState = Keyboard.GetState();
-
-            _pressedKeys.Clear();
-            Keys[] _xnaPressedKeys = _keyboardState.GetPressedKeys();
-            for (int i = 0; i < _xnaPressedKeys.Length; i++) {
-                _pressedKeys.Add((Key) _xnaPressedKeys[i]);
-            }
-
-            // mouse
+        }
+
+        public static InputButtonState MouseButtonState(MouseButton button) {
+            ButtonState previousState = Instance._mouseButtonsLastState[button],
+                        currentState = Instance._mouseButtonsState[button];
+
+            if (previousState == ButtonState.Released) {
+                if (currentState == ButtonState.Pressed) {
+                    return InputButtonState.Pressed;
+                }
+
+                return InputButtonState.Up;
+            }
+
+            if (currentState == ButtonState.Released) {
+                return InputButtonState.Released;
+            }
+
+            return InputButtonState.Down;
+        }
+
+        public void Update(int delta) {
+            if (!Game.Instance.HasFocus) {
+                return;
+            }
+
+            // joystick states
+            /*
+            _joysticksPreviousState.Clear();
+            int id = 0;
+            JoysticksConnected = 0;
+            JoystickState joystickState = Joystick.GetState(id);
+            while (joystickState.IsConnected) {
+                if (_joysticksState.ContainsKey(id)) {
+                    _joysticksPreviousState[id] = _joysticksState[id];
+                }
+
+                _joysticksState[id] = joystickState;
+                joystickState = Joystick.GetState(++id);
+                JoysticksConnected++;
+            }
+
+            // clean unused states
+            if (id < _joysticksState.Count) {
+                for (int i = id; i < _joysticksState.Count; i++) {
+                    _joysticksState.Remove(i);
+                }
+            }
+            */
+
+            // keyboard state
+            _keyboardPreviousState = _keyboardState;
+            _keyboardState = Keyboard.GetState();
+
+            _pressedKeys.Clear();
+            Keys[] _xnaPressedKeys = _keyboardState.GetPressedKeys();
+            for (int i = 0; i < _xnaPressedKeys.Length; i++) {
+                _pressedKeys.Add((Key) _xnaPressedKeys[i]);
+            }
+
+            // mouse
             MouseState XNAMouseState = Mouse.GetState();

             // buttons
@@ -276,14 +276,14 @@
             }

             // ignore out of screen mouse interactions
-            if (XNAMouseState.X < 0 || XNAMouseState.X > Game.Instance.WindowWidth || XNAMouseState.Y < 0 || XNAMouseState.Y > Game.Instance.WindowHeight) {
-                _mouseButtonsState[MouseButton.Left] = _mouseButtonsState[MouseButton.Middle] = _mouseButtonsState[MouseButton.Right] = _mouseButtonsState[MouseButton.M4] = _mouseButtonsState[MouseButton.M5] = ButtonState.Released;
-                MouseScrollWheelDelta = 0;
-
-                if (LockMouseOnWindow) {
-                    Mouse.SetPosition(Util.Math.Clamp(XNAMouseState.X, 0, Game.Instance.WindowWidth), Util.Math.Clamp(XNAMouseState.Y, 0, Game.Instance.WindowHeight));
-                }
-                return;
+            if (XNAMouseState.X < 0 || XNAMouseState.X > Game.Instance.WindowWidth || XNAMouseState.Y < 0 || XNAMouseState.Y > Game.Instance.WindowHeight) {
+                _mouseButtonsState[MouseButton.Left] = _mouseButtonsState[MouseButton.Middle] = _mouseButtonsState[MouseButton.Right] = _mouseButtonsState[MouseButton.M4] = _mouseButtonsState[MouseButton.M5] = ButtonState.Released;
+                MouseScrollWheelDelta = 0;
+
+                if (LockMouseOnWindow) {
+                    Mouse.SetPosition(Util.Math.Clamp(XNAMouseState.X, 0, Game.Instance.WindowWidth), Util.Math.Clamp(XNAMouseState.Y, 0, Game.Instance.WindowHeight));
+                }
+                return;
             }

             // positions
@@ -309,27 +309,27 @@
             _mouseButtonsState[MouseButton.M5] = XNAMouseState.XButton2;

             // scroll
-            if (_activated) { // reset scroll wheel values if mouse is coming out of game screen
-                MouseScrollWheelDelta = 0;
-                MouseScrollWheel = XNAMouseState.ScrollWheelValue;
-                _activated = false;
-                return;
+            if (_activated) { // reset scroll wheel values if mouse is coming out of game screen
+                MouseScrollWheelDelta = 0;
+                MouseScrollWheel = XNAMouseState.ScrollWheelValue;
+                _activated = false;
+                return;
             }

             MouseScrollWheelDelta = XNAMouseState.ScrollWheelValue - MouseScrollWheel;
-            MouseScrollWheel = XNAMouseState.ScrollWheelValue;
-        }
-
-        #endregion Public Methods
-
-        #region Private Methods
-
-        /*
-        private void ProcessTextInput(object sender, Microsoft.Xna.Framework.TextInputEventArgs e) {
-            OnTextInput(e.Character, (Key) e.Key);
-        }
-        */
-
-        #endregion Private Methods
-    }
-}
+            MouseScrollWheel = XNAMouseState.ScrollWheelValue;
+        }
+
+        #endregion Public Methods
+
+        #region Private Methods
+
+        /*
+        private void ProcessTextInput(object sender, Microsoft.Xna.Framework.TextInputEventArgs e) {
+            OnTextInput(e.Character, (Key) e.Key);
+        }
+        */
+
+        #endregion Private Methods
+    }
+}


Minor

Minor

--- Snittlistan/Infrastructure/Indexes/Match_ByDate.cs
+++ Snittlistan/Infrastructure/Indexes/Match_ByDate.cs
@@ -1,16 +1,16 @@
-using System.Linq;
-using Raven.Abstractions.Indexing;
-using Raven.Client.Indexes;
-using Snittlistan.Models;
+namespace Snittlistan.Infrastructure.Indexes
+{
+    using System.Linq;
+    using Raven.Abstractions.Indexing;
+    using Raven.Client.Indexes;
+    using Snittlistan.Models;

-namespace Snittlistan.Infrastructure.Indexes
-{
-	public class Match_ByDate : AbstractIndexCreationTask<Match>
-	{
-		public Match_ByDate()
-		{
-			Map = matches => from match in matches
-							 select new { match.Date };
-		}
-	}
+    public class Match_ByDate : AbstractIndexCreationTask<Match>
+    {
+        public Match_ByDate()
+        {
+            Map = matches => from match in matches
+                             select new { match.Date };
+        }
+    }
 }


Fix incorrect reliable sequence numbering

--- RconClient/RakNetSession.cs
+++ RconClient/RakNetSession.cs
@@ -19,8 +19,7 @@
         private IPEndPoint Address;
         private byte[] ClientId;

-        private UInt32 NextUnreliablePacketId = 0;
-        private UInt32 NextReliablePacketId = 0;
+        private UInt32 NextPacketId = 0;
         private UInt32 NextReliableId = 0;
         private UInt32 NextSequenceId = 0;
         private UInt32 NextOrderId = 0;
@@ -230,16 +229,7 @@
         {
             var dataPkt = new DataPacket();
             dataPkt.Id = (byte)PacketId.EncapsulatedData;
-            if (reliability == EncapsulatedReliability.Unreliable
-                || reliability == EncapsulatedReliability.UnreliableAcked
-                || reliability == EncapsulatedReliability.UnreliableSequenced)
-            {
-                dataPkt.Sequence.Number = NextUnreliablePacketId++;
-            }
-            else
-            {
-                dataPkt.Sequence.Number = NextReliablePacketId++;
-            }
+            dataPkt.Sequence.Number = NextPacketId++;

             var encapPkt = new EncapsulatedPacket();
             encapPkt.Flags.Reliability = reliability;


Ghetto way of panning to selected image/layer


Refs #1781 De check op overlappende verzekeringen is minder streng voor verzekeringen die lopen tot het einde van het werkjaar, om toe te laten dat je ze al afsluit in het nieuwe werkjaar voordat de vorige verlopen is.

--- Solution/Chiro.Gap.Workers/VerzekeringenManager.cs
+++ Solution/Chiro.Gap.Workers/VerzekeringenManager.cs
@@ -89,11 +89,13 @@
             // dit meer inhoudt dan een unique index/unique constraint.
             var query = from v in l.GelieerdePersoon.Persoon.PersoonsVerzekering
                         where v.VerzekeringsType.ID == verz.ID
-                              && (v.Tot > beginDatum && beginDatum >= v.Van || v.Van < eindDatum && eindDatum <= v.Tot)
+                              && ((verz.TotEindeWerkJaar && v.Tot == eindDatum)
+                                        // Een verzekering tot het einde van het jaar mag wat overlappen (met vorig jaar) zolang je er nog geen hebt voor dat jaar.
+                                  || (!verz.TotEindeWerkJaar && (v.Tot > beginDatum && beginDatum >= v.Van || v.Van < eindDatum && eindDatum <= v.Tot)))
+                                        // Anders laten we geen overlap toe.
                         select v;

             var bestaande = query.FirstOrDefault();
-
             if (bestaande != null)
             {
                 throw new BlokkerendeObjectenException<PersoonsVerzekering>(


Added code to apply default culture settings at startup.

--- Source/Applications/openXDA/openXDA/ServiceHost.cs
+++ Source/Applications/openXDA/openXDA/ServiceHost.cs
@@ -70,6 +70,7 @@
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
+using System.Globalization;
 using System.IO;
 using System.Linq;
 using System.Reflection;
@@ -143,6 +144,16 @@

         public ServiceHost()
         {
+            // Make sure default service settings exist
+            ConfigurationFile configFile = ConfigurationFile.Current;
+            CategorizedSettingsElementCollection systemSettings = configFile.Settings["systemSettings"];
+            systemSettings.Add("DefaultCulture", "en-US", "Default culture to use for language, country/region and calendar formats.");
+
+            // Attempt to set default culture
+            string defaultCulture = systemSettings["DefaultCulture"].ValueAs("en-US");
+            CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture(defaultCulture);     // Defaults for date formatting, etc.
+            CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture(defaultCulture);   // Culture for resource strings, etc.
+
             InitializeComponent();

             // Register event handlers.


closed #17 enumをプロパティに持つ型とのマッピングに対応

closed #17
enumをプロパティに持つ型とのマッピングに対応

--- Source/DeclarativeSql/Mapping/ColumnMappingInfo.cs
+++ Source/DeclarativeSql/Mapping/ColumnMappingInfo.cs
@@ -92,15 +92,18 @@
         /// <returns>列情報のマッピングインスタンス</returns>
         public static This From(PropertyInfo info)
         {
-            var isPrimary = info.Has<KeyAttribute>();
-            var required  = info.Has<RequiredAttribute>();
-            var sequence  = info.GetCustomAttribute<SequenceAttribute>();
+            var isPrimary   = info.Has<KeyAttribute>();
+            var required    = info.Has<RequiredAttribute>();
+            var sequence    = info.GetCustomAttribute<SequenceAttribute>();
+            var propType    = info.PropertyType.IsEnum
+                            ? Enum.GetUnderlyingType(info.PropertyType)
+                            : info.PropertyType;
             return new This()
             {
                 PropertyName    = info.Name,
                 PropertyType    = info.PropertyType,
                 ColumnName      = This.GetColumnName(info),
-                ColumnType      = This.typeMap[info.PropertyType],
+                ColumnType      = This.typeMap[propType],
                 IsPrimaryKey    = isPrimary,
                 IsNullable      = !(isPrimary || required),
                 IsIdentity      = This.GetDatabaseGeneratedOption(info) == DatabaseGeneratedOption.Identity,


fixed a C&P error in the PDF417 decoder

fixed a C&P error in the PDF417 decoder

git-svn-id: 98f681d7a2907ee2a41df434552134740bcc8829@88439 81fbe566-5dc4-48c1-bdea-7421811ca204

--- Source/lib/pdf417/decoder/PDF417ScanningDecoder.cs
+++ Source/lib/pdf417/decoder/PDF417ScanningDecoder.cs
@@ -515,7 +515,7 @@
          codeword = detectionResult.DetectionResultColumns[barcodeColumn].getCodewordNearby(imageRow);
          if (codeword != null)
          {
-            return leftToRight ? codeword.EndX : codeword.StartX;
+            return leftToRight ? codeword.StartX : codeword.EndX;
          }
          if (isValidBarcodeColumn(detectionResult, barcodeColumn - offset))
          {


@ SARSALearning.cs: the naive implementation of __update_q_value from original algorithm, not tested

--- ReinforcementLearning/SarsaLearning.cs
+++ ReinforcementLearning/SarsaLearning.cs
@@ -75,15 +75,10 @@
         /// <returns>The updated Q-Value</returns>
         protected override QVal __update_q_value(State st, Action a, State stplus, Reward r, params object[] o)
         {
+            if (o.Length == 0 || (o[0] is Action))
+                throw new ArgumentException("Expecting an action as last comment", "o");
             var qt = this.__get_q_value(st, a);
-            QVal v = QVal.MinValue;
-            var gh = new GridHelper(this.Grid);
-            foreach (var __a in this.Actions)
-            {
-                var __q = this.__get_q_value(stplus, __a);
-                if (v < __q)
-                    v = __q;
-            }
+            var v = this.__get_q_value(stplus, (Action)o[0]);
             qt = (1 - this.Alpha) * qt + this.Alpha * (r + this.Gamma * v);
             this.__set_q_value(st, a, qt);
             return qt;


Add option to raise an event via EventSystem

--- SPAD.Interfaces/Events/IEventSystem.cs
+++ SPAD.Interfaces/Events/IEventSystem.cs
@@ -31,6 +31,8 @@
         IReadOnlyList<IDataDefinition> BrowseDataDefinitonMulti(string curOffset, string titleName, string rootName, bool bWriteOperation, object parentWindow = null);
         void StartRecording();
         IEnumerable<IMonitorableValue> StopRecording();
+
+        void RaiseEvent(string eventName, ISPADEventArgs e);
     }

     public sealed class EventSystem
@@ -130,5 +132,11 @@
         {
             return EventSystemHandler.StopRecording();
         }
+
+        public static void RaiseEvent(string eventName, ISPADEventArgs e)
+        {
+            EventSystemHandler.RaiseEvent(eventName, e);
+        }
+
     }
 }


Renamed to lastMoveArrowPen.

Renamed to lastMoveArrowPen.

--- Sandra.UI.WF/StandardChessBoardForm.cs
+++ Sandra.UI.WF/StandardChessBoardForm.cs
@@ -96,7 +96,7 @@

             PlayingBoard.Paint += playingBoard_Paint;

-            dotPen = new Pen(Color.DimGray)
+            lastMoveArrowPen = new Pen(Color.DimGray)
             {
                 DashStyle = DashStyle.Dot,
                 Width = 2,
@@ -408,7 +408,7 @@

         MoveCommitEventArgs lastCommittedMove;

-        Pen dotPen;
+        Pen lastMoveArrowPen;

         private void playingBoard_Paint(object sender, PaintEventArgs e)
         {
@@ -434,7 +434,7 @@
                 int endPointX = targetSquareCenterX - (targetSquareCenterX - startSquareCenterX) / distance * 3 / 8;
                 int endPointY = targetSquareCenterY - (targetSquareCenterY - startSquareCenterY) / distance * 3 / 8;

-                e.Graphics.DrawLine(dotPen,
+                e.Graphics.DrawLine(lastMoveArrowPen,
                                     endPointX, endPointY,
                                     startSquareCenterX, startSquareCenterY);

@@ -450,16 +450,16 @@
                 double arrow2EndX = endPointX + Math.Cos(arrow2Phi) * targetLength;
                 double arrow2EndY = endPointY + Math.Sin(arrow2Phi) * targetLength;

-                dotPen.DashStyle = DashStyle.Solid;
-                dotPen.EndCap = LineCap.Round;
-                e.Graphics.DrawLine(dotPen,
+                lastMoveArrowPen.DashStyle = DashStyle.Solid;
+                lastMoveArrowPen.EndCap = LineCap.Round;
+                e.Graphics.DrawLine(lastMoveArrowPen,
                                     endPointX, endPointY,
                                     (float)arrow1EndX, (float)arrow1EndY);
-                e.Graphics.DrawLine(dotPen,
+                e.Graphics.DrawLine(lastMoveArrowPen,
                                     endPointX, endPointY,
                                     (float)arrow2EndX, (float)arrow2EndY);
-                dotPen.DashStyle = DashStyle.Dot;
-                dotPen.EndCap = LineCap.RoundAnchor;
+                lastMoveArrowPen.DashStyle = DashStyle.Dot;
+                lastMoveArrowPen.EndCap = LineCap.RoundAnchor;
             }

             // Draw subtle corners just inside the edges of a legal target square.
@@ -498,7 +498,7 @@
         {
             if (disposing)
             {
-                dotPen.Dispose();
+                lastMoveArrowPen.Dispose();
             }

             base.Dispose(disposing);


Move curly bracket to new line

Move curly bracket to new line

--- ShopifySharp/Lists/LinkHeaderParser.cs
+++ ShopifySharp/Lists/LinkHeaderParser.cs
@@ -40,7 +40,8 @@

             var decodedUriQuery = Uri.UnescapeDataString(uri.Query);

-            string GetQueryParam(string name) {
+            string GetQueryParam(string name)
+            {
                 return decodedUriQuery.Split('?', '&')
                     .FirstOrDefault(p => p.StartsWith($"{name}="))
                     ?.Substring ($"{name}=".Length);


Add fill opacities to GitHub corner SVG

Add fill opacities to GitHub corner SVG


Delete BrickCollectionsTest.cs

Delete BrickCollectionsTest.cs

--- Test/BrickPi.Uwp.UnitTests/BrickCollectionsTest.cs
+++ Test/BrickPi.Uwp.UnitTests/BrickCollectionsTest.cs
@@ -1,31 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using BrickPi.Uwp.Base;
-using BrickPi.Uwp.Sensors;
-using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
-
-namespace BrickPi.Uwp.UnitTests
-{
-    [TestClass]
-    public class SensorCollectionTest
-    {
-        [TestMethod()]
-        public void SimpleEnumeratorTest()
-        {
-            SensorCollection collection = new SensorCollection(null);
-            Assert.IsNull(collection[Arduino.Arduino1, ArduinoPort.Port1]);
-        }
-
-        [TestMethod()]
-        public void SimpleEnumerationTest()
-        {
-            SensorCollection collection = new SensorCollection(null);
-            foreach(RawSensor sensor in collection)
-                Assert.IsNull(sensor);
-        }
-
-    }
-}


Add several unit tests for SHA1

Add several unit tests for SHA1

--- UnitTestUsefullFunctions/UnitTestFunctionCrypto.cs
+++ UnitTestUsefullFunctions/UnitTestFunctionCrypto.cs
@@ -221,6 +221,26 @@
       byte[] result = CryptoFunc.ComputeHashSha1(source);
       Assert.AreEqual(Convert.ToBase64String(result), expected);
     }
+
+    [TestMethod]
+    public void TestMethod_ComputeHashSha1_message_a()
+    {
+      const string source2 = "a";
+      byte[] source = Encoding.UTF8.GetBytes(source2);
+      string expected = "hvfkN/qlp/zhXR3cuerq6jd2Z7g=";
+      byte[] result = CryptoFunc.ComputeHashSha1(source);
+      Assert.AreEqual(Convert.ToBase64String(result), expected);
+    }
+
+    [TestMethod]
+    public void TestMethod_ComputeHashSha1_message_b()
+    {
+      const string source2 = "b";
+      byte[] source = Encoding.UTF8.GetBytes(source2);
+      string expected = "6dcfXufJLW3J6S/9rRe4vUlBj5g=";
+      byte[] result = CryptoFunc.ComputeHashSha1(source);
+      Assert.AreEqual(Convert.ToBase64String(result), expected);
+    }
     #endregion

     #region HMAC


Fix ',' typo in ChessLogic for loop

Fix ',' typo in ChessLogic for loop

--- WizardsChess/WizardsChessUtils/Chess/ChessLogic.cs
+++ WizardsChess/WizardsChessUtils/Chess/ChessLogic.cs
@@ -223,7 +223,7 @@
 			int i, j;
 			for (i = 0; i < ChessBoard.Size; i++)
 			{
-				for (j = 0; j < ChessBoard.Size, j++)
+				for (j = 0; j < ChessBoard.Size; j++)
 				{
 					var piece = board.PieceAt(i, j);
 					if (piece != null && piece.Team != Turn)


Fixed FluentMapping.

Fixed FluentMapping.

--- Source/Mapping/FluentMappingBuilder.cs
+++ Source/Mapping/FluentMappingBuilder.cs
@@ -79,7 +79,7 @@

 		public EntityMappingBuilder<T> Entity<T>(string configuration = null)
 		{
-			return new EntityMappingBuilder<T>(this, null);
+			return new EntityMappingBuilder<T>(this, configuration);
 		}
 	}
 }