public static string GetDocFxExecutablePath(string contentRootPath)
        {
            // Read the projects.assets.json for nuget path and docFx library version
            string assetsJsonPath = Path.Combine(contentRootPath, "obj\\project.assets.json");
            string nugetPackPath  = null;
            string docFxLibPath   = null;

            using (StreamReader sr = new StreamReader(new FileStream(assetsJsonPath, FileMode.Open, FileAccess.Read)))
            {
                using (JsonReader reader = new JsonTextReader(sr))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    JObject        assetsObj  = (JObject)serializer.Deserialize(reader);
                    //Get the default nuget package path
                    nugetPackPath = assetsObj?.Properties()
                                    .Where(pp => pp.Name == "packageFolders")
                                    .Descendants()
                                    .Cast <JObject>()
                                    .FirstOrDefault()?
                                    .Properties()
                                    .FirstOrDefault()?
                                    .Name;
                    if (string.IsNullOrWhiteSpace(nugetPackPath) ||
                        !Directory.Exists(nugetPackPath))
                    {
                        throw new DirectoryNotFoundException("packageFolders node not found in manifest or invalid nuget package path. Unable to locate default nuget package path");
                    }


                    //Get DocFx.console package and version path
                    var libPath = assetsObj?
                                  .Properties()
                                  .Where(pp => pp.Name == "libraries")
                                  .Descendants()
                                  .Cast <JObject>()
                                  .Properties()
                                  .Where(wp => wp.Name.StartsWith("docfx.console"))
                                  .FirstOrDefault()?
                                  .Name ?? string.Empty;
                    docFxLibPath = Path.Combine(nugetPackPath, libPath);
                    if (string.IsNullOrWhiteSpace(libPath) ||
                        !Directory.Exists(docFxLibPath))
                    {
                        throw new DirectoryNotFoundException("Unable to locate docfx.console package directory. Make sure docfx.console package in installed with nuget package manager.");
                    }

                    string fullDocFxExePath = Path.Combine(docFxLibPath, "tools\\docfx.exe");
                    if (File.Exists(fullDocFxExePath))
                    {
                        return(fullDocFxExePath);
                    }
                    else
                    {
                        throw new FileNotFoundException("Unable to locate default docfx.exe.");
                    }
                }
            }
        }
Example #2
0
        public static void Update([NotNull] TObject destination, [NotNull] TObject source, JObject objectJson)
        {
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            CheckInitialization();
            var fieldsModified = objectJson?.Properties();

            if (fieldsModified == null)
            {
                return;
            }

            foreach (var fieldName in fieldsModified)
            {
                Action <TObject, TObject, JObject> copier;
                // ReSharper disable once InconsistentlySynchronizedField
                if (PropertyCopiers.TryGetValue(fieldName.Name, out copier))
                {
                    copier(destination, source, fieldName.Value as JObject);
                }
            }
        }
        private static Difference FindJObjectDifference(JObject actual, JToken expected, JPath path, bool ignoreExtraProperties)
        {
            if (!(expected is JObject expectedObject))
            {
                return(new Difference(DifferenceKind.OtherType, path, Describe(actual.Type), Describe(expected.Type)));
            }

            return(CompareProperties(actual?.Properties(), expectedObject.Properties(), path, ignoreExtraProperties));
        }
Example #4
0
        private static Difference FindJObjectDifference(JObject actual, JToken expected, JPath path)
        {
            if (!(expected is JObject expectedObject))
            {
                return(new Difference(DifferenceKind.OtherType, path));
            }

            return(CompareProperties(actual?.Properties(), expectedObject.Properties(), path));
        }
        private static IEnumerable <string> GetUnchangedKeys(JObject current, JToken model)
        {
            var unchangedKeys = current?.Properties()
                                .Where(c => JToken.DeepEquals(c.Value, model[c.Name]))
                                .Select(c => c.Name)
                                .ToList();

            return(unchangedKeys);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            List <SlotAttributes> slots = null;


            JObject jsonObject = null;

            try
            {
                jsonObject = JObject.Load(reader);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error deserializing slots: {ex}");
            }

            if (jsonObject?.Properties() != null)
            {
                slots = new List <SlotAttributes>();
                var properties = jsonObject.Properties().ToList();
                foreach (var jprop in properties)
                {
                    SlotAttributes slotAttrib = new SlotAttributes();

                    slotAttrib.Name = jprop.Name;

                    if (jprop.Value is JObject propVal)
                    {
                        var props = propVal.Properties();
                        if (propVal.Properties() != null)
                        {
                            var propValue = props.FirstOrDefault(x =>
                                                                 x.Name.Equals("value", StringComparison.OrdinalIgnoreCase));

                            if (propValue != null)
                            {
                                slotAttrib.Value = (string)propValue.Value;
                            }

                            propValue = props.FirstOrDefault(x =>
                                                             x.Name.Equals("id", StringComparison.OrdinalIgnoreCase));

                            if (propValue != null)
                            {
                                slotAttrib.Id = (string)propValue.Value;
                            }
                        }
                    }

                    slots.Add(slotAttrib);
                }
            }

            return(slots);
        }
        private static List <string> GetAddedKeys(JObject current, JObject model)
        {
            var addedKeys = current?.Properties()
                            .Select(c => c.Name)
                            .Except(model?.Properties()
                                    .Select(c => c.Name) ?? throw new ArgumentNullException(nameof(model)))
                            .ToList();

            return(addedKeys);
        }
        private static IEnumerable <string> GetRemovedKeys(JObject current, JObject model)
        {
            var removedKeys = model?.Properties()
                              .Select(c => c.Name)
                              .Except(current?.Properties()
                                      .Select(c => c.Name) ?? throw new ArgumentNullException(nameof(current)))
                              .ToList();

            return(removedKeys);
        }
        private static IEnumerable <string> GetModifiedKeys(JObject current, IEnumerable <string> addedKeys,
                                                            IEnumerable <string> unchangedKeys)
        {
            var potentiallyModifiedKeys = current?.Properties()
                                          .Select(c => c.Name)
                                          .Except(addedKeys)
                                          .Except(unchangedKeys);

            return(potentiallyModifiedKeys);
        }
Example #10
0
        private static IDictionary <string, object> ConvertDynamicProperties(string id, JObject token)
        {
            var result = new Dictionary <string, object>();

            if (null == token)
            {
                return(result);
            }

            foreach (var prop in token?.Properties())
            {
                if (null == prop.Value)
                {
                    continue;
                }
                result[prop.Name] = ConvertValue(prop.Name, id, prop.Value);
            }

            return(result);
        }
Example #11
0
        /// <summary>
        /// Merge an object's properties into one of our child objects
        /// E.g., the "resources" object should accumulate values from all levels
        /// </summary>
        /// <param name="jobject">The object to write to</param>
        /// <param name="propertyName">The name of the property to write to</param>
        /// <param name="token">The object containing properties to merge</param>
        /// <returns>
        /// Returns
        /// </returns>
        public static void SafeMerge(this JObject jobject, string propertyName, JToken token)
        {
            JObject srcObj = token as JObject;

            // No need to do anything if source object is null or empty
            if (srcObj?.Properties().Any() ?? false)
            {
                if (!jobject.ContainsKey(propertyName))
                {
                    jobject[propertyName] = new JObject();
                }
                JObject targetJson = jobject[propertyName] as JObject;
                if (targetJson != null)
                {
                    foreach (JProperty property in srcObj.Properties())
                    {
                        targetJson.SafeAdd(property.Name, property.Value);
                    }
                }
            }
        }
Example #12
0
        private List <KeyValuePair <string, string> > DeserializeListKeyValuePair(JObject jobj)
        {
            List <KeyValuePair <string, string> > lst = new List <KeyValuePair <string, string> >();

            if ((jobj?.Properties()?.Count() ?? 0) > 0)
            {
                foreach (JProperty prop in jobj.Properties())
                {
                    if (prop == null)
                    {
                        continue;
                    }

                    string keyR   = prop.Name;
                    string valueR = jobj[keyR]?.ToString();
                    lst.Add(new KeyValuePair <string, string>(keyR, valueR));
                }
            }

            return(lst);
        }
        public void Example()
        {
            #region Usage
            JObject o = new JObject
            {
                { "name1", "value1" },
                { "name2", "value2" }
            };

            foreach (JProperty property in o.Properties())
            {
                Console.WriteLine(property.Name + " - " + property.Value);
            }
            // name1 - value1
            // name2 - value2

            foreach (KeyValuePair<string, JToken> property in o)
            {
                Console.WriteLine(property.Key + " - " + property.Value);
            }
            // name1 - value1
            // name2 - value2
            #endregion
        }
Example #14
0
        private static JToken BuildObjectDiff(JObject original, JObject patched)
        {
            var result     = new JObject();
            var properties = original?.Properties() ?? patched.Properties();

            foreach (var property in properties)
            {
                var propertyName   = property.Name;
                var originalJToken = original?.GetValue(propertyName);
                var patchedJToken  = patched?.GetValue(propertyName);

                var patchToken = BuildDiff(originalJToken, patchedJToken);
                if (patchToken != null)
                {
                    result.Add(propertyName, patchToken);
                }
            }

            if (result.Properties().Any())
            {
                return(result);
            }
            return(null);
        }
Example #15
0
File: Add.ashx.cs Project: uvbs/mmp
        public void ProcessRequest(HttpContext context)
        {
            UserInfo nUser = new UserInfo();

            nUser               = bllTableFieldMap.ConvertRequestToModel <UserInfo>(nUser);
            nUser.UserID        = string.Format("PCUser{0}", Guid.NewGuid().ToString());//Guid
            nUser.Password      = ZentCloud.Common.Rand.Str_char(12);
            nUser.UserType      = 2;
            nUser.WebsiteOwner  = bllTableFieldMap.WebsiteOwner;
            nUser.LastLoginDate = DateTime.Now;


            List <TableFieldMapping> formField = bllTableFieldMap.GetTableFieldMapByWebsite(bllTableFieldMap.WebsiteOwner, "ZCJ_UserInfo", null, null, context.Request["mapping_type"]);

            formField = formField.Where(p => p.IsReadOnly == 0 && p.IsDelete == 0 && p.Field != "AutoID" && p.Field != "UserID").ToList();

            List <string> defFields = new List <string>()
            {
                "AutoID", "UserID", "Password", "UserType", "TrueName", "Phone", "WebsiteOwner"
            };

            JObject          jtCurUser     = JObject.FromObject(nUser);
            List <JProperty> listPropertys = jtCurUser.Properties().ToList();

            foreach (var item in formField.Where(p => p.FieldIsNull == 1 && !defFields.Contains(p.Field)).OrderBy(p => p.Sort))
            {
                if (!listPropertys.Exists(p => p.Name.Equals(item.Field)))
                {
                    continue;
                }
                if (string.IsNullOrWhiteSpace(jtCurUser[item.Field].ToString()))
                {
                    apiResp.code = (int)APIErrCode.OperateFail;
                    apiResp.msg  = "请完善" + item.MappingName;
                    bllTableFieldMap.ContextResponse(context, apiResp);
                    return;
                }
                if (!string.IsNullOrWhiteSpace(item.FormatValiFunc))
                {
                    #region 检查数据格式
                    //检查数据格式
                    if (item.FormatValiFunc == "number")
                    {
                        if (!MyRegex.IsNumber(jtCurUser[item.Field].ToString()))
                        {
                            apiResp.code = (int)APIErrCode.OperateFail;
                            apiResp.msg  = string.Format("{0}格式不正确", item.MappingName);
                            bllTableFieldMap.ContextResponse(context, apiResp);
                            return;
                        }
                    }
                    if (item.FormatValiFunc == "phone")//email检查
                    {
                        if (!MyRegex.PhoneNumLogicJudge(jtCurUser[item.Field].ToString()))
                        {
                            apiResp.code = (int)APIErrCode.OperateFail;
                            apiResp.msg  = string.Format("{0}格式不正确", item.MappingName);
                            bllTableFieldMap.ContextResponse(context, apiResp);
                            return;
                        }
                    }
                    if (item.FormatValiFunc == "email")//email检查
                    {
                        if (!MyRegex.EmailLogicJudge(jtCurUser[item.Field].ToString()))
                        {
                            apiResp.code = (int)APIErrCode.OperateFail;
                            apiResp.msg  = string.Format("{0}格式不正确", item.MappingName);
                            bllTableFieldMap.ContextResponse(context, apiResp);
                            return;
                        }
                    }
                    if (item.FormatValiFunc == "url")                                                                                                             //url检查
                    {
                        System.Text.RegularExpressions.Regex regUrl = new System.Text.RegularExpressions.Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"); //网址
                        System.Text.RegularExpressions.Match match  = regUrl.Match(jtCurUser[item.Field].ToString());
                        if (!match.Success)
                        {
                            apiResp.code = (int)APIErrCode.OperateFail;
                            apiResp.msg  = string.Format("{0}格式不正确", item.MappingName);
                            bllTableFieldMap.ContextResponse(context, apiResp);
                            return;
                        }
                    }
                    #endregion
                }
            }

            if (bllTableFieldMap.Add(nUser))
            {
                if (!string.IsNullOrEmpty(nUser.TagName))
                {
                    foreach (var tag in nUser.TagName.Split(','))
                    {
                        if (bllUser.GetCount <ZentCloud.BLLJIMP.Model.MemberTag>(string.Format(" WebsiteOwner='{0}' And TagName='{1}' And TagType='Member'", bllUser.WebsiteOwner, tag)) == 0)
                        {
                            ZentCloud.BLLJIMP.Model.MemberTag model = new BLLJIMP.Model.MemberTag();
                            model.CreateTime   = DateTime.Now;
                            model.WebsiteOwner = bllUser.WebsiteOwner;
                            model.TagType      = "Member";
                            model.TagName      = tag;
                            model.Creator      = currentUserInfo.UserID;
                            if (!bllUser.Add(model))
                            {
                                apiResp.msg  = "新增标签失败";
                                apiResp.code = (int)APIErrCode.OperateFail;
                                bllTableFieldMap.ContextResponse(context, apiResp);
                            }
                        }
                    }
                }
                apiResp.status = true;
                apiResp.msg    = "新增完成";
                apiResp.code   = (int)APIErrCode.IsSuccess;
            }
            else
            {
                apiResp.msg  = "新增失败";
                apiResp.code = (int)APIErrCode.OperateFail;
            }
            bllTableFieldMap.ContextResponse(context, apiResp);
        }
        /// <summary>
        /// ReadJson
        /// </summary>
        /// <param name="reader">json reader</param>
        /// <param name="objectType">objectType value</param>
        /// <param name="existingValue">existing value</param>
        /// <param name="serliazer">serliazer value</param>
        /// <returns>void</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jsonObject = JObject.Load(reader);
            object  target;

            if (objectType.IsAbstract)
            {
                target = GetInstanceofAbstractType(objectType, jsonObject);
            }
            else
            {
                target = Activator.CreateInstance(objectType);
            }

            foreach (JProperty prop in jsonObject.Properties())
            {
                PropertyInfo propExist = objectType.GetProperty(prop.Name);
                //test if property exist in object with node name
                if (propExist == null)
                {
                    //property with node name does not exist. Look for XMLAttribute definition with node name.
                    //iterate each property and find one with XmlElementAttribute having name as node name
                    foreach (PropertyInfo objectTypeProp in objectType.GetProperties())
                    {
                        //ReferenceType has a property with Value which is serialized as value (small v).
                        //This property is annotated with XmlTextAttribute
                        System.Xml.Serialization.XmlTextAttribute[] attrsText = (System.Xml.Serialization.XmlTextAttribute[])objectTypeProp.GetCustomAttributes((new System.Xml.Serialization.XmlTextAttribute()).GetType(), false);
                        foreach (System.Xml.Serialization.XmlTextAttribute attr in attrsText)
                        {
                            if (prop.Name == "value")
                            {
                                PropertyInfo targetProp = target.GetType().GetProperty(objectTypeProp.Name);
                                targetProp.SetValue(target, prop.Value.ToString(), null);
                            }
                        }

                        System.Xml.Serialization.XmlElementAttribute[] attrs = (System.Xml.Serialization.XmlElementAttribute[])objectTypeProp.GetCustomAttributes((new System.Xml.Serialization.XmlElementAttribute()).GetType(), false);
                        foreach (System.Xml.Serialization.XmlElementAttribute attr in attrs)
                        {
                            if (prop.Name == attr.ElementName || (prop.Name == "TaxService" && objectTypeProp.Name == "AnyIntuitObject"))
                            {
                                //check if this property is of type ChoiceElement
                                System.Xml.Serialization.XmlChoiceIdentifierAttribute[] choiceattrs = (System.Xml.Serialization.XmlChoiceIdentifierAttribute[])objectTypeProp.GetCustomAttributes((new System.Xml.Serialization.XmlChoiceIdentifierAttribute()).GetType(), false);
                                if (choiceattrs.Count() > 0)
                                {
                                    //get the property
                                    foreach (System.Xml.Serialization.XmlChoiceIdentifierAttribute choiceAttr in choiceattrs)
                                    {
                                        PropertyInfo choiceProp = target.GetType().GetProperty(choiceAttr.MemberName);
                                        if (choiceProp.PropertyType.IsArray)
                                        {
                                            PropertyInfo targetProp = target.GetType().GetProperty(objectTypeProp.Name);
                                            Array        choiceArr  = choiceProp.GetValue(target, null) as Array;
                                            Array        objectArr  = targetProp.GetValue(target, null) as Array;
                                            if (choiceArr == null)
                                            {
                                                choiceArr = Array.CreateInstance(choiceProp.PropertyType.GetElementType(), 1);
                                                objectArr = Array.CreateInstance(targetProp.PropertyType.GetElementType(), 1);
                                            }
                                            else
                                            {
                                                choiceArr = ResizeArray(choiceArr, choiceArr.Length + 1);
                                                objectArr = ResizeArray(objectArr, objectArr.Length + 1);
                                            }
                                            choiceArr.SetValue(Enum.Parse(choiceProp.PropertyType.GetElementType(), attr.ElementName), choiceArr.Length - 1);
                                            choiceProp.SetValue(target, choiceArr, null);

                                            int   propertyValueCount = prop.Value.Count();
                                            int   elementIndex       = 0;
                                            Array elementArray       = Array.CreateInstance(attr.Type, propertyValueCount);
                                            foreach (var ele in prop.Value)
                                            {
                                                if (ele.Type != JTokenType.Property)
                                                {
                                                    if (attr.Type.IsArray)
                                                    {
                                                        elementArray.SetValue(ele.ToObject(attr.Type.GetElementType(), serializer), elementIndex);
                                                    }
                                                    else
                                                    {
                                                        elementArray.SetValue(ele.ToObject(attr.Type, serializer), elementIndex);
                                                    }
                                                    elementIndex++;
                                                }
                                            }
                                            if (elementIndex == 0)
                                            {
                                                objectArr.SetValue(prop.Value.ToObject(attr.Type, serializer), objectArr.Length - 1);
                                            }
                                            else
                                            {
                                                objectArr.SetValue(elementArray, objectArr.Length - 1);
                                            }
                                            targetProp.SetValue(target, objectArr, null);
                                        }
                                        else
                                        {
                                            Type type = Assembly.Load("Intuit.Ipp.Data").GetTypes().Where(a => a.Name == objectTypeProp.PropertyType.Name).FirstOrDefault();
                                            AssignValueToProperty(target, prop, type, objectTypeProp.Name, serializer);

                                            PropertyInfo specifiedProp = target.GetType().GetProperty(choiceAttr.MemberName);
                                            if (specifiedProp != null)
                                            {
                                                specifiedProp.SetValue(target, Enum.Parse(choiceProp.PropertyType, prop.Name), null);
                                            }
                                        }
                                    }
                                }
                                else
                                {   // Added if and else if statement to fix SDK-304 bug ( https://jira.intuit.com/browse/SDK-304)
                                    // This bug is due to CheckPayment and CreditCardPayment being a type and ElementName at the same time.
                                    // Due to this the serializer converts the CheckPayment to type CheckPayment instead of BillCheckPayment. Same as with CreditCardPayment
                                    if (attr.ElementName == "CheckPayment" && objectType.Name == "BillPayment" && objectTypeProp.Name == "AnyIntuitObject")
                                    {
                                        Type type = Assembly.Load("Intuit.Ipp.Data").GetTypes().Where(a => a.Name == "BillPaymentCheck").FirstOrDefault();
                                        AssignValueToProperty(target, prop, type, objectTypeProp.Name, serializer);
                                    }
                                    else if (attr.ElementName == "CreditCardPayment" && objectType.Name == "BillPayment" && objectTypeProp.Name == "AnyIntuitObject")
                                    {
                                        Type type = Assembly.Load("Intuit.Ipp.Data").GetTypes().Where(a => a.Name == "BillPaymentCreditCard").FirstOrDefault();
                                        AssignValueToProperty(target, prop, type, objectTypeProp.Name, serializer);
                                    }
                                    else
                                    {
                                        //actual type in object which is annotated with name in XmlElementAttribute
                                        Type type = Assembly.Load("Intuit.Ipp.Data").GetTypes().Where(a => a.Name == prop.Name).FirstOrDefault();
                                        AssignValueToProperty(target, prop, type, objectTypeProp.Name, serializer);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    //property with node name exist. Assign the value to property.
                    Type type = target.GetType().GetProperty(prop.Name).PropertyType;
                    Type typ1 = target.GetType().GetProperty(prop.Name).PropertyType.GetElementType();
                    AssignValueToProperty(target, prop, type, prop.Name, serializer);
                }
            }
            return(target);
        }
Example #17
0
        internal IMnBaseElement GetJbElement(JObject jsonObject)
        {
            IMnBaseElement mnElement;
            var            properties = jsonObject.Properties().ToList();

            if (properties.All(p => p.Name != "Type"))
            {
                return(null);
            }
            var elementType  = (string)properties.Single(p => p.Name == "Type").Value;
            var typeFull     = properties.SingleOrDefault(p => p.Name == "Type.FullName");
            var assemblyName = properties.SingleOrDefault(p => p.Name == "Type.AssemblyName");

            if (elementType == typeof(MnTextBox).Name)
            {
                mnElement = new MnTextBox();
                (mnElement as MnTextBox).Value = (string)properties.Single(p => p.Name == "Value").Value;
                if (properties.Any(p => p.Name == "PlaceHolder"))
                {
                    (mnElement as MnTextBox).PlaceHolder = (string)properties.Single(p => p.Name == "PlaceHolder").Value;
                }
                else
                {
                    (mnElement as MnTextBox).PlaceHolder = string.Empty;
                }
            }
            else if (elementType == typeof(MnNumber).Name)
            {
                mnElement = new MnNumber();
                (mnElement as MnNumber).Value = (string)properties.Single(p => p.Name == "Value").Value;
                if (properties.Any(p => p.Name == "PlaceHolder"))
                {
                    (mnElement as MnNumber).PlaceHolder = (string)properties.Single(p => p.Name == "PlaceHolder").Value;
                }
                else
                {
                    (mnElement as MnNumber).PlaceHolder = string.Empty;
                }

                if (properties.Any(p => p.Name == "MinVal") && !string.IsNullOrEmpty((string)properties.Single(p => p.Name == "MinVal").Value))
                {
                    (mnElement as MnNumber).MinVal = (int)properties.Single(p => p.Name == "MinVal").Value;
                }

                if (properties.Any(p => p.Name == "MaxVal") && !string.IsNullOrEmpty((string)properties.Single(p => p.Name == "MaxVal").Value))
                {
                    (mnElement as MnNumber).MaxVal = (int)properties.Single(p => p.Name == "MaxVal").Value;
                }
            }
            else if (elementType == typeof(MnEmail).Name)
            {
                mnElement = new MnEmail();
                (mnElement as MnEmail).Value = (string)properties.Single(p => p.Name == "Value").Value;
                if (properties.Any(p => p.Name == "PlaceHolder"))
                {
                    (mnElement as MnEmail).PlaceHolder = (string)properties.Single(p => p.Name == "PlaceHolder").Value;
                }
                else
                {
                    (mnElement as MnEmail).PlaceHolder = string.Empty;
                }
            }
            else if (elementType == typeof(MnParagraph).Name)
            {
                mnElement = new MnParagraph();
                (mnElement as MnParagraph).Value = (string)properties.Single(p => p.Name == "Value").Value;
            }
            else if (elementType == typeof(MnHidden).Name)
            {
                mnElement = new MnHidden();
                (mnElement as MnHidden).Value = (string)properties.Single(p => p.Name == "Value").Value;
            }
            else if (elementType == typeof(MnCheckBox).Name)
            {
                mnElement = new MnCheckBox();
                (mnElement as MnCheckBox).Value = (bool)properties.Single(p => p.Name == "Value").Value;
            }
            else if (elementType == typeof(MnDropDown).Name)
            {
                mnElement = new MnDropDown();
                (mnElement as MnDropDown).Items =
                    properties.Single(p => p.Name == "Items").Value.ToObject <List <MnElementItem> >();
            }
            else if (elementType == typeof(MnCheckBoxList).Name)
            {
                mnElement = new MnCheckBoxList();
                (mnElement as MnCheckBoxList).Items =
                    properties.Single(p => p.Name == "Items").Value.ToObject <List <JbSelectedItem> >();
            }
            else if (elementType == typeof(MnSection).Name)
            {
                mnElement = new MnSection();
                var innerElements = properties.Single(p => p.Name == "Elements").Value.ToObject <List <object> >();
                foreach (var element in innerElements)
                {
                    (mnElement as MnSection).Elements.Add(GetJbElement(element as JObject));
                }
            }
            else if (elementType == typeof(MnAddress).Name)
            {
                mnElement = new MnAddress();
            }
            else
            {
                Type typ;
                if (typeFull == null)
                {
                    typ = Type.GetType(string.Format("{0}.Forms.{1}, {0}", this.GetType().Assembly.GetName().Name, elementType), true);
                }
                else
                {
                    typ = Type.GetType((string)typeFull.Value + "," + (string)assemblyName.Value, true);
                }

                mnElement = (IMnBaseElement)Activator.CreateInstance(typ);
            }

            if (mnElement is IInputElement)
            {
                //if (properties.Any(p => p.Name == "IsRequired"))
                //    (mnElement as IInputElement).IsRequired =
                //        (bool)properties.Single(p => p.Name == "IsRequired").Value;
                //else
                //    (mnElement as IInputElement).IsRequired = false;
            }

            foreach (var property in properties)
            {
                if (property.Name.Equals("Type"))
                {
                    continue;
                }
                var proInfo = mnElement.GetType().GetProperty(property.Name);
                if (proInfo == null)
                {
                    continue;
                }
                if (proInfo.PropertyType == mnElement.AccessRole.GetType())
                {
                    var accessRoles = property.Value.ToObject <Dictionary <string, AccessMode> >();
                    proInfo.SetValue(mnElement, accessRoles);
                }
                else if (proInfo.PropertyType == mnElement.Validations.GetType())
                {
                    var validations = property.Value.ToObject <List <BaseElementValidator> >();
                    proInfo.SetValue(mnElement, validations);
                }
                else if (Attribute.IsDefined(proInfo, typeof(JsonConverterAttribute)))
                {
                    var jsonAttr = proInfo.GetCustomAttribute <JsonConverterAttribute>(false);
                    if (jsonAttr.ConverterType == typeof(StringEnumConverter))
                    {
                        var mode = property.Value.ToObject(proInfo.PropertyType);
                        proInfo.SetValue(mnElement, Enum.ToObject(proInfo.PropertyType, mode));
                    }
                }
                else
                {
                    if (typeof(System.Collections.IList).IsAssignableFrom(proInfo.PropertyType))
                    {
                        continue;
                    }
                    if (!string.IsNullOrEmpty((string)property.Value))
                    {
                        proInfo.SetValue(mnElement, Convert.ChangeType(property.Value, proInfo.PropertyType));
                    }
                }
            }
            return(mnElement as MnBaseElement ?? mnElement as IMnBaseElement);
        }
Example #18
0
 static public IEnumerable <KeyValuePair <string, Int64> > SubsetPropertyInt(this JObject jObject) =>
 jObject?.Properties()
 ?.Select(property => new KeyValuePair <string, Int64?>(property.Name, property.Value.ValueAsIntIfInteger()))
 ?.Where(property => property.Value.HasValue)
 ?.Select(property => new KeyValuePair <string, Int64>(property.Key, property.Value.Value));
Example #19
0
 public static void Remove(this JObject jObj, Func <JProperty, bool> predicate)
 => jObj?.Properties()
 .Where(predicate)
 .Select(p => p.Name)
 .ToArray().ForEach(p => jObj.Remove(p));
Example #20
0
 internal IEnumerable <KeyValuePair <string, string> > VisitJObject(JObject jObject)
 {
     return(jObject.Properties().SelectMany(property => VisitProperty(property.Name, property.Value)));
 }
Example #21
0
        /// <summary>
        /// Upserts the specified entity name.
        /// </summary>
        /// <param name="entityName">Name of the entity.</param>
        /// <param name="input">Data to be saved, can be anything including anonymous type. But Anonymous Type must include Id parameter</param>
        public JObject UpsertRecord(string entityName, object inputObject)
        {
            var type = _dataType.FromName(entityName);

            if (type is StaticDataType)
            {
                return(JObject.FromObject(this.UpsertStaticRecord(entityName, inputObject)));
            }

            JObject jObject = inputObject as JObject;

            if (jObject == null)
            {
                jObject = JObject.FromObject(inputObject);
            }

            List <JProperty> removed = new List <JProperty>();

            // converts complex properties to Json
            foreach (var prop in jObject.Properties().ToList()) // to-list to allow us to add property
            {
                if (prop.Value.Type == JTokenType.Array || prop.Value.Type == JTokenType.Object)
                {
                    // array or objects are converted to JSON when stored in table
                    jObject["js_" + prop.Name] = prop.Value.ToString(Formatting.None);

                    prop.Remove();
                    removed.Add(prop);
                }
            }

            type = _dataType.FromJObject(entityName, jObject);
            var actualType = type.GetCompiledType();

            jObject["__updatedAt"] = DateTime.Now;

            int id = 0;

            if (jObject.Property("id") != null) // try to get Id
            {
                id = (int)jObject["id"];

                jObject["Id"] = id;
                jObject.Remove("id");
            }

            if (jObject.Property("Id") != null)
            {
                id = (int)jObject["Id"];
            }

            if (id == 0)
            {
                jObject["__createdAt"] = DateTime.Now;

                // needs to convert to object to get Id later
                dynamic toInsert = jObject.ToObject(actualType);

                NancyBlackDatabase.ObjectCreating(this, entityName, toInsert);

                _db.Insert(toInsert, actualType);
                jObject["Id"] = toInsert.Id;

                NancyBlackDatabase.ObjectCreated(this, entityName, toInsert);
            }
            else
            {
                NancyBlackDatabase.ObjectUpdating(this, entityName, jObject);

                _db.Update(jObject.ToObject(actualType), actualType);

                NancyBlackDatabase.ObjectUpdated(this, entityName, jObject);
            }

            // remove "js_" properties
            foreach (var prop in jObject.Properties().ToList()) // to-list to allow us to add/remove property
            {
                if (prop.Name.StartsWith("js_"))
                {
                    prop.Remove();
                }
            }

            // add removed complex properties back
            foreach (var prop in removed)
            {
                jObject.Add(prop.Name, prop.Value);
            }

            return(jObject);
        }
Example #22
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]);
        }
Example #23
0
        public static UserControl CreateOption(JToken token, string _work_name = null, string _index = null)
        {
            ConfigOptionManager.Clear();

            root     = token;
            workName = _work_name;
            index    = _index;

            JObject new_root = token.DeepClone() as JObject;

            if (_work_name != null)
            {
                JObject jobj_work = ((token as JObject)?.GetValue("work_group") as JObject)?.GetValue(_work_name) as JObject;
                foreach (var v in jobj_work.Properties())
                {
                    if (v.Value as JArray == null)
                    {
                        JObject jobj_cur = new_root.GetValue(v.Name) as JObject;
                        if (jobj_cur == null)
                        {
                            continue;
                        }
                        foreach (var prop in (v.Value as JObject)?.Properties())
                        {
                            jobj_cur[prop.Name] = prop.Value;
                            if (prop.Name[0] == ConfigOptionManager.StartDisableProperty)
                            {
                                jobj_cur[prop.Name.Substring(1)]?.Parent?.Remove();
                            }
                            else
                            {
                                jobj_cur[ConfigOptionManager.StartDisableProperty + prop.Name]?.Parent?.Remove();
                            }
                        }
                    }
                    else
                    {
                        JArray jarr_cur = new_root.GetValue(v.Name) as JArray;
                        if (jarr_cur == null)
                        {
                            continue;
                        }
                        int idx = 0;
                        foreach (var jobj in (v.Value as JArray))
                        {
                            foreach (var prop in (jobj as JObject)?.Properties())
                            {
                                jarr_cur[idx][prop.Name] = prop.Value;
                                if (prop.Name[0] == ConfigOptionManager.StartDisableProperty)
                                {
                                    jarr_cur[idx][prop.Name.Substring(1)]?.Parent?.Remove();
                                }
                                else
                                {
                                    jarr_cur[idx][ConfigOptionManager.StartDisableProperty + prop.Name]?.Parent?.Remove();
                                }
                            }
                            idx++;
                        }
                    }
                }
            }
            if (_work_name != null && _index != null)
            {
                JObject jobj_process = ((((token as JObject)?.GetValue("work_group") as JObject)?.GetValue(_work_name) as JObject)?.GetValue("processes") as JArray)?[Int32.Parse(_index)] as JObject;
                foreach (var v in jobj_process?.Properties())
                {
                    if (v.Value as JArray == null)
                    {
                        JObject jobj_cur = new_root.GetValue(v.Name) as JObject;
                        if (jobj_cur == null)
                        {
                            continue;
                        }
                        foreach (var prop in (v.Value as JObject)?.Properties())
                        {
                            jobj_cur[prop.Name] = prop.Value;
                            if (prop.Name[0] == ConfigOptionManager.StartDisableProperty)
                            {
                                jobj_cur[prop.Name.Substring(1)]?.Parent?.Remove();
                            }
                            else
                            {
                                jobj_cur[ConfigOptionManager.StartDisableProperty + prop.Name]?.Parent?.Remove();
                            }
                        }
                    }
                    else
                    {
                        JArray jarr_cur = new_root.GetValue(v.Name) as JArray;
                        if (jarr_cur == null)
                        {
                            continue;
                        }
                        int idx = 0;
                        foreach (var jobj in (v.Value as JArray))
                        {
                            foreach (var prop in (jobj as JObject)?.Properties())
                            {
                                jarr_cur[idx][prop.Name] = prop.Value;
                                if (prop.Name[0] == ConfigOptionManager.StartDisableProperty)
                                {
                                    jarr_cur[idx][prop.Name.Substring(1)]?.Parent?.Remove();
                                }
                                else
                                {
                                    jarr_cur[idx][ConfigOptionManager.StartDisableProperty + prop.Name]?.Parent?.Remove();
                                }
                            }
                            idx++;
                        }
                    }
                }
            }

            current = CreateOption(token["type"]?.ToString(), new_root);
            return(current);
        }
Example #24
0
        //Open save json and parsing
        private void Button_JSON_open_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog
            {
                DefaultExt       = ".json",
                Filter           = "JSON (*.json)|*.json",
                Title            = "Open TTS save",
                InitialDirectory = TB_JSON_path.Text
            };

            Nullable <bool> result = dlg.ShowDialog();

            if (result == true)
            {
                string filename = dlg.FileName;
                TB_JSON_path.Text = filename;
                using (StreamReader jsonSave = File.OpenText(TB_JSON_path.Text))
                    using (JsonTextReader reader = new JsonTextReader(jsonSave))
                    {
                        string[] FindURL(JArray Objects)
                        {
                            SortedSet <string> urls = new SortedSet <string>();

                            if (Objects == null)
                            {
                                return(urls.ToArray());
                            }
                            foreach (JObject ob in Objects)
                            {
                                if (ob["Name"].ToString().Equals("Custom_Tile") ||
                                    ob["Name"].ToString().Equals("Custom_Token") ||
                                    ob["Name"].ToString().Equals("Figurine_Custom"))
                                {
                                    JObject tmp = (JObject)ob["CustomImage"];
                                    if (!urls.Add(tmp["ImageURL"].ToString()).Equals(""))
                                    {
                                        urls.Add(tmp["ImageURL"].ToString());
                                    }
                                    if (!tmp["ImageSecondaryURL"].ToString().Equals(""))
                                    {
                                        urls.Add(tmp["ImageSecondaryURL"].ToString());
                                    }
                                    if (ob.ContainsKey("States"))
                                    {
                                        JObject tmpO = (JObject)ob["States"];
                                        JArray  tmpA = new JArray();
                                        foreach (JProperty t in tmpO.Properties())
                                        {
                                            tmpA.Add(t.First);
                                        }
                                        string[] tmp1 = FindURL(tmpA);
                                        foreach (string s in tmp1)
                                        {
                                            urls.Add(s);
                                        }
                                    }
                                }
                                else if (ob["Name"].ToString().Equals("Custom_Model"))
                                {
                                    JObject tmp = (JObject)ob["CustomMesh"];
                                    if (!tmp["DiffuseURL"].ToString().Equals(""))
                                    {
                                        urls.Add(tmp["DiffuseURL"].ToString());
                                    }
                                }
                                else if (ob["Name"].ToString().Equals("Deck") ||
                                         ob["Name"].ToString().Equals("DeckCustom") ||
                                         ob["Name"].ToString().Equals("Card") ||
                                         ob["Name"].ToString().Equals("CardCustom"))
                                {
                                    foreach (var x in (JObject)ob["CustomDeck"])
                                    {
                                        string  name = x.Key;
                                        JObject tmp  = (JObject)x.Value;
                                        urls.Add(tmp["FaceURL"].ToString());
                                        urls.Add(tmp["BackURL"].ToString());
                                    }
                                }
                                else if (ob["Name"].ToString().Equals("Custom_Model_Infinite_Bag") ||
                                         ob["Name"].ToString().Equals("Custom_Model_Bag"))
                                {
                                    JObject tmpo = (JObject)ob["CustomMesh"];
                                    if (!tmpo["DiffuseURL"].ToString().Equals(""))
                                    {
                                        urls.Add(tmpo["DiffuseURL"].ToString());
                                    }
                                    string[] tmp = FindURL((JArray)ob["ContainedObjects"]);
                                    foreach (string s in tmp)
                                    {
                                        urls.Add(s);
                                    }
                                }
                                else if (ob["Name"].ToString().Equals("Bag") ||
                                         ob["Name"].ToString().Equals("Infinite_Bag"))
                                {
                                    string[] tmp = FindURL((JArray)ob["ContainedObjects"]);
                                    foreach (string s in tmp)
                                    {
                                        urls.Add(s);
                                    }
                                }
                            }
                            return(urls.ToArray());
                        }

                        JObject jsonO = (JObject)JToken.ReadFrom(reader);

                        //System.Console.WriteLine(string.Join("\n", urls.ToArray()));
                        DataTable dt = new DataTable();

                        dt.Columns.Add("#", typeof(int));
                        dt.Columns.Add("Original", typeof(string));
                        dt.Columns.Add("New", typeof(string));
                        string[] ua = FindURL((JArray)jsonO["ObjectStates"]);
                        for (int idx = 0; idx < ua.Count(); idx++)
                        {
                            dt.Rows.Add(new string[] { idx.ToString(), ua[idx], "" });
                        }
                        URLtable.ItemsSource         = dt.DefaultView;
                        URLtable.IsReadOnly          = true;
                        URLtable.SelectionMode       = DataGridSelectionMode.Single;
                        URLtable.Columns[0].Width    = DataGridLength.SizeToCells;
                        URLtable.Columns[1].MaxWidth = 380;
                        saveOpened = true;
                    }
            }
        }
        /// <summary>
        /// Get the private config value for a specific attribute.
        /// The private config looks like this:
        /// XML:
        ///    <PrivateConfig xmlns="namespace">
        ///      <StorageAccount name = "name" key="key" endpoint="endpoint" />
        ///      <EventHub Url = "url" SharedAccessKeyName="sasKeyName" SharedAccessKey="sasKey"/>
        ///    </PrivateConfig>
        ///
        /// JSON:
        ///    "PrivateConfig":{
        ///      "storageAccountName":"name",
        ///      "storageAccountKey":"key",
        ///      "storageAccountEndPoint":"endpoint",
        ///      "EventHub":{
        ///        "Url":"url",
        ///        "SharedAccessKeyName":"sasKeyName",
        ///        "SharedAccessKey":"sasKey"
        ///      }
        ///    }
        /// </summary>
        /// <param name="configurationPath">The path to the configuration file</param>
        /// <param name="elementName">The element name of the private config. e.g., StorageAccount, EventHub</param>
        /// <param name="attributeName">The attribute name of the element</param>
        /// <returns></returns>
        public static string GetConfigValueFromPrivateConfig(string configurationPath, string elementName, string attributeName)
        {
            string value          = string.Empty;
            var    configFileType = GetConfigFileType(configurationPath);

            if (configFileType == ConfigFileType.Xml)
            {
                var xmlConfig = XElement.Load(configurationPath);

                if (xmlConfig.Name.LocalName == DiagnosticsConfigurationElemStr)
                {
                    var privateConfigElem = xmlConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == PrivateConfigElemStr);
                    var configElem        = privateConfigElem == null ? null : privateConfigElem.Elements().FirstOrDefault(ele => ele.Name.LocalName == elementName);
                    var attribute         = configElem == null ? null : configElem.Attributes().FirstOrDefault(a => string.Equals(a.Name.LocalName, attributeName));
                    value = attribute == null ? null : attribute.Value;
                }
            }
            else if (configFileType == ConfigFileType.Json)
            {
                // Find the PrivateConfig
                var jsonConfig            = JsonConvert.DeserializeObject <JObject>(File.ReadAllText(configurationPath));
                var properties            = jsonConfig.Properties().Select(p => p.Name);
                var privateConfigProperty = properties.FirstOrDefault(p => p.Equals(PrivateConfigElemStr));

                if (privateConfigProperty == null)
                {
                    return(value);
                }
                var privateConfig = jsonConfig[privateConfigProperty] as JObject;

                // Find the target config object corresponding to elementName
                JObject targetConfig = null;
                if (elementName == StorageAccountElemStr)
                {
                    // Special handling as private storage config is flattened
                    targetConfig = privateConfig;
                    var attributeNameMapping = new Dictionary <string, string>()
                    {
                        { PrivConfNameAttr, "storageAccountName" },
                        { PrivConfKeyAttr, "storageAccountKey" },
                        { PrivConfEndpointAttr, "storageAccountEndPoint" }
                    };
                    attributeName = attributeNameMapping.FirstOrDefault(m => m.Key == attributeName).Value;
                }
                else
                {
                    properties = privateConfig.Properties().Select(p => p.Name);
                    var configProperty = properties.FirstOrDefault(p => p.Equals(elementName));
                    targetConfig = configProperty == null ? null : privateConfig[configProperty] as JObject;
                }

                if (targetConfig == null || attributeName == null)
                {
                    return(value);
                }

                // Find the config value corresponding to attributeName
                properties = targetConfig.Properties().Select(p => p.Name);
                var attributeProperty = properties.FirstOrDefault(p => p.Equals(attributeName));
                value = attributeProperty == null ? null : targetConfig[attributeProperty].Value <string>();
            }

            return(value);
        }
        public static IReadOnlyDictionary <string, IList <string> > ParseExtraArgs(this CommandLineApplication app, IList <string> extraArgFileNames)
        {
            Dictionary <string, IList <string> > parameters = new Dictionary <string, IList <string> >();

            // Note: If the same param is specified multiple times across the files, last-in-wins
            // TODO: consider another course of action.
            if (extraArgFileNames.Count > 0)
            {
                foreach (string argFile in extraArgFileNames)
                {
                    using (Stream s = File.OpenRead(argFile))
                        using (TextReader r = new StreamReader(s, Encoding.UTF8, true, 4096, true))
                            using (JsonTextReader reader = new JsonTextReader(r))
                            {
                                JObject obj = JObject.Load(reader);

                                foreach (JProperty property in obj.Properties())
                                {
                                    if (property.Value.Type == JTokenType.String)
                                    {
                                        IList <string> values = new List <string>
                                        {
                                            property.Value.ToString()
                                        };

                                        // adding 2 dashes to the file-based params
                                        // won't work right if there's a param that should have 1 dash
                                        //
                                        // TOOD: come up with a better way to deal with this
                                        parameters["--" + property.Name] = values;
                                    }
                                }
                            }
                }
            }

            for (int i = 0; i < app.RemainingArguments.Count; ++i)
            {
                string        key     = app.RemainingArguments[i];
                CommandOption arg     = app.Options.FirstOrDefault(x => x.Template.Split('|').Any(y => string.Equals(y, key, StringComparison.OrdinalIgnoreCase)));
                bool          handled = false;

                if (arg != null)
                {
                    if (arg.OptionType != CommandOptionType.NoValue)
                    {
                        handled = arg.TryParse(app.RemainingArguments[i + 1]);
                        ++i;
                    }
                    else
                    {
                        handled = arg.TryParse(null);
                    }
                }

                if (handled)
                {
                    continue;
                }

                if (!key.StartsWith("-", StringComparison.Ordinal))
                {
                    throw new Exception(LocalizableStrings.ParameterNamePrefixError);
                }

                // Check the next value. If it doesn't start with a '-' then it's a value for the current param.
                // Otherwise it's its own param.
                string value = null;
                if (app.RemainingArguments.Count > i + 1)
                {
                    value = app.RemainingArguments[i + 1];

                    if (value.StartsWith("-", StringComparison.Ordinal))
                    {
                        value = null;
                    }
                    else
                    {
                        ++i;
                    }
                }

                if (!parameters.TryGetValue(key, out IList <string> valueList))
                {
                    valueList = new List <string>();
                    parameters.Add(key, valueList);
                }

                valueList.Add(value);
            }

            return(parameters);
        }
        public override ExchangeOrderResult GetOrderDetails(string orderId)
        {
            //{
            //    "status": "Finished",
            //    "id": 1022694747,
            //    "transactions": [
            //    {
            //        "fee": "0.000002",
            //        "bch": "0.00882714",
            //        "price": "0.12120000",
            //        "datetime": "2018-02-24 14:15:29.133824",
            //        "btc": "0.0010698493680000",
            //        "tid": 56293144,
            //        "type": 2
            //    }]
            //}
            if (string.IsNullOrWhiteSpace(orderId))
            {
                return(null);
            }
            string url = "/order_status/";
            Dictionary <string, object> payload = GetNoncePayload();

            payload["id"] = orderId;
            JObject result = MakeJsonRequest <JObject>(url, null, payload, "POST");

            CheckError(result);

            // status can be 'In Queue', 'Open' or 'Finished'
            JArray transactions = result["transactions"] as JArray;

            // empty transaction array means that order is InQueue or Open and AmountFilled == 0
            // return empty order in this case. no any additional info available at this point
            if (transactions.Count() == 0)
            {
                return(new ExchangeOrderResult()
                {
                    OrderId = orderId
                });
            }
            JObject       first          = transactions.First() as JObject;
            List <string> excludeStrings = new List <string>()
            {
                "tid", "price", "fee", "datetime", "type", "btc", "usd", "eur"
            };

            string baseCurrency;
            string marketCurrency = first.Properties().FirstOrDefault(p => !excludeStrings.Contains(p.Name, StringComparer.InvariantCultureIgnoreCase))?.Name;

            if (string.IsNullOrWhiteSpace(marketCurrency))
            {
                // the only 2 cases are BTC-USD and BTC-EUR
                marketCurrency = "btc";
                excludeStrings.RemoveAll(s => s.Equals("usd") || s.Equals("eur"));
                baseCurrency = first.Properties().FirstOrDefault(p => !excludeStrings.Contains(p.Name, StringComparer.InvariantCultureIgnoreCase))?.Name;
            }
            else
            {
                excludeStrings.RemoveAll(s => s.Equals("usd") || s.Equals("eur") || s.Equals("btc"));
                excludeStrings.Add(marketCurrency);
                baseCurrency = first.Properties().FirstOrDefault(p => !excludeStrings.Contains(p.Name, StringComparer.InvariantCultureIgnoreCase))?.Name;
            }
            string symbol = $"{marketCurrency}-{baseCurrency}";

            decimal amountFilled = 0, spentBaseCurrency = 0, price = 0;

            foreach (var t in transactions)
            {
                int type = t["type"].ConvertInvariant <int>();
                if (type != 2)
                {
                    continue;
                }
                spentBaseCurrency += t[baseCurrency].ConvertInvariant <decimal>();
                amountFilled      += t[marketCurrency].ConvertInvariant <decimal>();
                //set price only one time
                if (price == 0)
                {
                    price = t["price"].ConvertInvariant <decimal>();
                }
            }

            // No way to know if order IsBuy, Amount, OrderDate
            return(new ExchangeOrderResult()
            {
                AmountFilled = amountFilled,
                Symbol = symbol,
                AveragePrice = spentBaseCurrency / amountFilled,
                Price = price,
            });
        }
        private RecognizerResult MergeResults(RecognizerResult[] results)
        {
            var     recognizerResult = new RecognizerResult();
            JObject instanceData     = new JObject();

            recognizerResult.Entities["$instance"] = instanceData;

            foreach (var result in results)
            {
                var(intent, score) = result.GetTopScoringIntent();
                if (intent != "None")
                {
                    // merge text
                    if (recognizerResult.Text == null)
                    {
                        recognizerResult.Text = result.Text;
                    }
                    else if (result.Text != recognizerResult.Text)
                    {
                        recognizerResult.AlteredText = result.Text;
                    }

                    // merge intents
                    foreach (var intentPair in result.Intents)
                    {
                        if (recognizerResult.Intents.TryGetValue(intentPair.Key, out var prevScore))
                        {
                            if (intentPair.Value.Score < prevScore.Score)
                            {
                                continue; // we already have a higher score for this intent
                            }
                        }

                        recognizerResult.Intents[intentPair.Key] = intentPair.Value;
                    }
                }

                // merge entities
                // entities shape is:
                //   {
                //      "name": ["value1","value2","value3"],
                //      "$instance": {
                //          "name": [ { "startIndex" : 15, ... }, ... ]
                //      }
                //   }
                foreach (var entityProperty in result.Entities.Properties())
                {
                    if (entityProperty.Name == "$instance")
                    {
                        // property is "$instance" so get the instance data
                        JObject resultInstanceData = (JObject)entityProperty.Value;
                        foreach (var name in resultInstanceData.Properties())
                        {
                            // merge sourceInstanceData[name] => instanceData[name]
                            MergeArrayProperty(resultInstanceData, name, instanceData);
                        }
                    }
                    else
                    {
                        // property is a "name" with values,
                        // merge result.Entities["name"] => recognizerResult.Entities["name"]
                        MergeArrayProperty(result.Entities, entityProperty, recognizerResult.Entities);
                    }
                }
            }

            if (!recognizerResult.Intents.Any())
            {
                recognizerResult.Intents.Add("None", new IntentScore()
                {
                    Score = 1.0d
                });
            }

            return(recognizerResult);
        }
Example #29
0
        internal static EnrichedActivity FromJson(JObject obj)
        {
            EnrichedActivity             activity             = new EnrichedActivity();
            EnrichedAggregatedActivity   aggregateActivity    = null;
            EnrichedNotificationActivity notificationActivity = null;

            if (obj.Properties().Any(p => p.Name == Field_Activities))
            {
                if ((obj.Properties().Any(p => p.Name == Field_IsRead)) ||
                    (obj.Properties().Any(p => p.Name == Field_IsSeen)))
                {
                    activity = aggregateActivity = notificationActivity = new EnrichedNotificationActivity();
                }
                else
                {
                    activity = aggregateActivity = new EnrichedAggregatedActivity();
                }
            }

            obj.Properties().ForEach((prop) =>
            {
                switch (prop.Name)
                {
                case Field_Id: activity.Id = prop.Value.Value <string>(); break;

                case Field_Actor: activity.Actor = EnrichableField.FromJSON(prop.Value); break;

                case Field_Verb: activity.Verb = EnrichableField.FromJSON(prop.Value); break;

                case Field_Object: activity.Object = EnrichableField.FromJSON(prop.Value); break;

                case Field_Target: activity.Target = EnrichableField.FromJSON(prop.Value); break;

                case Field_ForeignId: activity.ForeignId = EnrichableField.FromJSON(prop.Value); break;

                case Field_Time: activity.Time = prop.Value.Value <DateTime>(); break;

                case Field_To:
                    {
                        JArray array = prop.Value as JArray;
                        if ((array != null) && (array.SafeCount() > 0))
                        {
                            if (array.First.Type == JTokenType.Array)
                            {
                                // need to take the first from each array
                                List <string> tos = new List <string>();

                                foreach (var child in array)
                                {
                                    var str = child.ToObject <string[]>();
                                    tos.Add(str[0]);
                                }

                                activity.To = tos;
                            }
                            else
                            {
                                activity.To = prop.Value.ToObject <string[]>().ToList();
                            }
                        }
                        else
                        {
                            activity.To = new List <string>();
                        }
                        break;
                    }

                case Field_Activities:
                    {
                        var activities = new List <EnrichedActivity>();

                        JArray array = prop.Value as JArray;
                        if ((array != null) && (array.SafeCount() > 0))
                        {
                            foreach (var child in array)
                            {
                                var childJO = child as JObject;
                                if (childJO != null)
                                {
                                    activities.Add(FromJson(childJO));
                                }
                            }
                        }

                        if (aggregateActivity != null)
                        {
                            aggregateActivity.Activities = activities;
                        }
                        break;
                    }

                case Field_ActorCount:
                    {
                        if (aggregateActivity != null)
                        {
                            aggregateActivity.ActorCount = prop.Value.Value <int>();
                        }
                        break;
                    }

                case Field_IsRead:
                    {
                        if (notificationActivity != null)
                        {
                            notificationActivity.IsRead = prop.Value.Value <bool>();
                        }
                        break;
                    }

                case Field_IsSeen:
                    {
                        if (notificationActivity != null)
                        {
                            notificationActivity.IsSeen = prop.Value.Value <bool>();
                        }
                        break;
                    }

                case Field_CreatedAt:
                    {
                        if (aggregateActivity != null)
                        {
                            aggregateActivity.CreatedAt = prop.Value.Value <DateTime>();
                        }
                        break;
                    }

                case Field_UpdatedAt:
                    {
                        if (aggregateActivity != null)
                        {
                            aggregateActivity.UpdatedAt = prop.Value.Value <DateTime>();
                        }
                        break;
                    }

                case Field_Group:
                    {
                        if (aggregateActivity != null)
                        {
                            aggregateActivity.Group = prop.Value.Value <string>();
                        }
                        break;
                    }

                case Field_OwnReactions:
                    {
                        activity.OwnReactions = prop.Value.ToObject <IDictionary <string, IEnumerable <Reaction> > >();
                        break;
                    }

                case Field_LatestReactions:
                    {
                        activity.LatestReactions = prop.Value.ToObject <IDictionary <string, IEnumerable <Reaction> > >();
                        break;
                    }

                case Field_ReactionCounts:
                    {
                        activity.ReactionCounts = prop.Value.ToObject <IDictionary <string, int> >();
                        break;
                    }

                default:
                    {
                        // stash everything else as custom
                        activity._data[prop.Name] = prop.Value;
                        break;
                    };
                }
            });
            return(activity);
        }
Example #30
0
        public override void Validate(object state)
        {
            if (RecordType != null)
            {
                Init(RecordType);
            }

            base.Validate(state);

            string[] fieldNames = null;
            JObject  jObject    = null;

            if (state is Tuple <long, JObject> )
            {
                jObject = ((Tuple <long, JObject>)state).Item2;
            }
            else
            {
                fieldNames = state as string[];
            }

            if (AutoDiscoverColumns &&
                JSONRecordFieldConfigurations.Count == 0)
            {
                if (RecordType != null && !IsDynamicObject && /*&& RecordType != typeof(ExpandoObject)*/
                    ChoTypeDescriptor.GetProperties(RecordType).Where(pd => pd.Attributes.OfType <ChoJSONRecordFieldAttribute>().Any()).Any())
                {
                    MapRecordFields(RecordType);
                }
                else if (jObject != null)
                {
                    Dictionary <string, ChoJSONRecordFieldConfiguration> dict = new Dictionary <string, ChoJSONRecordFieldConfiguration>(StringComparer.CurrentCultureIgnoreCase);
                    string name = null;
                    foreach (var attr in jObject.Properties())
                    {
                        name = attr.Name;
                        if (!dict.ContainsKey(name))
                        {
                            dict.Add(name, new ChoJSONRecordFieldConfiguration(name, (string)null));
                        }
                        else
                        {
                            throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(name));
                        }
                    }

                    foreach (ChoJSONRecordFieldConfiguration obj in dict.Values)
                    {
                        JSONRecordFieldConfigurations.Add(obj);
                    }
                }
                else if (!fieldNames.IsNullOrEmpty())
                {
                    foreach (string fn in fieldNames)
                    {
                        var obj = new ChoJSONRecordFieldConfiguration(fn, (string)null);
                        JSONRecordFieldConfigurations.Add(obj);
                    }
                }
            }
            else
            {
                foreach (var fc in JSONRecordFieldConfigurations)
                {
                    fc.ComplexJPathUsed = !(fc.JSONPath.IsNullOrWhiteSpace() || String.Compare(fc.FieldName, fc.JSONPath, true) == 0);
                }
            }

            if (JSONRecordFieldConfigurations.Count <= 0)
            {
                throw new ChoRecordConfigurationException("No record fields specified.");
            }

            //Validate each record field
            foreach (var fieldConfig in JSONRecordFieldConfigurations)
            {
                fieldConfig.Validate(this);
            }

            //Check field position for duplicate
            string[] dupFields = JSONRecordFieldConfigurations.GroupBy(i => i.Name)
                                 .Where(g => g.Count() > 1)
                                 .Select(g => g.Key).ToArray();

            if (dupFields.Length > 0)
            {
                throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(String.Join(",", dupFields)));
            }

            PIDict = new Dictionary <string, System.Reflection.PropertyInfo>();
            PDDict = new Dictionary <string, PropertyDescriptor>();
            foreach (var fc in JSONRecordFieldConfigurations)
            {
                if (fc.PropertyDescriptor == null)
                {
                    fc.PropertyDescriptor = ChoTypeDescriptor.GetProperties(RecordType).Where(pd => pd.Name == fc.Name).FirstOrDefault();
                }
                if (fc.PropertyDescriptor == null)
                {
                    continue;
                }

                PIDict.Add(fc.PropertyDescriptor.Name, fc.PropertyDescriptor.ComponentType.GetProperty(fc.PropertyDescriptor.Name));
                PDDict.Add(fc.PropertyDescriptor.Name, fc.PropertyDescriptor);
            }

            RecordFieldConfigurationsDict = JSONRecordFieldConfigurations.Where(i => !i.Name.IsNullOrWhiteSpace()).ToDictionary(i => i.Name);

            LoadNCacheMembers(JSONRecordFieldConfigurations);
        }
Example #31
0
 public static List <string> Keys(this JObject json)
 => json?.Properties()?
 .Select(p => p.Name)?.ToList();
Example #32
0
    public void CreateJTokenTree()
    {
      JObject o =
        new JObject(
          new JProperty("Test1", "Test1Value"),
          new JProperty("Test2", "Test2Value"),
          new JProperty("Test3", "Test3Value"),
          new JProperty("Test4", null)
        );

      Assert.AreEqual(4, o.Properties().Count());

      Assert.AreEqual(@"{
  ""Test1"": ""Test1Value"",
  ""Test2"": ""Test2Value"",
  ""Test3"": ""Test3Value"",
  ""Test4"": null
}", o.ToString());

      JArray a =
        new JArray(
          o,
          new DateTime(2000, 10, 10, 0, 0, 0, DateTimeKind.Utc),
          55,
          new JArray(
            "1",
            2,
            3.0,
            new DateTime(4, 5, 6, 7, 8, 9, DateTimeKind.Utc)
          ),
          new JConstructor(
            "ConstructorName",
            "param1",
            2,
            3.0
          )
        );

      Assert.AreEqual(5, a.Count());
      Assert.AreEqual(@"[
  {
    ""Test1"": ""Test1Value"",
    ""Test2"": ""Test2Value"",
    ""Test3"": ""Test3Value"",
    ""Test4"": null
  },
  ""2000-10-10T00:00:00Z"",
  55,
  [
    ""1"",
    2,
    3.0,
    ""0004-05-06T07:08:09Z""
  ],
  new ConstructorName(
    ""param1"",
    2,
    3.0
  )
]", a.ToString());
    }
Example #33
0
        private static LinkObject ParseLinkObject(JObject outer, string rel)
        {
            var link = new LinkObject {
                Rel = rel
            };
            string href = null;

            foreach (var inner in outer.Properties())
            {
                var value = inner.Value.ToString();

                if (string.IsNullOrEmpty(value))
                {
                    continue;                     // nothing to assign, just leave the default value ...
                }
                var attribute = inner.Name.ToLowerInvariant();

                switch (attribute)
                {
                case "href":
                    href = value;
                    break;

                case "templated":
                    link.Templated = value.Equals("true", StringComparison.OrdinalIgnoreCase);
                    break;

                case "type":
                    link.Type = value;
                    break;

                case "deprication":
                    link.SetDeprecation(value);
                    break;

                case "name":
                    link.Name = value;
                    break;

                case "profile":
                    link.SetProfile(value);
                    break;

                case "title":
                    link.Title = value;
                    break;

                case "hreflang":
                    link.HrefLang = value;
                    break;

                default:
                    throw new NotSupportedException("Unsupported link attribute encountered: " + attribute);
                }
            }

            if (link.Templated)
            {
                link.Template = href;
            }
            else
            {
                link.SetHref(href);
            }

            return(link);
        }