Improved type validation

Improved type validation

--- NJsonSchema/JsonSchemaValidator.cs
+++ NJsonSchema/JsonSchemaValidator.cs
@@ -1,390 +1,422 @@
-//-----------------------------------------------------------------------
-// <copyright file="JsonSchemaValidator.cs" company="NJsonSchema">
-//     Copyright (c) Rico Suter. All rights reserved.
-// </copyright>
-// <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license>
-// <author>Rico Suter, mail@rsuter.com</author>
-//-----------------------------------------------------------------------
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text.RegularExpressions;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-using NJsonSchema.Validation;
-
-namespace NJsonSchema
-{
-    /// <summary>Class to validate a JSON schema against a given <see cref="JToken"/>. </summary>
-    internal class JsonSchemaValidator
-    {
-        private readonly JsonSchema4 _schema;
-
-        /// <summary>Initializes a new instance of the <see cref="JsonSchemaValidator"/> class. </summary>
-        /// <param name="schema">The schema. </param>
-        public JsonSchemaValidator(JsonSchema4 schema)
-        {
-            _schema = schema;
-        }
-
-        /// <summary>Validates the given JSON token. </summary>
-        /// <param name="token">The token. </param>
-        /// <param name="propertyName">The current property name. </param>
-        /// <param name="propertyPath">The current property path. </param>
-        /// <returns>The list of validation errors. </returns>
-        public virtual List<ValidationError> Validate(JToken token, string propertyName, string propertyPath)
-        {
-            var errors = new List<ValidationError>();
-
-            ValidateAnyOf(token, propertyName, propertyPath, errors);
-            ValidateAllOf(token, propertyName, propertyPath, errors);
-            ValidateOneOf(token, propertyName, propertyPath, errors);
-            ValidateNot(token, propertyName, propertyPath, errors);
-
-            ValidateEnum(token, propertyName, propertyPath, errors);
-            ValidateString(token, propertyName, propertyPath, errors);
-            ValidateNumber(token, propertyName, propertyPath, errors);
-            ValidateInteger(token, propertyName, propertyPath, errors);
-            ValidateBoolean(token, propertyName, propertyPath, errors);
-            ValidateNull(token, propertyName, propertyPath, errors);
-            ValidateObject(token, propertyName, propertyPath, errors);
-            ValidateArray(token, propertyName, propertyPath, errors);
-            ValidateProperties(token, propertyName, propertyPath, errors);
-
-            return errors;
-        }
-
-        private void ValidateAnyOf(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.AnyOf.Count > 0)
-            {
-                var propertyErrors = _schema.AnyOf.ToDictionary(s => s, s => s.Validate(token));
-                if (propertyErrors.All(s => s.Value.Count != 0))
-                    errors.Add(new ChildSchemaValidationError(ValidationErrorKind.NotAnyOf, propertyName, propertyPath, propertyErrors));
-            }
-        }
-
-        private void ValidateAllOf(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.AllOf.Count > 0)
-            {
-                var propertyErrors = _schema.AllOf.ToDictionary(s => s, s => s.Validate(token));
-                if (propertyErrors.Any(s => s.Value.Count != 0))
-                    errors.Add(new ChildSchemaValidationError(ValidationErrorKind.NotAllOf, propertyName, propertyPath, propertyErrors));
-            }
-        }
-
-        private void ValidateOneOf(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.OneOf.Count > 0)
-            {
-                var propertyErrors = _schema.OneOf.ToDictionary(s => s, s => s.Validate(token));
-                if (propertyErrors.Count(s => s.Value.Count == 0) != 1)
-                    errors.Add(new ChildSchemaValidationError(ValidationErrorKind.NotOneOf, propertyName, propertyPath, propertyErrors));
-            }
-        }
-
-        private void ValidateNot(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.Not != null)
-            {
-                if (_schema.Not.Validate(token).Count == 0)
-                    errors.Add(new ValidationError(ValidationErrorKind.ExcludedSchemaValidates, propertyName, propertyPath));
-            }
-        }
-
-        private void ValidateNull(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.Type.HasFlag(JsonObjectType.Null))
-            {
-                if (token != null && token.Type != JTokenType.Null)
-                    errors.Add(new ValidationError(ValidationErrorKind.NullExpected, propertyName, propertyPath));
-            }
-        }
-
-        private void ValidateEnum(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.Enumeration.Count > 0 && _schema.Enumeration.All(v => v.ToString() != token.ToString()))
-                errors.Add(new ValidationError(ValidationErrorKind.NotInEnumeration, propertyName, propertyPath));
-        }
-
-        private void ValidateString(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            var isString = token.Type == JTokenType.String || token.Type == JTokenType.Date ||
-                           token.Type == JTokenType.Guid || token.Type == JTokenType.TimeSpan ||
-                           token.Type == JTokenType.Uri;
-
-            if (isString)
-            {
-                var value = token.Value<string>();
-                if (value != null)
-                {
-                    if (!string.IsNullOrEmpty(_schema.Pattern))
-                    {
-                        if (!Regex.IsMatch(value, _schema.Pattern))
-                            errors.Add(new ValidationError(ValidationErrorKind.PatternMismatch, propertyName, propertyPath));
-                    }
-
-                    if (_schema.MinLength.HasValue && value.Length < _schema.MinLength)
-                        errors.Add(new ValidationError(ValidationErrorKind.StringTooShort, propertyName, propertyPath));
-
-                    if (_schema.MaxLength.HasValue && value.Length > _schema.MaxLength)
-                        errors.Add(new ValidationError(ValidationErrorKind.StringTooLong, propertyName, propertyPath));
-
-                    if (!string.IsNullOrEmpty(_schema.Format))
-                    {
-                        if (_schema.Format == JsonFormatStrings.DateTime)
-                        {
-                            DateTime dateTimeResult;
-                            if (token.Type != JTokenType.Date && DateTime.TryParse(value, out dateTimeResult) == false)
-                                errors.Add(new ValidationError(ValidationErrorKind.DateTimeExpected, propertyName, propertyPath));
-                        }
-
-                        if (_schema.Format == JsonFormatStrings.Uri)
-                        {
-                            Uri uriResult;
-                            if (token.Type != JTokenType.Uri && Uri.TryCreate(value, UriKind.Absolute, out uriResult) == false)
-                                errors.Add(new ValidationError(ValidationErrorKind.UriExpected, propertyName, propertyPath));
-                        }
-
-                        if (_schema.Format == JsonFormatStrings.Email)
-                        {
-                            var isEmail = Regex.IsMatch(value, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*" +
-                                @"@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);
-                            if (!isEmail)
-                                errors.Add(new ValidationError(ValidationErrorKind.EmailExpected, propertyName, propertyPath));
-                        }
-
-                        // TODO: Implement other format types (hostname, ipv4, ipv6)
-                    }
-                }
-            }
-            else
-            {
-                if (_schema.Type.HasFlag(JsonObjectType.String))
-                    errors.Add(new ValidationError(ValidationErrorKind.StringExpected, propertyName, propertyPath));
-            }
-        }
-
-        private void ValidateNumber(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.Type.HasFlag(JsonObjectType.Number))
-            {
-                if (token.Type != JTokenType.Float && token.Type != JTokenType.Integer)
-                    errors.Add(new ValidationError(ValidationErrorKind.NumberExpected, propertyName, propertyPath));
-            }
-
-            if (token.Type == JTokenType.Float || token.Type == JTokenType.Integer)
-            {
-                var value = token.Value<double>();
-
-                if (_schema.Minimum.HasValue && (_schema.IsExclusiveMinimum ? value <= _schema.Minimum : value < _schema.Minimum))
-                    errors.Add(new ValidationError(ValidationErrorKind.NumberTooSmall, propertyName, propertyPath));
-
-                if (_schema.Maximum.HasValue && (_schema.IsExclusiveMaximum ? value >= _schema.Maximum : value > _schema.Maximum))
-                    errors.Add(new ValidationError(ValidationErrorKind.NumberTooBig, propertyName, propertyPath));
-
-                if (_schema.MultipleOf.HasValue && value % _schema.MultipleOf != 0)
-                    errors.Add(new ValidationError(ValidationErrorKind.NumberNotMultipleOf, propertyName, propertyPath));
-            }
-        }
-
-        private void ValidateInteger(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.Type.HasFlag(JsonObjectType.Integer))
-            {
-                if (token.Type != JTokenType.Integer)
-                    errors.Add(new ValidationError(ValidationErrorKind.IntegerExpected, propertyName, propertyPath));
-            }
-        }
-
-        private void ValidateBoolean(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.Type.HasFlag(JsonObjectType.Boolean))
-            {
-                if (token.Type != JTokenType.Boolean)
-                    errors.Add(new ValidationError(ValidationErrorKind.BooleanExpected, propertyName, propertyPath));
-            }
-        }
-
-        private void ValidateObject(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.Type.HasFlag(JsonObjectType.Object))
-            {
-                var obj = token as JObject;
-                if (obj == null)
-                    errors.Add(new ValidationError(ValidationErrorKind.ObjectExpected, propertyName, propertyPath));
-            }
-        }
-
-        private void ValidateProperties(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            var obj = token as JObject;
-            foreach (var propertyInfo in _schema.Properties)
-            {
-                var newPropertyPath = propertyName != null ? propertyName + "." + propertyInfo.Key : propertyInfo.Key;
-
-                var property = obj != null ? obj.Property(propertyInfo.Key) : null;
-                if (property != null)
-                {
-                    var propertyValidator = new JsonSchemaValidator(propertyInfo.Value);
-                    var propertyErrors = propertyValidator.Validate(property.Value, propertyInfo.Key, newPropertyPath);
-                    errors.AddRange(propertyErrors);
-                }
-                else if (propertyInfo.Value.IsRequired)
-                    errors.Add(new ValidationError(ValidationErrorKind.PropertyRequired, propertyInfo.Key, newPropertyPath));
-            }
-
-            if (obj != null)
-            {
-                var properties = obj.Properties().ToList();
-
-                ValidateMaxProperties(properties, propertyName, propertyPath, errors);
-                ValidateMinProperties(properties, propertyName, propertyPath, errors);
-
-                var additionalProperties = properties.Where(p => !_schema.Properties.ContainsKey(p.Name)).ToList();
-
-                ValidatePatternProperties(additionalProperties, errors);
-                ValidateAdditionalProperties(additionalProperties, propertyName, propertyPath, errors);
-            }
-        }
-
-        private void ValidateMaxProperties(IList<JProperty> properties, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.MaxProperties > 0 && properties.Count() > _schema.MaxProperties)
-                errors.Add(new ValidationError(ValidationErrorKind.TooManyProperties, propertyName, propertyPath));
-        }
-
-        private void ValidateMinProperties(IList<JProperty> properties, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.MinProperties > 0 && properties.Count() < _schema.MinProperties)
-                errors.Add(new ValidationError(ValidationErrorKind.TooFewProperties, propertyName, propertyPath));
-        }
-
-        private void ValidatePatternProperties(List<JProperty> additionalProperties, List<ValidationError> errors)
-        {
-            foreach (var property in additionalProperties.ToArray())
-            {
-                var patternPropertySchema = _schema.PatternProperties.FirstOrDefault(p => Regex.IsMatch(property.Name, p.Key));
-                if (patternPropertySchema.Value != null)
-                {
-                    var error = TryCreateChildSchemaError(patternPropertySchema.Value, property,
-                        ValidationErrorKind.AdditionalPropertiesNotValid, property.Name, property.Path);
-
-                    if (error != null)
-                        errors.Add(error);
-
-                    additionalProperties.Remove(property);
-                }
-            }
-        }
-
-        private void ValidateAdditionalProperties(List<JProperty> additionalProperties,
-            string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.AdditionalPropertiesSchema != null)
-            {
-                foreach (var property in additionalProperties)
-                {
-                    var error = TryCreateChildSchemaError(_schema.AdditionalPropertiesSchema, property.Value,
-                        ValidationErrorKind.AdditionalPropertiesNotValid, property.Name, property.Path);
-                    if (error != null)
-                        errors.Add(error);
-                }
-            }
-            else
-            {
-                if (!_schema.AllowAdditionalProperties && additionalProperties.Any())
-                    errors.Add(new ValidationError(ValidationErrorKind.TooManyPropertiesInTuple, propertyName, propertyPath));
-            }
-        }
-
-        private void ValidateArray(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
-        {
-            var array = token as JArray;
-            if (array != null)
-            {
-                if (_schema.MinItems > 0 && array.Count < _schema.MinItems)
-                    errors.Add(new ValidationError(ValidationErrorKind.TooFewItems, propertyName, propertyPath));
-
-                if (_schema.MaxItems > 0 && array.Count > _schema.MaxItems)
-                    errors.Add(new ValidationError(ValidationErrorKind.TooManyItems, propertyName, propertyPath));
-
-                if (_schema.UniqueItems && array.Count != array.Distinct().Count())
-                    errors.Add(new ValidationError(ValidationErrorKind.ItemsNotUnique, propertyName, propertyPath));
-
-                var itemValidator = _schema.Item != null ? new JsonSchemaValidator(_schema.Item) : null;
-                for (var index = 0; index < array.Count; index++)
-                {
-                    var item = array[index];
-
-                    var propertyIndex = string.Format("[{0}]", index);
-                    var itemPath = propertyName != null ? propertyName + "." + propertyIndex : propertyIndex;
-
-                    if (_schema.Item != null && itemValidator != null)
-                    {
-                        var error = TryCreateChildSchemaError(itemValidator, _schema.Item, item, ValidationErrorKind.ArrayItemNotValid, propertyIndex, itemPath);
-                        if (error != null)
-                            errors.Add(error);
-                    }
-
-                    ValidateAdditionalItems(item, index, propertyPath, errors);
-                }
-            }
-            else if (_schema.Type.HasFlag(JsonObjectType.Array))
-                errors.Add(new ValidationError(ValidationErrorKind.ArrayExpected, propertyName, propertyPath));
-        }
-
-        private void ValidateAdditionalItems(JToken item, int index, string propertyPath, List<ValidationError> errors)
-        {
-            if (_schema.Items.Count > 0)
-            {
-                var propertyIndex = string.Format("[{0}]", index);
-                if (_schema.Items.Count > index)
-                {
-                    var error = TryCreateChildSchemaError(_schema.Items.ElementAt(index), item,
-                        ValidationErrorKind.ArrayItemNotValid, propertyIndex, propertyPath + propertyIndex);
-                    if (error != null)
-                        errors.Add(error);
-                }
-                else
-                {
-                    if (_schema.AdditionalItemsSchema != null)
-                    {
-                        var error = TryCreateChildSchemaError(_schema.AdditionalItemsSchema, item,
-                            ValidationErrorKind.AdditionalItemNotValid, propertyIndex, propertyPath + propertyIndex);
-                        if (error != null)
-                            errors.Add(error);
-                    }
-                    else
-                    {
-                        if (!_schema.AllowAdditionalItems)
-                        {
-                            errors.Add(new ValidationError(ValidationErrorKind.TooManyItemsInTuple,
-                                propertyIndex, propertyPath + propertyIndex));
-                        }
-                    }
-                }
-            }
-        }
-
-        private ChildSchemaValidationError TryCreateChildSchemaError(JsonSchema4 schema, JToken token, ValidationErrorKind errorKind, string property, string path)
-        {
-            var validator = new JsonSchemaValidator(schema);
-            return TryCreateChildSchemaError(validator, schema, token, errorKind, property, path);
-        }
-
-        private ChildSchemaValidationError TryCreateChildSchemaError(JsonSchemaValidator validator, JsonSchema4 schema, JToken token, ValidationErrorKind errorKind, string property, string path)
-        {
-            var errors = validator.Validate(token, null, null);
-            if (errors.Count == 0)
-                return null;
-
-            var errorDictionary = new Dictionary<JsonSchema4, ICollection<ValidationError>>();
-            errorDictionary.Add(schema, errors);
-
-            return new ChildSchemaValidationError(errorKind, property, path, errorDictionary);
-        }
-    }
+//-----------------------------------------------------------------------
+// <copyright file="JsonSchemaValidator.cs" company="NJsonSchema">
+//     Copyright (c) Rico Suter. All rights reserved.
+// </copyright>
+// <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license>
+// <author>Rico Suter, mail@rsuter.com</author>
+//-----------------------------------------------------------------------
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using NJsonSchema.Validation;
+
+namespace NJsonSchema
+{
+    /// <summary>Class to validate a JSON schema against a given <see cref="JToken"/>. </summary>
+    internal class JsonSchemaValidator
+    {
+        private readonly JsonSchema4 _schema;
+
+        /// <summary>Initializes a new instance of the <see cref="JsonSchemaValidator"/> class. </summary>
+        /// <param name="schema">The schema. </param>
+        public JsonSchemaValidator(JsonSchema4 schema)
+        {
+            _schema = schema;
+        }
+
+        /// <summary>Validates the given JSON token. </summary>
+        /// <param name="token">The token. </param>
+        /// <param name="propertyName">The current property name. </param>
+        /// <param name="propertyPath">The current property path. </param>
+        /// <returns>The list of validation errors. </returns>
+        public virtual List<ValidationError> Validate(JToken token, string propertyName, string propertyPath)
+        {
+            var errors = new List<ValidationError>();
+
+            ValidateAnyOf(token, propertyName, propertyPath, errors);
+            ValidateAllOf(token, propertyName, propertyPath, errors);
+            ValidateOneOf(token, propertyName, propertyPath, errors);
+            ValidateNot(token, propertyName, propertyPath, errors);
+            ValidateType(token, propertyName, propertyPath, errors);
+            ValidateEnum(token, propertyName, propertyPath, errors);
+            ValidateArray(token, propertyName, propertyPath, errors);
+            ValidateProperties(token, propertyName, propertyPath, errors);
+
+            return errors;
+        }
+
+        private void ValidateType(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            var types = GetTypes().ToDictionary(t => t, t => new List<ValidationError>());
+            if (types.Count > 0)
+            {
+                foreach (var type in types)
+                {
+                    ValidateString(token, propertyName, propertyPath, type.Value);
+                    ValidateNumber(token, propertyName, propertyPath, type.Value);
+                    ValidateInteger(token, propertyName, propertyPath, type.Value);
+                    ValidateBoolean(token, propertyName, propertyPath, type.Value);
+                    ValidateNull(token, propertyName, propertyPath, type.Value);
+                    ValidateObject(token, propertyName, propertyPath, type.Value);
+                }
+
+                // just one has to validate when multiple types are defined
+                if (types.All(t => t.Value.Count > 0))
+                    errors.AddRange(types.SelectMany(t => t.Value));
+            }
+            else
+            {
+                ValidateString(token, propertyName, propertyPath, errors);
+                ValidateNumber(token, propertyName, propertyPath, errors);
+                ValidateInteger(token, propertyName, propertyPath, errors);
+                ValidateBoolean(token, propertyName, propertyPath, errors);
+                ValidateNull(token, propertyName, propertyPath, errors);
+                ValidateObject(token, propertyName, propertyPath, errors);
+            }
+        }
+
+        private IEnumerable<JsonObjectType> GetTypes()
+        {
+            return Enum
+                .GetValues(typeof(JsonObjectType))
+                .Cast<JsonObjectType>()
+                .Where(t => t != JsonObjectType.None && _schema.Type.HasFlag(t));
+        }
+
+        private void ValidateAnyOf(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.AnyOf.Count > 0)
+            {
+                var propertyErrors = _schema.AnyOf.ToDictionary(s => s, s => s.Validate(token));
+                if (propertyErrors.All(s => s.Value.Count != 0))
+                    errors.Add(new ChildSchemaValidationError(ValidationErrorKind.NotAnyOf, propertyName, propertyPath, propertyErrors));
+            }
+        }
+
+        private void ValidateAllOf(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.AllOf.Count > 0)
+            {
+                var propertyErrors = _schema.AllOf.ToDictionary(s => s, s => s.Validate(token));
+                if (propertyErrors.Any(s => s.Value.Count != 0))
+                    errors.Add(new ChildSchemaValidationError(ValidationErrorKind.NotAllOf, propertyName, propertyPath, propertyErrors));
+            }
+        }
+
+        private void ValidateOneOf(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.OneOf.Count > 0)
+            {
+                var propertyErrors = _schema.OneOf.ToDictionary(s => s, s => s.Validate(token));
+                if (propertyErrors.Count(s => s.Value.Count == 0) != 1)
+                    errors.Add(new ChildSchemaValidationError(ValidationErrorKind.NotOneOf, propertyName, propertyPath, propertyErrors));
+            }
+        }
+
+        private void ValidateNot(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.Not != null)
+            {
+                if (_schema.Not.Validate(token).Count == 0)
+                    errors.Add(new ValidationError(ValidationErrorKind.ExcludedSchemaValidates, propertyName, propertyPath));
+            }
+        }
+
+        private void ValidateNull(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.Type.HasFlag(JsonObjectType.Null))
+            {
+                if (token != null && token.Type != JTokenType.Null)
+                    errors.Add(new ValidationError(ValidationErrorKind.NullExpected, propertyName, propertyPath));
+            }
+        }
+
+        private void ValidateEnum(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.Enumeration.Count > 0 && _schema.Enumeration.All(v => v.ToString() != token.ToString()))
+                errors.Add(new ValidationError(ValidationErrorKind.NotInEnumeration, propertyName, propertyPath));
+        }
+
+        private void ValidateString(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            var isString = token.Type == JTokenType.String || token.Type == JTokenType.Date ||
+                           token.Type == JTokenType.Guid || token.Type == JTokenType.TimeSpan ||
+                           token.Type == JTokenType.Uri;
+
+            if (isString)
+            {
+                var value = token.Value<string>();
+                if (value != null)
+                {
+                    if (!string.IsNullOrEmpty(_schema.Pattern))
+                    {
+                        if (!Regex.IsMatch(value, _schema.Pattern))
+                            errors.Add(new ValidationError(ValidationErrorKind.PatternMismatch, propertyName, propertyPath));
+                    }
+
+                    if (_schema.MinLength.HasValue && value.Length < _schema.MinLength)
+                        errors.Add(new ValidationError(ValidationErrorKind.StringTooShort, propertyName, propertyPath));
+
+                    if (_schema.MaxLength.HasValue && value.Length > _schema.MaxLength)
+                        errors.Add(new ValidationError(ValidationErrorKind.StringTooLong, propertyName, propertyPath));
+
+                    if (!string.IsNullOrEmpty(_schema.Format))
+                    {
+                        if (_schema.Format == JsonFormatStrings.DateTime)
+                        {
+                            DateTime dateTimeResult;
+                            if (token.Type != JTokenType.Date && DateTime.TryParse(value, out dateTimeResult) == false)
+                                errors.Add(new ValidationError(ValidationErrorKind.DateTimeExpected, propertyName, propertyPath));
+                        }
+
+                        if (_schema.Format == JsonFormatStrings.Uri)
+                        {
+                            Uri uriResult;
+                            if (token.Type != JTokenType.Uri && Uri.TryCreate(value, UriKind.Absolute, out uriResult) == false)
+                                errors.Add(new ValidationError(ValidationErrorKind.UriExpected, propertyName, propertyPath));
+                        }
+
+                        if (_schema.Format == JsonFormatStrings.Email)
+                        {
+                            var isEmail = Regex.IsMatch(value, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*" +
+                                @"@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);
+                            if (!isEmail)
+                                errors.Add(new ValidationError(ValidationErrorKind.EmailExpected, propertyName, propertyPath));
+                        }
+
+                        // TODO: Implement other format types (hostname, ipv4, ipv6)
+                    }
+                }
+            }
+            else
+            {
+                if (_schema.Type.HasFlag(JsonObjectType.String))
+                    errors.Add(new ValidationError(ValidationErrorKind.StringExpected, propertyName, propertyPath));
+            }
+        }
+
+        private void ValidateNumber(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.Type.HasFlag(JsonObjectType.Number))
+            {
+                if (token.Type != JTokenType.Float && token.Type != JTokenType.Integer)
+                    errors.Add(new ValidationError(ValidationErrorKind.NumberExpected, propertyName, propertyPath));
+            }
+
+            if (token.Type == JTokenType.Float || token.Type == JTokenType.Integer)
+            {
+                var value = token.Value<double>();
+
+                if (_schema.Minimum.HasValue && (_schema.IsExclusiveMinimum ? value <= _schema.Minimum : value < _schema.Minimum))
+                    errors.Add(new ValidationError(ValidationErrorKind.NumberTooSmall, propertyName, propertyPath));
+
+                if (_schema.Maximum.HasValue && (_schema.IsExclusiveMaximum ? value >= _schema.Maximum : value > _schema.Maximum))
+                    errors.Add(new ValidationError(ValidationErrorKind.NumberTooBig, propertyName, propertyPath));
+
+                if (_schema.MultipleOf.HasValue && value % _schema.MultipleOf != 0)
+                    errors.Add(new ValidationError(ValidationErrorKind.NumberNotMultipleOf, propertyName, propertyPath));
+            }
+        }
+
+        private void ValidateInteger(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.Type.HasFlag(JsonObjectType.Integer))
+            {
+                if (token.Type != JTokenType.Integer)
+                    errors.Add(new ValidationError(ValidationErrorKind.IntegerExpected, propertyName, propertyPath));
+            }
+        }
+
+        private void ValidateBoolean(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.Type.HasFlag(JsonObjectType.Boolean))
+            {
+                if (token.Type != JTokenType.Boolean)
+                    errors.Add(new ValidationError(ValidationErrorKind.BooleanExpected, propertyName, propertyPath));
+            }
+        }
+
+        private void ValidateObject(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.Type.HasFlag(JsonObjectType.Object))
+            {
+                var obj = token as JObject;
+                if (obj == null)
+                    errors.Add(new ValidationError(ValidationErrorKind.ObjectExpected, propertyName, propertyPath));
+            }
+        }
+
+        private void ValidateProperties(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            var obj = token as JObject;
+            foreach (var propertyInfo in _schema.Properties)
+            {
+                var newPropertyPath = propertyName != null ? propertyName + "." + propertyInfo.Key : propertyInfo.Key;
+
+                var property = obj != null ? obj.Property(propertyInfo.Key) : null;
+                if (property != null)
+                {
+                    var propertyValidator = new JsonSchemaValidator(propertyInfo.Value);
+                    var propertyErrors = propertyValidator.Validate(property.Value, propertyInfo.Key, newPropertyPath);
+                    errors.AddRange(propertyErrors);
+                }
+                else if (propertyInfo.Value.IsRequired)
+                    errors.Add(new ValidationError(ValidationErrorKind.PropertyRequired, propertyInfo.Key, newPropertyPath));
+            }
+
+            if (obj != null)
+            {
+                var properties = obj.Properties().ToList();
+
+                ValidateMaxProperties(properties, propertyName, propertyPath, errors);
+                ValidateMinProperties(properties, propertyName, propertyPath, errors);
+
+                var additionalProperties = properties.Where(p => !_schema.Properties.ContainsKey(p.Name)).ToList();
+
+                ValidatePatternProperties(additionalProperties, errors);
+                ValidateAdditionalProperties(additionalProperties, propertyName, propertyPath, errors);
+            }
+        }
+
+        private void ValidateMaxProperties(IList<JProperty> properties, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.MaxProperties > 0 && properties.Count() > _schema.MaxProperties)
+                errors.Add(new ValidationError(ValidationErrorKind.TooManyProperties, propertyName, propertyPath));
+        }
+
+        private void ValidateMinProperties(IList<JProperty> properties, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.MinProperties > 0 && properties.Count() < _schema.MinProperties)
+                errors.Add(new ValidationError(ValidationErrorKind.TooFewProperties, propertyName, propertyPath));
+        }
+
+        private void ValidatePatternProperties(List<JProperty> additionalProperties, List<ValidationError> errors)
+        {
+            foreach (var property in additionalProperties.ToArray())
+            {
+                var patternPropertySchema = _schema.PatternProperties.FirstOrDefault(p => Regex.IsMatch(property.Name, p.Key));
+                if (patternPropertySchema.Value != null)
+                {
+                    var error = TryCreateChildSchemaError(patternPropertySchema.Value, property,
+                        ValidationErrorKind.AdditionalPropertiesNotValid, property.Name, property.Path);
+
+                    if (error != null)
+                        errors.Add(error);
+
+                    additionalProperties.Remove(property);
+                }
+            }
+        }
+
+        private void ValidateAdditionalProperties(List<JProperty> additionalProperties,
+            string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.AdditionalPropertiesSchema != null)
+            {
+                foreach (var property in additionalProperties)
+                {
+                    var error = TryCreateChildSchemaError(_schema.AdditionalPropertiesSchema, property.Value,
+                        ValidationErrorKind.AdditionalPropertiesNotValid, property.Name, property.Path);
+                    if (error != null)
+                        errors.Add(error);
+                }
+            }
+            else
+            {
+                if (!_schema.AllowAdditionalProperties && additionalProperties.Any())
+                    errors.Add(new ValidationError(ValidationErrorKind.TooManyPropertiesInTuple, propertyName, propertyPath));
+            }
+        }
+
+        private void ValidateArray(JToken token, string propertyName, string propertyPath, List<ValidationError> errors)
+        {
+            var array = token as JArray;
+            if (array != null)
+            {
+                if (_schema.MinItems > 0 && array.Count < _schema.MinItems)
+                    errors.Add(new ValidationError(ValidationErrorKind.TooFewItems, propertyName, propertyPath));
+
+                if (_schema.MaxItems > 0 && array.Count > _schema.MaxItems)
+                    errors.Add(new ValidationError(ValidationErrorKind.TooManyItems, propertyName, propertyPath));
+
+                if (_schema.UniqueItems && array.Count != array.Distinct().Count())
+                    errors.Add(new ValidationError(ValidationErrorKind.ItemsNotUnique, propertyName, propertyPath));
+
+                var itemValidator = _schema.Item != null ? new JsonSchemaValidator(_schema.Item) : null;
+                for (var index = 0; index < array.Count; index++)
+                {
+                    var item = array[index];
+
+                    var propertyIndex = string.Format("[{0}]", index);
+                    var itemPath = propertyName != null ? propertyName + "." + propertyIndex : propertyIndex;
+
+                    if (_schema.Item != null && itemValidator != null)
+                    {
+                        var error = TryCreateChildSchemaError(itemValidator, _schema.Item, item, ValidationErrorKind.ArrayItemNotValid, propertyIndex, itemPath);
+                        if (error != null)
+                            errors.Add(error);
+                    }
+
+                    ValidateAdditionalItems(item, index, propertyPath, errors);
+                }
+            }
+            else if (_schema.Type.HasFlag(JsonObjectType.Array))
+                errors.Add(new ValidationError(ValidationErrorKind.ArrayExpected, propertyName, propertyPath));
+        }
+
+        private void ValidateAdditionalItems(JToken item, int index, string propertyPath, List<ValidationError> errors)
+        {
+            if (_schema.Items.Count > 0)
+            {
+                var propertyIndex = string.Format("[{0}]", index);
+                if (_schema.Items.Count > index)
+                {
+                    var error = TryCreateChildSchemaError(_schema.Items.ElementAt(index), item,
+                        ValidationErrorKind.ArrayItemNotValid, propertyIndex, propertyPath + propertyIndex);
+                    if (error != null)
+                        errors.Add(error);
+                }
+                else
+                {
+                    if (_schema.AdditionalItemsSchema != null)
+                    {
+                        var error = TryCreateChildSchemaError(_schema.AdditionalItemsSchema, item,
+                            ValidationErrorKind.AdditionalItemNotValid, propertyIndex, propertyPath + propertyIndex);
+                        if (error != null)
+                            errors.Add(error);
+                    }
+                    else
+                    {
+                        if (!_schema.AllowAdditionalItems)
+                        {
+                            errors.Add(new ValidationError(ValidationErrorKind.TooManyItemsInTuple,
+                                propertyIndex, propertyPath + propertyIndex));
+                        }
+                    }
+                }
+            }
+        }
+
+        private ChildSchemaValidationError TryCreateChildSchemaError(JsonSchema4 schema, JToken token, ValidationErrorKind errorKind, string property, string path)
+        {
+            var validator = new JsonSchemaValidator(schema);
+            return TryCreateChildSchemaError(validator, schema, token, errorKind, property, path);
+        }
+
+        private ChildSchemaValidationError TryCreateChildSchemaError(JsonSchemaValidator validator, JsonSchema4 schema, JToken token, ValidationErrorKind errorKind, string property, string path)
+        {
+            var errors = validator.Validate(token, null, null);
+            if (errors.Count == 0)
+                return null;
+
+            var errorDictionary = new Dictionary<JsonSchema4, ICollection<ValidationError>>();
+            errorDictionary.Add(schema, errors);
+
+            return new ChildSchemaValidationError(errorKind, property, path, errorDictionary);
+        }
+    }
 }


* in assemblyversion

* in assemblyversion

--- NTraits/Properties/AssemblyInfo.cs
+++ NTraits/Properties/AssemblyInfo.cs
@@ -26,5 +26,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("1.0.0.0")]
+[assembly: AssemblyVersion("1.0.*")]
 [assembly: AssemblyFileVersion("1.0.0.0")]


Migrating existing methods to an asynchronous socle

--- Cdiscount.OpenApi.ProxyClient/OpenApiClient.cs
+++ Cdiscount.OpenApi.ProxyClient/OpenApiClient.cs
@@ -39,15 +39,15 @@
         /// <param name="requestUri">Request Uri</param>
         /// <param name="requestMessage">Request Message</param>
         /// <returns>Request response message</returns>
-        private static T Post<T>(string requestUri, object requestMessage) where T : BaseResponseMessage
+        private static async Task<T> Post<T>(string requestUri, object requestMessage) where T : BaseResponseMessage
         {
             T result;
             var jsonObject = JsonConvert.SerializeObject(requestMessage);

             using (var httpClient = new BaseHttpClient())
             using (var content = new BaseHttpContent(jsonObject))
-            using (HttpResponseMessage response = httpClient.PostAsync(requestUri, content).Result)
             {
+                HttpResponseMessage response = await httpClient.PostAsync(requestUri, content);
                 response.EnsureSuccessStatusCode();
                 Task<string> responseBody = response.Content.ReadAsStringAsync();
                 result = JsonConvert.DeserializeObject<T>(responseBody.Result);
@@ -71,7 +71,7 @@
                 PushToCartRequest = request
             };

-            return Post<PushToCartResponse>("OpenApi/json/PushToCart", requestMessage);
+            return Post<PushToCartResponse>("OpenApi/json/PushToCart", requestMessage).Result;
         }

         /// <summary>
@@ -88,7 +88,7 @@
                 CartRequest = request
             };

-            return Post<GetCartResponse>("OpenApi/json/GetCart", requestMessage);
+            return Post<GetCartResponse>("OpenApi/json/GetCart", requestMessage).Result;
         }

         public GetProductResponse GetProduct(GetProductRequest request)
@@ -100,7 +100,7 @@
                 ProductRequest = request
             };

-            return Post<GetProductResponse>("OpenApi/json/GetProduct", requestMessage);
+            return Post<GetProductResponse>("OpenApi/json/GetProduct", requestMessage).Result;
         }

         public SearchResponse Search(SearchRequest request)
@@ -117,7 +117,7 @@
                 SearchRequest = request
             };

-            return Post<SearchResponse>("OpenApi/json/Search", requestMessage);
+            return Post<SearchResponse>("OpenApi/json/Search", requestMessage).Result;
         }

         private void CheckConfiguration()


Move serviceName to variable - makes for easier debugging

--- CefSharp.BrowserSubprocess/CefRenderProcess.cs
+++ CefSharp.BrowserSubprocess/CefRenderProcess.cs
@@ -36,10 +36,12 @@
                 return;
             }

+            var serviceName = RenderprocessClientFactory.GetServiceName(ParentProcessId.Value, cefBrowserWrapper.BrowserId);
+
             channelFactory = new DuplexChannelFactory<IBrowserProcess>(
                 this,
                 new NetNamedPipeBinding(),
-                new EndpointAddress(RenderprocessClientFactory.GetServiceName(ParentProcessId.Value, cefBrowserWrapper.BrowserId))
+                new EndpointAddress(serviceName)
             );

             channelFactory.Open();


Added additional logic for Coaster ID4 schedule and used the change to consolidate debug block in holiday code.

--- NextBusDisplay/WebService1.asmx.cs
+++ NextBusDisplay/WebService1.asmx.cs
@@ -64,7 +64,7 @@
 #if DEBUG
                     // Uncomment the below line to test the display for specific time of day or day of week/year
                     // The #if statement will prevent this from accidentally carrying over into production if you forget to re-comment
-                    _currentTime = DateTime.Parse("2017-12-25 13:01");
+                    _currentTime = DateTime.Parse("2018-07-04 13:01");
 #endif
                 }

@@ -718,70 +718,70 @@
                        select h.Holiday).Count();

             bool isHoliday = tbl > 0 ? true : false;
+            string holidayName = string.Empty;
+            if (isHoliday) holidayName = (from h in dc2.Holidays
+                               where h.Holiday == CurrentTime
+                               select h.Description).First();
+
+            dc2.Dispose();
+            // Added enumerated days to prepare for auto download from NextBus - Each Day Will Be Enumerated By Itself
+            if (isHoliday && (route.ToLower() != "amtrak"))
+            {
+                days.Add("Weekends");
+                days.Add("Fri-Sun");
+                if (route.ToLower() == "398" && holidayName == "Independence Day") days.Add("Saturday"); // Special rule for coaster
+                else days.Add("Sunday");
+            }
+            else if (CurrentTime.DayOfWeek == DayOfWeek.Monday)
+            {
+                days.Add("Monday");
+                days.Add("Weekdays");
+                days.Add("Mo-Th");
+            }
+            else if (CurrentTime.DayOfWeek == DayOfWeek.Tuesday)
+            {
+                days.Add("Tuesday");
+                days.Add("Weekdays");
+                days.Add("Mo-Th");
+            }
+            else if (CurrentTime.DayOfWeek == DayOfWeek.Wednesday)
+            {
+                days.Add("Wednesday");
+                days.Add("Weekdays");
+                days.Add("Mo-Th");
+            }
+            else if (CurrentTime.DayOfWeek == DayOfWeek.Thursday)
+            {
+                days.Add("Thursday");
+                days.Add("Weekdays");
+                days.Add("Mo-Th");
+            }
+            else if (CurrentTime.DayOfWeek == DayOfWeek.Friday)
+            {
+                days.Add("Friday");
+                days.Add("Weekdays");
+                days.Add("Fri-Sun");
+            }
+            else if (CurrentTime.DayOfWeek == DayOfWeek.Saturday)
+            {
+                days.Add("Saturday");
+                days.Add("Weekends");
+                days.Add("Fri-Sun");
+            }
+            else if (CurrentTime.DayOfWeek == DayOfWeek.Sunday)
+            {
+                days.Add("Sunday");
+                days.Add("Weekends");
+                days.Add("Fri-Sun");
+            }
+
 #if DEBUG
             // Logs info about what schedule is being displayed
             Debug.Print($"Schedule for {route}");
             if (isHoliday)
             {
-                var holidayName = (from h in dc2.Holidays
-                                   where h.Holiday == CurrentTime
-                                   select h.Description).First();
                 Debug.Print($"Today is a Holiday - {holidayName}");
             }
-#endif
-            dc2.Dispose();
-            // Added enumerated days to prepare for auto download from NextBus - Each Day Will Be Enumerated By Itself
-            if (isHoliday && (route.ToLower() != "amtrak"))
-            {
-                days.Add("Weekends");
-                days.Add("Fri-Sun");
-                days.Add("Sunday");
-            }
-            else if (CurrentTime.DayOfWeek == DayOfWeek.Monday)
-            {
-                days.Add("Monday");
-                days.Add("Weekdays");
-                days.Add("Mo-Th");
-            }
-            else if (CurrentTime.DayOfWeek == DayOfWeek.Tuesday)
-            {
-                days.Add("Tuesday");
-                days.Add("Weekdays");
-                days.Add("Mo-Th");
-            }
-            else if (CurrentTime.DayOfWeek == DayOfWeek.Wednesday)
-            {
-                days.Add("Wednesday");
-                days.Add("Weekdays");
-                days.Add("Mo-Th");
-            }
-            else if (CurrentTime.DayOfWeek == DayOfWeek.Thursday)
-            {
-                days.Add("Thursday");
-                days.Add("Weekdays");
-                days.Add("Mo-Th");
-            }
-            else if (CurrentTime.DayOfWeek == DayOfWeek.Friday)
-            {
-                days.Add("Friday");
-                days.Add("Weekdays");
-                days.Add("Fri-Sun");
-            }
-            else if (CurrentTime.DayOfWeek == DayOfWeek.Saturday)
-            {
-                days.Add("Saturday");
-                days.Add("Weekends");
-                days.Add("Fri-Sun");
-            }
-            else if (CurrentTime.DayOfWeek == DayOfWeek.Sunday)
-            {
-                days.Add("Sunday");
-                days.Add("Weekends");
-                days.Add("Fri-Sun");
-            }
-
-#if DEBUG
-            // Logs info about what schedule is being displayed
             Debug.Print("The following weekdays are being used for the schedule");
             Debug.Print(String.Join(", ", days));
             Debug.Print("===============================");


Client v0.9.03

Client v0.9.03

-Connection Bugfix

--- Client/CSharp_Chatprojekt_Client/Verbindung.cs
+++ Client/CSharp_Chatprojekt_Client/Verbindung.cs
@@ -168,6 +168,7 @@
                 Array.Resize<byte>(ref buf, rec);
                 string recievedUTF8 = Encoding.UTF8.GetString(buf);
                 EmpfangenenBefehlSuchen(recievedUTF8);
+                sock.BeginReceive(new byte[] { 0 }, 0, 0, 0, callback, null);
             }

             catch(Exception ex)


Багфикс

Багфикс

--- AGO.Core/SessionFactoryBuilder.cs
+++ AGO.Core/SessionFactoryBuilder.cs
@@ -144,7 +144,7 @@
 			{
 				throw new DataAccessException(e);
 			}
-			}
+		}

 		public void CloseCurrentSession(bool forceRollback = false)
 		{
@@ -157,8 +157,13 @@
 			{
 				if (!CurrentSessionContext.HasBind(_SessionFactory))
 					return;
-			CurrentSessionContext.Unbind(_SessionFactory);
-		}
+
+				var session = _SessionFactory.GetCurrentSession();
+				if (session != null)
+					session.Close();
+
+				CurrentSessionContext.Unbind(_SessionFactory);
+			}
 			catch (HibernateException e)
 			{
 				throw new DataAccessException(e);


Don't update anim. GO when animator is disabled

--- APAnimatorComponent/APAnimator.cs
+++ APAnimatorComponent/APAnimator.cs
@@ -588,6 +588,7 @@
             if (!RequiredAssetsLoaded()) return;
             if (AnimatedGO == null) return;
             if (PathData == null) return;
+            if (!enabled) return;

             UpdateAnimatedGOPosition();
             UpdateAnimatedGORotation();


Made V1OAuth2APIConnector obsolete.

Made V1OAuth2APIConnector obsolete.


Removed name conflicts.

Removed name conflicts.

--- CodeGenerator/ProtocolParser/ProtocolParser.cs
+++ CodeGenerator/ProtocolParser/ProtocolParser.cs
@@ -65,7 +65,7 @@
     /// </summary>
     public static void WriteBytes(CitoStream stream, byte[] val)
     {
-        WriteUInt32(stream, ProtoPlatform.ArrayLength(val));
+        WriteUInt32_(stream, ProtoPlatform.ArrayLength(val));
         stream.Write(val, 0, ProtoPlatform.ArrayLength(val));
     }
     //}
@@ -106,7 +106,7 @@
         return Key.Create(n >> 3, (n & 0x07));
     }

-    public static Key ReadKey(byte firstByte, CitoStream stream)
+    public static Key ReadKey_(byte firstByte, CitoStream stream)
     {
         if (firstByte < 128)
             return Key.Create((firstByte >> 3), (firstByte & 0x07));
@@ -117,7 +117,7 @@
     public static void WriteKey(CitoStream stream, Key key)
     {
         int n = (key.GetField() << 3) | (key.GetWireType());
-        WriteUInt32(stream, n);
+        WriteUInt32_(stream, n);
     }

     /// <summary>
@@ -305,7 +305,7 @@
     /// </summary>
     public static void WriteZInt32(CitoStream stream, int val)
     {
-        WriteUInt32(stream, ((val << 1) ^ (val >> 31)));
+        WriteUInt32_(stream, ((val << 1) ^ (val >> 31)));
     }

     /// <summary>
@@ -352,7 +352,7 @@
     /// <summary>
     /// Unsigned VarInt format
     /// </summary>
-    public static void WriteUInt32(CitoStream stream, int val)
+    public static void WriteUInt32_(CitoStream stream, int val)
     {
         byte[] buffer = new byte[5];
         int count = 0;
@@ -665,14 +665,14 @@
 /// </summary>
 public class KeyValue
 {
-    Key Key;
+    Key Key_;

     byte[] Value;

     public static KeyValue Create(Key key, byte[] value)
     {
         KeyValue k = new KeyValue();
-        k.Key = key;
+        k.Key_ = key;
         k.Value = value;
         return k;
     }
@@ -689,7 +689,7 @@
     public abstract bool CanSeek();
     public abstract void Seek(int length, CitoSeekOrigin seekOrigin);
     public abstract void Write(byte[] val, int p, int p_3);
-    public abstract void Seek(uint p, CitoSeekOrigin seekOrigin);
+    public abstract void Seek_(int p, CitoSeekOrigin seekOrigin);
     public abstract int ReadByte();
     public abstract void WriteByte(byte p);
     public abstract int Position();
@@ -697,56 +697,56 @@

 public class CitoMemoryStream : CitoStream
 {
-    byte[] buffer;
-    int count;
+    byte[] buffer_;
+    int count_;
     int bufferlength;
-    int position;
+    int position_;

     public CitoMemoryStream()
     {
-        buffer = new byte[1];
-        count = 0;
+        buffer_ = new byte[1];
+        count_ = 0;
         bufferlength = 1;
-        position = 0;
+        position_ = 0;
     }

     public int Length()
     {
-        return count;
+        return count_;
     }

     public byte[] ToArray()
     {
-        return buffer;
+        return buffer_;
     }

     public static CitoMemoryStream Create(byte[] buffer, int length)
     {
         CitoMemoryStream m = new CitoMemoryStream();
-        m.buffer = buffer;
-        m.count = length;
+        m.buffer_ = buffer;
+        m.count_ = length;
         m.bufferlength = length;
-        m.position = 0;
+        m.position_ = 0;
         return m;
     }

     public byte[] GetBuffer()
     {
-        return buffer;
+        return buffer_;
     }

     public override int Read(byte[] buffer, int offset, int count)
     {
         for (int i = 0; i < count; i++)
         {
-            if (position + i >= this.count)
+            if (position_ + i >= this.count_)
             {
-                position += i;
+                position_ += i;
                 return i;
             }
-            buffer[offset + i] = this.buffer[position + i];
-        }
-        position += count;
+            buffer[offset + i] = this.buffer_[position_ + i];
+        }
+        position_ += count;
         return count;
     }

@@ -767,42 +767,42 @@
         }
     }

-    public override void Seek(uint p, CitoSeekOrigin seekOrigin)
+    public override void Seek_(int p, CitoSeekOrigin seekOrigin)
     {
     }

     public override int ReadByte()
     {
-        if (position >= count)
+        if (position_ >= count_)
         {
             return -1;
         }
-        return buffer[position++];
+        return buffer_[position_++];
     }

     public override void WriteByte(byte p)
     {
-        if (position >= bufferlength)
+        if (position_ >= bufferlength)
         {
             byte[] buffer2 = new byte[bufferlength * 2];
             for (int i = 0; i < bufferlength; i++)
             {
-                buffer2[i] = buffer[i];
+                buffer2[i] = buffer_[i];
             }
-            buffer = buffer2;
+            buffer_ = buffer2;
             bufferlength = bufferlength * 2;
         }
-        buffer[position] = p;
-        if (position == count)
-        {
-            count++;
-        }
-        position++;
+        buffer_[position_] = p;
+        if (position_ == count_)
+        {
+            count_++;
+        }
+        position_++;
     }

     public override int Position()
     {
-        return position;
+        return position_;
     }
 }

@@ -853,7 +853,7 @@
             return a.Length;
         }
 #else
-        return null;
+        return 0;
 #endif
 #else
         return a.Length;


Fix power grid announcements overlapping power-down sounds (#2096)

Both announcements play 3s after startup / shutdown

Co-authored-by: Metal Gear Sloth <5a6002283f4d0ed17bed24ee1f9d131baf85176c@gmail.com>

--- Content.Server/StationEvents/PowerGridCheck.cs
+++ Content.Server/StationEvents/PowerGridCheck.cs
@@ -1,4 +1,5 @@
 using System.Collections.Generic;
+using System.Threading;
 using Content.Server.GameObjects.Components.Power.ApcNetComponents;
 using JetBrains.Annotations;
 using Robust.Server.GameObjects.EntitySystems;
@@ -7,6 +8,7 @@
 using Robust.Shared.Interfaces.Random;
 using Robust.Shared.IoC;
 using Robust.Shared.Localization;
+using Timer = Robust.Shared.Timers.Timer;

 namespace Content.Server.StationEvents
 {
@@ -28,6 +30,13 @@
         private float _elapsedTime;
         private int _failDuration;

+        /// <summary>
+        ///     So we don't overlap the announcement with power-down sounds we'll delay it a few seconds.
+        /// </summary>
+        private bool _announced;
+
+        private CancellationTokenSource _announceCancelToken;
+
         private List<IEntity> _powered = new List<IEntity>();

@@ -35,8 +44,8 @@
         public override void Startup()
         {
             base.Startup();
-            EntitySystem.Get<AudioSystem>().PlayGlobal("/Audio/Announcements/power_off.ogg");

+            _announced = false;
             _elapsedTime = 0.0f;
             _failDuration = IoCManager.Resolve<IRobustRandom>().Next(30, 120);
             var componentManager = IoCManager.Resolve<IComponentManager>();
@@ -51,7 +60,6 @@
         public override void Shutdown()
         {
             base.Shutdown();
-            EntitySystem.Get<AudioSystem>().PlayGlobal("/Audio/Announcements/power_on.ogg");

             foreach (var entity in _powered)
             {
@@ -63,6 +71,12 @@
                 }
             }

+            _announceCancelToken?.Cancel();
+            _announceCancelToken = new CancellationTokenSource();
+            Timer.Spawn(3000, () =>
+            {
+                EntitySystem.Get<AudioSystem>().PlayGlobal("/Audio/Announcements/power_on.ogg");
+            }, _announceCancelToken.Token);
             _powered.Clear();
         }

@@ -71,6 +85,12 @@
             if (!Running)
             {
                 return;
+            }
+
+            if (!_announced && _elapsedTime > 3.0f)
+            {
+                EntitySystem.Get<AudioSystem>().PlayGlobal("/Audio/Announcements/power_off.ogg");
+                _announced = true;
             }

             _elapsedTime += frameTime;


update build script to package releasable packages on release branches.

--- parameters.cake
+++ parameters.cake
@@ -18,6 +18,7 @@
     public bool IsPullRequest { get; private set; }
     public bool IsMainRepo { get; private set; }
     public bool IsMasterBranch { get; private set; }
+    public bool IsReleaseBranch { get; private set; }
     public bool IsTagged { get; private set; }
     public bool IsReleasable { get; private set; }
     public bool IsMyGetRelease { get; private set; }
@@ -46,8 +47,9 @@
         SkipTests = context.HasArgument("skip-tests");

         // CONFIGURATION
-        MainRepo = "AvaloniaUI/Avalonia";
+        MainRepo = "https://github.com/AvaloniaUI/Avalonia";
         MasterBranch = "master";
+        ReleaseBranchPrefix = "release/";
         ReleaseConfiguration = "Release";
         MSBuildSolution = "./dirs.proj";

@@ -59,12 +61,14 @@
         IsRunningOnAzure = buildSystem.IsRunningOnVSTS || buildSystem.IsRunningOnTFS || context.EnvironmentVariable("LOGNAME") == "vsts";

         IsPullRequest = buildSystem.AppVeyor.Environment.PullRequest.IsPullRequest;
-        IsMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, buildSystem.AppVeyor.Environment.Repository.Name);
-        IsMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, buildSystem.AppVeyor.Environment.Repository.Branch);
+        IsMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, context.EnvironmentVariable("BUILD_REPOSITORY_URI"));
+        IsMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, context.EnvironmentVariable("BUILD_SOURCEBRANCHNAME"));
+        IsReleaseBranch = StringComparer.OrdinalIgnoreCase.StartsWith(ReleaseBranchPrefix, context.EnvironmentVariable("BUILD_SOURCEBRANCHNAME"));
         IsTagged = buildSystem.AppVeyor.Environment.Repository.Tag.IsTag
                 && !string.IsNullOrWhiteSpace(buildSystem.AppVeyor.Environment.Repository.Tag.Name);
         IsReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, Configuration);
         IsMyGetRelease = !IsTagged && IsReleasable;
+        IsNuGetRelease = IsMainRepo && IsReleasable && IsReleaseBranch;

         // VERSION
         Version = context.Argument("force-nuget-version", GetVersion());
@@ -92,9 +96,13 @@
         }
         else if (IsRunningOnAzure)
         {
+            if(!IsNuGetRelease)
+            {
                 // Use AssemblyVersion with Build as version
                 Version += "-build" + context.EnvironmentVariable("BUILD_BUILDID") + "-beta";
-                PublishTestResults = true;
+            }
+
+            PublishTestResults = true;
         }

         // DIRECTORIES


Fix handling of landmarks for systems with culture settings other than en_US. This fixes Mantis #5177.

--- OpenSim/Framework/AssetLandmark.cs
+++ OpenSim/Framework/AssetLandmark.cs
@@ -51,8 +51,16 @@
             string[] parts = temp.Split('\n');
             int.TryParse(parts[0].Substring(17, 1), out Version);
             UUID.TryParse(parts[1].Substring(10, 36), out RegionID);
-            // the vector is stored with spaces as separators, not with commas ("10.3 32.5 43" instead of "10.3, 32.5, 43")
-            Vector3.TryParse(parts[2].Substring(10, parts[2].Length - 10).Replace(" ", ","), out Position);
+            // The position is a vector with spaces as separators ("10.3 32.5 43").
+            // Parse each scalar separately to take into account the system's culture setting.
+            string[] scalars = parts[2].Substring(10, parts[2].Length - 10).Split(' ');
+            if (scalars.Length > 0)
+                System.Single.TryParse(scalars[0], out Position.X);
+            if (scalars.Length > 1)
+                System.Single.TryParse(scalars[1], out Position.Y);
+            if (scalars.Length > 2)
+                System.Single.TryParse(scalars[2], out Position.Z);
+
             ulong.TryParse(parts[3].Substring(14, parts[3].Length - 14), out RegionHandle);
         }
     }


MSDN documentation is unclear about whether exiting a lock() block will trigger a Monitor.Wait() to exit, so avoid some locks that don't actually affect the state of the internal queues in the BlockingQueue class.

--- OpenSim/Framework/BlockingQueue.cs
+++ OpenSim/Framework/BlockingQueue.cs
@@ -58,7 +58,7 @@
         {
             lock (m_queueSync)
             {
-                if (m_queue.Count < 1 && m_pqueue.Count < 1)
+                while (m_queue.Count < 1 && m_pqueue.Count < 1)
                 {
                     Monitor.Wait(m_queueSync);
                 }
@@ -91,6 +91,9 @@

         public bool Contains(T item)
         {
+            if (m_queue.Count < 1 && m_pqueue.Count < 1)
+                return false;
+
             lock (m_queueSync)
             {
                 if (m_pqueue.Contains(item))
@@ -101,14 +104,14 @@

         public int Count()
         {
-            lock (m_queueSync)
-            {
-                return m_queue.Count+m_pqueue.Count;
-            }
+            return m_queue.Count+m_pqueue.Count;
         }

         public T[] GetQueueArray()
         {
+            if (m_queue.Count < 1 && m_pqueue.Count < 1)
+                return new T[0];
+
             lock (m_queueSync)
             {
                 return m_queue.ToArray();


Add logging to help track sequence of events

--- OpenSim/Server/Base/ServerUtils.cs
+++ OpenSim/Server/Base/ServerUtils.cs
@@ -111,10 +111,12 @@
                 case ExtensionChange.Add:
                     if (a.AddinFile.Contains(Registry.DefaultAddinsFolder))
                     {
+                        m_log.InfoFormat("[SERVER]: Adding {0}", a.Name);
                         connector.PluginPath = String.Format("{0}/{1}", Registry.DefaultAddinsFolder, a.Name.Replace(',', '.'));
                     }
                     else
                     {
+                        m_log.InfoFormat("[SERVER]: Removing {0}", a.Name);
                         connector.PluginPath = a.AddinFile;
                     }
                     LoadPlugin(connector);


More time to settle down before timeout

More time to settle down before timeout

--- AddOns/FastAVN/FastAVN/Program.cs
+++ AddOns/FastAVN/FastAVN/Program.cs
@@ -350,8 +350,8 @@
             deadlineReached = true;
             KillSpawnedProcesses();

-            // Sleep for 2 seconds
-            System.Threading.Thread.Sleep(2 * 1000);
+            // Sleep for 5 seconds
+            System.Threading.Thread.Sleep(5 * 1000);

             // collate bugs
             lock (fslock)


[V2] Whitespace formatting only

[V2] Whitespace formatting only

--- packages/WindowsSDK/8.1/WindowsSDK.cs
+++ packages/WindowsSDK/8.1/WindowsSDK.cs
@@ -30,7 +30,7 @@
 namespace WindowsSDK
 {
     public sealed class WindowsSDKV2 :
-            C.V2.CSDKModule
+        C.V2.CSDKModule
     {
         public WindowsSDKV2()
         {


index SQL formatting

index SQL formatting

--- DbShell.Driver.SqlServer/SqlServerSqlDumper.cs
+++ DbShell.Driver.SqlServer/SqlServerSqlDumper.cs
@@ -171,26 +171,26 @@
                     break;
             }
             if (ix.IsUnique) Put(" ^unique");
-            Put(" ^index %i on %f (", ix.ConstraintName, ix.OwnerTable.FullName);
+            Put(" ^index %i &n^on %f (&>&n", ix.ConstraintName, ix.OwnerTable.FullName);
             bool was = false;
             foreach (var col in ix.Columns.Where(x => !x.IsIncluded))
             {
-                if (was) Put(" ,");
+                if (was) Put("&n,");
                 Put("%i %k", col.RefColumnName, col.IsDescending ? "DESC" : "ASC");
                 was = true;
             }
-            Put(")");
+            Put("&<&n)");
             was = false;
             if (ix.Columns.Any(x => x.IsIncluded))
             {
-                Put(" ^include (");
+                Put(" ^include (&>&n");
                 foreach (var col in ix.Columns.Where(x => x.IsIncluded))
                 {
-                    if (was) Put(" ,");
+                    if (was) Put("&n,");
                     Put("%i", col.RefColumnName);
                     was = true;
                 }
-                Put(")");
+                Put("&<&n)");
             }
             EndCommand();
         }


Set Transaction to null once ambient transaction is completed

--- DynamicRepository.MongoDB/MongoDBRepository.cs
+++ DynamicRepository.MongoDB/MongoDBRepository.cs
@@ -188,6 +188,7 @@

                     System.Transactions.Transaction.Current.TransactionCompleted += (sender, e) => {
                         AmbientTransactionRegister.AmbientTransactions.TryRemove(ambientTransactionId, out _);
+                        Transaction = null;
                     };

                     var enlistment = new MongoDBTransactionScopeEnlistment(Transaction);


Update Index.cshtml

Update Index.cshtml

--- Anlab.Mvc/Views/Home/Index.cshtml
+++ Anlab.Mvc/Views/Home/Index.cshtml
@@ -4,6 +4,7 @@

+        <button type="button" class="close" data-dismiss="alert">×</button>

The lab is experiencing much longer turnarounds than normal.  Most tests are subject to at least 6 - 8 weeks.

        We apologize for this inconvenience.  We are expanding our staffing to address this issue and hope to return to more reasonable turnaround times soon.

        Thank you for your understanding and patience.


Update Index.cshtml

Update Index.cshtml

New update about lab hours

--- Anlab.Mvc/Views/Home/Index.cshtml
+++ Anlab.Mvc/Views/Home/Index.cshtml
@@ -3,7 +3,13 @@
 }

-
We are currently open with normal business hours in order to support on-going essential agricultural research.  Please feel free to email us before shipping samples if there is any concern about a future closure.

+
Posted: April 6, 2020

+        We are scaling back to a bare minimum staff at this time.  We will only be working on samples where immediate testing is essential.  Assisting you with your research is very important to us and we are eager to return to full staffing as soon as it is safe.

+    For the week of April 6-10, receiving will be open from 9am to noon.

+    Starting April 13th for sample drop-off please email us at anlab@ucdavis.edu to arrange a time to meet at receiving.  If you need to ship samples to us, please email us with the expected delivery date.

+    Please use this option for samples requiring immediate testing for essential research.  We can also arrange for receipt of more routine samples if proper storage of samples cannot be arranged in your own facility as we await a return to normal business operations.

+    Please monitor our homepage for updates and thank you for your patience!

+    Please be safe.

The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.

Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses.


Tiny bit of Main() refactoring

Tiny bit of Main() refactoring

--- AntichamberSaveWatcher/Program.cs
+++ AntichamberSaveWatcher/Program.cs
@@ -26,19 +26,13 @@

 		static void Main(string[] args)
 		{
-			Console.CursorVisible = false;
-
 			parseArgs(args);

 			// If a path wasn't specified in a command line arg, attempt to find one from the running processes
 			if (!customPath)
 				findPath();

-			if (!noResize)
-			{
-				Console.SetBufferSize(115, 150);
-				Console.SetWindowSize(115, 8);
-			}
+            setupConsole();

 			if (!trackCubes && !trackSigns && !trackGuns)
 				Console.WriteLine("Currently tracking nothing - are the command line arguments correct?");
@@ -50,11 +44,22 @@
 			fsw.Changed += update;
 			fsw.EnableRaisingEvents = true;

-			//Swallow all keypresses
-			//TODO: Set a key to quit?
+			// Swallow all keypresses
+			// TODO: Set a key to quit?
 			while (true)
 				Console.ReadKey(true);
 		}
+
+        static void setupConsole()
+        {
+            Console.CursorVisible = false;
+
+            if (!noResize)
+            {
+                Console.SetBufferSize(115, 150);
+                Console.SetWindowSize(115, 8);
+            }
+        }

 		static void parseArgs(string[] args)
 		{


Loading the save file will now retry up to 5 times.

--- AntichamberSaveWatcher/Program.cs
+++ AntichamberSaveWatcher/Program.cs
@@ -183,7 +183,7 @@
 						previousGuns.Add(pickup.AssociatedGun);

 				//Reload the save file
-				if (!save.Reload())
+				if (!save.Reload(5))
 				{
 					if (ShowDebug)
 						Console.WriteLine("Unable to reload save file.");


Updated file names in RuntimeInfo.

Updated file names in RuntimeInfo.

--- AntlrGrammarEditor/RuntimeInfo.cs
+++ AntlrGrammarEditor/RuntimeInfo.cs
@@ -22,9 +22,9 @@
             {
                 Runtime = Runtime.CSharp,
                 Name = "C#",
-                JarGenerator = "antlr-4.5.3.jar",
+                JarGenerator = "antlr-4.6-complete.jar",
                 DLanguage = "CSharp",
-                RuntimeLibrary = "Antlr4.Runtime.dll",
+                RuntimeLibrary = "Antlr4.Runtime.Standard.dll",
                 Extensions = new[] { "cs" },
                 MainFile = "Program.cs",
                 AntlrInputStream = "AntlrInputStream",
@@ -34,9 +34,9 @@
             {
                 Runtime = Runtime.Java,
                 Name = "Java",
-                JarGenerator = "antlr-4.5.3.jar",
+                JarGenerator = "antlr-4.6-complete.jar",
                 DLanguage = "Java",
-                RuntimeLibrary = "antlr-runtime-4.5.3.jar",
+                RuntimeLibrary = "antlr-runtime-4.6.jar",
                 Extensions = new[] { "java" },
                 MainFile = "Main.java",
                 AntlrInputStream = "ANTLRInputStream",
@@ -46,7 +46,7 @@
             {
                 Runtime = Runtime.Python2,
                 Name = "Python2",
-                JarGenerator = "antlr-4.5.3.jar",
+                JarGenerator = "antlr-4.6-complete.jar",
                 DLanguage = "Python2",
                 RuntimeLibrary = "",
                 Extensions = new[] { "py" },
@@ -59,7 +59,7 @@
             {
                 Runtime = Runtime.Python3,
                 Name = "Python3",
-                JarGenerator = "antlr-4.5.3.jar",
+                JarGenerator = "antlr-4.6-complete.jar",
                 DLanguage = "Python3",
                 RuntimeLibrary = "",
                 Extensions = new[] { "py" },
@@ -72,7 +72,7 @@
             {
                 Runtime = Runtime.JavaScript,
                 Name = "JavaScript",
-                JarGenerator = "antlr-4.5.3.jar",
+                JarGenerator = "antlr-4.6-complete.jar",
                 DLanguage = "JavaScript",
                 RuntimeLibrary = "",
                 Extensions = new[] { "js" },
@@ -85,7 +85,7 @@
             {
                 Runtime = Runtime.CPlusPlus,
                 Name = "C++ SoftGems",
-                JarGenerator = "antlr-4.5.4-cpp.jar",
+                JarGenerator = "antlr-4.6-complete.jar",
                 DLanguage = "Cpp",
                 RuntimeLibrary = "antlr4-runtime.dll",
                 Extensions = new[] { "cpp", "h" }
@@ -94,7 +94,7 @@
             {
                 Runtime = Runtime.Go,
                 Name = "Go",
-                JarGenerator = "antlr-4.5.2-go.jar",
+                JarGenerator = "antlr-4.6-complete.jar",
                 DLanguage = "Go",
                 RuntimeLibrary = "",
                 Extensions = new[] { "go" },
@@ -102,7 +102,7 @@
                 AntlrInputStream = "antlr.NewInputStream",
                 DefaultCompilerPath = "go",
                 LexerPostfix = "_lexer",
-                ParserPostfix = "_parser"
+                ParserPostfix = "_parser",
             }
         };


Update Utilities.cs

Update Utilities.cs

--- ArchiSteamFarm.Tests/Utilities.cs
+++ ArchiSteamFarm.Tests/Utilities.cs
@@ -25,7 +25,7 @@

 namespace ArchiSteamFarm.Tests {
 	[TestClass]
-#pragma warning disable CA1724
+#pragma warning disable CA1724 // We don't care about the potential conflict, as ASF class name has a priority
 	public sealed class Utilities {
 		[TestMethod]
 		public void AdditionallyForbiddenWordsWeakenPassphrases() => Assert.IsTrue(TestPasswordStrength("10chars<!>asdf", new HashSet<string> { "chars<!>" }).IsWeak);
@@ -48,5 +48,5 @@
 		[TestMethod]
 		public void ShortPassphraseIsWeak() => Assert.IsTrue(TestPasswordStrength("four").IsWeak);
 	}
-#pragma warning restore CA1724
+#pragma warning restore CA1724 // We don't care about the potential conflict, as ASF class name has a priority
 }


fixed demo upload

fixed demo upload

--- Assets/Scripts/Api/Leaderboard.cs
+++ Assets/Scripts/Api/Leaderboard.cs
@@ -50,7 +50,7 @@
                     using (MemoryStream stream = new MemoryStream())
                     {
                         demo.SaveToStream(stream);
-                        RequestData demoData = new BinaryRequestData(stream.GetBuffer());
+                        RequestData demoData = new BinaryRequestData(stream.ToArray());
                         // TODO: get run id from highscore request
                         ApiRequest demoRq = new ApiRequest(Url.DEMOS + "/" + player.ID + "/" + mapID, POST, demoData);
                         demoRq.OnDone += (o, eventArgs) =>


replaced buggy script

replaced buggy script

--- Assets/Scripts/Cards/PointCard.cs
+++ Assets/Scripts/Cards/PointCard.cs
@@ -11,37 +11,23 @@
         GameObject OwnGO;
         GameObject Card;
         SpriteRenderer SpriteRenderer;
-        GameObject Shine;
-        Animator An;
+
         bool cardprocessdone;

         private void Start() {
             OwnGO = GameObject.Find(Slave.GetCardName(cardid, x, y));
-            GameObject F = GameObject.Find("Field");
+            F = GameObject.Find("Field");
             Card = GameObject.Find(Slave.GetCardName(CardID.Card, x, y));
             SpriteRenderer = Card.GetComponent<SpriteRenderer>();
             SpriteRenderer.sprite = Resources.Load<Sprite>(Slave.GetImagePath(team, F.GetComponent<GameManager>().currentChoosedCardGO.GetComponent<Handcards>().PointCardCounter));

-            Shine = (GameObject)Instantiate(Resources.Load("Animations/AN_Shine"));
-            An = Shine.GetComponent<Animator>();
-
-            Shine.transform.position = new Vector3(x, y, -3);
-
+            SetAnimationStart();

-            if (WinCondition() == true) {
-                F.GetComponent<GameManager>().WinScreen.enabled = true;
-                string playerName;
-                if (team == Team.blue) {
-                    playerName = "Player 1" + "!";
-                } else {
-                    playerName = "Player 2" + "!";
-                }
-                GameObject.Find("PlayerNameWin").GetComponent<Text>().text = playerName;
-

-            }
+
+
         }
         protected bool WinCondition() {
             //horizontal
@@ -161,21 +147,25 @@
         void Update() {
             if (cardprocessdone) return;

-            GameObject F = GameObject.Find("Field");
-            if (F.GetComponent<GameManager>().currentChoosedCard != CardID.Doublecard) {
+            if (IsSetAnimationEnd()) {
+                if (WinCondition() == true) {
+                    F.GetComponent<GameManager>().WinScreen.enabled = true;
+                    string playerName;
+                    if (team == Team.blue) {
+                        playerName = "Player 1" + "!";
+                    } else {
+                        playerName = "Player 2" + "!";
+                    }
+                    GameObject.Find("PlayerNameWin").GetComponent<Text>().text = playerName;
+                }
+                cardprocessdone = true;
+                if (F.GetComponent<GameManager>().currentChoosedCard != CardID.Doublecard) {
+                    AnimationDone();
+                }

-                if (An.GetCurrentAnimatorStateInfo(0).IsName("end")) {
-
-                    F.GetComponent<GameManager>().animationDone = true;
-                    cardprocessdone = true;
-                    Destroy(Shine);
-                }
+                //Shine.GetComponent<SpriteRenderer>().enabled = false;
+
             }
         }
     }
-}
-
-
-
-
-
+}


List to Hashset

List to Hashset

--- EngineLayer/ModernSearch/ModernSearchEngine.cs
+++ EngineLayer/ModernSearch/ModernSearchEngine.cs
@@ -159,7 +159,7 @@

         protected void CalculatePeptideScores(IMsDataScan<IMzSpectrum<IMzPeak>> spectrum, double[] peptideScores, double thePrecursorMass)
         {
-            List<int> listSeenipos = new List<int>();
+            HashSet<int> listSeenipos = new HashSet<int>();
             for (int i = 0; i < spectrum.MassSpectrum.Size; i++)
             {
                 var theAdd = 1 + spectrum.MassSpectrum[i].Intensity / spectrum.TotalIonCurrent;
@@ -199,7 +199,7 @@
             }
         }

-        protected void GeneratePeptideScores(double theAdd, double experimentalPeakInDaltons, double[] peptideScores, List<int> listSeenipos)
+        protected void GeneratePeptideScores(double theAdd, double experimentalPeakInDaltons, double[] peptideScores, HashSet<int> listSeenipos)
         {
             float closestPeak;
             var ipos = Array.BinarySearch(keys, (float)experimentalPeakInDaltons);


Adds game over function.

Adds game over function.

--- Assets/Scripts/LevelController.cs
+++ Assets/Scripts/LevelController.cs
@@ -8,14 +8,15 @@
 {
     private int maxBridgesToEndTurn;
     private IslandComponent mouseDownIsland = null;
-    private GameObject newBridge;
     public GameObject bridgeFire;
     public GameObject bridgePrefab;
-    public float maxBridgeLength = 12.0f;
-    private string errorMessage = null;
+    public float maxBridgeLength = 14.0f;
+    private string errorMessage;
+    private bool gameOver;

     void Start ()
     {
+        this.gameOver = false;
         WorldState state = this.FindState ();
         foreach (IslandComponent a in state.islands) {
             foreach (IslandComponent b in state.islands) {
@@ -72,7 +73,7 @@
         GameObject rubble = Instantiate (bridgeFire, bridge.transform.position, bridge.transform.rotation) as GameObject;
         rubble.transform.localScale = bridge.transform.localScale;
         Destroy (bridge.gameObject);
-        state.bridges.Remove(bridge);
+        state.bridges.Remove (bridge);
     }

     private void BuildBridge (WorldState state, IslandComponent island1, IslandComponent island2)
@@ -83,7 +84,7 @@
             bool bridgeAlreadyExists = state.AllIslandsAccessibleFromIsland (island1).Contains (island2);
             if (!bridgeAlreadyExists) {
                 //make a new bridge connecting them
-                newBridge = Instantiate (bridgePrefab, (island2.transform.position + island1.transform.position) / 2, Quaternion.identity) as GameObject;
+                GameObject newBridge = Instantiate (bridgePrefab, (island2.transform.position + island1.transform.position) / 2, Quaternion.identity) as GameObject;
                 this.errorMessage = null;

                 //the bridge prefab is an empty game object, so its child the cylinder is what we want to play with
@@ -105,18 +106,38 @@
         }
     }

+    private bool IsGameOver ()
+    {
+        return this.maxBridgesToEndTurn < 1;
+    }
+
+    private void OnGameOver (WorldState state)
+    {
+        this.errorMessage = String.Format ("Game over. You got {0} family members together! Space to play again.", this.CurrentScore (state));
+    }
+
     void Update ()
     {
         if (Input.GetKeyDown (KeyCode.Space)) {
             WorldState state = this.FindState ();
-            if (this.CanAdvanceTurn (state)) {
+            if (this.gameOver) {
+                Application.LoadLevel(Application.loadedLevel);
+            } else if (this.CanAdvanceTurn (state)) {
                 this.PerformEndTurnStateUpdates (state);
                 this.UpdateGameObjectsToReflectAbstractState (state);
-                this.errorMessage = null;
+                if (this.CanAdvanceTurn(state)) {
+                    this.errorMessage = "Press space to end turn!";
+                } else {
+                    this.errorMessage = null;
+                }
+                if (this.IsGameOver ()) {
+                    this.gameOver = true;
+                    this.OnGameOver (state);
+                }
             } else {
                 this.errorMessage = "You need fewer bridges before this turn can end.";
             }
-        } else if (Input.GetMouseButtonDown (0)) {
+        } else if (Input.GetMouseButtonDown (0) && !this.gameOver) {
             GameObject clicked = this.ClickedObject ();
             if (clicked) {
                 BridgeComponent clickedBridge = clicked.GetComponent<BridgeComponent> ();
@@ -134,7 +155,7 @@
                     this.mouseDownIsland = clickedIsland;
                 }
             }
-        } else if (Input.GetMouseButtonUp (0)) {
+        } else if (Input.GetMouseButtonUp (0) && !this.gameOver) {
             GameObject clicked = this.ClickedObject ();
             if (clicked) {
                 IslandComponent clickedIsland = clicked.GetComponent<IslandComponent> ();


Repeat: Provide IGremlinQuery<Unit> instead of non-typed IGremlinQuery to traversal-function.

--- ExRam.Gremlinq/Gremlin/GremlinQueryLanguage.cs
+++ ExRam.Gremlinq/Gremlin/GremlinQueryLanguage.cs
@@ -367,7 +367,7 @@
                 .AddStep<T>("range", low, high);
         }

-        public static IGremlinQuery<T> Repeat<T>(this IGremlinQuery query, Func<IGremlinQuery, IGremlinQuery<T>> repeatTraversal)
+        public static IGremlinQuery<T> Repeat<T>(this IGremlinQuery query, Func<IGremlinQuery<Unit>, IGremlinQuery<T>> repeatTraversal)
         {
             return query
                 .AddStep<T>("repeat", repeatTraversal(query.Cast<Unit>().ToAnonymous()));


Search in bin32 and bin64 subfolders for executables

--- source/UninstallTools/Factory/InfoAdders/AppExecutablesSearcher.cs
+++ source/UninstallTools/Factory/InfoAdders/AppExecutablesSearcher.cs
@@ -16,7 +16,7 @@
     {
         internal static readonly string[] BinaryDirectoryNames =
         {
-            "bin", "program", "client", "app", "application", "win32", "win64" //"system"
+            "bin", "bin32", "bin64", "program", "client", "app", "application", "win32", "win64" //"system"
         };

         public string[] CanProduceValueNames { get; } = {


Oops.  Broke something.  Fixed something.

Oops.  Broke something.  Fixed something.

git-svn-id: 64cc320d9ecd7aad470f8b18be342a8e58536f88@314 a61f9e97-bd4c-0410-8c65-85b29eaa70ff

--- Examples/Graphics/ShadersInSpaaace/MainForm.cs
+++ Examples/Graphics/ShadersInSpaaace/MainForm.cs
@@ -91,7 +91,7 @@
 			Vector2D pos = Vector2D.Zero;	// Position.

 			Gorgon.CurrentRenderTarget = _grainTarget;
-			_grainTarget.Clear(Drawing.Color.FromArgb((byte)_rnd.Next(32), 0, 0, 0));
+			_grainTarget.Clear(Drawing.Color.FromArgb((byte)_rnd.Next(32), 255, 255, 255));

 			_grainTarget.BeginDrawing();
 			for (int i = 0; i < 25; i++)


Update 1940 US Census

Update 1940 US Census

--- FTAnalyser/FactDateTest/CensusReferenceTest.cs
+++ FTAnalyser/FactDateTest/CensusReferenceTest.cs
@@ -92,10 +92,11 @@
             //UKCensusTest("Archive reference	RG11\nPiece number	870\nFolio	49\nPage	10", CensusDate.UKCENSUS1881, "870", "49", "10");
             UKCensusTest("RG11 Piece/Folio  4738 / 103 Page Number  16", CensusDate.UKCENSUS1881, "4738", "103", "16");
             UKCensusTest("RG11 Piece 2529 Folio 68 Page 1", CensusDate.UKCENSUS1881, "2529", "68", "1");
+            UKCensusTest("Class: RG11; Piece: 3934; Folio: 60; Page: 9; Line:; GSU roll: 1341939", CensusDate.UKCENSUS1881, "3934", "60", "9");

             Canadian1881Census("        123/A/55/35/1	Canada 1881", "123", "A", "35", "1");
             Canadian1881Census("        123/A/35/1	Canada 1881", "123", "A", "35", "1");
-            Canadian1881Census("C_13266; Page 67; Family 301", "132", "C", "67", "301");
+            //Canadian1881Census("C_13266; Page 67; Family 301", "132", "C", "67", "301");
             CanadianCensus("Year: 1881; Census Place: Richibucto, Kent, New Brunswick; Roll: C_13184; Page: 32; Family No: 144", CensusDate.CANADACENSUS1881, "C_13184", "32", "144");
             Canadian1881Census("1881 census - District 146/B, Page 59, Family 273 - living at Rainham, Haldimand, Ontario, Canada.", "146", "B", "59", "273");
             //CanadianCensus("Event Place: Dumfries South, Brant North, Ontario, Canada\nDistrict Number: 160\nSub-District: C\nDivision: 2\nPage Number: 1\nFamily Number: 3\nAffiliate Film Number: C-13264", , CensusDate.CANADACENSUS1881, "C_13184", "1", "3");


Consistency

Consistency

--- BethFile/Archive/SkyrimArchive.cs
+++ BethFile/Archive/SkyrimArchive.cs
@@ -26,18 +26,18 @@

             // "BSA\0", ASCII-encoded
             const uint Magic = 4281154;
-            if (BitConverter.ToUInt32(metaBuf, 0) != Magic)
+            if (MBitConverter.To<uint>(metaBuf, 0) != Magic)
             {
                 throw new NotSupportedException("I don't know how to read this stream as a BSA file.");
             }

-            var version = BitConverter.ToUInt32(metaBuf, 4);
+            var version = MBitConverter.To<uint>(metaBuf, 4);
             if (version != 104 && version != 103)
             {
                 throw new NotSupportedException("I don't know how to read BSA files for games other than Skyrim / Oblivion.");
             }

-            var flags = (ArchiveFlags)BitConverter.ToInt32(metaBuf, 12);
+            var flags = MBitConverter.To<ArchiveFlags>(metaBuf, 12);

             if (flags.HasFlag(ArchiveFlags.IsXbox360))
             {
@@ -52,14 +52,14 @@

             var embeddedFileNames = flags.HasFlag(ArchiveFlags.EmbedFileNames);

-            var numberOfFolders = checked((int)BitConverter.ToUInt32(metaBuf, 16));
-            var numberOfFiles = checked((int)BitConverter.ToUInt32(metaBuf, 20));
+            var numberOfFolders = checked((int)MBitConverter.To<uint>(metaBuf, 16));
+            var numberOfFiles = checked((int)MBitConverter.To<uint>(metaBuf, 20));

             var folders = new(int fileCount, string folder)[numberOfFolders];
             for (int i = 0; i < folders.Length; i++)
             {
                 await archiveStream.LoopedReadAsync(metaBuf, 0, 16, cancellationToken).ConfigureAwait(false);
-                folders[i].fileCount = checked((int)BitConverter.ToUInt32(metaBuf, 8));
+                folders[i].fileCount = checked((int)MBitConverter.To<uint>(metaBuf, 8));
             }

             var compressedOnes = new BitArray(numberOfFiles, flags.HasFlag(ArchiveFlags.CompressedByDefault));
@@ -75,8 +75,8 @@
                 for (int j = 0; j < fileCount; j++)
                 {
                     await archiveStream.LoopedReadAsync(metaBuf, 0, 16, cancellationToken).ConfigureAwait(false);
-                    files[currFileIndex].size = checked((int)BitConverter.ToUInt32(metaBuf, 8));
-                    files[currFileIndex].dataOffset = checked((int)BitConverter.ToUInt32(metaBuf, 12));
+                    files[currFileIndex].size = checked((int)MBitConverter.To<uint>(metaBuf, 8));
+                    files[currFileIndex].dataOffset = checked((int)MBitConverter.To<uint>(metaBuf, 12));

                     if ((files[currFileIndex].size & (1 << 30)) != 0)
                     {


Improving and formating an example

Improving and formating an example

--- Biggy/Examples/CompressedStore.cs
+++ Biggy/Examples/CompressedStore.cs
@@ -4,68 +4,45 @@
 using System.IO.Compression;
 using Biggy;

-namespace BiggyTry
+namespace Biggy.Examples
 {
-    // Here is an example of compressed file store decorator, which takes advantage of that
-    // JsonStore (or any file-based store) doesn't use file system directly. So we can simply
-    // add file compression above of other store, which knowns how to serialize objects.
-    //
-    // USAGE (decorate file-base store with CompressedStore):
-    //
-    //         var gzipStore = new CompressedStore<Person>(new JsonStore<Person>());
-    //         var biggyList = new BiggyList<Person>(gzipStore);
-    public class CompressedStore<T> : Biggy.FileSystemStore<T>, IBiggyStore<T> where T : new()
-    {
-        // Decorated store which knows how to serialize (like JsonStore)
-        private readonly FileSystemStore<T> _fs;
+  // Here is an example of compressed file store decorator, which takes advantage of that
+  // JsonStore (or any file-based store) doesn't use file system directly. So we can simply
+  // add file compression above of other store, which knows how to serialize objects.
+  //
+  // USAGE (decorate file-base store with CompressedStore):
+  //
+  //         var gzipStore = new CompressedStore<Person>(new JsonStore<Person>());
+  //         var biggyList = new BiggyList<Person>(gzipStore);
+  //
+  public class CompressedStore<T> : Biggy.FileSystemStore<T> where T : new() {
+    // Decorated store which knows how to serialize (e.g. JsonStore)
+    private readonly FileSystemStore<T> _fs;

-        public CompressedStore(FileSystemStore<T> store)
-        {
-            _fs = store;
-        }
+    public CompressedStore(FileSystemStore<T> store) {
+      _fs = store;
+    }

-        protected override string GetFileName(string dbname)
-        {
-            return dbname + ".gzip";
-        }
+    protected override string GetFileName(string dbname) {
+      return dbname + ".gzip";
+    }

-        // Because file operations are done in FileSystemStore and decorated store (_fs) only uses
-        // stream object to read/write, then we just need to inject compression stream when read/write
-        // from compressed file.
-        public override List<T> Load(Stream stream)
-        {
-            using (var gzip = new GZipStream(stream, CompressionMode.Decompress))
-                return _fs.Load(gzip);
-        }
+    // Because file operations are done in FileSystemStore and decorated store (_fs) only uses
+    // stream object to read/write, then we just need to inject compression stream when read/write
+    // from compressed file. Lol even append works well ;-)
+    public override List<T> Load(Stream stream) {
+      using (var gzip = new GZipStream(stream, CompressionMode.Decompress))
+        return _fs.Load(gzip);
+    }

-        public override void SaveAll(Stream stream, List<T> items)
-        {
-            using (var gzip = new GZipStream(stream, CompressionLevel.Fastest))
-                _fs.SaveAll(gzip, items);
-        }
+    public override void SaveAll(Stream stream, List<T> items) {
+      using (var gzip = new GZipStream(stream, CompressionLevel.Fastest))
+        _fs.SaveAll(gzip, items);
+    }

-        // However there is one catch here. JsonStore can append items to list without rewrite whole file
-        // and FileSystemStore calls Append method passing appendable stream to just append more lines to the file.
-        // In compressed file I think this is no longer possible, so we need change this behaviour and flush
-        // to file in case of adding items.
-        T IBiggyStore<T>.Add(T item)
-        {
-            _items.Add(item);
-            ((IBiggyStore<T>)this).SaveAll(_items);
-            return item;
-        }
-
-        List<T> IBiggyStore<T>.Add(List<T> items)
-        {
-            _items.AddRange(items);
-            ((IBiggyStore<T>)this).SaveAll(_items);
-            return items;
-        }
-
-        // We have changed above "Add" methods, that Append won't be called so we can ignore this method
-        public override void Append(Stream stream, List<T> items)
-        {
-            throw new NotImplementedException();
-        }
+    public override void Append(Stream stream, List<T> items) {
+      using (var gzip = new GZipStream(stream, CompressionLevel.Fastest))
+        _fs.Append(gzip, items);
     }
+  }
 }


Made it so that you must wave with your tracking hand to get out of selection mode. Waving with your non-tracking hand with switch tracking hands

--- iNetworkClient/MainWindow.xaml.cs
+++ iNetworkClient/MainWindow.xaml.cs
@@ -396,16 +396,20 @@
             switch (e.GestureName)
             {
                 case "WaveLeft":
+                    if(TrackingJoint == JointType.HandLeft)
+                        InSelectionMode = !InSelectionMode;
+
                     TrackingJoint = JointType.HandLeft;
                     trackingBrush.ImageSource = new BitmapImage(new Uri(@"../../Resources/leftHand.png", UriKind.Relative));
                     break;
                 case "WaveRight":
+                    if (TrackingJoint == JointType.HandRight)
+                        InSelectionMode = !InSelectionMode;
+
                     TrackingJoint = JointType.HandRight;
                     trackingBrush.ImageSource = new BitmapImage(new Uri(@"../../Resources/rightHand.png", UriKind.Relative));
                     break;
             }
-
-            InSelectionMode = !InSelectionMode;
         }


Update

Update

--- src/EditorFeatures/CSharpTest/UseIndexOrRangeOperator/UseIndexOperatorTests.cs
+++ src/EditorFeatures/CSharpTest/UseIndexOrRangeOperator/UseIndexOperatorTests.cs
@@ -307,4 +307,3 @@
 }", parameters: s_testParameters);
         }
     }
-}


Remove unused using

Remove unused using

--- src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs
+++ src/Features/Core/Portable/EncapsulateField/AbstractEncapsulateFieldService.cs
@@ -13,7 +13,6 @@
 using Microsoft.CodeAnalysis;
 using Microsoft.CodeAnalysis.CodeGeneration;
 using Microsoft.CodeAnalysis.Editing;
-using Microsoft.CodeAnalysis.FindSymbols;
 using Microsoft.CodeAnalysis.Formatting;
 using Microsoft.CodeAnalysis.Host;
 using Microsoft.CodeAnalysis.PooledObjects;