refactoring of duplicated code in client testing app to be able add new methods in simply way, some more work will be needed

--- src/ServiceFabricPubSub/ClientApp/ClientApi/Request.cs
+++ src/ServiceFabricPubSub/ClientApp/ClientApi/Request.cs
@@ -96,11 +96,10 @@
                 tracingParameters.Add("cancellationToken", cancellationToken);
                 ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
             }
-            // Construct URL
-            var _baseUrl = Client.BaseUri.AbsoluteUri;
-            var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Request/{tenantId}/{topicName}").ToString();
-            _url = _url.Replace("{tenantId}", System.Uri.EscapeDataString(tenantId));
-            _url = _url.Replace("{topicName}", System.Uri.EscapeDataString(topicName));
+            // Construct URL
+            var _urlTemplate = "api/Request/{tenantId}/{topicName}";
+            string _url = CreateUrl(tenantId, topicName, _urlTemplate);
+
             List<string> _queryParameters = new List<string>();
             if (subscriber != null)
             {
@@ -115,12 +114,184 @@
             HttpResponseMessage _httpResponse = null;
             _httpRequest.Method = new HttpMethod("GET");
             _httpRequest.RequestUri = new System.Uri(_url);
+            // Set Headers
+            AddCustomHeaders(customHeaders, _httpRequest);
+
+            // Serialize Request
+            string _requestContent = null;
+            // Send Request
+            if (_shouldTrace)
+            {
+                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
+            }
+            cancellationToken.ThrowIfCancellationRequested();
+            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
+            if (_shouldTrace)
+            {
+                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
+            }
+            HttpStatusCode _statusCode = _httpResponse.StatusCode;
+            cancellationToken.ThrowIfCancellationRequested();
+            HttpOperationResponse<object> _result = await GetResult(_shouldTrace, _invocationId, _httpRequest, _httpResponse, _requestContent, _statusCode);
+            return _result;
+        }
+
+        /// <param name='tenantId'>
+        /// </param>
+        /// <param name='topicName'>
+        /// </param>
+        /// <param name='customHeaders'>
+        /// Headers that will be added to request.
+        /// </param>
+        /// <param name='cancellationToken'>
+        /// The cancellation token.
+        /// </param>
+        /// <exception cref="HttpOperationException">
+        /// Thrown when the operation returned an invalid status code
+        /// </exception>
+        /// <exception cref="SerializationException">
+        /// Thrown when unable to deserialize the response
+        /// </exception>
+        /// <exception cref="ValidationException">
+        /// Thrown when a required parameter is null
+        /// </exception>
+        /// <exception cref="System.ArgumentNullException">
+        /// Thrown when a required parameter is null
+        /// </exception>
+        /// <return>
+        /// A response object containing the response body and response headers.
+        /// </return>
+        public async Task<HttpOperationResponse<object>> PostWithHttpMessagesAsync(string tenantId, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
+        {
+            if (tenantId == null)
+            {
+                throw new ValidationException(ValidationRules.CannotBeNull, "tenantId");
+            }
+            if (topicName == null)
+            {
+                throw new ValidationException(ValidationRules.CannotBeNull, "topicName");
+            }
+            // Tracing
+            bool _shouldTrace = ServiceClientTracing.IsEnabled;
+            string _invocationId = null;
+            if (_shouldTrace)
+            {
+                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
+                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
+                tracingParameters.Add("tenantId", tenantId);
+                tracingParameters.Add("topicName", topicName);
+                tracingParameters.Add("cancellationToken", cancellationToken);
+                ServiceClientTracing.Enter(_invocationId, this, "Post", tracingParameters);
+            }
+            // Construct URL
+            var _urlTemplate = "api/Request/{tenantId}/{topicName}";
+            string _url = CreateUrl(tenantId, topicName, _urlTemplate);
+
+            // Create HTTP transport objects
+            var _httpRequest = new HttpRequestMessage();
+            HttpResponseMessage _httpResponse = null;
+            _httpRequest.Method = new HttpMethod("POST");
+            _httpRequest.RequestUri = new System.Uri(_url);
+
+            // Set Headers
+            AddCustomHeaders(customHeaders, _httpRequest);
+
+            // Serialize Request
+            string _requestContent = null;
+            // Send Request
+            if (_shouldTrace)
+            {
+                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
+            }
+            cancellationToken.ThrowIfCancellationRequested();
+            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
+            if (_shouldTrace)
+            {
+                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
+            }
+            HttpStatusCode _statusCode = _httpResponse.StatusCode;
+            cancellationToken.ThrowIfCancellationRequested();
+            HttpOperationResponse<object> _result = await GetResult(_shouldTrace, _invocationId, _httpRequest, _httpResponse, _requestContent, _statusCode);
+            return _result;
+        }
+
+        /// <param name='tenantId'>
+        /// </param>
+        /// <param name='customHeaders'>
+        /// Headers that will be added to request.
+        /// </param>
+        /// <param name='cancellationToken'>
+        /// The cancellation token.
+        /// </param>
+        /// <exception cref="HttpOperationException">
+        /// Thrown when the operation returned an invalid status code
+        /// </exception>
+        /// <exception cref="SerializationException">
+        /// Thrown when unable to deserialize the response
+        /// </exception>
+        /// <exception cref="ValidationException">
+        /// Thrown when a required parameter is null
+        /// </exception>
+        /// <exception cref="System.ArgumentNullException">
+        /// Thrown when a required parameter is null
+        /// </exception>
+        /// <return>
+        /// A response object containing the response body and response headers.
+        /// </return>
+        public async Task<HttpOperationResponse<object>> GetTopicsWithHttpMessagesAsync(string tenantId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
+        {
+            if (tenantId == null)
+            {
+                throw new ValidationException(ValidationRules.CannotBeNull, "tenantId");
+            }
+            // Tracing
+            bool _shouldTrace = ServiceClientTracing.IsEnabled;
+            string _invocationId = null;
+            if (_shouldTrace)
+            {
+                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
+                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
+                tracingParameters.Add("tenantId", tenantId);
+                tracingParameters.Add("cancellationToken", cancellationToken);
+                ServiceClientTracing.Enter(_invocationId, this, "GetTopics", tracingParameters);
+            }
+            // Construct URL
+            var _urlTemplate = "api/Request/{tenantId}";
+            string _url = CreateUrl(tenantId, "", _urlTemplate);
+
+            // Create HTTP transport objects
+            var _httpRequest = new HttpRequestMessage();
+            HttpResponseMessage _httpResponse = null;
+            _httpRequest.Method = new HttpMethod("GET");
+            _httpRequest.RequestUri = new System.Uri(_url);
+
             // Set Headers
-
-
+            AddCustomHeaders(customHeaders, _httpRequest);
+
+            // Serialize Request
+            string _requestContent = null;
+            // Send Request
+            if (_shouldTrace)
+            {
+                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
+            }
+            cancellationToken.ThrowIfCancellationRequested();
+            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
+            if (_shouldTrace)
+            {
+                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
+            }
+            HttpStatusCode _statusCode = _httpResponse.StatusCode;
+            cancellationToken.ThrowIfCancellationRequested();
+            HttpOperationResponse<object> _result = await GetResult(_shouldTrace, _invocationId, _httpRequest, _httpResponse, _requestContent, _statusCode);
+            return _result;
+        }
+
+        private static void AddCustomHeaders(Dictionary<string, List<string>> customHeaders, HttpRequestMessage _httpRequest)
+        {
             if (customHeaders != null)
             {
-                foreach(var _header in customHeaders)
+                foreach (var _header in customHeaders)
                 {
                     if (_httpRequest.Headers.Contains(_header.Key))
                     {
@@ -129,30 +300,30 @@
                     _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                 }
             }
-
-            // Serialize Request
-            string _requestContent = null;
-            // Send Request
-            if (_shouldTrace)
-            {
-                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
-            }
-            cancellationToken.ThrowIfCancellationRequested();
-            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
-            if (_shouldTrace)
-            {
-                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
-            }
-            HttpStatusCode _statusCode = _httpResponse.StatusCode;
-            cancellationToken.ThrowIfCancellationRequested();
+        }
+
+        private string CreateUrl(string tenantId, string topicName, string _urlTemplate)
+        {
+            // TODO: pass dictionary with parameters
+            var _baseUrl = Client.BaseUri.AbsoluteUri;
+            var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), _urlTemplate).ToString();
+            _url = _url.Replace("{tenantId}", System.Uri.EscapeDataString(tenantId));
+            _url = _url.Replace("{topicName}", System.Uri.EscapeDataString(topicName));
+            return _url;
+        }
+
+        private async Task<HttpOperationResponse<object>> GetResult(bool _shouldTrace, string _invocationId, HttpRequestMessage _httpRequest, HttpResponseMessage _httpResponse, string _requestContent, HttpStatusCode _statusCode)
+        {
             string _responseContent = null;
             if ((int)_statusCode != 200)
             {
                 var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
-                if (_httpResponse.Content != null) {
+                if (_httpResponse.Content != null)
+                {
                     _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                 }
-                else {
+                else
+                {
                     _responseContent = string.Empty;
                 }
                 ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
@@ -194,278 +365,10 @@
             {
                 ServiceClientTracing.Exit(_invocationId, _result);
             }
+
             return _result;
         }

-        /// <param name='tenantId'>
-        /// </param>
-        /// <param name='topicName'>
-        /// </param>
-        /// <param name='customHeaders'>
-        /// Headers that will be added to request.
-        /// </param>
-        /// <param name='cancellationToken'>
-        /// The cancellation token.
-        /// </param>
-        /// <exception cref="HttpOperationException">
-        /// Thrown when the operation returned an invalid status code
-        /// </exception>
-        /// <exception cref="SerializationException">
-        /// Thrown when unable to deserialize the response
-        /// </exception>
-        /// <exception cref="ValidationException">
-        /// Thrown when a required parameter is null
-        /// </exception>
-        /// <exception cref="System.ArgumentNullException">
-        /// Thrown when a required parameter is null
-        /// </exception>
-        /// <return>
-        /// A response object containing the response body and response headers.
-        /// </return>
-        public async Task<HttpOperationResponse<object>> PostWithHttpMessagesAsync(string tenantId, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
-        {
-            if (tenantId == null)
-            {
-                throw new ValidationException(ValidationRules.CannotBeNull, "tenantId");
-            }
-            if (topicName == null)
-            {
-                throw new ValidationException(ValidationRules.CannotBeNull, "topicName");
-            }
-            // Tracing
-            bool _shouldTrace = ServiceClientTracing.IsEnabled;
-            string _invocationId = null;
-            if (_shouldTrace)
-            {
-                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
-                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
-                tracingParameters.Add("tenantId", tenantId);
-                tracingParameters.Add("topicName", topicName);
-                tracingParameters.Add("cancellationToken", cancellationToken);
-                ServiceClientTracing.Enter(_invocationId, this, "Post", tracingParameters);
-            }
-            // Construct URL
-            var _baseUrl = Client.BaseUri.AbsoluteUri;
-            var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Request/{tenantId}/{topicName}").ToString();
-            _url = _url.Replace("{tenantId}", System.Uri.EscapeDataString(tenantId));
-            _url = _url.Replace("{topicName}", System.Uri.EscapeDataString(topicName));
-            // Create HTTP transport objects
-            var _httpRequest = new HttpRequestMessage();
-            HttpResponseMessage _httpResponse = null;
-            _httpRequest.Method = new HttpMethod("POST");
-            _httpRequest.RequestUri = new System.Uri(_url);
-            // Set Headers
-
-
-            if (customHeaders != null)
-            {
-                foreach(var _header in customHeaders)
-                {
-                    if (_httpRequest.Headers.Contains(_header.Key))
-                    {
-                        _httpRequest.Headers.Remove(_header.Key);
-                    }
-                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
-                }
-            }
-
-            // Serialize Request
-            string _requestContent = null;
-            // Send Request
-            if (_shouldTrace)
-            {
-                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
-            }
-            cancellationToken.ThrowIfCancellationRequested();
-            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
-            if (_shouldTrace)
-            {
-                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
-            }
-            HttpStatusCode _statusCode = _httpResponse.StatusCode;
-            cancellationToken.ThrowIfCancellationRequested();
-            string _responseContent = null;
-            if ((int)_statusCode != 200)
-            {
-                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
-                if (_httpResponse.Content != null) {
-                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
-                }
-                else {
-                    _responseContent = string.Empty;
-                }
-                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
-                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
-                if (_shouldTrace)
-                {
-                    ServiceClientTracing.Error(_invocationId, ex);
-                }
-                _httpRequest.Dispose();
-                if (_httpResponse != null)
-                {
-                    _httpResponse.Dispose();
-                }
-                throw ex;
-            }
-            // Create Result
-            var _result = new HttpOperationResponse<object>();
-            _result.Request = _httpRequest;
-            _result.Response = _httpResponse;
-            // Deserialize Response
-            if ((int)_statusCode == 200)
-            {
-                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
-                try
-                {
-                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<object>(_responseContent, Client.DeserializationSettings);
-                }
-                catch (JsonException ex)
-                {
-                    _httpRequest.Dispose();
-                    if (_httpResponse != null)
-                    {
-                        _httpResponse.Dispose();
-                    }
-                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
-                }
-            }
-            if (_shouldTrace)
-            {
-                ServiceClientTracing.Exit(_invocationId, _result);
-            }
-            return _result;
-        }
-
-        /// <param name='tenantId'>
-        /// </param>
-        /// <param name='customHeaders'>
-        /// Headers that will be added to request.
-        /// </param>
-        /// <param name='cancellationToken'>
-        /// The cancellation token.
-        /// </param>
-        /// <exception cref="HttpOperationException">
-        /// Thrown when the operation returned an invalid status code
-        /// </exception>
-        /// <exception cref="SerializationException">
-        /// Thrown when unable to deserialize the response
-        /// </exception>
-        /// <exception cref="ValidationException">
-        /// Thrown when a required parameter is null
-        /// </exception>
-        /// <exception cref="System.ArgumentNullException">
-        /// Thrown when a required parameter is null
-        /// </exception>
-        /// <return>
-        /// A response object containing the response body and response headers.
-        /// </return>
-        public async Task<HttpOperationResponse<object>> GetTopicsWithHttpMessagesAsync(string tenantId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
-        {
-            if (tenantId == null)
-            {
-                throw new ValidationException(ValidationRules.CannotBeNull, "tenantId");
-            }
-            // Tracing
-            bool _shouldTrace = ServiceClientTracing.IsEnabled;
-            string _invocationId = null;
-            if (_shouldTrace)
-            {
-                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
-                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
-                tracingParameters.Add("tenantId", tenantId);
-                tracingParameters.Add("cancellationToken", cancellationToken);
-                ServiceClientTracing.Enter(_invocationId, this, "GetTopics", tracingParameters);
-            }
-            // Construct URL
-            var _baseUrl = Client.BaseUri.AbsoluteUri;
-            var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Request/{tenantId}").ToString();
-            _url = _url.Replace("{tenantId}", System.Uri.EscapeDataString(tenantId));
-            // Create HTTP transport objects
-            var _httpRequest = new HttpRequestMessage();
-            HttpResponseMessage _httpResponse = null;
-            _httpRequest.Method = new HttpMethod("GET");
-            _httpRequest.RequestUri = new System.Uri(_url);
-            // Set Headers
-
-
-            if (customHeaders != null)
-            {
-                foreach(var _header in customHeaders)
-                {
-                    if (_httpRequest.Headers.Contains(_header.Key))
-                    {
-                        _httpRequest.Headers.Remove(_header.Key);
-                    }
-                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
-                }
-            }
-
-            // Serialize Request
-            string _requestContent = null;
-            // Send Request
-            if (_shouldTrace)
-            {
-                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
-            }
-            cancellationToken.ThrowIfCancellationRequested();
-            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
-            if (_shouldTrace)
-            {
-                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
-            }
-            HttpStatusCode _statusCode = _httpResponse.StatusCode;
-            cancellationToken.ThrowIfCancellationRequested();
-            string _responseContent = null;
-            if ((int)_statusCode != 200)
-            {
-                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
-                if (_httpResponse.Content != null) {
-                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
-                }
-                else {
-                    _responseContent = string.Empty;
-                }
-                ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
-                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
-                if (_shouldTrace)
-                {
-                    ServiceClientTracing.Error(_invocationId, ex);
-                }
-                _httpRequest.Dispose();
-                if (_httpResponse != null)
-                {
-                    _httpResponse.Dispose();
-                }
-                throw ex;
-            }
-            // Create Result
-            var _result = new HttpOperationResponse<object>();
-            _result.Request = _httpRequest;
-            _result.Response = _httpResponse;
-            // Deserialize Response
-            if ((int)_statusCode == 200)
-            {
-                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
-                try
-                {
-                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<object>(_responseContent, Client.DeserializationSettings);
-                }
-                catch (JsonException ex)
-                {
-                    _httpRequest.Dispose();
-                    if (_httpResponse != null)
-                    {
-                        _httpResponse.Dispose();
-                    }
-                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
-                }
-            }
-            if (_shouldTrace)
-            {
-                ServiceClientTracing.Exit(_invocationId, _result);
-            }
-            return _result;
-        }

     }
 }


A simpler patch As noted in email today, WebResponse is IDisposable Dispose() is preferred over Close()

--- src/SevenDigital.Api.Wrapper/Http/HttpClientWrapper.cs
+++ src/SevenDigital.Api.Wrapper/Http/HttpClientWrapper.cs
@@ -12,22 +12,10 @@
 		public Response Get(GetRequest request)
 		{
 			var webRequest = MakeWebRequest(request.Url, "GET", request.Headers);
-
-			WebResponse webResponse;
-			try
+			using (var webResponse = GetWebResponse(webRequest))
 			{
-				webResponse = webRequest.GetResponse();
+				return MakeResponse(webResponse);
 			}
-			catch (WebException ex)
-			{
-				if (ex.Response == null)
-				{
-					throw;
-				}
-				webResponse = ex.Response;
-			}
-
-			return MakeResponse(webResponse);
 		}

 		public void GetAsync(GetRequest request, Action<Response> callback)
@@ -36,46 +24,22 @@
 			webRequest.BeginGetResponse(iar => callback(GetAsyncResponse(iar)), webRequest);
 		}

+
 		private Response GetAsyncResponse(IAsyncResult iar)
 		{
-			var webRequest = (WebRequest)iar.AsyncState;
-
-			WebResponse webResponse;
-			try
+			using (var webResponse = GetWebResponseAsync(iar))
 			{
-				webResponse = webRequest.EndGetResponse(iar);
+				return MakeResponse(webResponse);
 			}
-			catch (WebException ex)
-			{
-				if (ex.Response == null)
-				{
-					throw;
-				}
-				webResponse = ex.Response;
-			}
-
-			return MakeResponse(webResponse);
 		}

 		public Response Post(PostRequest request)
 		{
 			var webRequest = MakePostRequest(request);
-
-			WebResponse webResponse;
-			try
+			using (var webResponse = GetWebResponse(webRequest))
 			{
-				webResponse = webRequest.GetResponse();
+				return MakeResponse(webResponse);
 			}
-			catch (WebException ex)
-			{
-				if (ex.Response == null)
-				{
-					throw;
-				}
-				webResponse = ex.Response;
-			}
-
-			return MakeResponse(webResponse);
 		}

 		public void PostAsync(PostRequest request, Action<Response> callback)
@@ -84,6 +48,42 @@

 			webRequest.BeginGetResponse(iar => callback(GetAsyncResponse(iar)), webRequest);
 		}
+
+		private WebResponse GetWebResponse(WebRequest webRequest)
+		{
+			try
+			{
+				return webRequest.GetResponse();
+			}
+			catch (WebException ex)
+			{
+				if (ex.Response == null)
+				{
+					throw;
+				}
+
+				return ex.Response;
+			}
+		}
+
+		private static WebResponse GetWebResponseAsync(IAsyncResult iar)
+		{
+			var webRequest = (WebRequest)iar.AsyncState;
+
+			try
+			{
+				return webRequest.EndGetResponse(iar);
+			}
+			catch (WebException ex)
+			{
+				if (ex.Response == null)
+				{
+					throw;
+				}
+				return ex.Response;
+			}
+		}
+

 		private static HttpWebRequest MakeWebRequest(string url, string method, IDictionary<string, string> headers)
 		{
@@ -109,11 +109,7 @@
 			var statusCode = ReadStatusCode(webResponse);
 			var headers = MapHeaders(webResponse.Headers);

-			var response = new Response(statusCode, headers, output);
-
-			webResponse.Close();
-
-			return response;
+			return new Response(statusCode, headers, output);
 		}

 		private static HttpWebRequest MakePostRequest(PostRequest request)
@@ -146,7 +142,7 @@

 		private static HttpStatusCode ReadStatusCode(WebResponse webResponse)
 		{
-			HttpWebResponse httpResponse = webResponse as HttpWebResponse;
+			var httpResponse = webResponse as HttpWebResponse;
 			if (httpResponse == null)
 			{
 				return HttpStatusCode.NoContent;


Convert some deferred executions into immediate ones

--- src/Simple.OData.Client.V4.Adapter/CommandFormatter.cs
+++ src/Simple.OData.Client.V4.Adapter/CommandFormatter.cs
@@ -137,7 +137,7 @@
                 {
                     if (excludePaths.Count == 1 && excludePaths[0] == StarString)
                     {
-                        var firstSegmentPropertyNames = _session.Metadata.GetNavigationPropertyNames(collection.Name).Select(x => FormatFirstSegment(x));
+                        var firstSegmentPropertyNames = new HashSet<string>(_session.Metadata.GetNavigationPropertyNames(collection.Name).Select(x => FormatFirstSegment(x)));
                         resultColumns.AddRange(columns.Where(x => HasMultipleSegments(x) && !firstSegmentPropertyNames.Any(y => y.Contains(FormatFirstSegment(x)))));
                     }
                     else
@@ -153,7 +153,7 @@
                 var firstSegment = FormatFirstSegment(path);
                 if (firstSegment == StarString)
                 {
-                    var propertyNames = _session.Metadata.GetNavigationPropertyNames(collection.Name);
+                    var propertyNames = new HashSet<string>(_session.Metadata.GetNavigationPropertyNames(collection.Name));
                     return columns
                         .Where(x => HasMultipleSegments(x) && propertyNames.Contains(FormatFirstSegment(x)))
                         .Select(x => FormatSkipSegments(x, 1)).ToList();
@@ -177,7 +177,7 @@
                 {
                     if (excludePaths.Count == 1 && excludePaths[0] == StarString)
                     {
-                        var firstSegmentPropertyNames = _session.Metadata.GetNavigationPropertyNames(collection.Name).Select(x => FormatFirstSegment(x));
+                        var firstSegmentPropertyNames = new HashSet<string>(_session.Metadata.GetNavigationPropertyNames(collection.Name).Select(x => FormatFirstSegment(x)));
                         resultColumns.AddRange(columns.Where(x => HasMultipleSegments(x) && !firstSegmentPropertyNames.Any(y => y.Contains(FormatFirstSegment(x)))));
                     }
                     else
@@ -193,7 +193,7 @@
                 var firstSegment = FormatFirstSegment(path);
                 if (firstSegment == StarString)
                 {
-                    var propertyNames = _session.Metadata.GetNavigationPropertyNames(collection.Name);
+                    var propertyNames = new HashSet<string>(_session.Metadata.GetNavigationPropertyNames(collection.Name));
                     return columns
                         .Where(x => HasMultipleSegments(x) && propertyNames.Contains(FormatFirstSegment(x)))
                         .Select(x => new KeyValuePair<string, bool>(FormatSkipSegments(x, 1), x.Value)).ToList();


Update binary version in Unity installation script.

PiperOrigin-RevId: 435178219
Change-Id: I0cf372bc5e42aa585dbf2ce60f97ea7fcec2595f

--- unity/Runtime/Bindings/MujocoBinaryRetriever.cs
+++ unity/Runtime/Bindings/MujocoBinaryRetriever.cs
@@ -35,7 +35,7 @@
       if (AssetDatabase.LoadMainAssetAtPath(mujocoPath + "/mujoco.dylib") == null) {
         File.Copy(
             "/Applications/MuJoCo.app/Contents/Frameworks" +
-            "/MuJoCo.framework/Versions/Current/libmujoco.2.1.1.dylib",
+            "/MuJoCo.framework/Versions/Current/libmujoco.2.1.2.dylib",
             mujocoPath + "/mujoco.dylib");
         AssetDatabase.Refresh();
       }
@@ -43,7 +43,7 @@
       if (AssetDatabase.LoadMainAssetAtPath(mujocoPath + "/libmujoco.so") == null) {
         File.Copy(
             Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
-            "/.mujoco/mujoco-2.1.1/lib/libmujoco_nogl.so.2.1.1",
+            "/.mujoco/mujoco-2.1.2/lib/libmujoco_nogl.so.2.1.2",
             mujocoPath + "/libmujoco.so");
         AssetDatabase.Refresh();
       }


More tricky test cases

More tricky test cases


Updated version #.

Updated version #.

--- SharedAssemblyVersion.cs
+++ SharedAssemblyVersion.cs
@@ -18,5 +18,5 @@

 using System.Reflection;

-[assembly: AssemblyVersion("1.1.0")]
-[assembly: AssemblyInformationalVersion("1.1.0-pre11")]+[assembly: AssemblyVersion("1.2.0")]
+[assembly: AssemblyInformationalVersion("1.2.0-pre01")]


Added an additional check to GetGroupPeerPublicKey

--- SharpTox/Core/Tox.cs
+++ SharpTox/Core/Tox.cs
@@ -1320,7 +1320,10 @@
                 throw new ObjectDisposedException(GetType().FullName);

             byte[] key = new byte[ToxConstants.ClientIdSize];
-            ToxFunctions.GroupPeerPubkey(_tox, groupNumber, peerNumber, key);
+            int result = ToxFunctions.GroupPeerPubkey(_tox, groupNumber, peerNumber, key);
+
+            if (result != 0)
+                return null;

             return new ToxKey(ToxKeyType.Public, key);
         }


Add missed KIS messages

Add missed KIS messages

--- Source/Controller.cs
+++ Source/Controller.cs
@@ -60,6 +60,8 @@
   Message VesselIsNotControllableMsg = "Is NOT controllable";
   Message<CameraStabilization> CameraStabilizationModeChanged = "EVS stabilization: {0}";
   Message<float> DistantVesselTargeted = "Vessel is too distant: {0:N0}m";
+  Message vesselIsAttachedToTheGroundMsg = "IS attached to the ground";
+  Message vesselIsNotAttachedToTheGroundMsg = "Is NOT attached to the ground";
   // ===== END of localizable strings

   /// <summary>A mode of camera stabilization.</summary>


Fixed crash in PICSChanges.cs (#8)

Fixed crash in PICSChanges.cs (#8)

The Log.WriteWarn() on line 68 would cause a crash due to incorrect number of parameters.

--- Steam/PICSChanges.cs
+++ Steam/PICSChanges.cs
@@ -65,7 +65,7 @@
             if (PreviousChangeNumber == 0)
             {
                 Log.WriteWarn("PICSChanges", "Looks like there are no changelists in the database.");
-                Log.WriteWarn("PICSChanges", "If you want to fill up your database first, restart with \"FullRun\" setting set to {1}.", (int)FullRunState.Enumerate);
+                Log.WriteWarn("PICSChanges", "If you want to fill up your database first, restart with \"FullRun\" setting set to {0}.", (int)FullRunState.Enumerate);
             }
         }


Fix for new API

Fix for new API

--- SteamTrade/Schema.cs
+++ SteamTrade/Schema.cs
@@ -15,7 +15,7 @@
     public class Schema
     {
         private const string SchemaMutexName = "steam_bot_cache_file_mutex";
-        private const string SchemaApiUrlBase = "http://api.steampowered.com/IEconItems_440/GetSchema/v0001/?key=";
+        private const string SchemaApiUrlBase = "https://api.steampowered.com/IEconItems_440/GetSchemaItems/v1/?key=";
         private const string cachefile = "tf_schema.cache";

         /// <summary>
@@ -30,7 +30,7 @@
         {
             var url = SchemaApiUrlBase + apiKey;
             if (schemaLang != null)
-                url += "&language=" + schemaLang;
+                url += "&format=json&language=" + schemaLang;

             // just let one thread/proc do the initial check/possible update.
             bool wasCreated;
@@ -49,18 +49,38 @@
                 }
             }

-            using(HttpWebResponse response = new SteamWeb().Request(url, "GET"))
-            {
-                DateTime schemaLastModified = response.LastModified;
-
-                string result = GetSchemaString(response, schemaLastModified);
-
-                // were done here. let others read.
-                mre.Set();
-
-                SchemaResult schemaResult = JsonConvert.DeserializeObject<SchemaResult>(result);
-                return schemaResult.result ?? null;
-            }
+            bool keepUpdating = true;
+            SchemaResult schemaResult = new SchemaResult();
+            string tmpUrl = url;
+
+            do
+            {
+                if(schemaResult.result != null)
+                    tmpUrl = url + "&start=" + schemaResult.result.Next;
+
+                string result = new SteamWeb().Fetch(tmpUrl, "GET");
+
+                if (schemaResult.result == null || schemaResult.result.Items == null)
+                {
+                    schemaResult = JsonConvert.DeserializeObject<SchemaResult>(result);
+                }
+                else
+                {
+                    SchemaResult tempResult = JsonConvert.DeserializeObject<SchemaResult>(result);
+                    var items = schemaResult.result.Items.Concat(tempResult.result.Items);
+                    schemaResult.result.Items = items.ToArray();
+                    schemaResult.result.Next = tempResult.result.Next;
+                }
+
+                if (schemaResult.result.Next <= schemaResult.result.Items.Count())
+                    keepUpdating = false;
+            } while (keepUpdating);
+
+            // were done here. let others read.
+            mre.Set();
+            DateTime schemaLastModified = DateTime.Now;
+
+            return schemaResult.result ?? null;
         }

         // Gets the schema from the web or from the cached file.


Now it ignores If on attributes too

Now it ignores If on attributes too

--- SuperXML/Compiler.cs
+++ SuperXML/Compiler.cs
@@ -345,7 +345,7 @@
                             if (!If()) continue;
                             var isTemplate = Name == TemplateKey;
                             if (!isTemplate) writer.WriteStartElement(Name);
-                            foreach (var attribute in Attributes.Where(attribute => attribute.Name != RepeaterKey))
+                            foreach (var attribute in Attributes.Where(attribute => attribute.Name != RepeaterKey && attribute.Name != IfKey))
                             {
                                 writer.WriteAttributeString(attribute.Name, Inject(attribute.Value));
                             }


Optimized bold(), italic() and underline() methods to prevent necessary for loops.

--- TextPoint/FRMMain.cs
+++ TextPoint/FRMMain.cs
@@ -478,14 +478,28 @@
         }
         private void Italic()
         {
-            if (RTBText.SelectionFont == null) { ChangeFormat("Italic", "unknown"); }
+            if (RTBText.SelectionFont != null && SameSizeSelection())
+            {
+                var style = RTBText.SelectionFont.Style;
+                if (!RTBText.SelectionFont.Italic) { style = style | FontStyle.Italic; }
+                else { style = style & ~FontStyle.Italic; }
+                RTBText.SelectionFont = new Font(RTBText.SelectionFont, style);
+            }
+            else if (RTBText.SelectionFont == null) { ChangeFormat("Italic", "unknown"); }
             else if (ItalicCheckboxBtn.Checked) { ChangeFormat("Italic", "italic"); }
             else { ChangeFormat("Italic", "notitalic"); }
             RTBText.Focus();
         }
         private void Underline()
         {
-            if (RTBText.SelectionFont == null) { ChangeFormat("Underline", "unknown"); }
+            if (RTBText.SelectionFont != null && SameSizeSelection())
+            {
+                var style = RTBText.SelectionFont.Style;
+                if (!RTBText.SelectionFont.Underline) { style = style | FontStyle.Underline; }
+                else { style = style & ~FontStyle.Underline; }
+                RTBText.SelectionFont = new Font(RTBText.SelectionFont, style);
+            }
+            else if (RTBText.SelectionFont == null) { ChangeFormat("Underline", "unknown"); }
             else if (UnderlineCheckboxBtn.Checked) { ChangeFormat("Underline", "underline"); }
             else { ChangeFormat("Underline", "notunderline"); }
             RTBText.Focus();


Change the GUI for commendations

Change the GUI for commendations

--- Titan/UI/MainForm.cs
+++ Titan/UI/MainForm.cs
@@ -19,6 +19,7 @@
         private readonly DropDown _dropDown;
         private readonly TextBox _targetBox;
         private readonly TextBox _matchIDBox;
+        private readonly Label _matchIDLabel;

         public MainForm()
         {
@@ -30,7 +31,11 @@
             // Selected arguments for the UI
             _targetBox = new TextBox { PlaceholderText = "STEAM_0:0:131983088" };
             _matchIDBox = new TextBox { PlaceholderText = "3203363151840018511" };
+            _matchIDLabel = new Label { Text = "Match ID" };
+
             _dropDown = new DropDown { Items = { "Report", "Commend" }, SelectedIndex = 0 };
+            _dropDown.SelectedIndexChanged += OnDropDownIndexChange;
+
             var bombBtn = new Button { Text = "Bomb!" };
             bombBtn.Click += OnBombButtonClick;

@@ -49,7 +54,7 @@
                         _targetBox
                     ),
                     new TableRow(
-                        new Label { Text = "Match ID" },
+                        _matchIDLabel,
                         _matchIDBox
                     ),
                     new TableRow(new TableCell(), new TableCell()),
@@ -103,7 +108,25 @@
             }
             else
             {
-                MessageBox.Show("Please provide the Target and the Match ID.", "Error - Titan", MessageBoxType.Error);
+                MessageBox.Show(
+                    mode == BotMode.Commend
+                        ? "Please provide the Target."
+                        : "Please provide the Target and the Match ID.", "Error - Titan",
+                    MessageBoxType.Error);
+            }
+        }
+
+        public void OnDropDownIndexChange(object sender, EventArgs args)
+        {
+            if(_dropDown.SelectedIndex == 0)
+            {
+                _matchIDLabel.Visible = true;
+                _matchIDBox.Visible = true;
+            }
+            else if(_dropDown.SelectedIndex == 1)
+            {
+                _matchIDLabel.Visible = false;
+                _matchIDBox.Visible = false;
             }
         }


Remove, using statements

Remove, using statements

Removed unused using statements

--- TryRetry/TryRetry.cs
+++ TryRetry/TryRetry.cs
@@ -1,8 +1,5 @@
 using System;
 using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;

 namespace TryRetry
 {


clean up TODO

clean up TODO

--- code/SoftwareThresher/SoftwareThresher/Tasks/NotReferenced.cs
+++ code/SoftwareThresher/SoftwareThresher/Tasks/NotReferenced.cs
@@ -5,7 +5,6 @@

 namespace SoftwareThresher.Tasks {
    public class NotReferenced : Task {
-      // TODO - Can we build into the base to just return the class name?
       public override string DefaultReportHeaderText => "Not Referenced";

       readonly Search search;


Derive MovesTextBox from ScintillaEx, which duplicates a bit of code but MovesTextBox was never intended to be editable anyway.

--- Sandra.UI/MovesTextBox.cs
+++ Sandra.UI/MovesTextBox.cs
@@ -36,7 +36,7 @@
     /// <summary>
     /// Represents a read-only Windows rich text box which displays a list of chess moves.
     /// </summary>
-    public partial class MovesTextBox : SyntaxEditor<IPGNTerminalSymbol>
+    public partial class MovesTextBox : ScintillaEx
     {
         private const int activeMoveStyleIndex = 8;

@@ -47,12 +47,25 @@
         private static readonly Color activeMoveForeColor = Color.DarkRed;
         private static readonly Font activeMoveFont = new Font("Candara", 10, FontStyle.Bold);

+        private readonly TextIndex<IPGNTerminalSymbol> TextIndex;
+
+        private Style DefaultStyle => Styles[Style.Default];
         private Style ActiveMoveStyle => Styles[activeMoveStyleIndex];

+        private void ApplyStyle(TextElement<IPGNTerminalSymbol> element, Style style)
+            => ApplyStyle(style, element.Start, element.Length);
+
         private int CaretPosition;

         public MovesTextBox()
         {
+            TextIndex = new TextIndex<IPGNTerminalSymbol>();
+
+            HScrollBar = false;
+            VScrollBar = true;
+
+            Margins.ForEach(x => x.Width = 0);
+
             BorderStyle = BorderStyle.None;
             ReadOnly = true;
             WrapMode = WrapMode.Whitespace;


clean up

clean up

--- Sensus.Shared/Protocol.cs
+++ Sensus.Shared/Protocol.cs
@@ -2077,17 +2077,6 @@

             if (completedInputs != null)
             {
-                var selectedProbeObjs = completedInputs.Where(w => w.GetType() == typeof(ItemPickerPageInput)).FirstOrDefault()?.Value as List<object>;
-                _probesSelectedOnStartUp = selectedProbeObjs?.Select(s => s.ToString())?.ToList() ?? new List<string>();
-                if (AllowProbeDisableOnStartUp == true)
-                {
-                    if (selectedProbeObjs.Count == 0)
-                    {
-                        await SensusServiceHelper.Get().FlashNotificationAsync("You must select at least one probe to include in this study.  Cannot Start.");
-                        start = false;
-                    }
-                }
-                enabledProbes.ForEach(e => e.Selected = _probesSelectedOnStartUp == null || _probesSelectedOnStartUp.Contains(e.DisplayName));

                 if (_startConfirmationMode == ProtocolStartConfirmationMode.None || !string.IsNullOrWhiteSpace(_participantId))
                 {
@@ -2142,6 +2131,19 @@
                         start = true;
                     }
                 }
+
+                var selectedProbeObjs = completedInputs.Where(w => w.GetType() == typeof(ItemPickerPageInput)).FirstOrDefault()?.Value as List<object>;
+                _probesSelectedOnStartUp = selectedProbeObjs?.Select(s => s.ToString())?.ToList();
+                if (AllowProbeDisableOnStartUp == true)
+                {
+                    if (selectedProbeObjs.Count == 0)
+                    {
+                        await SensusServiceHelper.Get().FlashNotificationAsync("You must select at least one probe to include in this study.  Cannot Start.");
+                        start = false;
+                    }
+                }
+                enabledProbes.ForEach(e => e.Selected = _probesSelectedOnStartUp == null || _probesSelectedOnStartUp.Contains(e.DisplayName));
+
             }

             if (start)


(TFS CS 3179)

(TFS CS 3179)

--- Signum.Web/AppSettings.cs
+++ Signum.Web/AppSettings.cs
@@ -25,5 +25,6 @@
         public const string UseCaptcha = "sfUseCaptcha";    //"1" if we wish to use captcha
         public const string Development = "sfDevelopment";  //"1" if development scenario
         public const string MergeScriptsBottom = "sfMergeScriptsBottom"; //"1" if we want to merge the scripts included by controls and partial views merged at bottom
+        public const string GoogleAnalytics = "sfGoogleAnalytics"; //Contains the UA-* value
     }
 }


Updates RespondTo to use newRegexPartTwo rather than regexStr.

--- SlackBotRedux.Core/Bot.cs
+++ SlackBotRedux.Core/Bot.cs
@@ -71,7 +71,7 @@

             var newRegexPartOne = String.Format(@"^@?{0}[:,]\s+", Regex.Escape(_botName));
             var newRegexPartTwo = regexStr;
-            var finalRegex = new Regex(newRegexPartOne + regexStr);
+            var finalRegex = new Regex(newRegexPartOne + newRegexPartTwo);

             _listeners.Add(new TextListener(finalRegex, callback));
         }


Fix failure on first launch of unit tests

--- Source/UnitTests/Setup.cs
+++ Source/UnitTests/Setup.cs
@@ -31,7 +31,6 @@
 using log4net.Config;
 using Nini.Config;
 using NUnit.Framework;
-using LibWhipLru.Server;

 namespace UnitTests {
 	[SetUpFixture]
@@ -67,8 +66,18 @@
 			// Read in the ini file
 			configSource.Merge(new IniConfigSource(Constants.INI_PATH));

-			Directory.Delete(DATABASE_FOLDER_PATH, true);
-			File.Delete(WRITE_CACHE_FILE_PATH);
+#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
+			try {
+				Directory.Delete(DATABASE_FOLDER_PATH, true);
+			}
+			catch (Exception) {
+			}
+			try {
+				File.Delete(WRITE_CACHE_FILE_PATH);
+			}
+			catch (Exception) {
+			}
+#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
 			Directory.CreateDirectory(DATABASE_FOLDER_PATH);

 			// Start booting server


Handplacement Update

Handplacement Update

updated the part of the  code that handles putting items in hands, should work better and be more efficient

--- UnityProject/Assets/Scripts/Objects/Canister.cs
+++ UnityProject/Assets/Scripts/Objects/Canister.cs
@@ -227,23 +227,39 @@
 			SetConnectedSprite(null);
 		}
 	}
-
+ 	/// <summary>
+ 	/// Respawns the modified container back into the world
+ 	/// </summary>
 	public void EjectInsertedContainer()
 	{
 		ItemStorage player = networkTab.LastInteractedPlayer().GetComponent<PlayerScript>().ItemStorage;
 		InsertedContainer.GetComponent<CustomNetTransform>().AppearAtPositionServer(gameObject.WorldPosServer());
-		if (player.GetNamedItemSlot(NamedSlot.rightHand) == null)
-		{
-			Inventory.ServerAdd(InsertedContainer, player.GetNamedItemSlot(NamedSlot.rightHand),
-				ReplacementStrategy.DropOther);
-		}
-		else
-		{
-			Inventory.ServerAdd(InsertedContainer, player.GetNamedItemSlot(NamedSlot.leftHand),
-				ReplacementStrategy.DropOther);
-		}
+		HandInsert(player);
 		hasContainerInserted = false;
 		InsertedContainer = null;
 		ServerOnExternalTankInserted.Invoke(false);
 	}
-}+
+	/// <summary>
+	/// Checks to see if it can put it in any hand, if it cant it will do nothing meaning the item should just drop.
+	/// </summary>
+	/// <param name="player"></param>
+	private void HandInsert(ItemStorage player)
+	{
+		ItemSlot activeHand = player.GetActiveHandSlot();
+		if (Inventory.ServerAdd(InsertedContainer, activeHand)) return;
+		switch (activeHand.NamedSlot)
+		{
+			case NamedSlot.leftHand:
+				ItemSlot rSlot = player.GetNamedItemSlot(NamedSlot.rightHand);
+				Inventory.ServerAdd(InsertedContainer, rSlot);
+				break;
+
+			case NamedSlot.rightHand:
+				ItemSlot lSlot= player.GetNamedItemSlot(NamedSlot.leftHand);
+				Inventory.ServerAdd(InsertedContainer, lSlot);
+				break;
+		}
+	}
+}
+


Ignore if addition overflowed because it is irrelevant

--- WalletWasabi/Crypto/SchnorrBlindingSignature.cs
+++ WalletWasabi/Crypto/SchnorrBlindingSignature.cs
@@ -43,7 +43,7 @@
 				var R = rECPubKey.Q.ToGroupElementJacobian();
 				var t = FE.Zero;

-				retry:
+			retry:

 				RandomUtils.GetBytes(tmp);
 				_v = new Scalar(tmp, out int overflow);
@@ -82,8 +82,8 @@
 					goto retry;
 				}

-				var cp = _c.Add(_w.Negate(), out overflow); // this is sent to the signer (blinded message)
-				if (cp.IsZero || overflow != 0)
+				var cp = _c + _w.Negate(); // this is sent to the signer (blinded message)
+				if (cp.IsZero)
 				{
 					goto retry;
 				}


added UpdateThumbValues to setter

added UpdateThumbValues to setter

--- Xamarin.RangeSlider.Droid/RangeSliderControl.cs
+++ Xamarin.RangeSlider.Droid/RangeSliderControl.cs
@@ -576,11 +576,13 @@
         public void SetCustomThumbPressedImage(Bitmap customThumbImage)
         {
             ThumbPressedImage = customThumbImage;
+            UpdateThumbValues();
         }

         public void SetCustomThumbDisabledImage(Bitmap customThumbDisabledImage)
         {
             ThumbDisabledImage = customThumbDisabledImage;
+            UpdateThumbValues();
         }

         /// <summary>


Fix button colors in beatmap options test

--- osu.Game.Tests/Visual/SongSelect/TestSceneBeatmapOptionsOverlay.cs
+++ osu.Game.Tests/Visual/SongSelect/TestSceneBeatmapOptionsOverlay.cs
@@ -3,8 +3,8 @@

 using System.ComponentModel;
 using osu.Framework.Graphics.Sprites;
+using osu.Game.Graphics;
 using osu.Game.Screens.Select.Options;
-using osuTK.Graphics;

 namespace osu.Game.Tests.Visual.SongSelect
 {
@@ -15,10 +15,12 @@
         {
             var overlay = new BeatmapOptionsOverlay();

-            overlay.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, Color4.Purple, null);
-            overlay.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, Color4.Purple, null);
-            overlay.AddButton(@"Delete", @"all difficulties", FontAwesome.Solid.Trash, Color4.Pink, null);
-            overlay.AddButton(@"Edit", @"beatmap", FontAwesome.Solid.PencilAlt, Color4.Yellow, null);
+            var colours = new OsuColour();
+
+            overlay.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, colours.Purple, null);
+            overlay.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, colours.Purple, null);
+            overlay.AddButton(@"Delete", @"all difficulties", FontAwesome.Solid.Trash, colours.Pink, null);
+            overlay.AddButton(@"Edit", @"beatmap", FontAwesome.Solid.PencilAlt, colours.Yellow, null);

             Add(overlay);


Logging for the features executor (#2172)

* logging

* fixes per review

* fix per review

--- src/Stratis.Bitcoin/Builder/FullNodeFeatureExecutor.cs
+++ src/Stratis.Bitcoin/Builder/FullNodeFeatureExecutor.cs
@@ -51,30 +51,40 @@
         /// <inheritdoc />
         public void Initialize()
         {
+            this.logger.LogTrace("()");
+
             try
             {
                 this.Execute(service => service.ValidateDependencies(this.node.Services));
                 this.Execute(service => service.Initialize());
             }
-            catch (Exception ex)
+            catch
             {
-                this.logger.LogError("An error occurred starting the application: {0}", ex);
+                this.logger.LogError("An error occurred starting the application.");
+                this.logger.LogTrace("(-)[INITIALIZE_EXCEPTION]");
                 throw;
             }
+
+            this.logger.LogTrace("(-)");
         }

         /// <inheritdoc />
         public void Dispose()
         {
+            this.logger.LogTrace("()");
+
             try
             {
                 this.Execute(feature => feature.Dispose(), true);
             }
-            catch (Exception ex)
+            catch
             {
-                this.logger.LogError("An error occurred stopping the application", ex);
+                this.logger.LogError("An error occurred stopping the application.");
+                this.logger.LogTrace("(-)[DISPOSE_EXCEPTION]");
                 throw;
             }
+
+            this.logger.LogTrace("(-)");
         }

         /// <summary>
@@ -82,42 +92,48 @@
         /// </summary>
         /// <param name="callback">Delegate to run start or stop method of the feature.</param>
         /// <param name="reverseOrder">Reverse the order of which the features are executed.</param>
-        /// <remarks>This method catches exception of start/stop methods and then, after all start/stop methods were called
-        /// for all features, it throws AggregateException if there were any exceptions.</remarks>
+        /// <exception cref="AggregateException">Thrown in case one or more callbacks threw an exception.</exception>
         private void Execute(Action<IFullNodeFeature> callback, bool reverseOrder = false)
         {
+            this.logger.LogTrace("({0}:{1})", nameof(reverseOrder), reverseOrder);
+
             List<Exception> exceptions = null;

-            if (this.node.Services != null)
+            if (this.node.Services == null)
             {
-                IEnumerable<IFullNodeFeature> iterator = this.node.Services.Features;
+                this.logger.LogTrace("(-)[NO_SERVICES]");
+                return;
+            }

-                if (reverseOrder)
-                    iterator = iterator.Reverse();
+            IEnumerable<IFullNodeFeature> features = this.node.Services.Features;

-                foreach (IFullNodeFeature service in iterator)
+            if (reverseOrder)
+                features = features.Reverse();
+
+            foreach (IFullNodeFeature feature in features)
+            {
+                try
                 {
-                    try
-                    {
-                        callback(service);
-                    }
-                    catch (Exception ex)
-                    {
-                        if (exceptions == null)
-                        {
-                            exceptions = new List<Exception>();
-                        }
+                    callback(feature);
+                }
+                catch (Exception ex)
+                {
+                    if (exceptions == null)
+                        exceptions = new List<Exception>();

-                        exceptions.Add(ex);
-                    }
-                }
-
-                // Throw an aggregate exception if there were any exceptions
-                if (exceptions != null)
-                {
-                    throw new AggregateException(exceptions);
+                    exceptions.Add(ex);
+                    this.logger.LogError("An error occurred: '{0}'", ex.ToString());
                 }
             }
+
+            // Throw an aggregate exception if there were any exceptions.
+            if (exceptions != null)
+            {
+                this.logger.LogTrace("(-)[EXECUTION_FAILED]");
+                throw new AggregateException(exceptions);
+            }
+
+            this.logger.LogTrace("(-)");
         }
     }
 }


Fix HttpContent.CopyToAsync to return rather than throw exception

I broke this as part of my async/await refactorings.  It was supposed to return a Task.FromException but instead was throwing.

--- src/System.Net.Http/src/System/Net/Http/HttpContent.cs
+++ src/System.Net.Http/src/System/Net/Http/HttpContent.cs
@@ -283,7 +283,7 @@
             }
             catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e))
             {
-                throw GetStreamCopyException(e);
+                return Task.FromException(GetStreamCopyException(e));
             }
         }


Reduce System.Runtime.Numerics outerloop test time from ~180s to ~90s

There are two remaining individual tests each taking ~80s doing lots of calculations (RunDoubleExplicitCastFromLargeBigIntegerTests and RunLargeValueLogTests)... I don't know the importance enough of what those are testing to determine whether it's ok to change them, so I've left them as is, which means it's going to be difficult to significantly reduce the overall running time (which on my machine is now ~90s) much further.  Still, this small change brings the running time on my machine down from ~150 seconds to ~90 seconds.

Changes:
- The ModPow3LargeInt test was generated 10 sets of random values, using BigInteger.ModPow with them, and then comparing the result against another, very inefficient implementation of modpow, resulting in a test taking ~150 seconds (and another one calling it with slightly different inputs taking ~30s).  I simply pre-generated a set of 10 inputs and expected outputs (using the same algorithm the test was previously using), and put those into the test as InlineData.

--- src/System.Runtime.Numerics/tests/BigInteger/modpow.cs
+++ src/System.Runtime.Numerics/tests/BigInteger/modpow.cs
@@ -170,30 +170,35 @@
             BigIntTools.Utils.RunWithFakeThreshold("ReducerThreshold", 8, ModPow2Large1SmallInt);
         }

-        [Fact]
+        // InlineData randomly generated using a new Random(0) and the same logic as is used in MyBigIntImp
+        // When using the VerifyModPowString approach, these tests were taking over 100s to execute.
+        [Theory]
         [OuterLoop]
-        public static void ModPow3LargeInt()
-        {
-            byte[] tempByteArray1;
-            byte[] tempByteArray2;
-            byte[] tempByteArray3;
-
-            // ModPow Method - Three large BigIntegers
-            for (int i = 0; i < s_samples; i++)
-            {
-                tempByteArray1 = GetRandomByteArray(s_random);
-                tempByteArray2 = GetRandomPosByteArray(s_random);
-                tempByteArray3 = GetRandomByteArray(s_random);
-                VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow");
-            }
-        }
-
-        [Fact]
-        [OuterLoop]
-        public static void ModPow3LargeInt_Threshold()
-        {
-            // Again, with lower threshold
-            BigIntTools.Utils.RunWithFakeThreshold("ReducerThreshold", 8, ModPow3LargeInt);
+        [InlineData("16152447169612934532253858872860101823992426489763666485380167221632010974596350526903901586786157942589749704137347759619657187784260082814484793173551647870373927196771852", "81750440863317178198977948957223170296434385667401518194303765341584160931262254891905182291359611229458113456891057547210603179481274334549407149567413965138338569615186383", "-7196805437625531929619339290119232497987723600413951949478998858079935202962418871178150151495255147489121599998392939293913217145771279946557062800866475934948778", "5616380469802854111883204613624062553120851412450654399190717359559254034938493684003207209263083893212739965150170342564431867389596229480294680122528026782956958")]
+        [InlineData("-19804882257271871615998867413310154569092691610863183900352723872936597192840601413521317416195627481021453523098672122338092864102790996172", "5005126326020660905045117276428380928616741884628331700680598638081087432348216495484429178211470872172882902036752474804904132643", "-103139435102033366056363338063498713727200190198435", "-4559679593639479333979462122256288215243720737403")]
+        [InlineData("-2263742881720266366742488789295767051326353176981812961528848101545308514727342989711034207353102864275894987436688194776201313772226059035143797121004935923223042331190890429211181925543749113890129660515170733848725", "313166794469483345944045915670847620773229708424183728974404367769353433443313247319899209581239311758905801464781585268041623664425", "3984523819293796257818294503433333109083365267654089093971156331037874112339941681299823291492643701164442964256327008451060278818307268485187524722068240", "-1502346344475556570236985614111713440763176490652894928852811056060906839905964408583918853958610145894621840382970373570196361549098246030413222124498085")]
+        [InlineData("-342701069914551895507647608205424602441707687704978754182486401529587201154652163656221404036731562708712821963465111719289193200432064875769386559645346920", "247989781302056934762335026151076445832166884867735502165354252207668083157132317377069604102049233014316799294014890817943261246892765157594412634897440785353202366563028", "121555428622583377664148832113619145387775383377032217138159544127299380518157949963314283123957062240152711187509503414343", "87578369862034238407481381238856926729112161247036763388287150463197193460326629595765471822752579542310337770783772458710")]
+        [InlineData("-282593950368131775131360433563237877977879464854725217398276355042086422366377452969365517205334520940629323311057746859", "5959258935361466196732788139899933762310441595693546573755448590100882267274831199165902682626769861372370905838130200967035", "6598019436100687108279703832125132357070343951841815860721553173215685978621505459125000339496396952653080051757197617932586296524960251609958919233462530", "-4035534917213670830138661334307123840766321272945538719146336835321463334263841831803093764143165039453996360590495570418141622764990299884920213157241339")]
+        [InlineData("-283588760164723199492097446398514238808996680579814508529658395835708678571214111525627362048679162021949222615325057958783388520044013697149834530411072380435126870273057157745943859", "1042611904427950637176782337251399378305726352782300537151930702574076654415735617544217054055762002017753284951033975382044655538090809873113604", "11173562248848713955826639654969725554069867375462328112124015145073186375237811117727665778232780449525476829715663254692620996726130822561707626585790443774041565237684936409844925424596571418502946", "6662129352542591544500713232459850446949913817909326081510506555775206102887692404112984526760120407457772674917650956873499346517965094865621779695963015030158124625116211104048940313058280680420919")]
+        [InlineData("683399436848090272429540515929404372035986606104192913128573936597145312908480564700882440819526500604918037963508399983297602351856208190565527", "223751878996658298590720798129833935741775535718632942242965085592936259576946732440406302671204348239437556817289012497483482656", "1204888420642360606571457515385663952017382888522547766961071698778167608427220546474854934298311882921224875807375321847274969073309433075566441363244101914489524538123410250010519308563731930923389473186", "1136631484875680074951300738594593722168933395227758228596156355418704717505715681950525129323209331607163560404958604424924870345828742295978850144844693079191828839673460389985036424301333691983679427765")]
+        [InlineData("736513799451968530811005754031332418210960966881742655756522735504778110620671049112529346250333710388060811959329786494662578020803", "2461175085563866950903873687720858523536520498137697316698237108626602445202960480677695918813575265778826908481129155012799", "-4722693720735888562993277045098354134891725536023070176847814685098361292027040929352405620815883795027263132404351040", "4351573186631261607388198896754285562669240685903971199359912143458682154189588696264319780329366022294935204028039787")]
+        [InlineData("1596188639947986471148999794547338", "685242191738212089917782567856594513073397739443", "41848166029740752457613562518205823134173790454761036532025758411484449588176128053901271638836032557551179866133091058357374964041641117585422447497779410336188602585660372002644517668041207657383104649333118253", "39246949850380693159338034407642149926180988060650630387722725303281343126585456713282439764667310808891687831648451269002447916277601468727040185218264602698691553232132525542650964722093335105211816394635493987")]
+        [InlineData("-1506852741293695463963822334869441845197951776565891060639754936248401744065969556756496718308248025911048010080232290368562210204958094544173209793990218122", "64905085725614938357105826012272472070910693443851911667721848542473785070747281964799379996923261457185847459711", "2740467233603031668807697475486217767705051", "-1905434239471820365929630558127219204166613")]
+        public static void ModPow3LargeInt(string value, string exponent, string modulus, string expected)
+        {
+            BigInteger valueInt = BigInteger.Parse(value);
+            BigInteger exponentInt = BigInteger.Parse(exponent);
+            BigInteger modulusInt = BigInteger.Parse(modulus);
+            BigInteger resultInt = BigInteger.Parse(expected);
+
+            // Once with default threshold
+            Assert.Equal(resultInt, BigInteger.ModPow(valueInt, exponentInt, modulusInt));
+
+            // Once with reduced threshold
+            BigIntTools.Utils.RunWithFakeThreshold("ReducerThreshold", 8, () =>
+            {
+                Assert.Equal(resultInt, BigInteger.ModPow(valueInt, exponentInt, modulusInt));
+            });
         }

         [Fact]


Add separate test for the remove crash

Add separate test for the remove crash

--- src/TrackingCollectionTests/TrackingCollectionTests.cs
+++ src/TrackingCollectionTests/TrackingCollectionTests.cs
@@ -1806,15 +1806,17 @@
             GetThing(9, 9),
         });

-        col.Filter = (item, position, list) => true;
+        col.Filter = null;

         expectedCount = 14;
-        col.RemoveItem(GetThing(0));
+        col.RemoveItem(GetThing(100)); // this one won't result in a new element from the observable
+        col.RemoveItem(GetThing(10));
         Assert.True(evt.WaitOne(40));
         evt.Reset();

         Assert.AreEqual(8, col.Count);
         CollectionAssert.AreEqual(col, new List<Thing> {
+            GetThing(0, 0),
             GetThing(1, 1),
             GetThing(3, 3),
             GetThing(4, 4),
@@ -1822,29 +1824,44 @@
             GetThing(7, 7),
             GetThing(8, 8),
             GetThing(9, 9),
-            GetThing(10, 10),
-        });
-
-        col.Filter = null;
-
-        expectedCount = 15;
-        col.RemoveItem(GetThing(100)); // this one won't result in a new element from the observable
-        col.RemoveItem(GetThing(10));
+        });
+
+        col.Dispose();
+    }
+
+    [Test]
+    public void RemovingFirstItemWithFilterWorks()
+    {
+        var source = new Subject<Thing>();
+
+        ITrackingCollection<Thing> col = new TrackingCollection<Thing>(
+            Observable.Range(0, 5).Select(x => GetThing(x, x)),
+            OrderedComparer<Thing>.OrderBy(x => x.UpdatedAt).Compare,
+            (item, position, list) => true);
+        col.ProcessingDelay = TimeSpan.Zero;
+
+        var count = 0;
+        var expectedCount = 5;
+        var evt = new ManualResetEvent(false);
+        col.Subscribe(t =>
+        {
+            if (++count == expectedCount)
+                evt.Set();
+        }, () => { });
+
         Assert.True(evt.WaitOne(40));
         evt.Reset();

-        Assert.AreEqual(7, col.Count);
-        CollectionAssert.AreEqual(col, new List<Thing> {
-            GetThing(1, 1),
-            GetThing(3, 3),
-            GetThing(4, 4),
-            GetThing(6, 6),
-            GetThing(7, 7),
-            GetThing(8, 8),
-            GetThing(9, 9),
-        });
-
-        col.Dispose();
+        expectedCount = 6;
+        col.RemoveItem(GetThing(0));
+
+        Assert.True(evt.WaitOne(40));
+        evt.Reset();
+
+        CollectionAssert.AreEqual(col, Enumerable.Range(1, 4).Select(x => GetThing(x, x)));
+
+        col.Dispose();
+
     }

     [Test]


U4-2635 add failing test

U4-2635 add failing test

Only first occurrence of oldString is replaced.

--- src/Umbraco.Tests/CoreStrings/StringExtensionsTests.cs
+++ src/Umbraco.Tests/CoreStrings/StringExtensionsTests.cs
@@ -80,6 +80,15 @@
             Assert.AreEqual(shouldBe, trimmed);
         }

+        [TestCase("Hello this is my string", "hello", "replaced", "replaced this is my string", StringComparison.CurrentCultureIgnoreCase)]
+        [TestCase("Hello this is hello my string", "hello", "replaced", "replaced this is replaced my string", StringComparison.CurrentCultureIgnoreCase)]
+        [TestCase("Hello this is my string", "nonexistent", "replaced", "Hello this is my string", StringComparison.CurrentCultureIgnoreCase)]
+        public void ReplaceWithStringComparison(string input, string oldString, string newString, string shouldBe, StringComparison stringComparison)
+        {
+            var replaced = input.Replace(oldString, newString, stringComparison);
+            Assert.AreEqual(shouldBe, replaced);
+        }
+
         [TestCase(null, null)]
         [TestCase("", "")]
         [TestCase("x", "X")]


Simplifies ContentStore for all the instances it's trying to find a linked node by a gen

--- src/Umbraco.Web/PublishedCache/NuCache/ContentStore.cs
+++ src/Umbraco.Web/PublishedCache/NuCache/ContentStore.cs
@@ -506,6 +506,14 @@

         public int Count => _contentNodes.Count;

+        /// <summary>
+        /// Get the most recent version of the LinkedNode stored in the dictionary for the supplied key
+        /// </summary>
+        /// <typeparam name="TKey"></typeparam>
+        /// <typeparam name="TValue"></typeparam>
+        /// <param name="dict"></param>
+        /// <param name="key"></param>
+        /// <returns></returns>
         private static LinkedNode<TValue> GetHead<TKey, TValue>(ConcurrentDictionary<TKey, LinkedNode<TValue>> dict, TKey key)
             where TValue : class
         {
@@ -855,12 +863,13 @@
         /// <param name="link"></param>
         /// <param name="gen">The generation requested, use null to avoid the lookup</param>
         /// <returns></returns>
-        private LinkedNode<ContentNode> GetLinkedNodeGen(LinkedNode<ContentNode> link, long? gen)
+        private LinkedNode<TValue> GetLinkedNodeGen<TValue>(LinkedNode<TValue> link, long? gen)
+            where TValue : class
         {
             if (!gen.HasValue) return link;

-            //find the correct snapshot
-            while (link != null && link.Gen != gen)
+            //find the correct snapshot, find the first that is <= the requested gen
+            while (link != null && link.Gen > gen)
             {
                 link = link.Next;
             }
@@ -1105,17 +1114,11 @@

         public IEnumerable<ContentNode> GetAtRoot(long gen)
         {
-            var z = _root;
-            while (z != null)
-            {
-                if (z.Gen <= gen)
-                    break;
-                z = z.Next;
-            }
-            if (z == null)
+            var root = GetLinkedNodeGen(_root, gen);
+            if (root == null)
                 yield break;

-            var id = z.Value.FirstChildContentId;
+            var id = root.Value.FirstChildContentId;

             while (id > 0)
             {
@@ -1130,13 +1133,8 @@
         {
             // look ma, no lock!
             var link = GetHead(dict, key);
-            while (link != null)
-            {
-                if (link.Gen <= gen)
-                    return link.Value; // may be null
-                link = link.Next;
-            }
-            return null;
+            link = GetLinkedNodeGen(link, gen);
+            return link?.Value; // may be null
         }

         public IEnumerable<ContentNode> GetAll(long gen)
@@ -1146,17 +1144,9 @@
             var links = _contentNodes.Values.ToArray();
             foreach (var l in links)
             {
-                var link = l;
-                while (link != null)
-                {
-                    if (link.Gen <= gen)
-                    {
-                        if (link.Value != null)
-                            yield return link.Value;
-                        break;
-                    }
-                    link = link.Next;
-                }
+                var link = GetLinkedNodeGen(l, gen);
+                if (link?.Value != null)
+                    yield return link.Value;
             }
         }

@@ -1164,14 +1154,8 @@
         {
             var has = _contentNodes.Any(x =>
             {
-                var link = x.Value;
-                while (link != null)
-                {
-                    if (link.Gen <= gen && link.Value != null)
-                        return true;
-                    link = link.Next;
-                }
-                return false;
+                var link = GetLinkedNodeGen(x.Value, gen);
+                return link?.Value != null;
             });
             return has == false;
         }


Convert collection into a new list before enumerating (#331)

--- src/WireMock.Net/Server/FluentMockServer.LogEntries.cs
+++ src/WireMock.Net/Server/FluentMockServer.LogEntries.cs
@@ -39,7 +39,7 @@
         {
             var results = new Dictionary<LogEntry, RequestMatchResult>();

-            foreach (var log in _options.LogEntries)
+            foreach (var log in _options.LogEntries.ToList())
             {
                 var requestMatchResult = new RequestMatchResult();
                 foreach (var matcher in matchers)


Open app bar when hint control is tapped

--- src/Controls/AppBarHint.cs
+++ src/Controls/AppBarHint.cs
@@ -1,8 +1,27 @@
-using Windows.UI.Xaml.Controls;
+using Windows.UI.Xaml;
+using Windows.UI.Xaml.Controls;
+using Windows.UI.Xaml.Input;

 namespace Japf.Win8.AppBarHint.Demo.Controls
 {
     public class AppBarHint : Button
     {
+        protected override void OnTapped(TappedRoutedEventArgs e)
+        {
+            base.OnTapped(e);
+
+            if (Window.Current.Content is Frame)
+            {
+                var frame = (Frame) Window.Current.Content;
+                if (frame.Content is Page)
+                {
+                    var page = (Page) frame.Content;
+                    if (page.BottomAppBar != null)
+                    {
+                        page.BottomAppBar.IsOpen = true;
+                    }
+                }
+            }
+        }
     }
 }


Fix oldClassRecordSize support (Unreal 1 etc).

--- src/Core/Classes/UClass.cs
+++ src/Core/Classes/UClass.cs
@@ -105,7 +105,7 @@

             if( Package.Version <= 61 )
             {
-                var oldClassRecordSize = _Buffer.ReadIndex();
+                var oldClassRecordSize = _Buffer.ReadInt32();
                 Record( "oldClassRecordSize", oldClassRecordSize );
             }


HighScoreController commit

HighScoreController commit

--- src/HighScoreController.cs
+++ src/HighScoreController.cs
@@ -199,7 +199,6 @@
 			_Scores.RemoveAt(_Scores.Count - 1);
 			_Scores.Add(s);
 			_Scores.Sort();
-			SaveScores ();

 			GameController.EndCurrentState();
 		}


Attempt to wait till socket is open before returning Start()

--- src/HttpMock/HttpServer.cs
+++ src/HttpMock/HttpServer.cs
@@ -1,5 +1,6 @@
 using System;
 using System.Net;
+using System.Net.Sockets;
 using System.Threading;
 using Kayak;
 using Kayak.Http;
@@ -35,11 +36,29 @@

 			_thread = new Thread(StartListening);
 			_thread.Start();
+			WaitTillServerIsListening();
+		}

+		private void WaitTillServerIsListening() {
+			int timesToWait = 5;
+			using(var tcpClient = new TcpClient() ) {
+				int attempts = 0;
+				while (attempts < timesToWait) {
+					TryConnect(tcpClient);
+					if (tcpClient.Connected) {
+						break;
+					}
+					Thread.Sleep(10);
+					attempts++;
+				}
+			}
+		}
+
+		private void TryConnect(TcpClient tcpClient) {
+			tcpClient.Connect(_uri.Host, _uri.Port);
 		}

 		private void StartListening() {
-			Console.WriteLine("Listener thread about to start");
 			IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, _uri.Port);
 			_scheduler.Post(() => {
 			                	KayakServer.Factory


Updated disturbance bar chart

Updated disturbance bar chart

--- src/PQDashboard/DataHub.cs
+++ src/PQDashboard/DataHub.cs
@@ -565,6 +565,26 @@
             EventSet eventSet = new EventSet();
             eventSet.StartDate = DateTime.Parse(targetDateFrom);
             eventSet.EndDate = DateTime.Parse(targetDateTo);
+            Dictionary<string, string> colors = new Dictionary<string, string>()
+            {
+                { "5", "#C00000" },
+                { "4", "#FF2800" },
+                { "3", "#FF9600" },
+                { "2", "#00FFF4" },
+                { "1", "#FFFF00" },
+                { "0", "#0000FF" },
+            };
+
+            List<string> disabledFields = DataContext.Table<DashSettings>().QueryRecords(restriction: new RecordRestriction("Name = 'DisturbanceChart' AND Enabled = 0")).Select(x => x.Value).ToList();
+            IEnumerable<DashSettings> usersColors = DataContext.Table<DashSettings>().QueryRecords(restriction: new RecordRestriction("Name = 'DisturbanceChartColors' AND Enabled = 1"));
+
+            foreach (var color in usersColors)
+            {
+                if (colors.ContainsKey(color.Value.Split(',')[0]))
+                    colors[color.Value.Split(',')[0]] = color.Value.Split(',')[1];
+                else
+                    colors.Add(color.Value.Split(',')[0], color.Value.Split(',')[1]);
+            }

             using (IDbCommand sc = DataContext.Connection.Connection.CreateCommand())
             {
@@ -589,37 +609,72 @@
                 sc.Parameters.Add(param4);

                 IDataReader rdr = sc.ExecuteReader();
+                DataTable table = new DataTable();
+                table.Load(rdr);
+
                 try
                 {
-                    eventSet.Types.Add(new EventSet.EventDetail());
-                    eventSet.Types[0].Name = "5";
-                    eventSet.Types[0].Color = "#C00000";
-                    eventSet.Types.Add(new EventSet.EventDetail());
-                    eventSet.Types[1].Name = "4";
-                    eventSet.Types[1].Color = "#FF2800";
-                    eventSet.Types.Add(new EventSet.EventDetail());
-                    eventSet.Types[2].Name = "3";
-                    eventSet.Types[2].Color = "#FF9600";
-                    eventSet.Types.Add(new EventSet.EventDetail());
-                    eventSet.Types[3].Name = "2";
-                    eventSet.Types[3].Color = "#FFFF00";
-                    eventSet.Types.Add(new EventSet.EventDetail());
-                    eventSet.Types[4].Name = "1";
-                    eventSet.Types[4].Color = "#00FFF4";
-                    eventSet.Types.Add(new EventSet.EventDetail());
-                    eventSet.Types[5].Name = "0";
-                    eventSet.Types[5].Color = "#0000FF";
-
-
-                    while (rdr.Read())
-                    {
-                        eventSet.Types[0].Data.Add(Tuple.Create(Convert.ToDateTime(rdr["thedate"]), Convert.ToInt32(rdr["5"])));
-                        eventSet.Types[1].Data.Add(Tuple.Create(Convert.ToDateTime(rdr["thedate"]), Convert.ToInt32(rdr["4"])));
-                        eventSet.Types[2].Data.Add(Tuple.Create(Convert.ToDateTime(rdr["thedate"]), Convert.ToInt32(rdr["3"])));
-                        eventSet.Types[3].Data.Add(Tuple.Create(Convert.ToDateTime(rdr["thedate"]), Convert.ToInt32(rdr["2"])));
-                        eventSet.Types[4].Data.Add(Tuple.Create(Convert.ToDateTime(rdr["thedate"]), Convert.ToInt32(rdr["1"])));
-                        eventSet.Types[5].Data.Add(Tuple.Create(Convert.ToDateTime(rdr["thedate"]), Convert.ToInt32(rdr["0"])));
-                    }
+                    foreach (DataRow row in table.Rows)
+                    {
+                        foreach (DataColumn column in table.Columns)
+                        {
+                            if (column.ColumnName != "thedate" && !disabledFields.Contains(column.ColumnName))
+                            {
+                                if (eventSet.Types.All(x => x.Name != column.ColumnName))
+                                {
+                                    eventSet.Types.Add(new EventSet.EventDetail());
+                                    eventSet.Types[eventSet.Types.Count - 1].Name = column.ColumnName;
+                                    if (colors.ContainsKey(column.ColumnName))
+                                        eventSet.Types[eventSet.Types.Count - 1].Color = colors[column.ColumnName];
+                                    else
+                                    {
+                                        Random r = new Random();
+                                        eventSet.Types[eventSet.Types.Count - 1].Color = "#" + r.Next(256).ToString("X2") + r.Next(256).ToString("X2") + r.Next(256).ToString("X2");
+                                        DashSettings ds = new DashSettings()
+                                        {
+                                            Name = "DisturbanceChartColors",
+                                            Value = column.ColumnName + "," + eventSet.Types[eventSet.Types.Count - 1].Color,
+                                            Enabled = true
+                                        };
+                                        DataContext.Table<DashSettings>().AddNewRecord(ds);
+                                    }
+                                }
+                                eventSet.Types[eventSet.Types.IndexOf(x => x.Name == column.ColumnName)].Data.Add(Tuple.Create(Convert.ToDateTime(row["thedate"]), Convert.ToInt32(row[column.ColumnName])));
+                            }
+                        }
+                    }
+
+                    if (!eventSet.Types.Any())
+                    {
+                        foreach (DataColumn column in table.Columns)
+                        {
+                            if (column.ColumnName != "thedate" && !disabledFields.Contains(column.ColumnName))
+                            {
+                                if (eventSet.Types.All(x => x.Name != column.ColumnName))
+                                {
+                                    eventSet.Types.Add(new EventSet.EventDetail());
+                                    eventSet.Types[eventSet.Types.Count - 1].Name = column.ColumnName;
+                                    if (colors.ContainsKey(column.ColumnName))
+                                        eventSet.Types[eventSet.Types.Count - 1].Color = colors[column.ColumnName];
+                                    else
+                                    {
+                                        Random r = new Random();
+                                        eventSet.Types[eventSet.Types.Count - 1].Color = "#" + r.Next(256).ToString("X2") + r.Next(256).ToString("X2") + r.Next(256).ToString("X2");
+                                        DashSettings ds = new DashSettings()
+                                        {
+                                            Name = "DisturbanceChartColors",
+                                            Value = column.ColumnName + "," + eventSet.Types[eventSet.Types.Count - 1].Color,
+                                            Enabled = true
+                                        };
+                                        DataContext.Table<DashSettings>().AddNewRecord(ds);
+
+                                    }
+                                }
+                            }
+                        }
+
+                    }
+
                 }
                 finally
                 {
@@ -629,7 +684,7 @@
                     }
                 }
             }
-            return eventSet;
+                return eventSet;
         }

         public EventSet GetTrendingForPeriod(string siteID, string targetDateFrom, string targetDateTo, string userName)


[dotnet] this value was incorrectly changed

--- dotnet/src/webdriver/DevTools/DevToolsSession.cs
+++ dotnet/src/webdriver/DevTools/DevToolsSession.cs
@@ -36,7 +36,7 @@
     ///</summary>
     public class DevToolsSession : IDevToolsSession
     {
-        public const int AutoDetectDevToolsProtocolVersion = 106;
+        public const int AutoDetectDevToolsProtocolVersion = 0;

         private readonly string debuggerEndpoint;
         private string websocketAddress;


Revert "Fixed #138"

Revert "Fixed #138"

This reverts commit d8e366fccd9eb79f8c214800cc4e8a34d425c2fe.

--- source/FFImageLoading.Droid/Views/ImageViewAsync.cs
+++ source/FFImageLoading.Droid/Views/ImageViewAsync.cs
@@ -103,7 +103,7 @@

 		protected override bool SetFrame(int l, int t, int r, int b)
 		{
-			if (!AdjustViewBounds && Drawable != null && Drawable.IntrinsicWidth != 0)
+			if (Drawable != null && Drawable.IntrinsicWidth != 0)
 			{
 				bool bottomAlignmentDefined = AlignMode != AlignMode.None;
 				if (ScaleToFit || bottomAlignmentDefined)


Update Property Status to eliminate the issue with error popup falling off the screen. bugid: 657

--- source/csla.silverlight/Csla/Xaml/PropertyStatus.cs
+++ source/csla.silverlight/Csla/Xaml/PropertyStatus.cs
@@ -30,6 +30,11 @@
   {
     private bool _isReadOnly = false;
     private FrameworkElement _lastImage;
+    private Point _lastPosition;
+    private Point _popupLastPosition;
+    private Size _lastAppSize;
+    private Size _lastPopupSize;
+

     #region Constructors

@@ -277,7 +282,7 @@
     public bool IsBusy
     {
       get { return _isBusy; }
-      private set
+      private set
       {
         if (value != _isBusy)
         {
@@ -368,8 +373,10 @@
     private void image_MouseEnter(object sender, MouseEventArgs e)
     {
       Popup popup = (Popup)FindChild(this, "popup");
-      if (popup != null && sender is UIElement)
-      {
+      if (popup != null && sender is UIElement && Application.Current.RootVisual != null)
+      {
+        _lastPosition = e.GetPosition(Application.Current.RootVisual);
+        _lastAppSize = Application.Current.RootVisual.RenderSize;
         Point p = e.GetPosition((UIElement)sender);
         Size size = ((UIElement)sender).DesiredSize;
         // ensure events are attached only once.
@@ -379,7 +386,31 @@

         popup.VerticalOffset = p.Y + size.Height;
         popup.HorizontalOffset = p.X + size.Width;
+        _popupLastPosition = new Point();
+        _popupLastPosition.X = popup.HorizontalOffset;
+        _popupLastPosition.Y = popup.VerticalOffset;
+        popup.Loaded += popup_Loaded;
         popup.IsOpen = true;
+      }
+    }
+
+    void popup_Loaded(object sender, RoutedEventArgs e)
+    {
+      (sender as Popup).Loaded -= popup_Loaded;
+      if (((sender as Popup).Child as UIElement).DesiredSize.Height > 0)
+      {
+        _lastPopupSize = ((sender as Popup).Child as UIElement).DesiredSize;
+      }
+      if (_lastAppSize != null && _lastPosition != null && _popupLastPosition != null && _lastPopupSize != null)
+      {
+        if (_lastAppSize.Width < _lastPosition.X + _popupLastPosition.X + _lastPopupSize.Width)
+        {
+          (sender as Popup).HorizontalOffset = _lastAppSize.Width - _lastPosition.X - _popupLastPosition.X - _lastPopupSize.Width;
+        }
+        if (_lastAppSize.Height < _lastPosition.Y + _popupLastPosition.Y + _lastPopupSize.Height)
+        {
+          (sender as Popup).VerticalOffset = _lastAppSize.Height - _lastPosition.Y - _popupLastPosition.Y - _lastPopupSize.Height;
+        }
       }
     }


SVG transparency problems fixes

SVG transparency problems fixes

--- source/FFImageLoading.Svg.Shared/SvgDataResolver.cs
+++ source/FFImageLoading.Svg.Shared/SvgDataResolver.cs
@@ -77,13 +77,16 @@
 				sizeY = VectorHeight;
 			}

-			using (var bitmap = new SKBitmap((int)sizeX, (int)sizeY, true))
+			using (var bitmap = new SKBitmap((int)sizeX, (int)sizeY))
 			using (var canvas = new SKCanvas(bitmap))
+			using (var paint = new SKPaint())
 			{
+				canvas.Clear(SKColors.Transparent);
 				float scaleX = sizeX / picture.Bounds.Width;
 				float scaleY = sizeY / picture.Bounds.Height;
 				var matrix = SKMatrix.MakeScale(scaleX, scaleY);
-				canvas.DrawPicture(picture, ref matrix);
+
+				canvas.DrawPicture(picture, ref matrix, paint);
 				canvas.Flush();

 				using (var image = SKImage.FromBitmap(bitmap))


Fix: Import of Battle.net games fails if beta games are installed #868

--- source/Plugins/BattleNetLibrary/BattleNetLibrary.cs
+++ source/Plugins/BattleNetLibrary/BattleNetLibrary.cs
@@ -72,7 +72,7 @@
         public Dictionary<string, Game> GetInstalledGames()
         {
             var games = new Dictionary<string, Game>();
-            foreach (var prog in Programs.GetUnistallProgramsList())
+            foreach (var prog in Programs.GetUnistallProgramsList())
             {
                 if (string.IsNullOrEmpty(prog.UninstallString))
                 {
@@ -105,7 +105,11 @@
                             IsInstalled = true
                         };

-                        games.Add(game.GameId, game);
+                        // Check in case there are more versions of single games installed.
+                        if (!games.TryGetValue(game.GameId, out var _))
+                        {
+                            games.Add(game.GameId, game);
+                        }
                     }
                 }
                 else
@@ -116,7 +120,7 @@
                         continue;
                     }

-                    if (prog.DisplayName.EndsWith("Test"))
+                    if (prog.DisplayName.EndsWith("Test") || prog.DisplayName.EndsWith("Beta"))
                     {
                         continue;
                     }
@@ -144,7 +148,11 @@
                         IsInstalled = true
                     };

-                    games.Add(game.GameId, game);
+                    // Check in case there are more versions of single games installed.
+                    if (!games.TryGetValue(game.GameId, out var _))
+                    {
+                        games.Add(game.GameId, game);
+                    }
                 }
             }


Update version number for new nugget.

Update version number for new nugget.

--- Src/GlobalAssemblyInfo.cs
+++ Src/GlobalAssemblyInfo.cs
@@ -19,5 +19,5 @@
 // You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("0.1.4.0")]
-[assembly: AssemblyFileVersion("0.1.4.0")]
+[assembly: AssemblyVersion("0.1.5.0")]
+[assembly: AssemblyFileVersion("0.1.5.0")]


Added example logging to main class.

Added example logging to main class.

--- StockExchangeGame/Main.cs
+++ StockExchangeGame/Main.cs
@@ -1,7 +1,10 @@
 using System;
+using System.Collections.Generic;
 using System.IO;
 using System.Linq;
+using System.Reflection;
 using System.Windows.Forms;
+using log4net;
 using Languages.Implementation;
 using Languages.Interfaces;
 using StockExchangeGame.Database.Generic;
@@ -14,6 +17,7 @@
         private readonly IDatabaseAdapter _databaseAdapter = new DatabaseAdapter();
         private readonly ILanguageManager _lm = new LanguageManager();
         private Language _lang;
+        private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

         public Main()
         {
@@ -33,8 +37,14 @@
         private void CreateAllTables()
         {
             var result = _databaseAdapter.CreateAllTables();
-            if (result.Result.Any(x => x.Results == null))
-                throw new InitializationException(_lang.GetWord("ErrorInDatabaseInit"));
+            if (result.Result.All(x => x.Results != null)) return;
+            LogDatabaseInitializationError(result.Result);
+        }
+
+        private void LogDatabaseInitializationError(List<CreateTablesResult> results)
+        {
+            var ex = new InitializationException(_lang.GetWord("ErrorInDatabaseInit"), results);
+            _log.Error(ex);
         }

         private void InitializeLanguageManager()


May have fixed system.lazy not found namespace

--- Skylight.Static/Tools.cs
+++ Skylight.Static/Tools.cs
@@ -59,8 +59,8 @@
         /// <summary>
         ///     The guest client
         /// </summary>
-        internal static readonly Lazy<Client> GuestClient =
-            new Lazy<Client>(() => PlayerIO.QuickConnect.SimpleConnect(GameId, GuestEmail, GuestPassword));
+        internal static readonly System.Lazy<Client> GuestClient =
+            new System.Lazy<Client>(() => PlayerIO.QuickConnect.SimpleConnect(GameId, GuestEmail, GuestPassword));

         /// <summary>
         ///     Occurs when a program message is sent.


Removed unused InputState

Removed unused InputState

--- System/UserInputAction.cs
+++ System/UserInputAction.cs
@@ -26,7 +26,6 @@
     public enum InputState
     {
         Active,
-        Update,
         Inactive,
     }


improved the code of SocketService

improved the code of SocketService

--- SocketService/Program.cs
+++ SocketService/Program.cs
@@ -34,9 +34,9 @@
             if (args == null || args.Length < 1)
             {
                 Console.WriteLine("Please press a key to continue...");
-                Console.WriteLine("c: Run this application as a console application;");
-                Console.WriteLine("i: Install this application as a Windows Service;");
-                Console.WriteLine("u: Uninstall this Windows Service application;");
+                Console.WriteLine("-[c]: Run this application as a console application;");
+                Console.WriteLine("-[i]: Install this application as a Windows Service;");
+                Console.WriteLine("-[u]: Uninstall this Windows Service application;");

                 while (true)
                 {


moved floating button to windowmanager

moved floating button to windowmanager

--- TCC.Core/WindowManager.cs
+++ TCC.Core/WindowManager.cs
@@ -49,6 +49,7 @@
         public static ChatWindow ChatWindow;
         public static SettingsWindow Settings;
         public static InfoWindow InfoWindow;
+        public static FloatingButtonWindow FloatingButton;
         public static ContextMenu ContextMenu;

         public static NotifyIcon TrayIcon;
@@ -143,6 +144,8 @@
         public static void Init()
         {
             LoadWindows();
+            FloatingButton = new FloatingButtonWindow();
+            FloatingButton.Show();
             ContextMenu = new ContextMenu();
             DefaultIcon = new Icon(Application.GetResourceStream(new Uri("resources/tcc-logo.ico", UriKind.Relative)).Stream);
             ConnectedIcon = new Icon(Application.GetResourceStream(new Uri("resources/tcc-logo-on.ico", UriKind.Relative)).Stream);


нужен тест гибридов картинками. нужен тест книжной ледида

--- Solver2/Solver2/Books.cs
+++ Solver2/Solver2/Books.cs
@@ -1,8 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using System.Collections.Generic;

 namespace Solver2
 {


Changed constructor signature for NullableIdInput to nullable.

--- src/Abp/Application/Services/Dto/NullableIdInput.cs
+++ src/Abp/Application/Services/Dto/NullableIdInput.cs
@@ -15,7 +15,7 @@

         }

-        public NullableIdInput(TId id)
+        public NullableIdInput(TId? id)
         {
             Id = id;
         }
@@ -31,7 +31,7 @@

         }

-        public NullableIdInput(int id)
+        public NullableIdInput(int? id)
             : base(id)
         {


check member types

check member types

--- src/AutoMapper/Configuration/PrimitiveExtensions.cs
+++ src/AutoMapper/Configuration/PrimitiveExtensions.cs
@@ -17,13 +17,13 @@

         public static MethodInfo GetInheritedMethod(this Type type, string name)
         {
-            return (MethodInfo) GetMember(type, name);
+            return GetMember(type, name) as MethodInfo;
         }

         public static MemberInfo GetFieldOrProperty(this Type type, string name)
         {
             var memberInfo = GetMember(type, name);
-            if(memberInfo == null)
+            if(memberInfo == null || (memberInfo.MemberType != MemberTypes.Field && memberInfo.MemberType != MemberTypes.Property))
             {
                 throw new ArgumentOutOfRangeException(nameof(name), "Cannot find a field or property named " + name);
             }


Did not parse unix type paths correctly. Made sure parser kept root char

--- src/AutoTest.Core/Caching/Projects/ProjectParser.cs
+++ src/AutoTest.Core/Caching/Projects/ProjectParser.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
@@ -211,8 +211,12 @@

         private string getAbsolutePath(string relativePath)
         {
-            var chunks = Path.Combine(Path.GetDirectoryName(_projectFile), relativePath)
-                .Split(Path.DirectorySeparatorChar);
+			var combinedPath = Path.Combine(Path.GetDirectoryName(_projectFile), relativePath);
+			var chunkList = new List<string>();
+			if (combinedPath.StartsWith(Path.DirectorySeparatorChar.ToString()))
+				chunkList.Add(Path.DirectorySeparatorChar.ToString());
+            chunkList.AddRange(combinedPath.Split(Path.DirectorySeparatorChar));
+			var chunks = chunkList.ToArray();
             var folders = makeAbsolute(chunks);
             var path = buildPathFromArray(folders);
             return Path.GetFullPath(path);
@@ -241,7 +245,12 @@
                 if (path.Length == 0)
                     path += item;
                 else
-                    path += string.Format("{0}{1}", Path.DirectorySeparatorChar, item);
+				{
+					if (path.Equals(Path.DirectorySeparatorChar.ToString()))
+						path += item;
+					else
+                    	path += string.Format("{0}{1}", Path.DirectorySeparatorChar, item);
+				}
             }
             return path;
         }