Fix crash in SSH

Fix crash in SSH

--- src/SSHDebugPS/AD7UnixAsyncCommand.cs
+++ src/SSHDebugPS/AD7UnixAsyncCommand.cs
@@ -20,9 +20,8 @@
         private readonly IDebugUnixShellCommandCallback _callback;
         private readonly LineBuffer _lineBuffer = new LineBuffer();
         private int _firedOnExit;
+        private int _bClosed = 0;
         private bool _beginReceived;
-        private bool _isClosed;
-
         private string _startCommand;

         public AD7UnixAsyncCommand(IStreamingShell streamingShell, IDebugUnixShellCommandCallback callback)
@@ -48,16 +47,19 @@

         void IDebugUnixShellAsyncCommand.WriteLine(string text)
         {
+            if (_bClosed == 1)
+            {
+                return;
+            }
+
             lock (_lock)
             {
-                if (_isClosed)
+                if (_streamingShell != null)
                 {
-                    return;
+                    _streamingShell.WriteLine(text);
+                    _streamingShell.Flush();
                 }
             }
-
-            _streamingShell.WriteLine(text);
-            _streamingShell.Flush();
         }

         void IDebugUnixShellAsyncCommand.Abort()
@@ -69,17 +71,14 @@
         {
             IEnumerable<string> linesToSend = null;

-            lock (_lock)
-            {
-                if (string.IsNullOrEmpty(e.Output))
-                    return;
+            if (string.IsNullOrEmpty(e.Output))
+                return;

-                _lineBuffer.ProcessText(e.Output, out linesToSend);
-            }
+            _lineBuffer.ProcessText(e.Output, out linesToSend);

             foreach (string line in linesToSend)
             {
-                if (_isClosed)
+                if (_bClosed == 1)
                 {
                     return;
                 }
@@ -128,7 +127,7 @@

         private void OnClosedOrDisconnected(object sender, EventArgs e)
         {
-            if (_firedOnExit == 0 && _isClosed == false)
+            if (_firedOnExit == 0 && _bClosed == 0)
             {
                 Debug.Fail("Why was the SSH session closed?");
                 OnError(sender, null);
@@ -137,30 +136,27 @@

         private void Close()
         {
-            lock (_lock)
+            // Don't want output processing thread and the PollThread to go through this at the same time
+            // If PollThread issues Dispose and the output processing thread block on the _lock below, it will cause ThreadInterruptedException
+            // in the output processing thread
+            if (Interlocked.CompareExchange(ref _bClosed, 1, 0) == 0)
             {
-                if (_isClosed)
-                    return;
-
-                _isClosed = true;
-
-                try
+                lock (_lock)
                 {
-                    if (_streamingShell != null && _streamingShell.IsOpen)
+                    try
                     {
-                        _streamingShell.Close();
+                        _streamingShell?.Dispose();
+                    }
+                    catch (ThreadInterruptedException)
+                    {
+                        // We will run into this when we are closing as a result of getting exit message
+                        // in OnOutputReceived method in error cases. The method will be called on the thread
+                        // that StreamingShell uses for output processing. Dispose tries to interrupt the
+                        // same thread we are on leading to ThreadInterruptedException
                     }

-                    _streamingShell?.Dispose();
+                    _streamingShell = null;
                 }
-                catch (ThreadInterruptedException)
-                {
-                    // This can happen if the command failed on a timeout. Say dotnet restore failed because of insufficient permissions etc.
-                    // Calling dispose on StreamingShell throws ThreadInterruptedException as well. For this case, any operation on StreamingShell
-                    // will likely cause this exception to be thrown, setting it to null to allow cleanup.
-                }
-
-                _streamingShell = null;
             }
         }


DiscountCode entity configurations

DiscountCode entity configurations

--- src/Shop.Core/Entites/DiscountCode.cs
+++ src/Shop.Core/Entites/DiscountCode.cs
@@ -15,8 +15,13 @@

         [Key]
         public int DiscountCodeId { get; set; }
+
+        [Required]
+        [StringLength(25)]
         public string DiscountCodeReference { get; set; }

+        [Required]
+        [StringLength(25)]
         public string Code
         {
             get => _code;
@@ -40,6 +45,8 @@
                 _discountCodeType = value;
             }
         }
+
+        [Required]
         public decimal DiscountAmount
         {
             get => _discountAmount;


Moved AddMethod.

Moved AddMethod.

--- src/Tools/EngineWeaver/CecilCopier.cs
+++ src/Tools/EngineWeaver/CecilCopier.cs
@@ -156,6 +156,14 @@
             return (TypeDefinition)declaringType;
         }

+        public void AddMethod(TypeDefinition type, MethodDefinition method)
+        {
+            if(type.Methods.Any(m => m.FullName == method.FullName))
+                return;
+
+            type.Methods.Add(method);
+        }
+
         # region COPY METHODS

         private T GetLocalReference<T>(T @ref) where T : MemberReference
@@ -292,13 +300,6 @@
             return ret;
         }

-        private void AddMethod(TypeDefinition type, MethodDefinition method)
-        {
-            if(type.Methods.Any(m => m.FullName == method.FullName))
-                return;
-
-            type.Methods.Add(method);
-        }

         private EventDefinition Copy(EventDefinition def, TypeDefinition declaringType)
         {


Issue #AR-3_IEnumerable_support: all tests passing - but branching logic is difficult.

--- app/Umbraco/Umbraco.Archetype/Serialization/ArchetypeJsonConverter.cs
+++ app/Umbraco/Umbraco.Archetype/Serialization/ArchetypeJsonConverter.cs
@@ -38,17 +38,31 @@
             if (jToken == null)
                 return null;

-            var obj = Activator.CreateInstance(objectType);
-
-            if (null != obj as IEnumerable<object>
-                && jToken["fieldsets"] != null && jToken["fieldsets"].Any())
-            {
-                return DeserializeEnumerableObject(obj, jToken);
+            var obj = Activator.CreateInstance(objectType);
+
+            if (null != obj as IEnumerable<object>)
+            {
+                JToken enumerableToken;
+
+                if (TryParseJTokenAsEnumerable(jToken, out enumerableToken)
+                    || TryParseJTokenAsEnumerable(jToken["value"], out enumerableToken))
+                return DeserializeEnumerableObject(obj, enumerableToken);
             }

             return null == jToken as JArray
                         ? DeserializeObject(obj, jToken)
                         : PopulateProperties(obj, jToken);
+        }
+
+        private bool TryParseJTokenAsEnumerable(JToken jToken, out JToken resultToken)
+        {
+            resultToken = null;
+            var jTokenEnumerable = jToken != null && jToken["fieldsets"] != null && jToken["fieldsets"].Any();
+
+            if (jTokenEnumerable)
+                resultToken = jToken;
+
+            return jTokenEnumerable;
         }

         public override bool CanConvert(Type objectType)
@@ -84,9 +98,9 @@
             foreach (var propInfo in asFieldset)
             {
                 var propAlias = GetJsonPropertyName(propInfo);
-                var fsJToken = GetProperties(propInfo.PropertyType, jToken);
+                var fsJToken = GetPropertyToken(propInfo.PropertyType, jToken);
                 var propJToken =
-                    fsJToken.Single(p => p.SelectToken("alias").ToString().Equals(propAlias));
+                    fsJToken["properties"].Single(p => p.SelectToken("alias").ToString().Equals(propAlias));

                 if (propJToken == null)
                     continue;
@@ -94,19 +108,31 @@
                 var propValue = GetPropertyValue(propInfo, propJToken);

                 propInfo.SetValue(obj, propValue);
-            }
-
-            return PopulateProperties(obj, GetProperties(obj.GetType(), jToken));
-        }
-
-        private JToken GetProperties(Type objType, JToken jToken)
+            }
+
+            var propToken = GetPropertyToken(obj.GetType(), jToken);
+
+            return propToken == null
+                    ? obj
+                    : PopulateProperties(obj, propToken["properties"] ?? new JArray(propToken));
+        }
+
+        private JToken GetPropertyToken(Type objType, JToken jToken)
         {
             var objAlias = GetFieldsetName(objType);

             if (jToken["fieldsets"] != null)
-                return jToken["fieldsets"].Single(p => p.SelectToken("alias").ToString().Equals(objAlias)).SelectToken("properties");
-
-            return jToken["alias"].ToString().Equals(objAlias) ? jToken.SelectToken("properties") : null;
+                return jToken["fieldsets"].Single(p => p.SelectToken("alias").ToString().Equals(objAlias));
+
+            if (jToken["value"] != null && jToken["value"].HasValues && jToken["value"]["fieldsets"] != null)
+            {
+                var fsJToken = jToken["value"]["fieldsets"].SingleOrDefault(p => p.SelectToken("alias").ToString().Equals(objAlias));
+                if (fsJToken != null)
+                    return fsJToken;
+            }
+
+
+            return jToken["alias"].ToString().Equals(objAlias) ? jToken : null;
         }

         private object PopulateProperties(object obj, JToken jToken)
@@ -132,8 +158,8 @@

         private object GetPropertyValue(PropertyInfo propertyInfo, JToken propJToken)
         {
-            return IsTypeArchetypeDatatype(propertyInfo.PropertyType)
-                ? JsonConvert.DeserializeObject(propJToken["value"].ToString(), propertyInfo.PropertyType,
+            return IsTypeArchetypeDatatype(propertyInfo.PropertyType)
+                ? JsonConvert.DeserializeObject(propJToken.ToString(), propertyInfo.PropertyType,
                     this)
                     : IsTypeIEnumerableArchetypeDatatype(propertyInfo.PropertyType)
                     ? JsonConvert.DeserializeObject(propJToken["value"].SelectToken("fieldsets").ToString(), propertyInfo.PropertyType,


Issue #52 - Switch to pure container references.

--- src/_specs/Steps/ClientInteraction.cs
+++ src/_specs/Steps/ClientInteraction.cs
@@ -61,11 +61,9 @@
 			factoryMock.Setup(factory => factory.CreateRequest(It.IsAny<string>(), It.IsAny<Method>()))
 				.Returns<string, Method>((resource, method) => (_rest.Request = new RestRequest(resource, method)));

-			//TODO: switch back to pure container references once code-patterns issue #125 is fixed
-			//https://github.com/TheTribe/code-patterns/issues/125
-			var clientMock = new Mock<IRestClient>(MockBehavior.Strict);
+			IRestResponse response = _container.Mock<IRestResponse>().Object;

-			IRestResponse response = _container.Mock<IRestResponse>().Object;
+			var clientMock = _container.Mock<IRestClient>(MockBehavior.Strict);

 			clientMock.Setup(client => client.Execute(It.IsAny<IRestRequest>()))
 				.Returns(() => response);
@@ -80,10 +78,6 @@

 			factoryMock.Setup(factory => factory.CreateClient(It.IsAny<string>()))
 				.Returns(() => clientMock.Object);
-
-			//TODO: switch back to pure container references once code-patterns issue #125 is fixed
-			//https://github.com/TheTribe/code-patterns/issues/125
-			_container.Update(clientMock.Object);

 			_container.Update<IStargateOptions>(options.CreateInstance<StargateOptions>());


#176

--- examples/WireMock.Net.ConsoleApplication/MainApp.cs
+++ examples/WireMock.Net.ConsoleApplication/MainApp.cs
@@ -53,7 +53,7 @@
                     .WithPath("/proxy-execute-keep-alive")
                 )
                 .RespondWith(Response.Create()
-                    .WithProxy(new ProxyAndRecordSettings { Url = "http://localhost:9999", BlackListedHeaders = new [] { "Keep-Alive" } })
+                    .WithProxy(new ProxyAndRecordSettings { Url = "http://localhost:9999", BlackListedHeaders = new[] { "Keep-Alive" } })
                     .WithHeader("Keep-Alive-Test", "stef")
                 );

@@ -142,11 +142,13 @@
                     .WithBodyFromFile(@"c:\temp\x.json")
                 );

-            //server
-            //    .Given(Request.Create().WithPath("/file_rel").UsingGet())
-            //    .RespondWith(Response.Create()
-            //        .WithBodyFromFile("Program.cs", false)
-            //    );
+            server
+                .Given(Request.Create().WithPath("/file_rel").UsingGet())
+                .WithGuid("0000aaaa-fcf4-4256-a0d3-1c76e4862947")
+                .RespondWith(Response.Create()
+                    .WithHeader("Content-Type", "application/xml")
+                    .WithBodyFromFile("WireMock.Net.xml", false)
+                );

             server
                 .Given(Request.Create().WithHeader("ProxyThis", "true")
@@ -284,7 +286,7 @@
                 .Given(Request.Create().WithPath("/jsonpathtestTokenJson").UsingPost())
                 .RespondWith(Response.Create()
                     .WithHeader("Content-Type", "application/json")
-                    .WithBodyAsJson(new { status = "OK", url = "{{request.url}}", transformed = "{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}" } )
+                    .WithBodyAsJson(new { status = "OK", url = "{{request.url}}", transformed = "{{JsonPath.SelectToken request.body \"$.Manufacturers[?(@.Name == 'Acme Co')]\"}}" })
                     .WithTransformer()
                 );


added default constructor

added default constructor

--- data-structures-csharp/data-structures-csharp/List/MoveToFrontList.cs
+++ data-structures-csharp/data-structures-csharp/List/MoveToFrontList.cs
@@ -13,15 +13,37 @@
     public class MoveToFrontList<T> : IEnumerable<T>, ICollection<T>
         where T : IEquatable<T>
     {
-        private List<T> list = new List<T>();
+        private List<T> list;

-        public int Count { get { return list.Count; } }
-        public bool IsSynchronized { get { return false; } }
+        public int Count
+        {
+            get { return list.Count; }
+        }
+        public int Capacity
+        {
+            get { return list.Capacity; }
+        }
+        public bool IsSynchronized
+        {
+            get { return false; }
+        }

         [ContractInvariantMethod]
         private void ObjectInvariant()
         {
             //Contract.Requires(arg != null);
+        }
+
+        public MoveToFrontList()
+        {
+            list = new List<T>();
+        }
+
+        public MoveToFrontList(int capacity)
+        {
+            Contract.Requires<ArgumentOutOfRangeException>(capacity > 0);
+
+            list = new List<T>(capacity);
         }

         /// <summary>
@@ -32,6 +54,7 @@
         public T Get(T node)
         {
             Contract.Requires<ArgumentNullException>(node != null);
+
             T element = list.Where(e => e.Equals(node)).FirstOrDefault();
             if (element == null)
             {
@@ -49,6 +72,7 @@
         public void Add(T element)
         {
             Contract.Requires<ArgumentNullException>(element != null);
+
             list.Add(element);
         }

@@ -59,6 +83,7 @@
         public void Remove(T element)
         {
             Contract.Requires<ArgumentNullException>(element != null);
+
             list.Remove(element);
         }


* Fixed null reference exception when creating new map

--- source/SharpFlame/Mapping/clsMap.cs
+++ source/SharpFlame/Mapping/clsMap.cs
@@ -86,21 +86,27 @@

         public clsMap()
         {
-            frmMainLink = new ConnectedListLink<clsMap, frmMain>(this);
-            Gateways = new ConnectedList<clsGateway, clsMap>(this);
-
+            this.frmMainLink = new ConnectedListLink<clsMap, frmMain>( this );
+            this.Sectors = new clsSector[0, 0];
+            this.ShadowSectors = new clsShadowSector[0, 0];
+            this.HeightMultiplier = 2;
+            this._ReadyForUserInput = false;
+            this.ChangedSinceSave = false;
+            this.AutoSave = new clsAutoSave();
+            this.Painter = new Painter();
+            this.Tile_TypeNum = new byte[0];
+            this.Gateways = new ConnectedList<clsGateway, clsMap>( this );
+            this.Units = new ConnectedList<clsUnit, clsMap>( this );
+            this.UnitGroups = new ConnectedList<clsUnitGroup, clsMap>( this );
+            this.ScriptPositions = new ConnectedList<clsScriptPosition, clsMap>( this );
+            this.ScriptAreas = new ConnectedList<clsScriptArea, clsMap>( this );

             Initialize();
         }

-        public clsMap(sXY_int TileSize)
-        {
-            frmMainLink = new ConnectedListLink<clsMap, frmMain>(this);
-            Gateways = new ConnectedList<clsGateway, clsMap>(this);
-
-
+        public clsMap(sXY_int TileSize) : this()
+        {
             Initialize();
-
             TerrainBlank(TileSize);
             TileType_Reset();
         }
@@ -116,11 +122,8 @@
             ScriptAreas.MaintainOrder = true;
         }

-        public clsMap(clsMap MapToCopy, sXY_int Offset, sXY_int Area)
-        {
-            frmMainLink = new ConnectedListLink<clsMap, frmMain>(this);
-            Gateways = new ConnectedList<clsGateway, clsMap>(this);
-
+        public clsMap(clsMap MapToCopy, sXY_int Offset, sXY_int Area) : this()
+        {
             int EndX = 0;
             int EndY = 0;
             int X = 0;


Removed overrite for FloatStoreAndPop that wasn't used after testing.

--- source/XSharp/XSharp/Gen1/XS.FPU.cs
+++ source/XSharp/XSharp/Gen1/XS.FPU.cs
@@ -16,35 +16,6 @@
             }

             public static void FloatStoreAndPop(XSRegisters.Register32 register, bool isIndirect = false, int? displacement = null, XSRegisters.RegisterSize? size = null)
-            {
-                if (displacement != null)
-                {
-                    isIndirect = true;
-                    if (displacement == 0)
-                    {
-                        displacement = null;
-                    }
-                }
-
-                if (size == null)
-                {
-                    if (isIndirect)
-                    {
-                        throw new InvalidOperationException("No size specified!");
-                    }
-                    size = register.Size;
-                }
-
-                new FloatStoreAndPop
-                {
-                    DestinationReg = register.RegEnum,
-                    DestinationIsIndirect = isIndirect,
-                    DestinationDisplacement = displacement,
-                    Size = (byte)size
-                };
-            }
-
-            public static void FloatStoreAndPop(XSRegisters.RegisterFPU register, bool isIndirect = false, int? displacement = null, XSRegisters.RegisterSize? size = null)
             {
                 if (displacement != null)
                 {


made some members invisible to browser

made some members invisible to browser

--- src/AspectInjector.Broker/Source.cs
+++ src/AspectInjector.Broker/Source.cs
@@ -1,4 +1,5 @@
 using System;
+using System.ComponentModel;
 using System.Reflection;

 namespace AspectInjector.Broker
@@ -25,6 +26,7 @@
         /// Should be of type <see cref="MethodBase" />.
         /// </summary>
         [Obsolete("Use Source.Metadata instead.")]
+        [EditorBrowsable(EditorBrowsableState.Never)]
         Method = 3,

         /// <summary>
@@ -69,7 +71,8 @@
         /// Set of injections that trigger this advice./>.
         /// Should be of type <see cref="Attribute" />[].
         /// </summary>
-        [Obsolete("Use Source.Triggers instead")]
+        [Obsolete("Use Source.Triggers instead")]
+        [EditorBrowsable(EditorBrowsableState.Never)]
         Injections = 9,

         /// <summary>


Add LastError to AudioFileStream. Fixes #6385

--- src/AudioToolbox/AudioFileStream.cs
+++ src/AudioToolbox/AudioFileStream.cs
@@ -234,7 +234,7 @@

 		public AudioFileStreamStatus ParseBytes (int size, IntPtr data, bool discontinuity)
 		{
-			return AudioFileStreamParseBytes (handle, size, data, discontinuity ? (uint) 1 : (uint) 0);
+			return LastError = AudioFileStreamParseBytes (handle, size, data, discontinuity ? (uint) 1 : (uint) 0);
 		}

 		public AudioFileStreamStatus ParseBytes (byte [] bytes, bool discontinuity)
@@ -243,7 +243,7 @@
 				throw new ArgumentNullException ("bytes");
 			unsafe {
 				fixed (byte *bp = &bytes[0]){
-					return AudioFileStreamParseBytes (handle, bytes.Length, (IntPtr) bp, discontinuity ? (uint) 1 : (uint) 0);
+					return LastError = AudioFileStreamParseBytes (handle, bytes.Length, (IntPtr) bp, discontinuity ? (uint) 1 : (uint) 0);
 				}
 			}
 		}
@@ -261,7 +261,7 @@

 			unsafe {
 				fixed (byte *bp = &bytes[0]){
-					return AudioFileStreamParseBytes (handle, count, (IntPtr) (bp + offset) , discontinuity ? (uint) 1 : (uint) 0);
+					return LastError = AudioFileStreamParseBytes (handle, count, (IntPtr) (bp + offset) , discontinuity ? (uint) 1 : (uint) 0);
 				}
 			}
 		}
@@ -275,24 +275,25 @@
 		public AudioFileStreamStatus Seek (long packetOffset, out long dataByteOffset, out bool isEstimate)
 		{
 			int v = 0;
-			var code = AudioFileStreamSeek (handle, packetOffset, out dataByteOffset, ref v);
-			if (code != AudioFileStreamStatus.Ok){
+			LastError = AudioFileStreamSeek (handle, packetOffset, out dataByteOffset, ref v);
+			if (LastError != AudioFileStreamStatus.Ok){
 				isEstimate = false;
-				return code;
-			}
-			isEstimate = (v & 1) == 1;
-			return code;
-		}
-
-		[DllImport (Constants.AudioToolboxLibrary)]
-		extern static OSStatus AudioFileStreamGetPropertyInfo(
+			} else {
+				isEstimate = (v & 1) == 1;
+			}
+
+			return LastError;
+		}
+
+		[DllImport (Constants.AudioToolboxLibrary)]
+		extern static AudioFileStreamStatus AudioFileStreamGetPropertyInfo(
 			AudioFileStreamID inAudioFileStream,
 			AudioFileStreamProperty inPropertyID,
 			out int outPropertyDataSize,
 			out int isWritable);

 		[DllImport (Constants.AudioToolboxLibrary)]
-		extern static OSStatus AudioFileStreamGetProperty(
+		extern static AudioFileStreamStatus AudioFileStreamGetProperty(
 			AudioFileStreamID inAudioFileStream,
 			AudioFileStreamProperty inPropertyID,
 			ref int ioPropertyDataSize,
@@ -307,16 +308,16 @@
 		{
 			int writable;

-			var r = AudioFileStreamGetPropertyInfo (handle, property, out size, out writable);
-			if (r != 0)
+			LastError = AudioFileStreamGetPropertyInfo (handle, property, out size, out writable);
+			if (LastError != 0)
 				return IntPtr.Zero;

 			var buffer = Marshal.AllocHGlobal (size);
 			if (buffer == IntPtr.Zero)
 				return IntPtr.Zero;

-			r = AudioFileStreamGetProperty (handle, property, ref size, buffer);
-			if (r == 0)
+			LastError = AudioFileStreamGetProperty (handle, property, ref size, buffer);
+			if (LastError == 0)
 				return buffer;
 			Marshal.FreeHGlobal (buffer);
 			return IntPtr.Zero;
@@ -327,7 +328,8 @@
 			unsafe {
 				int val = 0;
 				int size = 4;
-				if (AudioFileStreamGetProperty (handle, property, ref size, (IntPtr) (&val)) == 0)
+				LastError = AudioFileStreamGetProperty (handle, property, ref size, (IntPtr) (&val));
+				if (LastError == 0)
 					return val;
 				return 0;
 			}
@@ -338,7 +340,8 @@
 			unsafe {
 				double val = 0;
 				int size = 8;
-				if (AudioFileStreamGetProperty (handle, property, ref size, (IntPtr) (&val)) == 0)
+				LastError = AudioFileStreamGetProperty (handle, property, ref size, (IntPtr) (&val));
+				if (LastError == 0)
 					return val;
 				return 0;
 			}
@@ -349,7 +352,8 @@
 			unsafe {
 				long val = 0;
 				int size = 8;
-				if (AudioFileStreamGetProperty (handle, property, ref size, (IntPtr) (&val)) == 0)
+				LastError = AudioFileStreamGetProperty (handle, property, ref size, (IntPtr) (&val));
+				if (LastError == 0)
 					return val;
 				return 0;
 			}
@@ -359,14 +363,15 @@
 		{
 			int size, writable;

-			if (AudioFileStreamGetPropertyInfo (handle, property, out size, out writable) != 0)
+			LastError = AudioFileStreamGetPropertyInfo (handle, property, out size, out writable);
+			if (LastError != 0)
 				return null;
 			var buffer = Marshal.AllocHGlobal (size);
 			if (buffer == IntPtr.Zero)
 				return null;
 			try {
-				var r = AudioFileStreamGetProperty (handle, property, ref size, buffer);
-				if (r == 0){
+				LastError = AudioFileStreamGetProperty (handle, property, ref size, buffer);
+				if (LastError == 0){
 					T result = *(T*) buffer;
 					return result;
 				}
@@ -378,7 +383,7 @@
 		}

 		[DllImport (Constants.AudioToolboxLibrary)]
-		extern static OSStatus AudioFileStreamSetProperty(
+		extern static AudioFileStreamStatus AudioFileStreamSetProperty(
 			AudioFileStreamID inAudioFileStream,
 			AudioFileStreamProperty inPropertyID,
 			int inPropertyDataSize,
@@ -386,11 +391,12 @@

 		public bool SetProperty (AudioFileStreamProperty property, int dataSize, IntPtr propertyData)
 		{
-			return AudioFileStreamSetProperty (handle, property, dataSize, propertyData) == 0;
+			LastError = AudioFileStreamSetProperty (handle, property, dataSize, propertyData);
+			return LastError == 0;
 		}

 		[DllImport (Constants.AudioToolboxLibrary)]
-		extern static OSStatus AudioFileStreamClose(AudioFileStreamID inAudioFileStream);
+		extern static AudioFileStreamStatus AudioFileStreamClose(AudioFileStreamID inAudioFileStream);

 		public bool ReadyToProducePackets {
 			get {
@@ -421,10 +427,10 @@
 			get {
 				int size;
 				var r = GetProperty (AudioFileStreamProperty.FormatList, out size);
-				var records = (AudioFormat *) r;
 				if (r == IntPtr.Zero)
 					return null;

+				var records = (AudioFormat *) r;
 				int itemSize = sizeof (AudioFormat);
 				int items = size/itemSize;
 				var ret = new AudioFormat [items];
@@ -505,7 +511,8 @@
 			unsafe {
 				AudioFramePacketTranslation *p = &buffer;
 				int size = sizeof (AudioFramePacketTranslation);
-				if (AudioFileStreamGetProperty (handle, AudioFileStreamProperty.PacketToFrame, ref size, (IntPtr) p) == 0)
+				LastError = AudioFileStreamGetProperty (handle, AudioFileStreamProperty.PacketToFrame, ref size, (IntPtr) p);
+				if (LastError == 0)
 					return buffer.Frame;
 				return -1;
 			}
@@ -519,7 +526,8 @@
 			unsafe {
 				AudioFramePacketTranslation *p = &buffer;
 				int size = sizeof (AudioFramePacketTranslation);
-				if (AudioFileStreamGetProperty (handle, AudioFileStreamProperty.FrameToPacket, ref size, (IntPtr) p) == 0){
+				LastError = AudioFileStreamGetProperty (handle, AudioFileStreamProperty.FrameToPacket, ref size, (IntPtr) p);
+				if (LastError == 0){
 					frameOffsetInPacket = buffer.FrameOffsetInPacket;
 					return buffer.Packet;
 				}
@@ -536,7 +544,8 @@
 			unsafe {
 				AudioBytePacketTranslation *p = &buffer;
 				int size = sizeof (AudioBytePacketTranslation);
-				if (AudioFileStreamGetProperty (handle, AudioFileStreamProperty.PacketToByte, ref size, (IntPtr) p) == 0){
+				LastError = AudioFileStreamGetProperty (handle, AudioFileStreamProperty.PacketToByte, ref size, (IntPtr) p);
+				if (LastError == 0){
 					isEstimate = (buffer.Flags & BytePacketTranslationFlags.IsEstimate) != 0;
 					return buffer.Byte;
 				}
@@ -553,7 +562,8 @@
 			unsafe {
 				AudioBytePacketTranslation *p = &buffer;
 				int size = sizeof (AudioBytePacketTranslation);
-				if (AudioFileStreamGetProperty (handle, AudioFileStreamProperty.ByteToPacket, ref size, (IntPtr) p) == 0){
+				LastError = AudioFileStreamGetProperty (handle, AudioFileStreamProperty.ByteToPacket, ref size, (IntPtr) p);
+				if (LastError == 0){
 					isEstimate = (buffer.Flags & BytePacketTranslationFlags.IsEstimate) != 0;
 					byteOffsetInPacket = buffer.ByteOffsetInPacket;
 					return buffer.Packet;
@@ -581,5 +591,7 @@
 				return GetDouble (AudioFileStreamProperty.AverageBytesPerPacket);
 			}
 		}
+
+		public AudioFileStreamStatus LastError { get; private set; }
 	}
 }


Added deserialize and set root component

--- src/Banzai/Factories/FlowBuilder.cs
+++ src/Banzai/Factories/FlowBuilder.cs
@@ -1,4 +1,5 @@
 using Banzai.Serialization;
+using Banzai.Utility;

 namespace Banzai.Factories
 {
@@ -56,5 +57,25 @@
             return SerializerProvider.Serializer.Serialize(RootComponent);
         }

+        /// <summary>
+        /// Deserializes the root component using the currently registered serializer.
+        /// </summary>
+        public FlowComponent<T> DeserializeRootComponent(string serializedComponent)
+        {
+            Guard.AgainstNullOrEmptyArgument("serializedComponent", serializedComponent);
+
+            return SerializerProvider.Serializer.Deserialize<T>(serializedComponent);
+        }
+
+        /// <summary>
+        /// Deserializes and sets the root component using the currently registered serializer.
+        /// </summary>
+        public FlowComponent<T> DeserializeAndSetRootComponent(string serializedComponent)
+        {
+            RootComponent = DeserializeRootComponent(serializedComponent);
+
+            return RootComponent;
+        }
+
     }
 }


Remove extra tab

Remove extra tab

--- src/BloomExe/Publish/PublishView.cs
+++ src/BloomExe/Publish/PublishView.cs
@@ -330,7 +330,7 @@
 			// The version we want to upload for web previews is the one that is shown for
 			// the _simplePDFRadio button, so pick AllPagesNoBooklet for both of these.
 			else if (_simplePDFRadio.Checked || _uploadRadio.Checked)
-					_model.BookletPortion = PublishModel.BookletPortions.AllPagesNoBooklet;
+				_model.BookletPortion = PublishModel.BookletPortions.AllPagesNoBooklet;
 			// otherwise, we don't yet know what version to show, so we don't show one.
 			else
 				_model.BookletPortion = PublishModel.BookletPortions.None;


 * Fixed #152 (Editing servers updates all servers)

git-svn-id: e2945e6dc2723cb01f425b5a7c3c201ce5019a89@856 080cfd25-d5d9-4c59-82ea-70d02a200d8b

--- src/Clients/WinForms/Persistance.cs
+++ src/Clients/WinForms/Persistance.cs
@@ -99,7 +99,7 @@

 			using (var cmd = db.CreateCommand())
 			{
-				cmd.CommandText = server.Id > 0 ? "UPDATE servers SET serverName=?,serverHost=?,serverPort=?,serverPassword=?,serverUserNickname=?,serverUserPhonetic=?,serverUserName=?,serverUserPassword=?"
+				cmd.CommandText = server.Id > 0 ? "UPDATE servers SET serverName=?,serverHost=?,serverPort=?,serverPassword=?,serverUserNickname=?,serverUserPhonetic=?,serverUserName=?,serverUserPassword=? WHERE (serverId=?)"
 					: "INSERT INTO servers (serverName,serverHost,serverPort,serverPassword,serverUserNickname,serverUserPhonetic,serverUserName,serverUserPassword) VALUES (?,?,?,?,?,?,?,?)";

 				cmd.Parameters.Add (new SQLiteParameter ("name", server.Name));


updated comments on DesktopShim

updated comments on DesktopShim

--- src/Compilers/Shared/DesktopShim.cs
+++ src/Compilers/Shared/DesktopShim.cs
@@ -7,8 +7,8 @@
 namespace Roslyn.Utilities
 {
     /// <summary>
-    /// This is a bridge for APIs that are only available on CoreCLR or .NET 4.6
-    /// and NOT on .NET 4.5. The compiler currently targets .NET 4.5 and CoreCLR
+    /// This is a bridge for APIs that are only available on Desktop
+    /// and NOT on CoreCLR. The compiler currently targets .NET 4.5 and CoreCLR
     /// so this shim is necessary for switching on the dependent behavior.
     /// </summary>
     internal static class DesktopShim


Fix some compiler warnings

Fix some compiler warnings

--- src/Corale.Colore/Logging/LibLog.cs
+++ src/Corale.Colore/Logging/LibLog.cs
@@ -499,6 +499,7 @@
         /// </summary>
         /// <param name="key">A key.</param>
         /// <param name="value">A value.</param>
+        /// <param name="destructure">Destructure context.</param>
         /// <returns>A disposable that when disposed removes the map from the context.</returns>
         IDisposable OpenMappedContext(string key, object value, bool destructure = false);
     }
@@ -664,6 +665,7 @@
         /// </summary>
         /// <param name="key">A key.</param>
         /// <param name="value">A value.</param>
+        /// <param name="destructure">Destructure context.</param>
         /// <returns>An <see cref="IDisposable"/> that closes context when disposed.</returns>
         [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "SetCurrentLogProvider")]
 #if LIBLOG_PUBLIC
@@ -780,7 +782,9 @@
         private readonly Func<bool> _getIsDisabled;
         internal const string FailedToGenerateLogMessage = "Failed to generate log message";

+#if !LIBLOG_PORTABLE
         Func<string> _lastExtensionMethod;
+#endif

         internal LoggerExecutionWrapper(Logger logger, Func<bool> getIsDisabled = null)
         {
@@ -861,7 +865,7 @@
         }
     }
 #endif
-}
+    }

 #if LIBLOG_PROVIDERS_ONLY
 namespace Corale.Colore.LibLog.LogProviders


Enable copy constructor generation on parser bindings.

--- src/CppParser/Bindings/ParserGen.cs
+++ src/CppParser/Bindings/ParserGen.cs
@@ -54,6 +54,7 @@
             options.Abi = Abi;
             options.LibraryName = "CppSharp.CppParser.dll";
             options.GeneratorKind = Kind;
+            options.GenerateCopyConstructors = true;
             options.Headers.AddRange(new string[]
             {
                 "AST.h",


Removed unused directives

Removed unused directives

--- src/Framework/N2/Web/EventBroker.cs
+++ src/Framework/N2/Web/EventBroker.cs
@@ -1,9 +1,7 @@
 using System;
 using System.Diagnostics;
 using System.IO;
-using System.Linq;
 using System.Web;
-using N2.Configuration;
 using N2.Engine;

 namespace N2.Web


Fix randomness issue with retry jitter

Fix randomness issue with retry jitter

--- src/Google.Api.Gax/RetrySettings.cs
+++ src/Google.Api.Gax/RetrySettings.cs
@@ -134,17 +134,23 @@

         private sealed class RandomJitterImpl : IJitter
         {
-            // We might want to move this code to a more general place, if we need multi-threaded randomness elsewhere.
-            private static int seed = Environment.TickCount;
+            private readonly object _lock = new object();

-            private static ThreadLocal<Random> randomWrapper = new ThreadLocal<Random>(() =>
-                new Random(Interlocked.Increment(ref seed))
-            );
+            // See http://stackoverflow.com/questions/36376888 for why we don't have a thread-local RNG.
+            // We only ever create one instance of RandomJitterImpl, so it doesn't really matter
+            // whether this is an instance variable or static; we'll only have a single Random instance.
+            private readonly Random _random = new Random();

             public TimeSpan GetDelay(TimeSpan maxDelay)
             {
-                var random = randomWrapper.Value;
-                return maxDelay.Ticks <= 0 ? maxDelay : new TimeSpan((long) (random.NextDouble() * maxDelay.Ticks));
+                if (maxDelay <= TimeSpan.Zero)
+                {
+                    return maxDelay;
+                }
+                lock (_lock)
+                {
+                    return new TimeSpan((long)(_random.NextDouble() * maxDelay.Ticks));
+                }
             }
         }


Fix the missing string.Empty on null

Fix the missing string.Empty on null

--- src/GraphQL/Utilities/AstPrinter.cs
+++ src/GraphQL/Utilities/AstPrinter.cs
@@ -15,7 +15,7 @@
         {
             var printer = new AstPrintVisitor();

-            return printer.Visit(node)?.ToString();
+            return printer.Visit(node)?.ToString() ?? string.Empty;
         }
     }


Missing word.

Missing word.

--- src/Gui/Window/MinimizableWindow.cs
+++ src/Gui/Window/MinimizableWindow.cs
@@ -22,7 +22,7 @@
         {
             if (MinimizedWindow == null)
             {
-                Log.ErrorOnce("[PrepareLanding] Trying to minimize while there no MinimizedWindow window available.",
+                Log.ErrorOnce("[PrepareLanding] Trying to minimize while there is no MinimizedWindow window available.",
                     0x1234cafe);
                 return;
             }
@@ -37,7 +37,7 @@
         {
             if (MinimizedWindow == null)
             {
-                Log.ErrorOnce("[PrepareLanding] Trying to maximize while there no MinimizedWindow window available.",
+                Log.ErrorOnce("[PrepareLanding] Trying to maximize while there is no MinimizedWindow window available.",
                     0x1236cafe);
                 return;
             }


Let check for pages as first condition, we only handle the 'page' token when it's surrounded by slashes.

--- src/Hosting/PageLocationExpander.cs
+++ src/Hosting/PageLocationExpander.cs
@@ -30,7 +30,7 @@
             {
                 foreach (var location in viewLocations)
                 {
-                    if (!location.Contains("/Shared/") && !location.Contains("/{1}/") || location.Contains("/Views/"))
+                    if (!location.Contains("/{1}/") && !location.Contains("/Shared/") || location.Contains("/Views/"))
                     {
                         yield return location;
                         continue;


add: LuryObject.Equalsを追加

add: LuryObject.Equalsを追加

--- src/Lury.Core/Runtime/LuryObject.cs
+++ src/Lury.Core/Runtime/LuryObject.cs
@@ -99,6 +99,21 @@

         public override string ToString() => Value.ToString();

+        public override bool Equals(object obj)
+        {
+            var other = obj as LuryObject;
+
+            if (other == null)
+                return false;
+
+            return Value.Equals(other.Value) && LuryTypeName.Equals(other.LuryTypeName);
+        }
+
+        public override int GetHashCode()
+        {
+            return Value.GetHashCode() ^ LuryTypeName.GetHashCode();
+        }
+
         #endregion

         #region -- Private Methods --


Changed to mitigate perf. loss

Changed to mitigate perf. loss

--- src/Mages.Core/StringBuilderPool.cs
+++ src/Mages.Core/StringBuilderPool.cs
@@ -11,7 +11,7 @@
     {
         #region Fields

-		private static readonly Stack<WeakReference> _builder = new Stack<WeakReference>();
+		private static readonly Stack<StringBuilder> _builder = new Stack<StringBuilder>();
         private static readonly Object _lock = new Object();

         #endregion
@@ -26,19 +26,14 @@
         {
             lock (_lock)
             {
-                while (_builder.Count != 0)
+                if (_builder.Count != 0)
                 {
-                    var reference = _builder.Pop();
-                    var builder = default(StringBuilder);
-
-                    if (reference.IsAlive && (builder = reference.Target as StringBuilder) != null)
-                    {
-                        builder.Length = 0;
-                        return builder;
-                    }
+                    var builder = _builder.Pop();
+                    builder.Length = 0;
+                    return builder;
                 }

-                return new StringBuilder();
+                return new StringBuilder();
             }
         }

@@ -52,8 +47,11 @@
         {
             lock (_lock)
             {
-                var reference = new WeakReference(sb);
-                _builder.Push(reference);
+                if (_builder.Count < 4)
+                {
+                    _builder.Push(sb);
+                }
+
                 return sb.ToString();
             }
         }


Uses extension method to get the user.

Uses extension method to get the user.

--- src/NancyAAD.Server/ValuesModule.cs
+++ src/NancyAAD.Server/ValuesModule.cs
@@ -12,7 +12,7 @@
             this.RequiresMSOwinAuthentication();
             Get["/values"] = _ =>
             {
-                ClaimsPrincipal claimsPrincipal = Context.GetAuthenticationManager().User;
+                ClaimsPrincipal claimsPrincipal = Context.GetMSOwinUser();
                 Console.WriteLine("==>I have been called by {0}", claimsPrincipal.FindFirst(ClaimTypes.Upn));
                 return new[] {"value1", "value2"};
             };


Fix bug in StrToDateTime method.

Fix bug in StrToDateTime method.

--- src/Parsers/StatisticsDumpParser.cs
+++ src/Parsers/StatisticsDumpParser.cs
@@ -184,7 +184,7 @@
                 var builder = new StringBuilder(64);
                 for (var i = 0; i < dateparts.Length; i++)
                     builder.Append(dateparts[i]);
-                var result = DateTime.ParseExact(src, "MMddyyHHmmss", CultureInfo.InvariantCulture);
+                var result = DateTime.ParseExact(builder.ToString(), "MMddyyHHmmss", CultureInfo.InvariantCulture);
                 return result;
             }
         }


runtime: conversion byte[] -> string respecting output encoding

--- src/Peachpie.Runtime/Conversions.cs
+++ src/Peachpie.Runtime/Conversions.cs
@@ -110,6 +110,11 @@
         /// Converts mutable string to string.
         /// </summary>
         public static string ToString(PhpString value, Context ctx) => value.ToString(ctx);
+
+        /// <summary>
+        /// Gets value as a string.
+        /// </summary>
+        public static string ToString(byte[] value, Context ctx) => ctx.StringEncoding.GetString(value);

         /// <summary>
         /// Converts mutable string to byte[].
@@ -1451,6 +1456,11 @@
         };

         /// <summary>
+        /// Gets value as a string.
+        /// </summary>
+        public static string ToString(byte[] value, Context ctx) => ctx.StringEncoding.GetString(value);
+
+        /// <summary>
         /// Gets the underlying PHP string if present, a new PHP string representing the value otherwise.
         /// </summary>
         public static PhpString ToPhpString(PhpValue value, Context ctx) => value.TypeCode switch


#7 服务描述符支持扩展。

#7 服务描述符支持扩展。

--- src/Rabbit.Rpc/ServiceDescriptor.cs
+++ src/Rabbit.Rpc/ServiceDescriptor.cs
@@ -1,13 +1,73 @@
-namespace Rabbit.Rpc
+using System;
+using System.Collections.Generic;
+
+namespace Rabbit.Rpc
 {
+    /// <summary>
+    /// 服务描述符扩展方法。
+    /// </summary>
+    public static class ServiceDescriptorExtensions
+    {
+        /// <summary>
+        /// 获取组名称。
+        /// </summary>
+        /// <param name="descriptor">服务描述符。</param>
+        /// <returns>组名称。</returns>
+        public static string GetGroupName(this ServiceDescriptor descriptor)
+        {
+            return descriptor.GetMetadata<string>("groupName");
+        }
+
+        /// <summary>
+        /// 设置组名称。
+        /// </summary>
+        /// <param name="descriptor">服务描述符。</param>
+        /// <param name="groupName">组名称。</param>
+        /// <returns>服务描述符。</returns>
+        public static ServiceDescriptor SetGroupName(this ServiceDescriptor descriptor, string groupName)
+        {
+            descriptor.Metadatas["groupName"] = groupName;
+
+            return descriptor;
+        }
+    }
+
     /// <summary>
     /// 服务描述符。
     /// </summary>
     public class ServiceDescriptor
     {
         /// <summary>
+        /// 初始化一个新的服务描述符。
+        /// </summary>
+        public ServiceDescriptor()
+        {
+            Metadatas = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
+        }
+
+        /// <summary>
         /// 服务Id。
         /// </summary>
         public string Id { get; set; }
+
+        /// <summary>
+        /// 元数据。
+        /// </summary>
+        public IDictionary<string, object> Metadatas { get; set; }
+
+        /// <summary>
+        /// 获取一个元数据。
+        /// </summary>
+        /// <typeparam name="T">元数据类型。</typeparam>
+        /// <param name="name">元数据名称。</param>
+        /// <param name="def">如果指定名称的元数据不存在则返回这个参数。</param>
+        /// <returns>元数据值。</returns>
+        public T GetMetadata<T>(string name, T def = default(T))
+        {
+            if (!Metadatas.ContainsKey(name))
+                return def;
+
+            return (T)Metadatas[name];
+        }
     }
 }


Add invariant check to InternableString.ExpensiveConvertToString (#6798)

We're getting hang dumps where a lock taken by the concurrent flavor of `WeakStringCache` is orphaned. This can possibly be caused by `InternableString.ExpensiveConvertToString`, which is running unsafe code under the lock, throwing a corrupting exception, thus preventing the lock-releasing finally blocks from running.

Since no bug has been found in stress runs and by extensive code inspection, I am adding a cheap invariant check to the unsafe method, hoping that it would help us figure out the issue.

--- src/StringTools/InternableString.cs
+++ src/StringTools/InternableString.cs
@@ -265,6 +265,15 @@
                         }
                     }
                 }
+
+                // The invariant that Length is the sum of span lengths is critical in this unsafe method.
+                // Violating it may lead to memory corruption and, since this code tends to run under a lock,
+                // to hangs caused by the lock getting orphaned. Attempt to detect that and throw now,
+                // before the corruption causes further problems.
+                if (destPtr != resultPtr + Length)
+                {
+                    throw new InvalidOperationException($"Length of {Length} does not match the sum of span lengths of {destPtr - resultPtr}.");
+                }
             }
             return result;
         }


Move AllowExecutorToRun setting in Run() to inside the critical section. I'm not sure why I had it outside before.

--- src/Symbooglix/Executor/Executor.cs
+++ src/Symbooglix/Executor/Executor.cs
@@ -403,13 +403,12 @@
         private Object ExecutorLoopLock = new object();
         public void Run(Implementation entryPoint, int timeout=0)
         {
-            AllowExecutorToRun = true;
-
             // This lock exists for two reasons
             // 1. Force calls to this method to be serialised.
             // 2. Allows the Terminate() method to block on this method.
             lock (ExecutorLoopLock)
             {
+                AllowExecutorToRun = true;
                 RunTimer.Start();
                 SetupTimeout(timeout);


fixes #7139 (#8171)

fixes #7139 (#8171)


handle exceptions in monolith; use local map list with 15 second refresh

--- hybrasyl/Monolith.cs
+++ hybrasyl/Monolith.cs
@@ -542,30 +542,46 @@

     internal class MonolithControl
     {
-        private IEnumerable<Map> _maps => Game.World.WorldData.Values<Map>();
+        private IEnumerable<Map> _maps { get; set; }
         private static Random _random;

         internal MonolithControl()
         {
             _random = new Random();
+            _maps = Game.World.WorldData.Values<Map>().ToList();
         }

         public void Start()
         {
+            var x = 0;
             while (true)
-            {
+            {
                 // Ignore processing if no one is logged in, what's the point

-                foreach (var map in _maps)
-                {
-                    if (map.Users.Count == 0) continue;
-
-                    foreach (var mob in map.Objects.Where(x => x is Monster).ToList())
-                    {
-                        Evaluate(mob as Monster, map);
-                    }
+                try
+                {
+                    foreach (var map in _maps)
+                    {
+                        if (map.Users.Count == 0) continue;
+
+                        foreach (var mob in map.Objects.Where(x => x is Monster).ToList())
+                        {
+                            Evaluate(mob as Monster, map);
+                        }
+                    }
+                }
+                catch (Exception e)
+                {
+                    GameLog.Fatal("Monolith thread error: {e}", e);
                 }
                 Thread.Sleep(1000);
+                x++;
+                // Refresh our list every 15 seconds in case of XML reloading
+                if (x == 15)
+                {
+                    _maps = Game.World.WorldData.Values<Map>().ToList();
+                    x = 0;
+                }
             }
         }


Adding summary to the Aspect property

Adding summary to the Aspect property


Fix failing unit test due configuration manager changing name to endpoint manager.


258.1: line2 sample

258.1: line2 sample


#6 - ReaderWriterLockSlim abstraction corrected some errros.


Corrected class name.

Corrected class name.


Reacting to testing changes

Reacting to testing changes


Fix for collision using the inversion of the masks. This fixes the pr… oblem by inverting the Y coordinate of the collision test. git commit quit q

--- cocos2d/sprite_nodes/CCMaskedSprite.cs
+++ cocos2d/sprite_nodes/CCMaskedSprite.cs
@@ -89,8 +89,8 @@
                     {
                         if ((y2 >= 0) && (y2 < height2))
                         {
-                            int iA = x1 + y1 * width1;
-                            int iB = x2 + y2 * width2;
+							int iA = x1 + (height1-y1) * width1;
+							int iB = x2 + (height2-y2) * width2;
                             if (iA >= maskA.Length || iB >= maskB.Length)
                             {
                                 continue;


Stubbing out the RSVP input form.

Stubbing out the RSVP input form.


Fix path of load file

Fix path of load file

Fixed the path used to load the save file

--- Assets/Classes/GGProductions/LetterStorm/Utilities/GameStateUtilities.cs
+++ Assets/Classes/GGProductions/LetterStorm/Utilities/GameStateUtilities.cs
@@ -16,14 +16,19 @@
         {
             PlayerData loadedData = null;

+			// If the save file exists...
             //if (File.Exists("C:/Users/David/AppData/LocalLow/Unity" + "/playerInfo.dat"))
             if (File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
             {
-                FileStream file = File.Open("C:/Users/David/AppData/LocalLow/Unity" + "/playerInfo.dat", FileMode.Open);
-                BinaryFormatter bf = new BinaryFormatter();
-
+				// Open up the save file for reading
+                //FileStream file = File.Open("C:/Users/David/AppData/LocalLow/Unity" + "/playerInfo.dat", FileMode.Open);
+				FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
+
+				// Create a binary formatter and use it to deserialize the PlayerData from the save file
+				BinaryFormatter bf = new BinaryFormatter();
                 loadedData = (PlayerData)bf.Deserialize(file);

+				// Close stream to the release lock on file
                 file.Close();
             }

@@ -41,7 +46,7 @@
             FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
             //FileStream file = File.Create("C:/Users/David/AppData/LocalLow/Unity" + "/playerInfo.dat");

-            // Create a binary formatter and use it to serialize this object to the save file
+            // Create a binary formatter and use it to serialize the PlayerData to the save file
             BinaryFormatter bf = new BinaryFormatter();
             bf.Serialize(file, dataToSave);


Fix a bug where callback method in ThrowIfTimeout is executed in wrong place.


ios client code fix

ios client code fix


remove priority change point forwarding in pct


Properties which no longer exist have no GUID. Remove these when reading and writing the data.

--- app/Umbraco/Umbraco.Archetype/PropertyEditors/ArcheTypePropertyEditor.cs
+++ app/Umbraco/Umbraco.Archetype/PropertyEditors/ArcheTypePropertyEditor.cs
@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.Linq;
 using Archetype.Extensions;
 using ClientDependency.Core;
 using Newtonsoft.Json;
@@ -62,6 +63,7 @@

 				foreach (var fieldset in archetype.Fieldsets)
 				{
+          fieldset.Properties = fieldset.Properties.Where( p => p.DataTypeGuid != null );
 					foreach (var propDef in fieldset.Properties)
 					{
                         try
@@ -94,6 +96,7 @@

 				foreach (var fieldset in archetype.Fieldsets)
 				{
+          fieldset.Properties = fieldset.Properties.Where( p => p.DataTypeGuid != null );
 					foreach (var propDef in fieldset.Properties)
 					{
                         try
@@ -124,6 +127,7 @@

 				foreach (var fieldset in archetype.Fieldsets)
 				{
+          fieldset.Properties = fieldset.Properties.Where( p => p.DataTypeGuid != null );
 					foreach (var propDef in fieldset.Properties)
 					{
                         try


Proper exception rethrowing in AI Steering system.

--- Content.Server/GameObjects/EntitySystems/AI/Steering/AiSteeringSystem.cs
+++ Content.Server/GameObjects/EntitySystems/AI/Steering/AiSteeringSystem.cs
@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.Runtime.ExceptionServices;
 using System.Threading;
 using System.Threading.Tasks;
 using Content.Server.GameObjects.Components.Access;
@@ -151,6 +152,7 @@
                     case null:
                         break;
                     default:
+                        ExceptionDispatchInfo.Capture(request.Job.Exception).Throw();
                         throw request.Job.Exception;
                 }
                 _pathfindingRequests.Remove(entity);


Set the Rectnagle to the whole row when the SelectionUnit is Row

--- Controls/Grid/Grid.UWP/AutomationPeers/DataGridCellInfoAutomationPeer.cs
+++ Controls/Grid/Grid.UWP/AutomationPeers/DataGridCellInfoAutomationPeer.cs
@@ -297,6 +297,25 @@
         /// <inheritdoc />
         protected override Rect GetBoundingRectangleCore()
         {
+            if (this.radDataGrid.SelectionUnit == DataGridSelectionUnit.Row)
+            {
+                var dataGridPeer = FrameworkElementAutomationPeer.FromElement(this.radDataGrid) as RadDataGridAutomationPeer;
+                if (dataGridPeer != null)
+                {
+                    var firstCellInRow = dataGridPeer.childrenCache.Where(a => a.Row == this.Row && a.Column == 0).FirstOrDefault();
+                    var lastCellInRow = dataGridPeer.childrenCache.Where(a => a.Row == this.Row && a.Column == (this.radDataGrid.Columns.Count - 1)).FirstOrDefault();
+
+                    if (firstCellInRow != null && lastCellInRow != null && firstCellInRow.ChildTextBlockPeer != null
+                        && lastCellInRow.ChildTextBlockPeer != null)
+                    {
+                        var startPointRect = firstCellInRow.ChildTextBlockPeer.GetBoundingRectangle();
+                        var endPointRect = lastCellInRow.ChildTextBlockPeer.GetBoundingRectangle();
+
+                        return new Rect(startPointRect.Left, endPointRect.Top, (endPointRect.Left + endPointRect.Width) - startPointRect.Left, startPointRect.Height);
+                    }
+                }
+            }
+
             if (this.ChildTextBlockPeer != null)
             {
                 return this.ChildTextBlockPeer.GetBoundingRectangle();


Working code fixer ;)

Working code fixer ;)

--- DebuggerStepThroughRemover/DebuggerStepThroughRemover/CodeFixProvider.cs
+++ DebuggerStepThroughRemover/DebuggerStepThroughRemover/CodeFixProvider.cs
@@ -54,14 +54,30 @@
                 .OfType<AttributeSyntax>()
                 .First(IsDebuggerStepThroughAttribute);

-            var indexToRemove = classDeclarationNode.AttributeLists.IndexOf((AttributeListSyntax)debuggerStepThroughAttribute.Parent);
-            var newClassDeclarationNode = classDeclarationNode
-                .WithAttributeLists(classDeclarationNode.AttributeLists.RemoveAt(indexToRemove));
+            var attributeListNode = (AttributeListSyntax) debuggerStepThroughAttribute.Parent;

-            var root = await originalDocument.GetSyntaxRootAsync(cancellationToken);
-            var newRoot = root.ReplaceNode(classDeclarationNode, newClassDeclarationNode);
+            if (attributeListNode.Attributes.Count > 1)
+            {
+                var indexToRemove = attributeListNode.Attributes.IndexOf(debuggerStepThroughAttribute);
+                var newAttributeListNode = attributeListNode.WithAttributes(
+                    attributeListNode.Attributes.RemoveAt(indexToRemove));

-            return originalDocument.WithSyntaxRoot(newRoot);
+                var root = await originalDocument.GetSyntaxRootAsync(cancellationToken);
+                var newRoot = root.ReplaceNode(attributeListNode, newAttributeListNode);
+
+                return originalDocument.WithSyntaxRoot(newRoot);
+            }
+            else
+            {
+                var indexToRemove = classDeclarationNode.AttributeLists.IndexOf((AttributeListSyntax)debuggerStepThroughAttribute.Parent);
+                var newClassDeclarationNode = classDeclarationNode
+                    .WithAttributeLists(classDeclarationNode.AttributeLists.RemoveAt(indexToRemove));
+
+                var root = await originalDocument.GetSyntaxRootAsync(cancellationToken);
+                var newRoot = root.ReplaceNode(classDeclarationNode, newClassDeclarationNode);
+
+                return originalDocument.WithSyntaxRoot(newRoot);
+            }
         }

         private static ClassDeclarationSyntax GetClassDeclarationNode(SyntaxNode root, TextSpan diagnosticSpan)


tests clean-up

tests clean-up

--- King.Service.ServiceBus.Integration.Test/Wrappers/BusTopicClientTests.cs
+++ King.Service.ServiceBus.Integration.Test/Wrappers/BusTopicClientTests.cs
@@ -3,7 +3,6 @@
     using System;
     using System.Configuration;
     using System.Threading.Tasks;
-    using Data;
     using King.Service.ServiceBus.Wrappers;
     using Microsoft.ServiceBus.Messaging;
     using NUnit.Framework;
@@ -21,8 +20,15 @@
             var random = new Random();
             this.name = string.Format("a{0}b", random.Next());

-            var init = new InitializeStorageTask(new BusTopic(name, connection));
-            init.Run();
+            var init = new BusTopic(name, connection);
+            init.CreateIfNotExists().Wait();
+        }
+
+        [TearDown]
+        public void TearDown()
+        {
+            var init = new BusTopic(name, connection);
+            init.Delete().Wait();
         }

         [Test]


Fixed null reference exception if point geometry is empty

--- Source/HelixToolkit.Wpf.SharpDX/Model/Elements3D/PointGeometryModel3D.cs
+++ Source/HelixToolkit.Wpf.SharpDX/Model/Elements3D/PointGeometryModel3D.cs
@@ -124,7 +124,7 @@

         protected override bool CanHitTest(IRenderMatrices context)
         {
-            return base.CanHitTest(context) && geometryInternal.Positions != null && geometryInternal.Positions.Count > 0 && geometryInternal is PointGeometry3D && context != null;
+            return base.CanHitTest(context) && geometryInternal != null && geometryInternal.Positions != null && geometryInternal.Positions.Count > 0 && geometryInternal is PointGeometry3D && context != null;
         }

         /// <summary>


Ensure streams are not unintentional closed during unit tests

--- Source/HttpMultipartParser.UnitTests/HttpMultipartFormParserUnitTests.cs
+++ Source/HttpMultipartParser.UnitTests/HttpMultipartFormParserUnitTests.cs
@@ -53,7 +53,6 @@
               I am the first data1
               --boundry--");

-
         /// <summary>
         ///     Test case for single files.
         /// </summary>
@@ -207,7 +206,6 @@
             }
         );

-
         /// <summary>
         ///     Raw test data for testing a multipart with the file as the last data section.
         /// </summary>
@@ -337,7 +335,6 @@
         #endregion

         #region Constructor
-

         /// <summary>
         ///     Initializes the test data before each run, this primarily
@@ -810,13 +807,15 @@
                             }

                             string expectedFileData;
-                            using (var reader = new StreamReader(expectedFile.Data))
+                            // The last boolean parameter MUST be set to true: it ensures the stream is left open
+                            using (var reader = new StreamReader(expectedFile.Data, Encoding.UTF8, false, 1024, true))
                             {
                                 expectedFileData = reader.ReadToEnd();
                             }

                             string actualFileData;
-                            using (var reader = new StreamReader(actualFile.Data))
+                            // The last boolean parameter MUST be set to true: it ensures the stream is left open
+                            using (var reader = new StreamReader(actualFile.Data, Encoding.UTF8, false, 1024, true))
                             {
                                 actualFileData = reader.ReadToEnd();
                             }


Update ApprenticeshipMapper.cs

Update ApprenticeshipMapper.cs


Performance optimization

Performance optimization

--- Src/Asp.Net/SqlSugar/Abstract/DbBindProvider/IDataReaderEntityBuilder.cs
+++ Src/Asp.Net/SqlSugar/Abstract/DbBindProvider/IDataReaderEntityBuilder.cs
@@ -258,7 +258,7 @@
                 case CSharpDataType.Guid:
                     CheckType(bind.GuidThrow, bindProperyTypeName, validPropertyName, propertyName);
                     if (bindProperyTypeName == "guid")
-                        method = isNullableType ? getConvertStringGuid : getStringGuid;
+                        method = isNullableType ? getConvertGuid : getStringGuid;
                     break;
                 case CSharpDataType.@byte:
                     if (bindProperyTypeName == "byte")


Add tests for relaxed JSON syntax supported by Json.NET

--- StyleCop.Analyzers/StyleCop.Analyzers.Test/Settings/SettingsUnitTests.cs
+++ StyleCop.Analyzers/StyleCop.Analyzers.Test/Settings/SettingsUnitTests.cs
@@ -139,6 +139,88 @@
             Assert.Equal("[InvalidReference]", styleCopSettings.DocumentationRules.CopyrightText);
         }

+        /// <summary>
+        /// Verifies that the settings successfully parse line comments.
+        /// </summary>
+        /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
+        [Fact]
+        public async Task VerifySettingsSupportsLineCommentsAsync()
+        {
+            var settings = @"
+{
+  // Set value for company name
+  ""settings"": {
+    ""documentationRules"": {
+      ""companyName"": ""TestCompany""
+    }
+  }
+}
+";
+            var context = await CreateAnalysisContextAsync(settings).ConfigureAwait(false);
+
+            var styleCopSettings = context.GetStyleCopSettings(CancellationToken.None);
+
+            Assert.Equal("TestCompany", styleCopSettings.DocumentationRules.CompanyName);
+            Assert.Equal("Copyright (c) TestCompany. All rights reserved.", styleCopSettings.DocumentationRules.CopyrightText);
+        }
+
+        /// <summary>
+        /// Verifies that the settings successfully parse block comments.
+        /// </summary>
+        /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
+        [Fact]
+        public async Task VerifySettingsSupportsBlockCommentsAsync()
+        {
+            var settings = @"
+{
+  /*
+   * Set value for company name
+   */
+  ""settings"": {
+    ""documentationRules"": {
+      ""companyName"": ""TestCompany""
+    }
+  }
+}
+";
+            var context = await CreateAnalysisContextAsync(settings).ConfigureAwait(false);
+
+            var styleCopSettings = context.GetStyleCopSettings(CancellationToken.None);
+
+            Assert.Equal("TestCompany", styleCopSettings.DocumentationRules.CompanyName);
+            Assert.Equal("Copyright (c) TestCompany. All rights reserved.", styleCopSettings.DocumentationRules.CopyrightText);
+        }
+
+        /// <summary>
+        /// Verifies that the settings successfully parse trailing commas.
+        /// </summary>
+        /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
+        [Fact]
+        public async Task VerifySettingsSupportsTrailingCommasAsync()
+        {
+            var settings = @"
+{
+  ""settings"": {
+    ""documentationRules"": {
+      ""companyName"": ""TestCompany"",
+    },
+    ""namingRules"": {
+      ""allowedHungarianPrefixes"": [ ""a"", ],
+    },
+  }
+}
+";
+            var context = await CreateAnalysisContextAsync(settings).ConfigureAwait(false);
+
+            var styleCopSettings = context.GetStyleCopSettings(CancellationToken.None);
+
+            Assert.Equal("TestCompany", styleCopSettings.DocumentationRules.CompanyName);
+            Assert.Equal("Copyright (c) TestCompany. All rights reserved.", styleCopSettings.DocumentationRules.CopyrightText);
+
+            Assert.Equal(1, styleCopSettings.NamingRules.AllowedHungarianPrefixes.Length);
+            Assert.Equal("a", styleCopSettings.NamingRules.AllowedHungarianPrefixes[0]);
+        }
+
         [Fact]
         public async Task VerifyInvalidJsonBehaviorAsync()
         {


Cache auto-generated header check

Cache auto-generated header check

--- StyleCop.Analyzers/StyleCop.Analyzers/GeneratedCodeAnalysisExtensions.cs
+++ StyleCop.Analyzers/StyleCop.Analyzers/GeneratedCodeAnalysisExtensions.cs
@@ -6,6 +6,7 @@
 namespace StyleCop.Analyzers
 {
     using System.Linq;
+    using System.Runtime.CompilerServices;
     using System.Text.RegularExpressions;
     using System.Threading;
     using Microsoft.CodeAnalysis;
@@ -15,6 +16,27 @@

     internal static class GeneratedCodeAnalysisExtensions
     {
+        /// <summary>
+        /// The value for a SyntaxTree in the <see cref="GeneratedHeaderPresentCheck"/> table
+        /// when the document has an auto-generated header.
+        /// </summary>
+        private static readonly object GeneratedHeaderPresent = new object();
+
+        /// <summary>
+        /// The value for a SyntaxTree in the <see cref="GeneratedHeaderPresentCheck"/> table
+        /// when the document does NOT have an auto-generated header.
+        /// </summary>
+        private static readonly object GeneratedHeaderAbsent = new object();
+
+        /// <summary>
+        /// A cache of the result of computing whether a document has an auto-generated header.
+        /// </summary>
+        /// <remarks>
+        /// This allows many analyzers that run on every token in the file to avoid checking
+        /// the same state in the document repeatedly.
+        /// </remarks>
+        private static readonly ConditionalWeakTable<SyntaxTree, object> GeneratedHeaderPresentCheck = new ConditionalWeakTable<SyntaxTree, object>();
+
         internal static bool IsGenerated(this SyntaxNodeAnalysisContext context, CancellationToken cancellationToken) => (context.Node.SyntaxTree?.IsGenerated(cancellationToken) ?? false) || (context.Node?.IsGenerated() ?? false);

         internal static bool IsGenerated(this SyntaxTreeAnalysisContext context, CancellationToken cancellationToken) => context.Tree?.IsGenerated(cancellationToken) ?? false;
@@ -38,7 +60,17 @@

         internal static bool HasAutoGeneratedComment(this SyntaxTree tree, CancellationToken cancellationToken)
         {
+            lock (GeneratedHeaderPresentCheck)
+            {
+                object previouslyDeterminedValue;
+                if (GeneratedHeaderPresentCheck.TryGetValue(tree, out previouslyDeterminedValue))
+                {
+                    return previouslyDeterminedValue == GeneratedHeaderPresent;
+                }
+            }
+
             var root = tree.GetRoot(cancellationToken);
+
             if (root == null) return false;
             var firstToken = root.GetFirstToken();
             SyntaxTriviaList trivia;
@@ -56,7 +88,17 @@

             var commentLines = trivia.Where(t => t.IsKind(SyntaxKind.SingleLineCommentTrivia)).Take(2).ToList();
             if (commentLines.Count != 2) return false;
-            return commentLines[1].ToString() == "// <auto-generated>";
+            bool autoGenerated = commentLines[1].ToString() == "// <auto-generated>";
+
+            lock (GeneratedHeaderPresentCheck)
+            {
+                // We don't know if there was a race, and we want to avoid throwing,
+                // so now that we have the lock, remove the key if it is already there.
+                GeneratedHeaderPresentCheck.Remove(tree);
+                GeneratedHeaderPresentCheck.Add(tree, autoGenerated ? GeneratedHeaderPresent : GeneratedHeaderAbsent);
+            }
+
+            return autoGenerated;
         }

         private static bool IsOnGeneratedFile(this string filePath) =>


Update Task 3.3 - Save Properties With BinaryWriter.cs


Fix Watchman issues of MS-OXWSMTGS.

Fix Watchman issues of MS-OXWSMTGS.

--- ExchangeWebServices/Source/MS-OXWSMTGS/TestSuite/S01_CreateGetDeleteCalendarRelatedItem.cs
+++ ExchangeWebServices/Source/MS-OXWSMTGS/TestSuite/S01_CreateGetDeleteCalendarRelatedItem.cs
@@ -53,6 +53,7 @@
                 calendarItem.IsOnlineMeeting = false;
                 calendarItem.IsOnlineMeetingSpecified = true;
             }
+
             calendarItem.IsAllDayEvent = true;
             calendarItem.IsAllDayEventSpecified = true;
             calendarItem.LegacyFreeBusyStatus = LegacyFreeBusyType.OOF;
@@ -306,6 +307,7 @@
                 meetingItem.IsOnlineMeeting = true;
                 meetingItem.IsOnlineMeetingSpecified = true;
             }
+
             meetingItem.AllowNewTimeProposal = true;
             meetingItem.AllowNewTimeProposalSpecified = true;
             meetingItem.ConferenceType = 1;
@@ -1201,6 +1203,7 @@
                 meeting.IsOnlineMeeting = true;
                 meeting.IsOnlineMeetingSpecified = true;
             }
+
             meeting.ConferenceType = 2;
             meeting.ConferenceTypeSpecified = true;
             meeting.AllowNewTimeProposal = true;
@@ -1947,6 +1950,7 @@
                 meeting.IsOnlineMeeting = false;
                 meeting.IsOnlineMeetingSpecified = true;
             }
+
             meeting.LegacyFreeBusyStatus = LegacyFreeBusyType.Free;
             meeting.LegacyFreeBusyStatusSpecified = true;

@@ -2812,7 +2816,7 @@
         }

         /// <summary>
-        /// This test case is designed to test MeetingRequestType PincipalWantsCopy indicates that the meeting request belongs to
+        /// This test case is designed to test MeetingRequestType PrincipalWantsCopy indicates that the meeting request belongs to
         /// a principal who has forwarded meeting messages to a delegate and this copy is informational.
         /// </summary>
         [TestCategory("MSOXWSMTGS"), TestMethod()]


Define 'UnicodeConverter.GetUtf16ToUtf8BufferLength'

--- stdlib/corlib/UnicodeConverter.cs
+++ stdlib/corlib/UnicodeConverter.cs
@@ -66,7 +66,7 @@
         public static uint ReadUtf8CodePoint(ref byte* data, byte* end)
         {
             byte c = *data;
-            int result = 0;
+            int count = 0;
             int cont = 0;
             while (data != end)
             {
@@ -76,7 +76,7 @@
                     switch (bytetype(c))
                     {
                         case ASCII:
-                            result = c;
+                            count = c;
                             break;
                         case LEAD2:
                             cont = 1;
@@ -84,21 +84,21 @@
                             * will cause the bits belonging to the LEAD byte to be
                             * eliminated, leaving the bits we care about.
                             */
-                            result = c & (~LEAD2);
+                            count = c & (~LEAD2);
                             break;
                         case LEAD3:
                             cont = 2;
-                            result = c & (~LEAD3);
+                            count = c & (~LEAD3);
                             break;
                         case LEAD4:
                             cont = 3;
-                            result = c & (~LEAD4);
+                            count = c & (~LEAD4);
                             break;
                         default:
                             /* either an unexpected CONT byte showed up
                             * or an invalid byte.
                             */
-                            result = BadCodePoint;
+                            count = BadCodePoint;
                             break;
                     }
                 }
@@ -107,15 +107,15 @@
                     switch (bytetype(c))
                     {
                         case CONT:
-                            result <<= 6; /* room for 6 more bits */
-                            result += c & (~CONT);
+                            count <<= 6; /* room for 6 more bits */
+                            count += c & (~CONT);
                             --cont;
                             break;
                         default:
                             /* There was something other than a CONT byte, either
                             * an invalid byte or an unexpected LEAD or ASCII byte
                             */
-                            result = BadCodePoint;
+                            count = BadCodePoint;
                             break;
                     }
                 }
@@ -123,7 +123,7 @@
                 data++;
                 if (cont == 0)
                 {
-                    return (uint)result;
+                    return (uint)count;
                 }
             }
         }
@@ -132,8 +132,10 @@
         /// Writes a code point to a UTF-8--encoded buffer.
         /// </summary>
         /// <param name="codePoint">The code point to write.</param>
-        /// <param name="buffer">The buffer to write the code point to.</param>
-        /// <returns>The number of bytes that were written to the buffer.</returns>
+        /// <param name="buffer">
+        /// The buffer to write the code point to.
+        /// If this buffer is <c>null</c>, then no bytes are written.</param>
+        /// <returns>The number of bytes that are used to encode the code point in UTF-8.</returns>
         public static int WriteUtf8CodePoint(uint codePoint, byte* buffer)
         {
             byte b = 0, c = 0, d = 0, e = 0;
@@ -202,13 +204,17 @@
                 n = 4;
             } while (false);

-            buffer[0] = b;
-            if (n > 1)
-                buffer[1] = c;
-            if (n > 2)
-                buffer[2] = d;
-            if (n > 3)
-                buffer[3] = e;
+            if (buffer != null)
+            {
+                buffer[0] = b;
+                if (n > 1)
+                    buffer[1] = c;
+                if (n > 2)
+                    buffer[2] = d;
+                if (n > 3)
+                    buffer[3] = e;
+            }
+
             return n;
         }

@@ -302,5 +308,20 @@
             buffer[1] = (char)(low | 0xDC00);
             return 2;
         }
+
+        /// <summary>
+        /// Gets the length of the UTF-8 buffer required to transcribe a UTF-16
+        /// string to a UTF-8 string.
+        /// </summary>
+        /// <returns>The size of the UTF-8 buffer in bytes.</returns>
+        public static int GetUtf16ToUtf8BufferLength(char* begin, char* end)
+        {
+            int count = 0;
+            while (begin != end)
+            {
+                count += WriteUtf8CodePoint(ReadUtf16CodePoint(ref begin, end), null);
+            }
+            return count;
+        }
     }
 }


Improve the md5 verifier test a bist

Improve the md5 verifier test a bist

--- Tests/ModInstallation.Tests/Implementations/Mods/MD5FileVerifierTests.cs
+++ Tests/ModInstallation.Tests/Implementations/Mods/MD5FileVerifierTests.cs
@@ -22,6 +22,15 @@
         public void ExtractTestFile()
         {
             var assembly = Assembly.GetExecutingAssembly();
+
+            var dirPath = Path.GetDirectoryName(_outPath);
+            if (dirPath != null)
+            {
+                if (!Directory.Exists(dirPath))
+                {
+                    Directory.CreateDirectory(dirPath);
+                }
+            }

             using (var stream = assembly.GetManifestResourceStream("ModInstallation.Tests.TestData.random.txt"))
             {
@@ -48,7 +57,7 @@

         #endregion

-        private readonly string _outPath = Path.Combine(Path.GetTempPath(), "random.txt");
+        private readonly string _outPath = Path.Combine(TestContext.CurrentContext.WorkDirectory, TestContext.CurrentContext.Test.Name, "random.txt");

         [NotNull, Test]
         public async Task TestVerifyFilePathAsync()


[Vsintegration] Added several project file properties that allow embedded variables in the form of $(SomeName). #928

--- VisualStudio/AppDesigner/Wix/projectproperty.cs
+++ VisualStudio/AppDesigner/Wix/projectproperty.cs
@@ -44,10 +44,16 @@
             XSharpProjectFileConstants.DefineConstants,
             XSharpProjectFileConstants.IntermediateOutputPath,
             XSharpProjectFileConstants.OutputPath,
+            XSharpProjectFileConstants.IncludePaths,
+            XSharpProjectFileConstants.StandardDefs,
+            XSharpProjectFileConstants.DocumentationFile,
             XSharpProjectFileConstants.PostBuildEvent,
             XSharpProjectFileConstants.PreBuildEvent,
+            XSharpProjectFileConstants.AssemblyOriginatorKeyFile,
             XSharpProjectFileConstants.DebuggerWorkingDirectory,
             XSharpProjectFileConstants.DebuggerCommand,
+            XSharpProjectFileConstants.DebuggerWorkingDirectory
+
         };

         private static readonly ICollection<string> ListProperties = new string[]


clean up code

clean up code

--- Weingartner.Json.Migration.Roslyn_/Constants.cs
+++ Weingartner.Json.Migration.Roslyn_/Constants.cs
@@ -1,5 +1,6 @@
 namespace Weingartner.Json.Migration.Roslyn
 {
+
     public static class Constants
     {
         public const string MigratableAttributeMetadataName = "Weingartner.Json.Migration.MigratableAttribute";


add of content link

add of content link


More fixes

More fixes

--- src/celestialbodies/name/NameTweak.cs
+++ src/celestialbodies/name/NameTweak.cs
@@ -80,9 +80,7 @@
         /// </summary>
         private CelestialBody GetNextStar(CelestialBody body)
         {
-            if (body.orbitDriver == null)
-                return body;
-            if (body.orbit.referenceBody.scaledBody.GetComponentsInChildren<SunShaderController>().Length != 0)
+            if (body.orbitDriver == null || body.scaledBody.GetComponentsInChildren<SunShaderController>().Length != 0)
                 return body;
             return GetNextStar(body.orbit.referenceBody);
         }


LWDEV-5629 bugfix

LWDEV-5629 bugfix


Replaced superfluous data with empty sequences for test cases where null argument checking was being tested for secondary parameters.

--- test/BackLINQ.Tests/EnumerableFixture.cs
+++ test/BackLINQ.Tests/EnumerableFixture.cs
@@ -311,8 +311,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void Except_secondArg_ArgumentNull_ThrowsArgumentNullException()
         {
-            var source = new OnceEnumerable<int>(new[] { 1, 4, 7 });
-            source.Except(null);
+            new object[0].Once().Except(null);
         }

         [Test]
@@ -419,8 +418,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void GroupBy_KeySelectorArg_NullAsKeySelector_ThrowsArgumentNullException()
         {
-            var source = new OnceEnumerable<Person>(Person.CreatePersons());
-            source.GroupBy<Person, String>(null);
+            new object[0].Once().GroupBy<object, object>(null);
         }

         [Test]
@@ -757,8 +755,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void Intersect_SecondArg_PassNullAsArgument_ThrowsArgumentNullException()
         {
-            var source = new OnceEnumerable<int>(new[] { 1, 2, 3 });
-            source.Intersect(null);
+            new object[0].Once().Intersect(null);
         }

         [Test]
@@ -782,8 +779,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void Join_InnerArgOuterKeySelectorArgInnerKeySelectorArgResultSelectorArg_PassNullAsArgument_ThrowsArgumentNullException()
         {
-            var persons = new OnceEnumerable<Person>(Person.CreatePersons());
-            persons.Join<Person, string, string, string>(null, null, null, null);
+            new object[0].Once().Join<object, object, object, object>(null, null, null, null);
         }

         [Test]
@@ -884,8 +880,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void Last_PredicateArg_NullAsPredicate_ThrowsArgumentNullException()
         {
-            var source = new OnceEnumerable<int>(new[] { 1, 2, 3 });
-            source.Last(null);
+            new object[0].Once().Last(null);
         }

         [Test]
@@ -942,8 +937,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void LongCount_PredicateArg_NullAsPredicate_ThrowsArgumentNullException()
         {
-            var source = new OnceEnumerable<int>(new[] { 1, 2, 3, 4 });
-            source.LongCount(null);
+            new object[0].Once().LongCount(null);
         }

         [Test]
@@ -1031,8 +1025,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void OrderBy_KeySelectorArg_NullAsKeySelector_ThrowsArgumentNullException()
         {
-            var source = new OnceEnumerable<int>(new[] { 1, 4, 2 });
-            source.OrderBy<int, int>(null);
+            new object[0].Once().OrderBy<object, object>(null);
         }

         [Test]
@@ -1265,8 +1258,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void SequenceEqual_SecondArg_NullAsArgument_ThrowsArgumentNullException()
         {
-            var source = new OnceEnumerable<int>(new[] { 1, 2, 3 });
-            source.SequenceEqual(null);
+            new object[0].Once().SequenceEqual(null);
         }

         [Test]
@@ -1332,8 +1324,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void Single_PredicateArg_PassNullAsPredicate_ThrowsArgumentNullException()
         {
-            var source = new[] { 1, 2, 3 };
-            source.Single(null);
+            new object[0].Once().Single(null);
         }

         [Test]
@@ -1393,8 +1384,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void SingleOrDefault_PredicateArg_PassNullAsPredicate_ThrowsArgumentNullException()
         {
-            var source = new[] { 4 };
-            source.SingleOrDefault(null);
+            new object[0].Once().SingleOrDefault(null);
         }

         [Test]
@@ -1444,8 +1434,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void SkipWhile_PredicateArg_PassNullAsPredicate_ThrowsArgumentNullException()
         {
-            var source = new[] { 1, 2, 3, 4, 5 };
-            source.SkipWhile((Func<int, bool>)null);
+            new object[0].Once().SkipWhile((Func<object, bool>) null);
         }

         [Test]
@@ -1525,8 +1514,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void TakeWhile_PassNullAsPredicate_ThrowsArgumentNullException()
         {
-            var source = new[] { 1, 2, 3, 4, 5 };
-            source.TakeWhile((Func<int, bool>)null);
+            new object[0].TakeWhile((Func<object, bool>) null);
         }

         [Test]
@@ -1634,8 +1622,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void Union_SecondArg_PassNullAsArgument_ThrowsArgumentNullException()
         {
-            var source = new[] { 5, 3, 9, 7, 5, 9, 3, 7 };
-            source.Union(null);
+            new object[0].Once().Union(null);
         }

         [Test]
@@ -1658,8 +1645,7 @@
         [ExpectedException(typeof(ArgumentNullException))]
         public void Where_PredicateArg_PassNullAsPredicate_ThrowsArgumentNullException()
         {
-            var source = new[] { 1, 2, 3, 4 };
-            source.Where((Func<int, bool>)null);
+            new object[0].Once().Where((Func<object, bool>) null);
         }

         [Test]


Document how to use a custom authentication header e.g Kerberos (#3518)

* Document how to subclass the HttpConnection to provide authentication headers, e.g for Kerberos

* move comment about examples to the top

(cherry picked from commit 980a5df358b7a79bff822b3b755a4a085a83efd0)


Surround imports with region.

Surround imports with region.

--- test/BackLINQ.Tests/EnumerableFixture.cs
+++ test/BackLINQ.Tests/EnumerableFixture.cs
@@ -25,17 +25,22 @@
 //
 #endregion

-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Text;
-using NUnit.Framework;
-using System.Linq;
-using System.Diagnostics;
-using Constraint = NUnit.Framework.Constraints.Constraint;
-using NUnit.Framework.SyntaxHelpers;
-
 namespace BackLinq.Tests {
+
+    #region Imports
+
+    using System;
+    using System.Collections.Generic;
+    using System.Globalization;
+    using System.Text;
+    using NUnit.Framework;
+    using System.Linq;
+    using System.Diagnostics;
+    using Constraint = NUnit.Framework.Constraints.Constraint;
+    using NUnit.Framework.SyntaxHelpers;
+
+    #endregion
+
     [TestFixture]
     public sealed class EnumerableFixture {


cleanup

cleanup

--- Source/DualityTemplates/Templates/SolutionTemplate/Source/Launchers/DualityGame/Program.cs
+++ Source/DualityTemplates/Templates/SolutionTemplate/Source/Launchers/DualityGame/Program.cs
@@ -1,7 +1,5 @@
 using System;
-using Duality;
 using Duality.Launcher;
-using Duality.Resources;

 namespace DualityGame
 {


We want these to fail if it's null. it shouldn't be null.

--- test/DieRoller.Tests/RollBuilderTests.cs
+++ test/DieRoller.Tests/RollBuilderTests.cs
@@ -11,8 +11,8 @@
         {
             var rollBuilder = RollBuilder.WithDie(Die.D6)
                 .Targeting(Target.ValueAndAbove(4)) as RollBuilder;
-
-            rollBuilder?.RollModifier.GetType().Should().Be<NoModifier>();
+
+            rollBuilder.RollModifier.GetType().Should().Be<NoModifier>();
         }

         [Fact]
@@ -20,8 +20,8 @@
         {
             var rollBuilder = RollBuilder.WithDie(Die.D6)
                 .Targeting(Target.ValueAndAbove(4)) as RollBuilder;
-
-            rollBuilder?.RerollBehaviour.GetType().Should().Be<RerollNone>();
+
+            rollBuilder.RerollBehaviour.GetType().Should().Be<RerollNone>();
         }
     }
 }


Fix spacing

Fix spacing

--- eng/GenerateAnalyzerNuspec.csx
+++ eng/GenerateAnalyzerNuspec.csx
@@ -115,14 +115,14 @@
             targets = allTargets;
         }

-		string assemblyNameWithoutExtension = Path.GetFileNameWithoutExtension(assembly);
+        string assemblyNameWithoutExtension = Path.GetFileNameWithoutExtension(assembly);
         string assemblyFolder = Path.Combine(artifactsBinDir, assemblyNameWithoutExtension, configuration, tfm);
         string assemblyPathForNuspec = Path.Combine(assemblyNameWithoutExtension, configuration, tfm, assembly);

         foreach (string target in targets)
         {
             result.AppendLine(FileElement(assemblyPathForNuspec, target));
-
+
             if (Directory.Exists(assemblyFolder))
             {
                 string resourceAssemblyName = assemblyNameWithoutExtension + ".resources.dll";


open image d

open image d


TSI-2303 : fixed location

TSI-2303 : fixed location

--- webapp-net/Core/Models/Entity/Teaser.cs
+++ webapp-net/Core/Models/Entity/Teaser.cs
@@ -54,6 +54,8 @@
         [SemanticProperty("c:date")]
         public DateTime? Date { get; set; }

+        [SemanticProperty("p:location")]
+        [SemanticProperty("c:location")]
         public Location Location { get; set; }

         //To store formatting options for the teaser (link style etc.)


WebSocketFrame

WebSocketFrame

--- websocket-sharp.clone/WebSocketFrame.cs
+++ websocket-sharp.clone/WebSocketFrame.cs
@@ -38,47 +38,21 @@

 	internal class WebSocketFrame : IEnumerable<byte>
 	{
-		#region Private Fields
-
-		private byte[] _extPayloadLength;
+	    private byte[] _extPayloadLength;
 		private Fin _fin;
-		private Mask _mask;
-		private byte[] _maskingKey;
-		private Opcode _opcode;
-		private PayloadData _payloadData;
-		private byte _payloadLength;
-		private Rsv _rsv1;
-		private Rsv _rsv2;
-		private Rsv _rsv3;
-
-		#endregion
-
-		#region Internal Fields
-
-		internal static readonly byte[] EmptyUnmaskPingBytes;
-
-		#endregion
-
-		#region Static Constructor
-
-		static WebSocketFrame()
+
+	    internal static readonly byte[] EmptyUnmaskPingBytes;
+
+	    static WebSocketFrame()
 		{
 			EmptyUnmaskPingBytes = CreatePingFrame(false).ToByteArray();
 		}

-		#endregion
-
-		#region Private Constructors
-
-		private WebSocketFrame()
-		{
-		}
-
-		#endregion
-
-		#region Internal Constructors
-
-		internal WebSocketFrame(Opcode opcode, PayloadData payloadData, bool mask)
+	    private WebSocketFrame()
+		{
+		}
+
+	    internal WebSocketFrame(Opcode opcode, PayloadData payloadData, bool mask)
 			: this(Fin.Final, opcode, payloadData, false, mask)
 		{
 		}
@@ -91,244 +65,92 @@
 		internal WebSocketFrame(Fin fin, Opcode opcode, PayloadData payloadData, bool compressed, bool mask)
 		{
 			_fin = fin;
-			_rsv1 = isData(opcode) && compressed ? Rsv.On : Rsv.Off;
-			_rsv2 = Rsv.Off;
-			_rsv3 = Rsv.Off;
-			_opcode = opcode;
+			Rsv1 = isData(opcode) && compressed ? Rsv.On : Rsv.Off;
+			Rsv2 = Rsv.Off;
+			Rsv3 = Rsv.Off;
+			Opcode = opcode;

 			var len = payloadData.Length;
 			if (len < 126)
 			{
-				_payloadLength = (byte)len;
+				PayloadLength = (byte)len;
 				_extPayloadLength = new byte[0];
 			}
 			else if (len < 0x010000)
 			{
-				_payloadLength = (byte)126;
+				PayloadLength = (byte)126;
 				_extPayloadLength = ((ushort)len).InternalToByteArray(ByteOrder.Big);
 			}
 			else
 			{
-				_payloadLength = (byte)127;
+				PayloadLength = (byte)127;
 				_extPayloadLength = len.InternalToByteArray(ByteOrder.Big);
 			}

 			if (mask)
 			{
-				_mask = Mask.Mask;
-				_maskingKey = createMaskingKey();
-				payloadData.Mask(_maskingKey);
+				Mask = Mask.Mask;
+				MaskingKey = createMaskingKey();
+				payloadData.Mask(MaskingKey);
 			}
 			else
 			{
-				_mask = Mask.Unmask;
-				_maskingKey = new byte[0];
-			}
-
-			_payloadData = payloadData;
-		}
-
-		#endregion
-
-		#region Public Properties
-
-		public byte[] ExtendedPayloadLength
-		{
-			get
-			{
-				return _extPayloadLength;
-			}
-		}
-
-		public Fin Fin
-		{
-			get
-			{
-				return _fin;
-			}
-		}
-
-		public bool IsBinary
-		{
-			get
-			{
-				return _opcode == Opcode.Binary;
-			}
-		}
-
-		public bool IsClose
-		{
-			get
-			{
-				return _opcode == Opcode.Close;
-			}
-		}
-
-		public bool IsCompressed
-		{
-			get
-			{
-				return _rsv1 == Rsv.On;
-			}
-		}
-
-		public bool IsContinuation
-		{
-			get
-			{
-				return _opcode == Opcode.Cont;
-			}
-		}
-
-		public bool IsControl
-		{
-			get
-			{
-				return _opcode == Opcode.Close || _opcode == Opcode.Ping || _opcode == Opcode.Pong;
-			}
-		}
-
-		public bool IsData
-		{
-			get
-			{
-				return _opcode == Opcode.Binary || _opcode == Opcode.Text;
-			}
-		}
-
-		public bool IsFinal
-		{
-			get
-			{
-				return _fin == Fin.Final;
-			}
-		}
-
-		public bool IsFragmented
-		{
-			get
-			{
-				return _fin == Fin.More || _opcode == Opcode.Cont;
-			}
-		}
-
-		public bool IsMasked
-		{
-			get
-			{
-				return _mask == Mask.Mask;
-			}
-		}
-
-		public bool IsPerMessageCompressed
-		{
-			get
-			{
-				return (_opcode == Opcode.Binary || _opcode == Opcode.Text) && _rsv1 == Rsv.On;
-			}
-		}
-
-		public bool IsPing
-		{
-			get
-			{
-				return _opcode == Opcode.Ping;
-			}
-		}
-
-		public bool IsPong
-		{
-			get
-			{
-				return _opcode == Opcode.Pong;
-			}
-		}
-
-		public bool IsText
-		{
-			get
-			{
-				return _opcode == Opcode.Text;
-			}
-		}
-
-		public ulong Length
-		{
-			get
-			{
-				return 2 + (ulong)(_extPayloadLength.Length + _maskingKey.Length) + _payloadData.Length;
-			}
-		}
-
-		public Mask Mask
-		{
-			get
-			{
-				return _mask;
-			}
-		}
-
-		public byte[] MaskingKey
-		{
-			get
-			{
-				return _maskingKey;
-			}
-		}
-
-		public Opcode Opcode
-		{
-			get
-			{
-				return _opcode;
-			}
-		}
-
-		public PayloadData PayloadData
-		{
-			get
-			{
-				return _payloadData;
-			}
-		}
-
-		public byte PayloadLength
-		{
-			get
-			{
-				return _payloadLength;
-			}
-		}
-
-		public Rsv Rsv1
-		{
-			get
-			{
-				return _rsv1;
-			}
-		}
-
-		public Rsv Rsv2
-		{
-			get
-			{
-				return _rsv2;
-			}
-		}
-
-		public Rsv Rsv3
-		{
-			get
-			{
-				return _rsv3;
-			}
-		}
-
-		#endregion
-
-		#region Private Methods
-
-		private static byte[] createMaskingKey()
+				Mask = Mask.Unmask;
+				MaskingKey = new byte[0];
+			}
+
+			PayloadData = payloadData;
+		}
+
+	    public byte[] ExtendedPayloadLength => _extPayloadLength;
+
+	    public Fin Fin => _fin;
+
+	    public bool IsBinary => Opcode == Opcode.Binary;
+
+	    public bool IsClose => Opcode == Opcode.Close;
+
+	    public bool IsCompressed => Rsv1 == Rsv.On;
+
+	    public bool IsContinuation => Opcode == Opcode.Cont;
+
+	    public bool IsControl => Opcode == Opcode.Close || Opcode == Opcode.Ping || Opcode == Opcode.Pong;
+
+	    public bool IsData => Opcode == Opcode.Binary || Opcode == Opcode.Text;
+
+	    public bool IsFinal => _fin == Fin.Final;
+
+	    public bool IsFragmented => _fin == Fin.More || Opcode == Opcode.Cont;
+
+	    public bool IsMasked => Mask == Mask.Mask;
+
+	    public bool IsPerMessageCompressed => (Opcode == Opcode.Binary || Opcode == Opcode.Text) && Rsv1 == Rsv.On;
+
+	    public bool IsPing => Opcode == Opcode.Ping;
+
+	    public bool IsPong => Opcode == Opcode.Pong;
+
+	    public bool IsText => Opcode == Opcode.Text;
+
+	    public ulong Length => 2 + (ulong)(_extPayloadLength.Length + MaskingKey.Length) + PayloadData.Length;
+
+	    public Mask Mask { get; private set; }
+
+	    public byte[] MaskingKey { get; private set; }
+
+	    public Opcode Opcode { get; private set; }
+
+	    public PayloadData PayloadData { get; private set; }
+
+	    public byte PayloadLength { get; private set; }
+
+	    public Rsv Rsv1 { get; private set; }
+
+	    public Rsv Rsv2 { get; private set; }
+
+	    public Rsv Rsv3 { get; private set; }
+
+	    private static byte[] createMaskingKey()
 		{
 			var key = new byte[4];
 			var rand = new Random();
@@ -420,11 +242,11 @@
 		{
 			/* Opcode */

-			var opcode = frame._opcode.ToString();
+			var opcode = frame.Opcode.ToString();

 			/* Payload Length */

-			var payloadLen = frame._payloadLength;
+			var payloadLen = frame.PayloadLength;

 			/* Extended Payload Length */

@@ -437,7 +259,7 @@
 			/* Masking Key */

 			var masked = frame.IsMasked;
-			var maskingKey = masked ? BitConverter.ToString(frame._maskingKey) : string.Empty;
+			var maskingKey = masked ? BitConverter.ToString(frame.MaskingKey) : string.Empty;

 			/* Payload Data */

@@ -446,8 +268,8 @@
 						  : payloadLen > 125
 							? string.Format("A {0} frame.", opcode.ToLower())
 							: !masked && !frame.IsFragmented && !frame.IsCompressed && frame.IsText
-							  ? Encoding.UTF8.GetString(frame._payloadData.ApplicationData)
-							  : frame._payloadData.ToString();
+							  ? Encoding.UTF8.GetString(frame.PayloadData.ApplicationData)
+							  : frame.PayloadData.ToString();

 			var fmt = @"
 					FIN: {0}
@@ -464,11 +286,11 @@
 			return string.Format(
 			  fmt,
 			  frame._fin,
-			  frame._rsv1,
-			  frame._rsv2,
-			  frame._rsv3,
+			  frame.Rsv1,
+			  frame.Rsv2,
+			  frame.Rsv3,
 			  opcode,
-			  frame._mask,
+			  frame.Mask,
 			  payloadLen,
 			  extPayloadLen,
 			  maskingKey,
@@ -510,12 +332,12 @@

 			var frame = new WebSocketFrame();
 			frame._fin = fin;
-			frame._rsv1 = rsv1;
-			frame._rsv2 = rsv2;
-			frame._rsv3 = rsv3;
-			frame._opcode = opcode;
-			frame._mask = mask;
-			frame._payloadLength = payloadLen;
+			frame.Rsv1 = rsv1;
+			frame.Rsv2 = rsv2;
+			frame.Rsv3 = rsv3;
+			frame.Opcode = opcode;
+			frame.Mask = mask;
+			frame.PayloadLength = payloadLen;

 			/* Extended Payload Length */

@@ -542,7 +364,7 @@
 				throw new WebSocketException("The 'Masking Key' of a frame cannot be read from the data source.");
 			}

-			frame._maskingKey = maskingKey;
+			frame.MaskingKey = maskingKey;

 			/* Payload Data */

@@ -576,7 +398,7 @@
 				data = new byte[0];
 			}

-			frame._payloadData = new PayloadData(data, masked);
+			frame.PayloadData = new PayloadData(data, masked);
 			if (unmask && masked)
 			{
 				frame.Unmask();
@@ -585,11 +407,7 @@
 			return frame;
 		}

-		#endregion
-
-		#region Internal Methods
-
-		internal static WebSocketFrame CreateCloseFrame(PayloadData payloadData, bool mask)
+	    internal static WebSocketFrame CreateCloseFrame(PayloadData payloadData, bool mask)
 		{
 			return new WebSocketFrame(Fin.Final, Opcode.Close, payloadData, false, mask);
 		}
@@ -629,21 +447,17 @@

 		internal void Unmask()
 		{
-			if (_mask == Mask.Unmask)
+			if (Mask == Mask.Unmask)
 			{
 				return;
 			}

-			_mask = Mask.Unmask;
-			_payloadData.Mask(_maskingKey);
-			_maskingKey = new byte[0];
-		}
-
-		#endregion
-
-		#region Public Methods
-
-		public IEnumerator<byte> GetEnumerator()
+			Mask = Mask.Unmask;
+			PayloadData.Mask(MaskingKey);
+			MaskingKey = new byte[0];
+		}
+
+	    public IEnumerator<byte> GetEnumerator()
 		{
 			return ((IEnumerable<byte>)ToByteArray()).GetEnumerator();
 		}
@@ -653,28 +467,28 @@
 			using (var buff = new MemoryStream())
 			{
 				var header = (int)_fin;
-				header = (header << 1) + (int)_rsv1;
-				header = (header << 1) + (int)_rsv2;
-				header = (header << 1) + (int)_rsv3;
-				header = (header << 4) + (int)_opcode;
-				header = (header << 1) + (int)_mask;
-				header = (header << 7) + (int)_payloadLength;
+				header = (header << 1) + (int)Rsv1;
+				header = (header << 1) + (int)Rsv2;
+				header = (header << 1) + (int)Rsv3;
+				header = (header << 4) + (int)Opcode;
+				header = (header << 1) + (int)Mask;
+				header = (header << 7) + (int)PayloadLength;
 				buff.Write(((ushort)header).InternalToByteArray(ByteOrder.Big), 0, 2);

-				if (_payloadLength > 125)
+				if (PayloadLength > 125)
 				{
 					buff.Write(_extPayloadLength, 0, _extPayloadLength.Length);
 				}

-				if (_mask == Mask.Mask)
+				if (Mask == Mask.Mask)
 				{
-					buff.Write(_maskingKey, 0, _maskingKey.Length);
+					buff.Write(MaskingKey, 0, MaskingKey.Length);
 				}

-				if (_payloadLength > 0)
+				if (PayloadLength > 0)
 				{
-					var payload = _payloadData.ToByteArray();
-					if (_payloadLength < 127)
+					var payload = PayloadData.ToByteArray();
+					if (PayloadLength < 127)
 					{
 						buff.Write(payload, 0, payload.Length);
 					}
@@ -694,15 +508,9 @@
 			return BitConverter.ToString(ToByteArray());
 		}

-		#endregion
-
-		#region Explicit Interface Implementations
-
-		IEnumerator IEnumerable.GetEnumerator()
+	    IEnumerator IEnumerable.GetEnumerator()
 		{
 			return GetEnumerator();
 		}
-
-		#endregion
 	}
 }


Cleaning up some script

Cleaning up some script