Пример #1
0
        public void IListClear()
        {
            var p = new JProperty("TestProperty", null);
            IList l = p;

            AssertException.Throws<JsonException>(() => { l.Clear(); }, "Cannot add or remove items from OpenGamingLibrary.Json.Linq.JProperty.");
        }
Пример #2
0
        public void IListCount()
        {
            var p = new JProperty("TestProperty", null);
            IList l = p;

            Assert.Equal(1, l.Count);
        }
Пример #3
0
        public void NullValue()
        {
			var p = new JProperty("TestProperty", null);
            Assert.NotNull(p.Value);
            Assert.Equal(JTokenType.Null, p.Value.Type);
            Assert.Equal(p, p.Value.Parent);

            p.Value = null;
            Assert.NotNull(p.Value);
            Assert.Equal(JTokenType.Null, p.Value.Type);
            Assert.Equal(p, p.Value.Parent);
        }
Пример #4
0
        public void ListChanged()
        {
            var p = new JProperty("TestProperty", null);
            IBindingList l = p;

            ListChangedType? listChangedType = null;
            int? index = null;

            l.ListChanged += (sender, args) =>
            {
                listChangedType = args.ListChangedType;
                index = args.NewIndex;
            };

            p.Value = 1;

            Assert.Equal(ListChangedType.ItemChanged, listChangedType.Value);
            Assert.Equal(0, index.Value);
        }
Пример #5
0
        public void ReplaceJPropertyWithJPropertyWithSameName()
        {
            JProperty p1 = new JProperty("Test1", 1);
            JProperty p2 = new JProperty("Test2", "Two");

            var o = new JObject(p1, p2);
            IList l = o;
            Assert.Equal(p1, l[0]);
            Assert.Equal(p2, l[1]);

            JProperty p3 = new JProperty("Test1", "III");

            p1.Replace(p3);
            Assert.Equal(null, p1.Parent);
            Assert.Equal(l, p3.Parent);

            Assert.Equal(p3, l[0]);
            Assert.Equal(p2, l[1]);

            Assert.Equal(2, l.Count);
            Assert.Equal(2, o.Properties().Count());

            JProperty p4 = new JProperty("Test4", "IV");

            p2.Replace(p4);
            Assert.Equal(null, p2.Parent);
            Assert.Equal(l, p4.Parent);

            Assert.Equal(p3, l[0]);
            Assert.Equal(p4, l[1]);
        }
        /// <summary>
        /// To handle custom settings, we serialize using LaunchProfileData first and then walk the settings
        /// to pick up other settings. Currently limited to boolean, integer, string and dictionary of string
        /// </summary>
        public static Dictionary <string, LaunchProfileData> DeserializeProfiles(JObject profilesObject)
        {
            var profiles = new Dictionary <string, LaunchProfileData>(StringComparer.Ordinal);

            if (profilesObject == null)
            {
                return(profiles);
            }

            // We walk the profilesObject and serialize each subobject component as either a string, or a dictionary<string,string>
            foreach (var profile in profilesObject)
            {
                // Name of profile is the key, value is it's contents. We have specific serializing of the data based on the
                // JToken type
                LaunchProfileData profileData = JsonConvert.DeserializeObject <LaunchProfileData>(profile.Value.ToString());

                // Now pick up any custom properties. Handle string, int, boolean
                Dictionary <string, object> customSettings = new Dictionary <string, object>(StringComparer.Ordinal);
                foreach (var data in profile.Value.Children())
                {
                    JProperty dataProperty = data as JProperty;
                    if (dataProperty == null)
                    {
                        continue;
                    }
                    if (!IsKnownProfileProperty(dataProperty.Name))
                    {
                        try
                        {
                            switch (dataProperty.Value.Type)
                            {
                            case JTokenType.Boolean:
                            {
                                bool value = bool.Parse(dataProperty.Value.ToString());
                                customSettings.Add(dataProperty.Name, value);
                                break;
                            }

                            case JTokenType.Integer:
                            {
                                int value = int.Parse(dataProperty.Value.ToString());
                                customSettings.Add(dataProperty.Name, value);
                                break;
                            }

                            case JTokenType.Object:
                            {
                                var value = JsonConvert.DeserializeObject <Dictionary <string, string> >(dataProperty.Value.ToString());
                                customSettings.Add(dataProperty.Name, value);
                                break;
                            }

                            case JTokenType.String:
                            {
                                customSettings.Add(dataProperty.Name, dataProperty.Value.ToString());
                                break;
                            }

                            default:
                            {
                                break;
                            }
                            }
                        }
                        catch
                        {
                            // TODO: should have message indicating the setting is being ignored. Fix as part of issue
                            //       https://github.com/dotnet/roslyn-project-system/issues/424
                        }
                    }
                }

                // Only add custom settings if we actually picked some up
                if (customSettings.Count > 0)
                {
                    profileData.OtherSettings = customSettings;
                }

                profiles.Add(profile.Key, profileData);
            }

            return(profiles);
        }
Пример #7
0
        public void IListGenericAdd()
        {
            IList<JToken> t = new JProperty("error", new List<string> { "one", "two" });

            AssertException.Throws<JsonException>(() => { t.Add(1); }, "OpenGamingLibrary.Json.Linq.JProperty cannot have multiple values.");
        }
Пример #8
0
        public void JPropertyDeepEquals()
        {
            JProperty p1 = new JProperty("TestProperty", null);
            JProperty p2 = new JProperty("TestProperty", null);

            Assert.Equal(true, JToken.DeepEquals(p1, p2));
        }
Пример #9
0
        public void IListSetItemInvalid()
        {
            AssertException.Throws<ArgumentException>(() =>
            {
                JProperty p1 = new JProperty("Test1", 1);
                JProperty p2 = new JProperty("Test2", "Two");
                IList l = new JObject(p1, p2);

                l[0] = new JValue(true);
            }, @"Can not add OpenGamingLibrary.Json.Linq.JValue to OpenGamingLibrary.Json.Linq.JObject.");
        }
Пример #10
0
        public void IListRemoveAt()
        {
            JProperty p1 = new JProperty("Test1", 1);
            JProperty p2 = new JProperty("Test2", "Two");
            IList l = new JObject(p1, p2);

            // won't do anything
            l.RemoveAt(0);

            l.Remove(p1);
            Assert.Equal(1, l.Count);

            l.Remove(p2);
            Assert.Equal(0, l.Count);
        }
Пример #11
0
        public void IListAddBadToken()
        {
            AssertException.Throws<ArgumentException>(() =>
            {
                JProperty p1 = new JProperty("Test1", 1);
                JProperty p2 = new JProperty("Test2", "Two");
                IList l = new JObject(p1, p2);

                l.Add(new JValue("Bad!"));
            }, "Can not add OpenGamingLibrary.Json.Linq.JValue to OpenGamingLibrary.Json.Linq.JObject.");
        }
        /// <summary>
        /// Verifies the extension rule.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            ServiceStatus serviceStatus    = ServiceStatus.GetInstance();
            DataFactory   dFactory         = DataFactory.Instance();
            var           detail           = new ExtensionRuleResultDetail(this.Name, serviceStatus.RootURL, HttpMethod.Post, string.Empty);
            string        updateUrl        = serviceStatus.RootURL;
            List <string> keyPropertyTypes = new List <string>()
            {
                "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String"
            };
            List <string> norPropertyTypes = new List <string>()
            {
                "Edm.String"
            };

            List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, null, NavigationRoughType.None).ToList();

            if (null == entityTypeElements || 0 == entityTypeElements.Count)
            {
                detail.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property and a string type normal property, but there is no this entity type in metadata so can not verify this rule.";
                info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail);

                return(passed);
            }

            EntityTypeElement entityType = null;

            Dictionary <string, Dictionary <KeyValuePair <string, string>, List <string> > > entityTypeInfo = new Dictionary <string, Dictionary <KeyValuePair <string, string>, List <string> > >();

            bool foundEntity = MetadataHelper.GetEntityTypesWithComplexProperty(serviceStatus.MetadataDocument, "Edm.String", out entityTypeInfo);

            if (foundEntity)
            {
                foreach (var en in entityTypeElements)
                {
                    if (entityTypeInfo.Keys.Contains(en.EntityTypeShortName) && !string.IsNullOrEmpty(en.EntitySetName))
                    {
                        entityType = en;
                        break;
                    }
                }
            }
            else
            {
                detail.ErrorMessage = "To verify this rule it expects an entity type with complex type normal property, but there is no this entity type in metadata so can not verify this rule.";
                info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail);

                return(passed);
            }

            if (entityType == null)
            {
                detail.ErrorMessage = "To verify this rule it expects an entity type with complex type normal property, but there is no this entity type in metadata so can not verify this rule.";
                info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail);

                return(passed);
            }

            Dictionary <KeyValuePair <string, string>, List <string> >   complexProps = entityTypeInfo[entityType.EntityTypeShortName];
            KeyValuePair <KeyValuePair <string, string>, List <string> > complexPop   = complexProps.First();
            string complexPropName = complexPop.Key.Key;

            string entitySetUrl = entityType.EntitySetName.MapEntitySetNameToEntitySetURL();

            updateUrl = entitySetUrl;

            string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl;

            updateUrl = url;
            var     additionalInfos = new List <AdditionalInfo>();
            JObject reqData         = dFactory.ConstructInsertedEntityData(entityType.EntitySetName, entityType.EntityTypeShortName, null, out additionalInfos);

            if (!dFactory.CheckOrAddTheMissingPropertyData(entityType.EntitySetName, complexPropName, ref reqData))
            {
                detail.ErrorMessage = "The property to update does not exist, and cannot be updated.";
                info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail);

                return(passed);
            }

            string reqDataStr  = reqData.ToString();
            bool   isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag);
            var    resp        = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, isMediaType, ref additionalInfos);

            detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr);

            if (HttpStatusCode.Created == resp.StatusCode)
            {
                string entityId = additionalInfos.Last().EntityId;
                updateUrl = entityId.TrimEnd('/') + "/" + complexPropName;
                bool hasEtag = additionalInfos.Last().HasEtag;
                resp   = WebHelper.GetPropertyValue(updateUrl);
                detail = new ExtensionRuleResultDetail(this.Name, entityId, HttpMethod.Get, string.Empty, resp);
                if (HttpStatusCode.OK == resp.StatusCode || HttpStatusCode.NoContent == resp.StatusCode)
                {
                    JProperty complexPropContent = null;

                    foreach (JProperty prop in reqData.Children <JProperty>())
                    {
                        if (prop.Name.Equals(complexPropName))
                        {
                            complexPropContent = prop;
                            break;
                        }
                    }

                    resp   = WebHelper.UpdateComplexProperty(updateUrl, context.RequestHeaders, complexPropContent, hasEtag, complexPop.Value);
                    detail = new ExtensionRuleResultDetail(this.Name, updateUrl, HttpMethod.Patch, string.Empty, resp, string.Empty, reqDataStr);
                    if (HttpStatusCode.NoContent == resp.StatusCode)
                    {
                        resp   = WebHelper.GetPropertyValue(updateUrl);
                        detail = new ExtensionRuleResultDetail(this.Name, updateUrl, HttpMethod.Get, string.Empty, resp, string.Empty, reqDataStr);

                        if (HttpStatusCode.OK == resp.StatusCode)
                        {
                            JObject value;
                            resp.ResponsePayload.TryToJObject(out value);

                            bool updated = true;

                            if (value != null && value.Type == JTokenType.Object)
                            {
                                foreach (var prop in value.Children <JProperty>())
                                {
                                    if (complexPop.Value.Contains(prop.Name))
                                    {
                                        updated = prop.Value.ToString().Equals(Constants.UpdateData);
                                    }

                                    if (!updated)
                                    {
                                        passed = false;
                                        detail.ErrorMessage = string.Format("The compelex property in request fails in HTTP patch updating.");
                                        break;
                                    }
                                }

                                if (updated)
                                {
                                    passed = true;
                                }
                            }
                        }
                        else
                        {
                            passed = false;
                            detail.ErrorMessage = "Can not get the updated entity.";
                        }
                    }
                    else
                    {
                        passed = false;
                        detail.ErrorMessage = "HTTP Patch the complex property failed.";
                    }
                }
                else
                {
                    detail.ErrorMessage = "Can not get the created entity from above URI.";
                }

                // Restore the service.
                var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos);
            }
            else
            {
                detail.ErrorMessage = "Created the new entity failed for above URI.";
            }

            var details = new List <ExtensionRuleResultDetail>()
            {
                detail
            };

            info = new ExtensionRuleViolationInfo(new Uri(updateUrl), serviceStatus.ServiceDocument, details);

            return(passed);
        }
Пример #13
0
 public Element(JProperty property)
 {
     FullName = property.Name;
     Hash     = property.Property("hash").Value.ToString();
     Size     = long.Parse(property.Property("size").Value.ToString());
 }
Пример #14
0
        /// <summary>
        /// Recursively sorts a JSON.NET JToken
        /// </summary>
        /// <param name="jtoken">The Internal tokenized representation of the JSON</param>
        /// <returns>a recursively sorted JToken object</returns>
        public static JToken Sort(JToken jtoken)
        {
            //base case 1: not a container
            if (!(jtoken is JContainer))
            {
                return(jtoken);
            }

            bool childIsContainer = jtoken.ChildIsContainer();
            var  childType        = jtoken.ChildType();

            //base case 2: property and child is not a container
            if (jtoken is JProperty && !childIsContainer)
            {
                return(jtoken);
            }

            //treat jtoken as container via jcontainer variable
            var jcontainer = jtoken as JContainer;

            //initialize a list of strings for storing serialized child tokens
            var serializedElements = new SortedDictionary <string, JToken>();

            //loop through all child tokens of the current token
            var children = jcontainer.Children();

            foreach (var child in children)
            {
                //recursively sort the child token
                var sorted = Sort(child);
                //serialize the sorted child token and add it to the string list
                serializedElements.Add(sorted.ToString(), child);
            }

            //handle JProperty
            if (jcontainer is JProperty && childIsContainer)
            {
                JContainer propValue;
                if (childType == JTokenType.Array)
                {
                    propValue = new JArray();
                }
                else
                {
                    propValue = new JObject();
                }

                foreach (var key in serializedElements.Keys)
                {
                    var sortedChildToAdd = serializedElements[key];
                    if (sortedChildToAdd.Type == JTokenType.Object && propValue.Type == JTokenType.Object)
                    {
                        propValue.Add(new JProperty((jcontainer as JProperty).Name, propValue));
                    }
                    else
                    {
                        propValue.Add(sortedChildToAdd);
                    }
                }

                jcontainer = new JProperty((jcontainer as JProperty).Name, propValue);

                //handle JObject and JArray
            }
            else
            {
                jcontainer.RemoveAll();

                foreach (var key in serializedElements.Keys)
                {
                    jcontainer.Add(serializedElements[key]);
                }
            }

            return(jcontainer);
        }
Пример #15
0
        public static JToken ReadJson(JsonTextReader jr, JToken own, bool isRoot = false)
        {
            if (own == null && isRoot)
            {
                own = new JObject();
            }
            JProperty jp = null;

            while (jr.Read())
            {
                switch (jr.TokenType)
                {
                case JsonToken.StartObject:
                {
                    JToken jo = null;
                    if (!isRoot)
                    {
                        jo = new JObject();
                        if (jp != null)
                        {
                            jp.Value = jo;
                            jp       = null;
                        }
                        else if (own is JObject)
                        {
                            ((JObject)own).Add(jo);
                        }
                        else if (own is JArray)
                        {
                            ((JArray)own).Add(jo);
                        }
                        else
                        {
                            throw new Exception($"Неизвестный тип владельца {own.GetType()}");
                        }
                    }
                    else
                    {
                        jo = own;
                    }
                    ReadJson(jr, jo);
                }
                break;

                case JsonToken.StartArray:
                {
                    JToken jo = null;
                    if (!isRoot)
                    {
                        jo = new JArray();
                        if (jp != null)
                        {
                            jp.Value = jo;
                            jp       = null;
                        }
                        else if (own is JObject)
                        {
                            ((JObject)own).Add(jo);
                        }
                        else if (own is JArray)
                        {
                            ((JArray)own).Add(jo);
                        }
                        else
                        {
                            throw new Exception($"Неправильный тип владельца {own.GetType()}");
                        }
                    }
                    else
                    {
                        jo = own;
                    }
                    ReadJson(jr, jo);
                }
                break;

                case JsonToken.EndObject:
                case JsonToken.EndArray:
                    return(own);

                case JsonToken.PropertyName:
                {
                    if (jp != null)
                    {
                        throw new Exception($"Свойство не сброшено {own.GetType()}");
                    }
                    jp = new JProperty(jr.Value.ToString().Replace("%#%", $"%#%_{FileId}"), null);
                    if (own is JObject)
                    {
                        ((JObject)own).Add(jp);
                    }
                    else
                    {
                        throw new Exception($"Неправильный тип владельца {own.GetType()}");
                    }
                }
                break;

                case JsonToken.String:
                {
                    JValue jv = new JValue(jr.Value);
                    if (jv.Value.ToString().Contains("%#%"))
                    {
                        jv.Value = jv.Value.ToString().Replace("%#%", $"%#%_{FileId}");
                    }
                    if (jp != null)
                    {
                        jp.Value = jv;
                    }
                    else
                    {
                        if (own is JArray)
                        {
                            ((JArray)own).Add(jv);
                        }
                        else
                        {
                            throw new Exception($"Неправильный тип владельца {own.GetType()}");
                        }
                    }
                    jp = null;
                }
                break;

                case JsonToken.Boolean:
                case JsonToken.Bytes:
                case JsonToken.Date:
                case JsonToken.Float:
                case JsonToken.Integer:
                case JsonToken.Null:
                {
                    JValue jv = new JValue(jr.Value);
                    if (jp != null)
                    {
                        jp.Value = jv;
                    }
                    else
                    {
                        if (own is JArray)
                        {
                            ((JArray)own).Add(jv);
                        }
                        else
                        {
                            throw new Exception($"Неправильный тип владельца {own.GetType()}");
                        }
                    }
                    jp = null;
                }
                break;

                case JsonToken.None:
                case JsonToken.Undefined:
                    break;

                case JsonToken.Comment:
                {
                    if (own is JObject)
                    {
                        string s = jr.Value.ToString().Trim().Replace("%#%", $"%#%_{FileId}");
                        if (s.ToLower().Contains("function"))
                        {
                            int i = s.IndexOf(':');
                            if (i > 0)
                            {
                                ((JObject)own).Add(new JProperty(s.Substring(0, i), s.Substring(i + 1).Trim()));
                            }
                        }
                    }
                }
                break;

                default:
                    throw new Exception($"Неправильный тип токена {jr.TokenType}");
                }
            }
            return(own);
        }
Пример #16
0
        public static object ReadJsonStatic(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (objectType == typeof(string))
            {
                if (reader.TokenType == JsonToken.String)
                {
                    var stringValue = reader.Value as string;
                    return(stringValue);
                }
                if (reader.TokenType == JsonToken.Null)
                {
                    return(null);
                }
            }

            if (objectType.IsSubClassOfGeneric(typeof(IReferenceable)))
            {
                if (objectType.IsSubClassOfGeneric(typeof(IRef <>)))
                {
                    var id = GetGuid();
                    if (id.IsDefault())
                    {
                        return(existingValue);
                    }
                    var refType = typeof(Ref <>).MakeGenericType(objectType.GenericTypeArguments);
                    return(Activator.CreateInstance(refType, id));
                }
            }

            if (objectType.IsSubClassOfGeneric(typeof(IReferenceableOptional)))
            {
                if (objectType.IsSubClassOfGeneric(typeof(IRefOptional <>)))
                {
                    var id = GetGuidMaybe();

                    if (id == null)
                    {
                        return(RefOptionalHelper.CreateEmpty(objectType.GenericTypeArguments.First()));
                    }

                    var refType = typeof(RefOptional <>).MakeGenericType(objectType.GenericTypeArguments);
                    return(Activator.CreateInstance(refType, id));
                }
            }

            if (objectType.IsSubClassOfGeneric(typeof(IReferences)))
            {
                if (objectType.IsSubClassOfGeneric(typeof(IRefs <>)))
                {
                    var ids     = GetGuids();
                    var refType = typeof(Refs <>).MakeGenericType(objectType.GenericTypeArguments);
                    return(Activator.CreateInstance(refType, ids));
                }
            }

            if (objectType.IsSubClassOfGeneric(typeof(IDictionary <,>)))
            {
                var dictionaryType = typeof(Dictionary <,>).MakeGenericType(objectType.GenericTypeArguments);
                var instance       = Activator.CreateInstance(dictionaryType);

                if (reader.TokenType == JsonToken.StartArray)
                {
                    var addMethod = dictionaryType.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);
                    while (reader.Read())
                    {
                        if (reader.TokenType == JsonToken.EndArray)
                        {
                            return(instance);
                        }

                        if (reader.TokenType != JsonToken.StartObject)
                        {
                            Console.WriteLine($"{reader.TokenType} != JsonToken.StartObject");
                            continue;
                        }
                        if (!reader.Read())
                        {
                            Console.WriteLine($"Reader terminated w/o finding JsonToken.EndArray");
                            return(instance);
                        }

                        if (!GetValue("key", objectType.GenericTypeArguments.First(), out object keyValue))
                        {
                            continue;
                        }

                        if (!GetValue("value", objectType.GenericTypeArguments.Last(), out object valueValue))
                        {
                            continue;
                        }

                        addMethod.Invoke(instance, new object[] { keyValue, valueValue });

                        if (reader.TokenType != JsonToken.EndObject)
                        {
                            Console.WriteLine($"{reader.TokenType} != JsonToken.EndObject");
                        }
                        //if (!reader.Read())
                        //{
                        //    Console.WriteLine($"Reader terminated w/o finding JsonToken.EndArray (after kvp).");
                        //    return instance;
                        //}
                        bool GetValue(string expectedName, Type type, out object value)
                        {
                            if (reader.TokenType != JsonToken.PropertyName)
                            {
                                value = null;
                                return(false);
                            }

                            var jprop = JProperty.Load(reader);
                            //Console.WriteLine($"Property[{jprop.Name}] = ({type.FullName}) {jprop.Value.Value<string>()}");
                            var name        = jprop.Name;
                            var valueReader = jprop.Value.CreateReader();

                            value = serializer.Deserialize(valueReader, type);
                            if (expectedName.Equals(name, StringComparison.InvariantCultureIgnoreCase))
                            {
                                return(true);
                            }

                            Console.WriteLine($"`{expectedName}` != `{name}`.");
                            return(false);
                        }
                    }
                    return(instance);
                }

                if (reader.TokenType == JsonToken.StartObject)
                {
                    if (!reader.Read())
                    {
                        return(instance);
                    }
                    var addMethod = dictionaryType.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);
                    do
                    {
                        Console.WriteLine($"{reader.Path} = ({reader.TokenType}) {reader.Value}");
                        if (reader.TokenType == JsonToken.EndObject)
                        {
                            return(instance);
                        }

                        if (reader.TokenType == JsonToken.PropertyName)
                        {
                            var jprop = JProperty.Load(reader);
                            var type  = objectType.GenericTypeArguments.Last();
                            Console.WriteLine($"Property[{jprop.Name}] = ({type.FullName}) {jprop.Value.Value<string>()}");
                            var name  = jprop.Name;
                            var value = serializer.Deserialize(jprop.Value.CreateReader(), type);
                            //var value = GetValue();
                            //object GetValue()
                            //{
                            //    if (jprop.Value.Type == JTokenType.String)
                            //        return jprop.Value.Value<string>();

                            //    if (jprop.Value.Type == JTokenType.Guid)
                            //        return jprop.Value.Value<Guid>();

                            //    return jprop.Value.Value<object>();
                            //}
                            //var value = serializer.Deserialize(reader, type);
                            addMethod.Invoke(instance, new object[] { name, value });
                            continue;
                        }
                        else
                        {
                            Console.WriteLine($"Using path for {reader.TokenType}: {reader.Path} = {reader.Value}");
                            addMethod.Invoke(instance, new object[] { reader.Path, reader.Value });
                            if (!reader.Read())
                            {
                                return(instance);
                            }
                        }
                    } while (true);
                }
                return(instance);
            }

            if (objectType == typeof(byte[]))
            {
                if (reader.TokenType == JsonToken.String)
                {
                    var bytesString = reader.Value as string;
                    return(bytesString.FromBase64String());
                }
            }

            if (objectType == typeof(Type))
            {
                if (reader.TokenType == JsonToken.String)
                {
                    var bytesString = reader.Value as string;
                    return(bytesString.GetClrType(
                               matched => matched,
                               () => default(Type)));
                }
                return(default(Type));
            }

            if (objectType.IsEnum)
            {
                if (reader.TokenType == JsonToken.String)
                {
                    var enumString = reader.Value as string;
                    if (Enum.TryParse(objectType, enumString, out object enumValue))
                    {
                        return(enumValue);
                    }
                }
            }

            return(existingValue);


            Guid GetGuid()
            {
                if (reader.TokenType == JsonToken.String)
                {
                    var guidString = reader.Value as string;
                    return(Guid.Parse(guidString));
                }
                if (reader.TokenType == JsonToken.Null)
                {
                    return(default(Guid));
                }
                throw new Exception();
            }

            Guid?GetGuidMaybe()
            {
                if (reader.TokenType == JsonToken.Null)
                {
                    return(default(Guid?));
                }
                return(GetGuid());
            }

            Guid[] GetGuids()
            {
                if (reader.TokenType == JsonToken.Null)
                {
                    return new Guid[] { }
                }
                ;

                IEnumerable <Guid> Enumerate()
                {
                    while (reader.TokenType != JsonToken.EndArray)
                    {
                        if (!reader.Read())
                        {
                            yield break;
                        }
                        var guidStr = reader.ReadAsString();
                        yield return(Guid.Parse(guidStr));
                    }
                }

                return(Enumerate().ToArray());
            }
        }
Пример #17
0
        /// <summary>
        /// Apply the merge using the UniqueKey to match items between JSON and entity.
        /// </summary>
        private static JsonEntityMergeResult MergeApplyUniqueKeyItems(JsonEntityMergeArgs args, IPropertyReflector pr, JProperty jp, object entity)
        {
            var hasError   = false;
            var hasChanges = false;
            var count      = 0;
            var ukc        = (UniqueKeyConfig)pr.Tag;
            var lo         = new List <object>();
            var ier        = pr.GetItemEntityReflector();

            // Determine the unique key for a comparison.
            var ukpr = ukc.GetPropertyReflectors(ier);

            // Get the current value to update.
            var current = (IEnumerable)pr.PropertyExpression.GetValue(entity);

            if (current == null)
            {
                hasChanges = true;
            }

            // Merge each item into the new collection.
            foreach (var ji in jp.Values())
            {
                // Check not null.
                if (ji.Type != JTokenType.Object)
                {
                    hasError = true;
                    args.Log(MessageItem.CreateErrorMessage(ji.Path, "The JSON token must be an object where Unique Key value(s) are required."));
                    continue;
                }

                // Generate the unique key from the json properties.
                bool skip = false;
                var  uk   = new object[ukpr.Length];
                for (int i = 0; i < ukc.Properties.Length; i++)
                {
                    var jk = ji[ukpr[i].JsonName];
                    if (jk == null)
                    {
                        hasError = skip = true;
                        args.Log(MessageItem.CreateErrorMessage(ji.Path, $"The JSON object must specify the '{ukpr[i].JsonName}' token as required for the unique key."));
                        break;
                    }

                    try
                    {
                        uk[i] = ukpr[i].GetJtokenValue(jk);
                    }
                    catch (FormatException fex)
                    {
                        hasError = skip = true;
                        args.Log(MessageItem.CreateMessage(jk.Path, MessageType.Error, $"The JSON token is malformed: {fex.Message}"));
                        break;
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }

                if (skip)
                {
                    continue;
                }

                // Get existing by unique key.
                var uniqueKey = new UniqueKey(uk);
                var item      = current == null ? null : ukc.IsEntityBaseCollection
                    ? ((IEntityBaseCollection)current).GetByUniqueKey(uniqueKey)
                    : current.OfType <EntityBase>().FirstOrDefault(x => uniqueKey.Equals(x.UniqueKey));

                // Create new if not found.
                if (item == null)
                {
                    hasChanges = true;
                    item       = pr.ComplexTypeReflector.CreateItemValue();
                }

                // Update.
                count++;
                var mr = MergeApply(args, ier, ji, item);
                if (mr == JsonEntityMergeResult.Error)
                {
                    hasError = true;
                }
                else
                {
                    if (mr == JsonEntityMergeResult.SuccessWithChanges)
                    {
                        hasChanges = true;
                    }

                    lo.Add(item);
                }
            }

            if (hasError)
            {
                return(JsonEntityMergeResult.Error);
            }

            // Confirm nothing was deleted (only needed where nothing changed so far).
            if (!hasChanges && count == (ukc.IsEntityBaseCollection ? ((IEntityBaseCollection)current).Count : current.OfType <EntityBase>().Count()))
            {
                return(JsonEntityMergeResult.SuccessNoChanges);
            }

            pr.ComplexTypeReflector.SetValue(entity, lo);
            return(JsonEntityMergeResult.SuccessWithChanges);
        }
Пример #18
0
        public void IListIndexOf()
        {
            JProperty p = new JProperty("Test", 1);
            IList l = new JObject(p);

            Assert.Equal(0, l.IndexOf(p));
            Assert.Equal(-1, l.IndexOf(new JProperty("Test", 1)));
        }
Пример #19
0
        public void IListCopyTo()
        {
            JProperty p1 = new JProperty("Test1", 1);
            JProperty p2 = new JProperty("Test2", "Two");
            IList l = new JObject(p1, p2);

            object[] a = new object[l.Count];

            l.CopyTo(a, 0);

            Assert.Equal(p1, a[0]);
            Assert.Equal(p2, a[1]);
        }
Пример #20
0
 public NavigatorState(JProperty pos)
 {
     Element = pos;
 }
Пример #21
0
        public void IListAddPropertyWithExistingName()
        {
            AssertException.Throws<ArgumentException>(() =>
            {
                JProperty p1 = new JProperty("Test1", 1);
                JProperty p2 = new JProperty("Test2", "Two");
                IList l = new JObject(p1, p2);

                JProperty p3 = new JProperty("Test2", "II");

                l.Add(p3);
            }, "Can not add property Test2 to OpenGamingLibrary.Json.Linq.JObject. Property with the same name already exists on object.");
        }
Пример #22
0
        public void ParseRef(JProperty jProperty, TestControl ctl)
        {
            JArray        array      = jProperty.Value as JArray;
            List <string> excelNames = new List <string>();

            if (array != null)
            {
                for (int i = 0; i < array.Count; i++)
                {
                    var data      = array[i];
                    var excelName = data.Value <string>();
                    excelNames.Add(excelName);
                }
            }

            foreach (var name in excelNames)
            {
                if (!ctl.HasExcel(name))
                {
                    SystemUtil.LogTestError(string.Format("({0}) 该表格不存在!", name), 4);
                    continue;
                }
                int idx = 5;
                foreach (var v in Values)
                {
                    idx++;
                    var listValue = ParseMultiValues(v);

                    if (listValue == null)
                    {
                        if (!ctl.HasExcelKey(name, v))
                        {
                            SystemUtil.LogTestError(string.Format("{0}.{1}.{2}.[{3}] ({4}行) 不存在于 [{5}] 中!",
                                                                  owner.ExcelName,
                                                                  owner.SheetName,
                                                                  FieldName,
                                                                  v,
                                                                  idx,
                                                                  name),
                                                    4);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < listValue.Count; i++)
                        {
                            var lv = listValue[i];

                            if (!ctl.HasExcelKey(name, lv))
                            {
                                SystemUtil.LogTestError(string.Format("{0}.{1}.{2}.[{3}] ({4}行) 不存在于 [{5}] 中!",
                                                                      owner.ExcelName,
                                                                      owner.SheetName,
                                                                      FieldName,
                                                                      lv,
                                                                      idx,
                                                                      name)
                                                        , 4);
                            }
                        }
                    }
                }
            }
        }
Пример #23
0
        public void IListSetItem()
        {
            JProperty p1 = new JProperty("Test1", 1);
            JProperty p2 = new JProperty("Test2", "Two");
            IList l = new JObject(p1, p2);

            JProperty p3 = new JProperty("Test3", "III");

            l[0] = p3;

            Assert.Equal(p3, l[0]);
            Assert.Equal(p2, l[1]);
        }
Пример #24
0
 static bool Contains(JProperty main, JProperty sub)
 {
     return(Contains(main.Value, sub.Value));
 }
Пример #25
0
        public void IListIsSynchronized()
        {
            JProperty p1 = new JProperty("Test1", 1);
            JProperty p2 = new JProperty("Test2", "Two");
            IList l = new JObject(p1, p2);

            Assert.False(l.IsSynchronized);
        }
Пример #26
0
        /// <summary>
        /// Update a value in the configuration file.
        /// </summary>
        /// <typeparam name="T">The type of the value</typeparam>
        /// <param name="scope">The ConfigScope of the configuration file to update.</param>
        /// <param name="key">The string key of the value.</param>
        /// <param name="value">The value to set.</param>
        /// <param name="addValue">Whether the key-value pair should be added to or removed from the file.</param>
        private void UpdateValueInFile <T>(ConfigScope scope, string key, T value, bool addValue)
        {
            string fileName = GetConfigFilePath(scope);

            fileLock.EnterWriteLock();
            try
            {
                // Since multiple properties can be in a single file, replacement
                // is required instead of overwrite if a file already exists.
                // Handling the read and write operations within a single FileStream
                // prevents other processes from reading or writing the file while
                // the update is in progress. It also locks out readers during write
                // operations.
                using (FileStream fs = WaitForFile(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
                {
                    JObject jsonObject = null;

                    // UTF8, BOM detection, and bufferSize are the same as the basic stream constructor.
                    // The most important parameter here is the last one, which keeps the StreamReader
                    // (and FileStream) open during Dispose so that it can be reused for the write
                    // operation.
                    using (StreamReader streamRdr = new StreamReader(fs, Encoding.UTF8, true, 1024, true))
                        using (JsonTextReader jsonReader = new JsonTextReader(streamRdr))
                        {
                            // Safely determines whether there is content to read from the file
                            bool isReadSuccess = jsonReader.Read();
                            if (isReadSuccess)
                            {
                                // Read the stream into a root JObject for manipulation
                                jsonObject = (JObject)JToken.ReadFrom(jsonReader);
                                JProperty propertyToModify = jsonObject.Property(key);

                                if (propertyToModify == null)
                                {
                                    // The property doesn't exist, so add it
                                    if (addValue)
                                    {
                                        jsonObject.Add(new JProperty(key, value));
                                    }
                                    // else the property doesn't exist so there is nothing to remove
                                }
                                // The property exists
                                else
                                {
                                    if (addValue)
                                    {
                                        propertyToModify.Replace(new JProperty(key, value));
                                    }
                                    else
                                    {
                                        propertyToModify.Remove();
                                    }
                                }
                            }
                            else
                            {
                                // The file doesn't already exist and we want to write to it
                                // or it exists with no content.
                                // A new file will be created that contains only this value.
                                // If the file doesn't exist and a we don't want to write to it, no
                                // action is necessary.
                                if (addValue)
                                {
                                    jsonObject = new JObject(new JProperty(key, value));
                                }
                                else
                                {
                                    return;
                                }
                            }
                        }

                    // Reset the stream position to the beginning so that the
                    // changes to the file can be written to disk
                    fs.Seek(0, SeekOrigin.Begin);

                    // Update the file with new content
                    using (StreamWriter streamWriter = new StreamWriter(fs))
                        using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
                        {
                            // The entire document exists within the root JObject.
                            // I just need to write that object to produce the document.
                            jsonObject.WriteTo(jsonWriter);

                            // This trims the file if the file shrank. If the file grew,
                            // it is a no-op. The purpose is to trim extraneous characters
                            // from the file stream when the resultant JObject is smaller
                            // than the input JObject.
                            fs.SetLength(fs.Position);
                        }
                }
            }
            finally
            {
                fileLock.ExitWriteLock();
            }
        }
Пример #27
0
        public void JPropertyContains()
        {
            JValue v = new JValue(1);
            var p = new JProperty("TestProperty", v);

            Assert.Equal(true, p.Contains(v));
            Assert.Equal(false, p.Contains(new JValue(1)));
        }
 private void ProcessProperty(JProperty property)
 {
     ProcessToken(property.Value);
 }
Пример #29
0
        /// <summary>
        /// Apply the merge as a full collection replacement; there is <b>no</b> way to detect changes or perform partial property update.
        /// </summary>
        private static JsonEntityMergeResult MergeApplyComplexItems(JsonEntityMergeArgs args, IPropertyReflector pr, JProperty jp, object entity)
        {
            var hasError = false;
            var lo       = new List <object>();
            var ier      = pr.GetItemEntityReflector();

            foreach (var ji in jp.Values())
            {
                if (ji.Type == JTokenType.Null)
                {
                    lo.Add(null);
                    continue;
                }

                var ival = pr.ComplexTypeReflector.CreateItemValue();
                if (MergeApply(args, ier, ji, ival) == JsonEntityMergeResult.Error)
                {
                    hasError = true;
                }
                else
                {
                    lo.Add(ival);
                }
            }

            if (hasError)
            {
                return(JsonEntityMergeResult.Error);
            }

            pr.ComplexTypeReflector.SetValue(entity, lo);
            return(JsonEntityMergeResult.SuccessWithChanges);
        }
Пример #30
0
        private async Task TransitionInternalNodeConnectionString()
        {
            var nodes = LightningOptions.Value.InternalLightningByCryptoCode.Values.Select(c => c.ToString()).ToHashSet();

            await using var ctx = _DBContextFactory.CreateContext();
            foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
            {
#pragma warning disable CS0618 // Type or member is obsolete
                if (!string.IsNullOrEmpty(store.DerivationStrategy))
                {
                    var     noLabel = store.DerivationStrategy.Split('-')[0];
                    JObject jObject = new JObject();
                    jObject.Add("BTC", new JObject()
                    {
                        new JProperty("signingKey", noLabel),
                        new JProperty("accountDerivation", store.DerivationStrategy),
                        new JProperty("accountOriginal", store.DerivationStrategy),
                        new JProperty("accountKeySettings", new JArray()
                        {
                            new JObject()
                            {
                                new JProperty("accountKey", noLabel)
                            }
                        })
                    });
                    store.DerivationStrategies = jObject.ToString();
                    store.DerivationStrategy   = null;
                }
                if (string.IsNullOrEmpty(store.DerivationStrategies))
                {
                    continue;
                }

                var  strats  = JObject.Parse(store.DerivationStrategies);
                bool updated = false;
                foreach (var prop in strats.Properties().Where(p => p.Name.EndsWith("LightningLike", StringComparison.OrdinalIgnoreCase)))
                {
                    var method          = ((JObject)prop.Value);
                    var lightningCharge = method.Property("LightningChargeUrl", StringComparison.OrdinalIgnoreCase);
                    var ln = method.Property("LightningConnectionString", StringComparison.OrdinalIgnoreCase);
                    if (lightningCharge != null)
                    {
                        var chargeUrl = lightningCharge.Value.Value <string>();
                        var usr       = method.Property("Username", StringComparison.OrdinalIgnoreCase)?.Value.Value <string>();
                        var pass      = method.Property("Password", StringComparison.OrdinalIgnoreCase)?.Value.Value <string>();
                        updated = true;
                        if (chargeUrl != null)
                        {
                            var fullUri = new UriBuilder(chargeUrl)
                            {
                                UserName = usr,
                                Password = pass
                            }.Uri.AbsoluteUri;
                            var newStr = $"type=charge;server={fullUri};allowinsecure=true";
                            if (ln is null)
                            {
                                ln = new JProperty("LightningConnectionString", newStr);
                                method.Add(ln);
                            }
                            else
                            {
                                ln.Value = newStr;
                            }
                        }
                        foreach (var p in new[] { "Username", "Password", "LightningChargeUrl" })
                        {
                            method.Property(p, StringComparison.OrdinalIgnoreCase)?.Remove();
                        }
                    }

                    var paymentId = method.Property("PaymentId", StringComparison.OrdinalIgnoreCase);
                    if (paymentId != null)
                    {
                        paymentId.Remove();
                        updated = true;
                    }

                    if (ln is null)
                    {
                        continue;
                    }
                    if (nodes.Contains(ln.Value.Value <string>()))
                    {
                        updated  = true;
                        ln.Value = null;
                        if (!(method.Property("InternalNodeRef", StringComparison.OrdinalIgnoreCase) is JProperty internalNode))
                        {
                            internalNode = new JProperty("InternalNodeRef", null);
                            method.Add(internalNode);
                        }
                        internalNode.Value = new JValue(LightningSupportedPaymentMethod.InternalNode);
                    }
                }

                if (updated)
                {
                    store.DerivationStrategies = strats.ToString();
                }
#pragma warning restore CS0618 // Type or member is obsolete
            }
            await ctx.SaveChangesAsync();
        }
Пример #31
0
        public void ListChanged()
        {
            JProperty p1 = new JProperty("Test1", 1);
            JProperty p2 = new JProperty("Test2", "Two");
            var o = new JObject(p1, p2);

            ListChangedType? changedType = null;
            int? index = null;

            o.ListChanged += (s, a) =>
            {
                changedType = a.ListChangedType;
                index = a.NewIndex;
            };

            JProperty p3 = new JProperty("Test3", "III");

            o.Add(p3);
            Assert.Equal(changedType, ListChangedType.ItemAdded);
            Assert.Equal(index, 2);
            Assert.Equal(p3, ((IList<JToken>)o)[index.Value]);

            JProperty p4 = new JProperty("Test4", "IV");

            ((IList<JToken>)o)[index.Value] = p4;
            Assert.Equal(changedType, ListChangedType.ItemChanged);
            Assert.Equal(index, 2);
            Assert.Equal(p4, ((IList<JToken>)o)[index.Value]);
            Assert.False(((IList<JToken>)o).Contains(p3));
            Assert.True(((IList<JToken>)o).Contains(p4));

            o["Test1"] = 2;
            Assert.Equal(changedType, ListChangedType.ItemChanged);
            Assert.Equal(index, 0);
            Assert.Equal(2, (int)o["Test1"]);
        }
        public override bool VisitPackage(JProperty package, string projectJsonPath)
        {
            var patterns = Enumerable.Empty <ValidationPattern>();

            if (ValidationPatterns != null)
            {
                patterns = ValidationPatterns
                           .Select(item => new ValidationPattern(item, Log))
                           .ToArray();
            }

            string id = package.Name;
            string version;

            if (package.Value is JObject)
            {
                JToken target = package.Value["target"];
                if (target != null && target.Value <string>() == "project")
                {
                    return(false);
                }

                version = package.Value["version"].Value <string>();
            }
            else if (package.Value is JValue)
            {
                version = package.Value.ToObject <string>();
            }
            else
            {
                throw new ArgumentException(string.Format(
                                                "Unrecognized dependency element for {0} in {1}",
                                                package.Name,
                                                projectJsonPath));
            }

            string dependencyMessage = string.Format(
                "{0} {1} in {2}",
                id,
                version,
                projectJsonPath);

            bool packageUpdated = false;

            foreach (var pattern in patterns)
            {
                packageUpdated |= pattern.VisitPackage(
                    package,
                    id,
                    version,
                    dependencyMessage,
                    UpdateInvalidDependencies);
            }

            if (!packageUpdated && ProhibitFloatingDependencies && version.Contains('*'))
            {
                // A * dependency was found but it hasn't been fixed. It might not have been fixed
                // because UpdateInvalidDependencies = false or because a pattern didn't match it:
                // either way this is an error.
                Log.LogError("Floating dependency detected: {0}", dependencyMessage);
            }

            return(packageUpdated);
        }
Пример #33
0
        public void IListContains()
        {
            JProperty p = new JProperty("Test", 1);
            IList l = new JObject(p);

            Assert.True(l.Contains(p));
            Assert.False(l.Contains(new JProperty("Test", 1)));
        }
            public bool VisitPackage(
                JProperty package,
                string packageId,
                string version,
                string dependencyMessage,
                bool updateInvalidDependencies)
            {
                bool   updatedPackage = false;
                string newVersion     = version;

                var          dependencyVersionRange = VersionRange.Parse(version);
                NuGetVersion dependencyVersion      = dependencyVersionRange.MinVersion;

                LogAction logAction;
                string    logPreamble;

                if (updateInvalidDependencies)
                {
                    logAction   = _log.LogWarning;
                    logPreamble = "Fixing invalid dependency: ";
                }
                else
                {
                    logAction   = _log.LogError;
                    logPreamble = "Dependency validation error: ";
                }
                logPreamble += "for " + dependencyMessage;

                if (_idPattern.IsMatch(packageId))
                {
                    if (!string.IsNullOrWhiteSpace(_expectedVersion) && _expectedVersion != version)
                    {
                        if (updateInvalidDependencies)
                        {
                            newVersion     = _expectedVersion;
                            updatedPackage = true;
                        }
                        logAction(
                            "{0} package version is '{1}' but expected '{2}' for packages matching '{3}'",
                            logPreamble,
                            version,
                            _expectedVersion,
                            _idPattern);
                    }
                    if (!string.IsNullOrWhiteSpace(_expectedPrerelease) &&
                        dependencyVersion.IsPrerelease &&
                        _expectedPrerelease != dependencyVersion.Release)
                    {
                        if (updateInvalidDependencies)
                        {
                            newVersion = new NuGetVersion(
                                dependencyVersion.Major,
                                dependencyVersion.Minor,
                                dependencyVersion.Patch,
                                _expectedPrerelease,
                                dependencyVersion.Metadata).ToNormalizedString();
                            updatedPackage = true;
                        }
                        logAction(
                            "{0} package prerelease is '{1}', but expected '{2}' for packages matching '{3}'",
                            logPreamble,
                            dependencyVersion.Release,
                            _expectedPrerelease,
                            _idPattern);
                    }
                }
                if (updatedPackage)
                {
                    if (package.Value is JObject)
                    {
                        package.Value["version"] = newVersion;
                    }
                    else
                    {
                        package.Value = newVersion;
                    }
                }
                return(updatedPackage);
            }
Пример #35
0
        public void IListClear()
        {
            JProperty p = new JProperty("Test", 1);
            IList l = new JObject(p);

            Assert.Equal(1, l.Count);

            l.Clear();

            Assert.Equal(0, l.Count);
        }
Пример #36
0
        public object ToJsonObject()
        {
            var content = new JProperty("highlight", new JObject());

            if (_tagsSchema != null)
            {
                content.Value["tags_schema"] = _tagsSchema;
            }

            if (_preTags != null)
            {
                content.Value["pre_tags"] = new JArray(_preTags);
            }

            if (_postTags != null)
            {
                content.Value["post_tags"] = new JArray(_postTags);
            }

            if (_order != null)
            {
                content.Value["order"] = _order;
            }

            if (_encoder != null)
            {
                content.Value["encoder"] = _encoder;
            }

            if (_fields != null && _fields.Count > 0)
            {
                content.Value["fields"] = new JObject();

                foreach (var field in _fields)
                {
                    content.Value["fields"][field.Name()] = new JObject();

                    if (field.FragmentSize().HasValue)
                    {
                        var fragmentSize = field.FragmentSize();
                        if (fragmentSize != null)
                        {
                            content.Value["fields"][field.Name()]["fragment_size"] = fragmentSize.Value;
                        }
                    }

                    if (field.NumOfFragments().HasValue)
                    {
                        var numOfFragments = field.NumOfFragments();
                        if (numOfFragments != null)
                        {
                            content.Value["fields"][field.Name()]["number_of_fragments"] = numOfFragments.Value;
                        }
                    }

                    if (field.FragmentOffset().HasValue)
                    {
                        var fragmentOffset = field.FragmentOffset();
                        if (fragmentOffset != null)
                        {
                            content.Value["fields"][field.Name()]["fragment_offset"] = fragmentOffset.Value;
                        }
                    }
                }
            }

            return(content);
        }
Пример #37
0
        public void IListAdd()
        {
            JProperty p1 = new JProperty("Test1", 1);
            JProperty p2 = new JProperty("Test2", "Two");
            IList l = new JObject(p1, p2);

            JProperty p3 = new JProperty("Test3", "III");

            l.Add(p3);

            Assert.Equal(3, l.Count);
            Assert.Equal(p3, l[2]);
        }
        public static bool FindSchema(Action <JSchema> setSchema, JSchema schema, Uri rootSchemaId, Uri reference, JSchemaReader schemaReader, ref JSchemaDiscovery discovery)
        {
            // todo, better way to get parts from Uri
            string[] parts = reference.ToString().Split('/');

            bool resolvedSchema;

            if (parts.Length > 0 && (parts[0] == "#" || parts[0] == rootSchemaId + "#"))
            {
                schemaReader._schemaStack.Push(schema);

                parts = parts.Skip(1).ToArray();

                object current = schema;
                foreach (string part in parts)
                {
                    string unescapedPart = UnescapeReference(part);

                    if (current is JSchema)
                    {
                        JSchema s = current as JSchema;

                        schemaReader._schemaStack.Push(s);

                        switch (unescapedPart)
                        {
                        case Constants.PropertyNames.Properties:
                            current = s._properties;
                            break;

                        case Constants.PropertyNames.Items:
                            current = s._items;
                            break;

                        case Constants.PropertyNames.AdditionalProperties:
                            current = s.AdditionalProperties;
                            break;

                        case Constants.PropertyNames.AdditionalItems:
                            current = s.AdditionalItems;
                            break;

                        case Constants.PropertyNames.Not:
                            current = s.Not;
                            break;

                        case Constants.PropertyNames.OneOf:
                            current = s._oneOf;
                            break;

                        case Constants.PropertyNames.AllOf:
                            current = s._allOf;
                            break;

                        case Constants.PropertyNames.AnyOf:
                            current = s._anyOf;
                            break;

                        case Constants.PropertyNames.Enum:
                            current = s._enum;
                            break;

                        case Constants.PropertyNames.PatternProperties:
                            current = s._patternProperties;
                            break;

                        case Constants.PropertyNames.Dependencies:
                            current = s._dependencies;
                            break;

                        default:
                            JToken t;
                            s.ExtensionData.TryGetValue(unescapedPart, out t);
                            current = t;
                            break;
                        }
                    }
                    else if (current is JToken)
                    {
                        JToken resolvedToken;

                        JToken t = (JToken)current;
                        if (t is JObject)
                        {
                            resolvedToken = t[unescapedPart];
                        }
                        else if (t is JArray || t is JConstructor)
                        {
                            int index;
                            if (int.TryParse(unescapedPart, NumberStyles.None, CultureInfo.InvariantCulture, out index))
                            {
                                if (index > t.Count() || index < 0)
                                {
                                    resolvedToken = null;
                                }
                                else
                                {
                                    resolvedToken = t[index];
                                }
                            }
                            else
                            {
                                resolvedToken = null;
                            }
                        }
                        else
                        {
                            resolvedToken = null;
                        }

                        if (resolvedToken != null)
                        {
                            JSchemaAnnotation annotation = resolvedToken.Annotation <JSchemaAnnotation>();
                            if (annotation != null)
                            {
                                current = annotation.Schema;
                            }
                            else
                            {
                                current = resolvedToken;
                            }
                        }
                        else
                        {
                            current = null;
                        }
                    }
                    else if (current is IDictionary)
                    {
                        IDictionary d = (IDictionary)current;

                        current = d[unescapedPart];
                    }
                    else if (current is IList)
                    {
                        IList l = (IList)current;

                        int index;
                        if (int.TryParse(unescapedPart, NumberStyles.None, CultureInfo.InvariantCulture, out index))
                        {
                            if (index > l.Count || index < 0)
                            {
                                current = null;
                            }
                            else
                            {
                                current = l[index];
                            }
                        }
                        else
                        {
                            current = null;
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                if (current is JToken)
                {
                    JToken t = (JToken)current;

                    JSchemaAnnotation annotation = t.Annotation <JSchemaAnnotation>();
                    if (annotation != null)
                    {
                        setSchema(annotation.Schema);
                        resolvedSchema = true;
                    }
                    else
                    {
                        JSchema inlineSchema = schemaReader.ReadInlineSchema(setSchema, t);

                        string path = reference.OriginalString;
                        if (path.StartsWith("#/", StringComparison.Ordinal))
                        {
                            path = path.Substring(2, path.Length - 2);
                        }

                        discovery.Discover(inlineSchema, rootSchemaId, path);

                        resolvedSchema = true;
                    }
                }
                else
                {
                    JSchema s = current as JSchema;
                    if (s != null)
                    {
                        setSchema(s);
                        resolvedSchema = true;

                        // schema is a reference schema and needs to be resolved
                        if (s.Reference != null)
                        {
                            schemaReader.AddDeferedSchema(setSchema, s);
                        }
                    }
                    else
                    {
                        resolvedSchema = false;
                    }
                }

                schemaReader._schemaStack.Clear();
            }
            else
            {
                discovery.Discover(schema, null);

                Uri resolvedReference = ResolveSchemaId(rootSchemaId, reference);

                // use firstordefault to handle duplicates
                KnownSchema knownSchema = discovery.KnownSchemas.FirstOrDefault(s => UriComparer.Instance.Equals(s.Id, resolvedReference));

                if (knownSchema != null)
                {
                    resolvedSchema = true;
                    setSchema(knownSchema.Schema);
                }
                else
                {
                    int hashIndex = resolvedReference.OriginalString.IndexOf('#');
                    if (hashIndex != -1)
                    {
                        Uri path     = new Uri(resolvedReference.OriginalString.Substring(0, hashIndex), UriKind.RelativeOrAbsolute);
                        Uri fragment = new Uri(resolvedReference.OriginalString.Substring(hashIndex), UriKind.RelativeOrAbsolute);

                        // there could be duplicated ids. use FirstOrDefault to get first schema with an id
                        knownSchema = discovery.KnownSchemas.FirstOrDefault(s => UriComparer.Instance.Equals(s.Id, path));

                        if (knownSchema != null)
                        {
                            // don't attempt to find a schema in the same schema again
                            // avoids stackoverflow
                            if (knownSchema.Schema != schema ||
                                !UriComparer.Instance.Equals(rootSchemaId, path) ||
                                !UriComparer.Instance.Equals(reference, fragment))
                            {
                                resolvedSchema = FindSchema(setSchema, knownSchema.Schema, path, fragment, schemaReader, ref discovery);
                            }
                            else
                            {
                                resolvedSchema = false;
                            }
                        }
                        else
                        {
                            resolvedSchema = false;
                        }
                    }
                    else
                    {
                        // special case
                        // look in the root schema's definitions for a definition with the same property name and id as reference
                        JToken definitions;
                        if (schema.ExtensionData.TryGetValue(Constants.PropertyNames.Definitions, out definitions))
                        {
                            JObject definitionsObject = definitions as JObject;
                            if (definitionsObject != null)
                            {
                                JProperty matchingProperty = definitionsObject.Properties().FirstOrDefault(p => TryCompare(p.Name, resolvedReference));

                                JObject o = matchingProperty?.Value as JObject;
                                if (o != null && TryCompare((string)o["id"], resolvedReference))
                                {
                                    JSchema inlineSchema = schemaReader.ReadInlineSchema(setSchema, o);

                                    discovery.Discover(inlineSchema, rootSchemaId, Constants.PropertyNames.Definitions + "/" + resolvedReference.OriginalString);

                                    resolvedSchema = true;
                                }
                                else
                                {
                                    resolvedSchema = false;
                                }
                            }
                            else
                            {
                                resolvedSchema = false;
                            }
                        }
                        else
                        {
                            resolvedSchema = false;
                        }
                    }
                }
            }

            return(resolvedSchema);
        }
Пример #39
0
        public void IListAddBadValue()
        {
            AssertException.Throws<ArgumentException>(() =>
            {
                JProperty p1 = new JProperty("Test1", 1);
                JProperty p2 = new JProperty("Test2", "Two");
                IList l = new JObject(p1, p2);

                l.Add("Bad!");
            }, "Argument is not a JToken.");
        }
Пример #40
0
 public IPathSegment CreatePathSegment(JProperty jProperty)
 {
     return(new JsonPathSegment(jProperty.Name, jProperty.IsEnumerable()));
 }
Пример #41
0
        public void IListRemove()
        {
            JProperty p1 = new JProperty("Test1", 1);
            JProperty p2 = new JProperty("Test2", "Two");
            IList l = new JObject(p1, p2);

            JProperty p3 = new JProperty("Test3", "III");

            // won't do anything
            l.Remove(p3);
            Assert.Equal(2, l.Count);

            l.Remove(p1);
            Assert.Equal(1, l.Count);
            Assert.False(l.Contains(p1));
            Assert.True(l.Contains(p2));

            l.Remove(p2);
            Assert.Equal(0, l.Count);
            Assert.False(l.Contains(p2));
            Assert.Equal(null, p2.Parent);
        }
        protected override void ProcessRecord()
        {
            var nestedresource = new Models.NestedResourceTemplate()
            {
                name = ResourceName
            };

            nestedresource.properties.templateLink.uri = String.Format(NestedTemplateResourceUri, ResourceName);

            if (AddParameterlink)
            {
                nestedresource.properties.parametersLink.uri = String.Format(NestedTemplateParameterUri, ResourceName);
            }
            else
            {
                nestedresource.properties.parametersLink = null;
                nestedresource.properties.parameters     = new JObject();

                if (!string.IsNullOrEmpty(DependsOn))
                {
                    nestedresource.dependsOn.Add(DependsOn);
                }

                var fileName = Path.Combine(ResourcePath, Path.GetFileName(ResourcePath) + ".json");

                using (Stream stream = File.OpenRead(fileName))
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        var nestedTemplate2 = new JsonTextReader(reader);

                        JsonSerializer se         = new JsonSerializer();
                        dynamic        parsedData = se.Deserialize(nestedTemplate2);
                        JObject        parameters = parsedData["parameters"];

                        foreach (JProperty parameter in parameters.Properties())
                        {
                            JProperty param = parameter.DeepClone() as JProperty;

                            if (nestedtemplate.parameters.ContainsKey(parameter.Name))
                            {
                                var v1 = (JObject)nestedtemplate.parameters[parameter.Name]; //.Value["defaultValue"]?.Value<string>();\
                                                                                             //v1.Properties[""];
                                foreach (var p in nestedtemplate.parameters.Properties())
                                {
                                    if (p.Name.StartsWith($"{parameter.Name}"))
                                    {
                                        var p1 = p.Value["defaultValue"];
                                        var p2 = parameter.Value["defaultValue"];

                                        if (JToken.DeepEquals(p1, p2))
                                        {
                                            param = p;
                                            break;
                                        }
                                    }
                                }

                                var existingParam = nestedtemplate.parameters.Properties().FirstOrDefault(p => p.Name.StartsWith($"{parameter.Name}") && JToken.DeepEquals(p.Value["defaultValue"], parameter.Value["defaultValue"]));

                                if (existingParam == null)
                                {
                                    var paramName = GetUniqueParamName(parameter.Name);

                                    param = new JProperty($"{paramName}", parameter.Value);


                                    nestedtemplate.parameters.Add(param);
                                }
                            }
                            else
                            {
                                nestedtemplate.parameters.Add(param);
                            }

                            nestedresource.properties.parameters.Add(parameter.Name, JObject.FromObject(new { value = $"[parameters('{param.Name}')]" }));
                        }
                    }
                }
            }
            nestedtemplate.resources.Add(JObject.FromObject(nestedresource));


            var result = JObject.FromObject(nestedtemplate);

            Sort(result["parameters"]);
            WriteObject(result.ToString());
        }
Пример #43
0
        public void IListInsert()
        {
            JProperty p1 = new JProperty("Test1", 1);
            JProperty p2 = new JProperty("Test2", "Two");
            IList l = new JObject(p1, p2);

            JProperty p3 = new JProperty("Test3", "III");

            l.Insert(1, p3);
            Assert.Equal(l, p3.Parent);

            Assert.Equal(p1, l[0]);
            Assert.Equal(p3, l[1]);
            Assert.Equal(p2, l[2]);
        }
Пример #44
0
 public virtual void Visit(JProperty property)
 {
     Visit(property.Value);
 }
Пример #45
0
        public void IListSetItemAlreadyExists()
        {
            AssertException.Throws<ArgumentException>(() =>
            {
                JProperty p1 = new JProperty("Test1", 1);
                JProperty p2 = new JProperty("Test2", "Two");
                IList l = new JObject(p1, p2);

                JProperty p3 = new JProperty("Test3", "III");

                l[0] = p3;
                l[1] = p3;
            }, "Can not add property Test3 to OpenGamingLibrary.Json.Linq.JObject. Property with the same name already exists on object.");
        }
 private void VisitProperty(JProperty property)
 {
     VisitToken(property.Value);
 }
Пример #47
0
        public void IListSyncRoot()
        {
            JProperty p1 = new JProperty("Test1", 1);
            JProperty p2 = new JProperty("Test2", "Two");
            IList l = new JObject(p1, p2);

            Assert.NotNull(l.SyncRoot);
        }
Пример #48
0
        private JObject GetAssessedGroups(JObject gppCategory)
        {
            Dictionary <string, Dictionary <string, string> > assessedGroupsDict = new Dictionary <string, Dictionary <string, string> >();
            Dictionary <string, Dictionary <string, string> > assessedUsersDict  = new Dictionary <string, Dictionary <string, string> >();

            foreach (JToken gppUsers in gppCategory.SelectTokens("User"))
            {
                foreach (JToken gppUser in gppUsers)
                {
                    // dictionary for results from this specific user.
                    Dictionary <string, string> assessedUserDict = new Dictionary <string, string>
                    {
                        { "InterestLevel", "3" }
                    };

                    JToken gppUserProps = gppUser["Properties"];

                    // check what the entry is doing to the user and turn it into real word
                    string userAction = GetActionString(gppUserProps["@action"].ToString());
                    assessedUserDict.Add("Action", userAction);

                    // get the username and a bunch of other details:
                    assessedUserDict.Add("Name", gppUser["@name"].ToString());
                    assessedUserDict.Add("User Name", gppUserProps["@userName"].ToString());
                    assessedUserDict.Add("DateTime Changed", gppUser["@changed"].ToString());
                    assessedUserDict.Add("Account Disabled", gppUserProps["@acctDisabled"].ToString());
                    assessedUserDict.Add("Password Never Expires", gppUserProps["@neverExpires"].ToString());
                    assessedUserDict.Add("Description", gppUserProps["@description"].ToString());
                    assessedUserDict.Add("Full Name", gppUserProps["@fullName"].ToString());
                    assessedUserDict.Add("New Name", gppUserProps["@newName"].ToString());


                    // check for cpasswords
                    string cpassword = gppUserProps["@cpassword"].ToString();
                    if (cpassword.Length > 0)
                    {
                        string decryptedCpassword = "";
                        decryptedCpassword = Utility.DecryptCpassword(cpassword);
                        // if we find one, that's super interesting.
                        assessedUserDict.Add("Cpassword", decryptedCpassword);
                        assessedUserDict["InterestLevel"] = "10";
                    }

                    // add to the output dict with a uid to keep it unique.
                    assessedUsersDict.Add(gppUser["@uid"].ToString(), assessedUserDict);
                }
            }

            // repeat the process for Groups
            foreach (JToken gppGroups in gppCategory.SelectTokens("Group"))
            {
                foreach (JToken gppGroup in gppGroups)
                {
                    //dictionary for results from this specific group
                    Dictionary <string, string> assessedGroupDict = new Dictionary <string, string>
                    {
                        { "InterestLevel", "3" }
                    };

                    JToken gppGroupProps = gppGroup["Properties"];

                    // check what the entry is doing to the group and turn it into real word
                    string groupAction = gppGroupProps["@action"].ToString();
                    groupAction = GetActionString(groupAction);

                    // get the group name and a bunch of other details:
                    assessedGroupDict.Add("Name", gppGroup["@name"].ToString());
                    //assessedGroupDict.Add("User Name", gppGroupProps["@userName"].ToString());
                    assessedGroupDict.Add("DateTime Changed", gppGroup["@changed"].ToString());
                    assessedGroupDict.Add("Description", gppGroupProps["@description"].ToString());
                    assessedGroupDict.Add("New Name", gppGroupProps["@newName"].ToString());
                    assessedGroupDict.Add("Delete All Users", gppGroupProps["@deleteAllUsers"].ToString());
                    assessedGroupDict.Add("Delete All Groups", gppGroupProps["@deleteAllGroups"].ToString());
                    assessedGroupDict.Add("Remove Accounts", gppGroupProps["@removeAccounts"].ToString());
                    assessedGroupDict.Add("Action", groupAction);
                    Utility.DebugWrite("You still need to figure out group members.");
                    //Utility.DebugWrite(gppGroupProps["Members"].ToString());


                    // add to the output dict with a uid to keep it unique.
                    assessedGroupsDict.Add(gppGroup["@uid"].ToString(), assessedGroupDict);
                }
            }

            // cast our Dictionaries back into JObjects
            JProperty assessedUsersJson  = new JProperty("gpp User settings", JToken.FromObject(assessedUsersDict));
            JProperty assessedGroupsJson = new JProperty("gpp Group settings", JToken.FromObject(assessedGroupsDict));
            // chuck the users and groups together in one JObject
            JObject assessedGppGroupsJson = new JObject();

            // only want to actually output these things if there's anything useful in them.
            if (assessedUsersDict.Count > 0)
            {
                assessedGppGroupsJson.Add(assessedUsersJson);
            }
            if (assessedGroupsDict.Count > 0)
            {
                assessedGppGroupsJson.Add(assessedGroupsJson);
            }
            return(assessedGppGroupsJson);
        }
Пример #49
0
        public void JPropertyLinq()
        {
            var p = new JProperty("TestProperty", null);
            IList l = p;

            List<JToken> result = l.Cast<JToken>().ToList();
            Assert.Equal(1, result.Count);
        }
        public void BatchingProcessTest()
        {
            EventListener.NestedLoggerHandler += eventData =>
            {
                if (eventData.EventId == (int)SharedLogEventId.CacheMissAnalysisBatchResults)
                {
                    m_cacheMissAnalysisBatchList.Add(eventData.Payload.ToArray()[0].ToString());
                }
            };

            m_cacheMissAnalysisBatchList = new List <string>();

            var lenUnit = 100;
            var string1 = new string('a', lenUnit);
            var string2 = new string('b', 2 * lenUnit);
            var string3 = new string('c', 3 * lenUnit);
            var string4 = new string('d', 4 * lenUnit);
            var string5 = new string('e', 3 * lenUnit);
            var string6 = new string('f', 2 * lenUnit);
            var string7 = new string('g', lenUnit);

            var       results = new List <JProperty>();
            JProperty result1 = new JProperty("p1", new JObject(new JProperty("Result", string1)));
            JProperty result2 = new JProperty("P2", new JObject(new JProperty("Result", string2)));
            JProperty result3 = new JProperty("P3", new JObject(new JProperty("Result", string3)));
            JProperty result4 = new JProperty("P4", new JObject(new JProperty("Result", string4)));
            JProperty result5 = new JProperty("P5", new JObject(new JProperty("Result", string5)));
            JProperty result6 = new JProperty("P6", new JObject(new JProperty("Result", string6)));
            JProperty result7 = new JProperty("P7", new JObject(new JProperty("Result", string7)));


            results.Add(result1);
            results.Add(result2);
            results.Add(result3);
            results.Add(result4);
            results.Add(result5);
            results.Add(result6);
            results.Add(result7);

            var result1Len = result1.Name.Length + result1.Value.ToString().Length;
            var result2Len = result2.Name.Length + result2.Value.ToString().Length;
            var result3Len = result3.Name.Length + result3.Value.ToString().Length;
            var result4Len = result4.Name.Length + result4.Value.ToString().Length;
            var result5Len = result5.Name.Length + result5.Value.ToString().Length;
            var result6Len = result6.Name.Length + result6.Value.ToString().Length;
            var result7Len = result7.Name.Length + result7.Value.ToString().Length;

            var timer = new Timer(o => { XAssert.IsTrue(false, "Process Timeout."); }, null, 10000, 10000);

            // 1 batch per process
            RuntimeCacheMissAnalyzer.s_numberOfBatchesLogged          = 0;
            Configuration.Logging.AriaIndividualMessageSizeLimitBytes = result1Len + result2Len + result3Len + result4Len + result5Len + result6Len + result7Len + 1;
            RuntimeCacheMissAnalyzer.ProcessResults(results.ToArray(), Configuration, LoggingContext);
            XAssert.AreEqual(m_cacheMissAnalysisBatchList.Count, 1, "Should have 1 batch logging.");
            XAssert.Contains(m_cacheMissAnalysisBatchList[0], string1, string2, string3, string4, string5, string6, string7);
            m_cacheMissAnalysisBatchList.Clear();

            // 2 batch per process
            RuntimeCacheMissAnalyzer.s_numberOfBatchesLogged          = 0;
            Configuration.Logging.AriaIndividualMessageSizeLimitBytes = result1Len + result2Len + result3Len + result4Len + 1;
            RuntimeCacheMissAnalyzer.ProcessResults(results.ToArray(), Configuration, LoggingContext);
            XAssert.AreEqual(m_cacheMissAnalysisBatchList.Count, 2, "Should have 2 batch logging.");
            XAssert.Contains(m_cacheMissAnalysisBatchList[0], string1, string2, string3, string4);
            XAssert.Contains(m_cacheMissAnalysisBatchList[1], string5, string6, string7);
            m_cacheMissAnalysisBatchList.Clear();

            // batch - single - batch in a process
            RuntimeCacheMissAnalyzer.s_numberOfBatchesLogged          = 0;
            Configuration.Logging.AriaIndividualMessageSizeLimitBytes = result1Len + result2Len + result3Len + 20;
            RuntimeCacheMissAnalyzer.ProcessResults(results.ToArray(), Configuration, LoggingContext);
            XAssert.AreEqual(m_cacheMissAnalysisBatchList.Count, 3, "Should have 3 batch logging.");
            XAssert.Contains(m_cacheMissAnalysisBatchList[0], string1, string2, string3);
            XAssert.Contains(m_cacheMissAnalysisBatchList[1], string4);
            XAssert.Contains(m_cacheMissAnalysisBatchList[2], string5, string6, string7);
            XAssert.ContainsNot(m_cacheMissAnalysisBatchList[2], string4); // Make sure there no previous result in it
            m_cacheMissAnalysisBatchList.Clear();

            // batch - single - single - single - batch in a process
            RuntimeCacheMissAnalyzer.s_numberOfBatchesLogged          = 0;
            Configuration.Logging.AriaIndividualMessageSizeLimitBytes = result1Len + result2Len + 1;
            RuntimeCacheMissAnalyzer.ProcessResults(results.ToArray(), Configuration, LoggingContext);
            XAssert.AreEqual(m_cacheMissAnalysisBatchList.Count, 5, "Should have 5 batch logging.");
            XAssert.Contains(m_cacheMissAnalysisBatchList[0], string1, string2);
            XAssert.Contains(m_cacheMissAnalysisBatchList[1], string3);
            XAssert.Contains(m_cacheMissAnalysisBatchList[2], string4.Substring(string4.Length - Configuration.Logging.AriaIndividualMessageSizeLimitBytes / 2 + 20));
            XAssert.ContainsNot(m_cacheMissAnalysisBatchList[2], string4);
            XAssert.Contains(m_cacheMissAnalysisBatchList[2], "[...]");
            XAssert.Contains(m_cacheMissAnalysisBatchList[3], string5);
            XAssert.Contains(m_cacheMissAnalysisBatchList[4], string6, string7);
            m_cacheMissAnalysisBatchList.Clear();

            // all single in a process
            RuntimeCacheMissAnalyzer.s_numberOfBatchesLogged          = 0;
            Configuration.Logging.AriaIndividualMessageSizeLimitBytes = result1Len + 1;
            RuntimeCacheMissAnalyzer.ProcessResults(results.ToArray(), Configuration, LoggingContext);
            XAssert.AreEqual(m_cacheMissAnalysisBatchList.Count, 7, "Should have 7 batch logging.");
            XAssert.Contains(m_cacheMissAnalysisBatchList[0], string1);
            XAssert.Contains(m_cacheMissAnalysisBatchList[1], string2.Substring(string2.Length - Configuration.Logging.AriaIndividualMessageSizeLimitBytes / 2 + 20));
            XAssert.ContainsNot(m_cacheMissAnalysisBatchList[1], string2);
            XAssert.Contains(m_cacheMissAnalysisBatchList[1], "[...]");
            XAssert.Contains(m_cacheMissAnalysisBatchList[2], string3.Substring(string3.Length - Configuration.Logging.AriaIndividualMessageSizeLimitBytes / 2 + 20));
            XAssert.ContainsNot(m_cacheMissAnalysisBatchList[2], string3);
            XAssert.Contains(m_cacheMissAnalysisBatchList[2], "[...]");
            XAssert.Contains(m_cacheMissAnalysisBatchList[3], string4.Substring(string4.Length - Configuration.Logging.AriaIndividualMessageSizeLimitBytes / 2 + 20));
            XAssert.ContainsNot(m_cacheMissAnalysisBatchList[3], string4);
            XAssert.Contains(m_cacheMissAnalysisBatchList[3], "[...]");
            XAssert.Contains(m_cacheMissAnalysisBatchList[4], string5.Substring(string5.Length - Configuration.Logging.AriaIndividualMessageSizeLimitBytes / 2 + 20));
            XAssert.ContainsNot(m_cacheMissAnalysisBatchList[4], string5);
            XAssert.Contains(m_cacheMissAnalysisBatchList[4], "[...]");
            XAssert.Contains(m_cacheMissAnalysisBatchList[5], string6.Substring(string6.Length - Configuration.Logging.AriaIndividualMessageSizeLimitBytes / 2 + 20));
            XAssert.ContainsNot(m_cacheMissAnalysisBatchList[5], string6);
            XAssert.Contains(m_cacheMissAnalysisBatchList[5], "[...]");
            XAssert.Contains(m_cacheMissAnalysisBatchList[6], string7);
            m_cacheMissAnalysisBatchList.Clear();

            // all single in a process, test a result's len == maxLogLen
            RuntimeCacheMissAnalyzer.s_numberOfBatchesLogged          = 0;
            Configuration.Logging.AriaIndividualMessageSizeLimitBytes = result3Len;
            RuntimeCacheMissAnalyzer.ProcessResults(results.ToArray(), Configuration, LoggingContext);
            XAssert.AreEqual(m_cacheMissAnalysisBatchList.Count, 7, "Should have 7 batch logging.");
            XAssert.Contains(m_cacheMissAnalysisBatchList[0], string1);
            XAssert.Contains(m_cacheMissAnalysisBatchList[1], string2);
            XAssert.Contains(m_cacheMissAnalysisBatchList[2], string3.Substring(string4.Length - Configuration.Logging.AriaIndividualMessageSizeLimitBytes / 2 + 20));// Result has exact length as maxLogLen
            XAssert.ContainsNot(m_cacheMissAnalysisBatchList[2], string3);
            XAssert.Contains(m_cacheMissAnalysisBatchList[2], "[...]");
            XAssert.Contains(m_cacheMissAnalysisBatchList[3], string4.Substring(string4.Length - Configuration.Logging.AriaIndividualMessageSizeLimitBytes / 2 + 20));
            XAssert.ContainsNot(m_cacheMissAnalysisBatchList[3], string4);
            XAssert.Contains(m_cacheMissAnalysisBatchList[3], "[...]");
            XAssert.Contains(m_cacheMissAnalysisBatchList[4], string5.Substring(string4.Length - Configuration.Logging.AriaIndividualMessageSizeLimitBytes / 2 + 20));// Result has exact length as maxLogLen
            XAssert.ContainsNot(m_cacheMissAnalysisBatchList[4], string5);
            XAssert.Contains(m_cacheMissAnalysisBatchList[4], "[...]");
            XAssert.Contains(m_cacheMissAnalysisBatchList[5], string6);
            XAssert.Contains(m_cacheMissAnalysisBatchList[6], string7);
            m_cacheMissAnalysisBatchList.Clear();

            timer.Dispose();
        }
Пример #51
0
        public void JPropertyIndexOf()
        {
            JValue v = new JValue(1);
            JProperty p1 = new JProperty("TestProperty", v);

            IList l1 = p1;
            Assert.Equal(0, l1.IndexOf(v));

            IList<JToken> l2 = p1;
            Assert.Equal(0, l2.IndexOf(v));
        }
        public void BatchingRealResultTruncateTest()
        {
            EventListener.NestedLoggerHandler += eventData =>
            {
                if (eventData.EventId == (int)SharedLogEventId.CacheMissAnalysisBatchResults)
                {
                    m_cacheMissAnalysisBatchList.Add(eventData.Payload.ToArray()[0].ToString());
                }
            };

            var    results    = new List <JProperty>();
            string resultJson = @"{
		""Description"": ""PipC1907BAC23BB4039, test"",
		""FromCacheLookup"": false,
		""Detail"": {
			""ActualMissType"": ""MissForDescriptorsDueToStrongFingerprints"",
			""ReasonFromAnalysis"": ""WeakFingerprints of the builds are different."",
			""Info"": {
				""WeakFingerprintMismatchResult"": {
					""WeakFingerprint"": {
						""Old"": ""126B618310A6F95C4B00E9A576CFE5EAF3B5D950"",
						""New"": ""311C6E5835CEA28399F62FACCA5380C8C18347E5""
					},
					""ExecutionAndFingerprintOptions"": {
						""Changed"": {
							""FingerprintVersion"": {
								""Old"": ""80"",
								""New"": ""81""
							}
						}
					},
					""Executable"": {
						""Old"": ""path1"",
						""New"": ""path2""
					},
					""UntrackedPaths"": {
						""Added"": [
							""path3""
						],
						""Removed"": [
							""Path4""
						]
					},
					""OldProvenance:"": {
						""SessionId"": ""fa485571-0100-ffff-0f37-d21e6b002ba0"",
						""RelatedSessionId"": ""5c4a3e30-dd7e-4cc1-864a-d21e6b002ba0""
					}
				}
			}
		}
	}"    ;

            m_cacheMissAnalysisBatchList = new List <string>();
            var       pipHash = "PipC1907BAC23BB4039";
            JProperty result  = new JProperty(pipHash, JObject.Parse(resultJson));

            results.Add(result);
            RuntimeCacheMissAnalyzer.s_numberOfBatchesLogged          = 0;
            Configuration.Logging.AriaIndividualMessageSizeLimitBytes = 600;
            RuntimeCacheMissAnalyzer.ProcessResults(results.ToArray(), Configuration, LoggingContext);
            XAssert.AreEqual(m_cacheMissAnalysisBatchList.Count, 1, "Should have 1 batch logging.");
            XAssert.Contains(m_cacheMissAnalysisBatchList[0], pipHash);
            XAssert.Contains(m_cacheMissAnalysisBatchList[0], "[...]");
            m_cacheMissAnalysisBatchList.Clear();
        }
Пример #53
0
        public void MultiContentConstructor()
        {
            var p = new JProperty("error", new List<string> { "one", "two" });
            JArray a = (JArray)p.Value;

            Assert.Equal(a.Count, 2);
            Assert.Equal("one", (string)a[0]);
            Assert.Equal("two", (string)a[1]);
        }
Пример #54
0
 static bool IsBaseType(JProperty property) => IsBaseType(property.Value as JObject);
Пример #55
0
        /// <summary>
        /// Unpatch a JSON object
        /// </summary>
        /// <param name="right">Patched JSON object</param>
        /// <param name="patch">JSON Patch Document</param>
        /// <returns>Unpatched JSON object</returns>
        /// <exception cref="System.IO.InvalidDataException">Thrown if the patch document is invalid</exception>
        public JToken Unpatch(JToken right, JToken patch)
        {
            if (patch == null)
            {
                return(right);
            }

            if (patch.Type == JTokenType.Object)
            {
                var       patchObj        = (JObject)patch;
                JProperty arrayDiffCanary = patchObj.Property("_t");

                if (right != null &&
                    right.Type == JTokenType.Array &&
                    arrayDiffCanary != null &&
                    arrayDiffCanary.Value.Type == JTokenType.String &&
                    arrayDiffCanary.ToObject <string>() == "a")
                {
                    return(ArrayUnpatch((JArray)right, patchObj));
                }

                return(ObjectUnpatch(right as JObject, patchObj));
            }

            if (patch.Type == JTokenType.Array)
            {
                var patchArray = (JArray)patch;

                if (patchArray.Count == 1)                 // Add (we need to remove the property)
                {
                    return(null);
                }
                else if (patchArray.Count == 2)                 // Replace
                {
                    return(patchArray[0]);
                }
                else if (patchArray.Count == 3)                 // Delete, Move or TextDiff
                {
                    if (patchArray[2].Type != JTokenType.Integer)
                    {
                        throw new InvalidDataException("Invalid patch object");
                    }

                    int op = patchArray[2].Value <int>();

                    if (op == 0)
                    {
                        return(patchArray[0]);
                    }
                    else if (op == 2)
                    {
                        var          dmp     = new diff_match_patch();
                        List <Patch> patches = dmp.patch_fromText(patchArray[0].ToObject <string>());

                        if (patches.Count != 1)
                        {
                            throw new InvalidDataException("Invalid textline");
                        }

                        string left = dmp.diff_text1(patches[0].diffs);
                        return(left);
                    }
                    else
                    {
                        throw new InvalidDataException("Invalid patch object");
                    }
                }
                else
                {
                    throw new InvalidDataException("Invalid patch object");
                }
            }

            return(null);
        }
Пример #56
0
        /// <summary>
        /// Apply the merge from the json to the entity value as a more complex type.
        /// </summary>
        private static JsonEntityMergeResult MergeApplyComplex(JsonEntityMergeArgs args, IPropertyReflector pr, JProperty jp, object entity)
        {
            if (jp.Value.Type == JTokenType.Null)
            {
                return(pr.SetValue(entity, null) ? JsonEntityMergeResult.SuccessWithChanges : JsonEntityMergeResult.SuccessNoChanges);
            }

            // Update the sub-entity.
            if (pr.ComplexTypeReflector.ComplexTypeCode == ComplexTypeCode.Object)
            {
                if (jp.Value.Type != JTokenType.Object)
                {
                    return(args.Log(MessageItem.CreateMessage(jp.Path, MessageType.Error, $"The JSON token is malformed and could not be parsed.")));
                }

                var hasChanged = true;
                var current    = pr.PropertyExpression.GetValue(entity);
                if (current == null)
                {
                    current = pr.NewValue(entity).value;
                }
                else
                {
                    hasChanged = false;
                }

                var mr = MergeApply(args, pr.GetEntityReflector(), jp.Value, current);
                return(mr == JsonEntityMergeResult.SuccessNoChanges ? (hasChanged ? JsonEntityMergeResult.SuccessWithChanges : JsonEntityMergeResult.SuccessNoChanges) : mr);
            }
            else
            {
                // Ensure we are dealing with an array.
                if (jp.Value.Type != JTokenType.Array)
                {
                    return(args.Log(MessageItem.CreateMessage(jp.Path, MessageType.Error, $"The JSON token is malformed and could not be parsed.")));
                }

                // Where empty array then update as such.
                if (!jp.Value.HasValues)
                {
                    return(UpdateArrayValue(args, pr, entity, (IEnumerable)pr.PropertyExpression.GetValue(entity), (IEnumerable)pr.ComplexTypeReflector.CreateValue()));
                }

                // Handle array with primitive types.
                if (!pr.ComplexTypeReflector.IsItemComplexType)
                {
                    var lo = new List <object>();
                    foreach (var iv in jp.Value.Values())
                    {
                        lo.Add(iv.ToObject(pr.ComplexTypeReflector.ItemType));
                    }

                    return(UpdateArrayValue(args, pr, entity, (IEnumerable)pr.PropertyExpression.GetValue(entity), (IEnumerable)pr.ComplexTypeReflector.CreateValue(lo)));
                }

                // Finally, handle array with complex entity items.
                return((pr.Tag == null) ? MergeApplyComplexItems(args, pr, jp, entity) : MergeApplyUniqueKeyItems(args, pr, jp, entity));
            }
        }
Пример #57
0
        private JArray ArrayUnpatch(JArray right, JObject patch)
        {
            var toRemove = new List <JProperty>();
            var toInsert = new List <JProperty>();
            var toModify = new List <JProperty>();

            foreach (JProperty op in patch.Properties())
            {
                if (op.Name == "_t")
                {
                    continue;
                }

                var value = op.Value as JArray;

                if (op.Name.StartsWith("_"))
                {
                    // removed item from original array
                    if (value != null && value.Count == 3 && (value[2].ToObject <int>() == (int)DiffOperation.Deleted || value[2].ToObject <int>() == (int)DiffOperation.ArrayMove))
                    {
                        var newOp = new JProperty(value[1].ToObject <int>().ToString(), op.Value);

                        if (value[2].ToObject <int>() == (int)DiffOperation.ArrayMove)
                        {
                            toInsert.Add(new JProperty(op.Name.Substring(1), new JArray(right[value[1].ToObject <int>()].DeepClone())));
                            toRemove.Add(newOp);
                        }
                        else
                        {
                            toInsert.Add(new JProperty(op.Name.Substring(1), new JArray(value[0])));
                        }
                    }
                    else
                    {
                        throw new Exception($"Only removal or move can be applied at original array indices. Context: {value}");
                    }
                }
                else
                {
                    if (value != null && value.Count == 1)
                    {
                        toRemove.Add(op);
                    }
                    else
                    {
                        toModify.Add(op);
                    }
                }
            }


            // remove items, in reverse order to avoid sawing our own floor
            toRemove.Sort((x, y) => int.Parse(x.Name).CompareTo(int.Parse(y.Name)));
            for (int i = toRemove.Count - 1; i >= 0; --i)
            {
                JProperty op = toRemove[i];
                right.RemoveAt(int.Parse(op.Name));
            }

            // insert items, in reverse order to avoid moving our own floor
            toInsert.Sort((x, y) => int.Parse(x.Name).CompareTo(int.Parse(y.Name)));
            foreach (var op in toInsert)
            {
                right.Insert(int.Parse(op.Name), ((JArray)op.Value)[0]);
            }

            foreach (var op in toModify)
            {
                JToken p = Unpatch(right[int.Parse(op.Name)], op.Value);
                right[int.Parse(op.Name)] = p;
            }

            return(right);
        }
Пример #58
0
        public void ITypedListGetItemProperties()
        {
            JProperty p1 = new JProperty("Test1", 1);
            JProperty p2 = new JProperty("Test2", "Two");
            ITypedList l = new JObject(p1, p2);

            PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null);
            Assert.Null(propertyDescriptors);
        }
Пример #59
0
        public void IListAdd()
        {
            var p = new JProperty("TestProperty", null);
            IList l = p;

            AssertException.Throws<JsonException>(() => { l.Add(null); }, "OpenGamingLibrary.Json.Linq.JProperty cannot have multiple values.");
        }
Пример #60
0
        public string DamRequestCreate(string jsonFile)
        {
            LogManager.DoLogOperation("[DAM Server] Receive Request to create DAM");

            DamRestCommand.JsonDamCreate test = DamRestCommand.LoadJson_DamCreate(jsonFile);
            /* format json response */
            JObject   result = new JObject();
            JProperty a;
            JProperty b;
            JProperty c;

            /*Calculate EncK*/
            byte[] EncK = DamCrypto.EncK(test.damauthkey, test.damdefaultkey, test.damdefaultkeyversion);

            /* secret dammac key */
            byte[] DAMMACKey = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            uint   iAid      = 0x000000;

            if (test.aid.Length != 3)
            {
                a = new JProperty("Enk", Converters.ByteArrayToSimpleHexString(EncK));
                result.Add(a);
                b = new JProperty("DAMMAC", Converters.ByteArrayToSimpleHexString(EncK));
                result.Add(b);
                c = new JProperty("status", "aid error");
                result.Add(c);

                return(JsonConvert.SerializeObject(result, Formatting.Indented));
            }

            iAid  = test.aid[2];
            iAid += (uint)(test.aid[1] << 8);
            iAid += (uint)(test.aid[0] << 16);

            /* Calculate DAMMAC */
            byte[] dammac = DamCrypto.DAMMAC(
                DAMMACKey,
                DF_CREATE_DELEGATED_APPLICATION,
                iAid, test.damslotno, test.damslotversion, test.quotalimit, test.key_setting1, test.key_setting2,
                test.key_setting3, test.aksversion, test.nokeyset, test.maxkeysize, test.rollkey,
                test.iso_df_id, test.iso_df_name,
                EncK);

            c = new JProperty("Result", "ok");
            result.Add(c);
            /* le proprietaire connait les valeurs en fonction de sa base de données */
            /* les valeurs correspondent au DAMMAC crée */
            c = new JProperty("damslotno", "0");
            result.Add(c);
            c = new JProperty("damslotversion", "FF");
            result.Add(c);
            c = new JProperty("quotalimit", "10");
            result.Add(c);

            a = new JProperty("Enck", Converters.ByteArrayToSimpleHexString(EncK));
            result.Add(a);
            b = new JProperty("DAMMAC", Converters.ByteArrayToSimpleHexString(dammac));
            result.Add(b);

            return(JsonConvert.SerializeObject(result, Formatting.Indented));
        }