Beispiel #1
0
        private static bool ParseCommandGroups <TOptions>(string[] args, ref TOptions options, TypeArgumentInfo arguments) where TOptions : new()
        {
            if (arguments.ActionArgument == null)
            {
                throw new ArgumentException("Cannot have groups unless Command argument has been specified");
            }

            if (args.Length == 0)
            {
                throw new ArgumentException("Required parameters have not been specified");
            }

            // parse based on the command passed in (the first arg).
            if (!arguments.ArgumentGroups.ContainsKey(args[0]))
            {
                throw new ArgumentException($"Unknown command [Cyan!{args[0]}]");
            }

            // short circuit the request for help!
            if (args.Length == 2 && (args[1] == "/?" || args[1] == "-?"))
            {
                HelpGenerator.DisplayHelpForCommmand(args[0], arguments.ArgumentGroups[args[0]]);
                return(false);
            }

            options = InternalParse <TOptions>(args, 1, arguments.ArgumentGroups[args[0]]);
            arguments.ActionArgument.SetValue(options, PropertyHelpers.GetValueAsType(args[0], arguments.ActionArgument));
            return(true);
        }
Beispiel #2
0
        private static List <PropertyInfo> ParseOptionalParameters <TOptions>(string[] args, int offsetInArray, ArgumentGroupInfo TypeArgumentInfo, TOptions options, ref int currentLogicalPosition) where TOptions : new()
        {
            // we are going to assume that all optionl parameters are not matched to values in 'args'
            List <PropertyInfo> unmatched = new List <PropertyInfo>(TypeArgumentInfo.OptionalArguments.Values);

            // process the optional arguments
            while (offsetInArray + currentLogicalPosition < args.Length)
            {
                if (args[offsetInArray + currentLogicalPosition][0] != '-')
                {
                    throw new ArgumentException("Optional parameter name should start with '-'");
                }

                PropertyInfo optionalProp      = null;
                var          optionalParamName = args[offsetInArray + currentLogicalPosition].Substring(1);
                if (!TypeArgumentInfo.OptionalArguments.TryGetValue(optionalParamName, out optionalProp))
                {
                    throw new ArgumentException($"Could not find argument {args[currentLogicalPosition]}");
                }

                // skip over the parameter name
                currentLogicalPosition++;

                var value = PropertyHelpers.GetValueFromArgsArray(args, offsetInArray, ref currentLogicalPosition, optionalProp);

                optionalProp.SetValue(options, value);
                unmatched.Remove(optionalProp);
            }

            return(unmatched);
        }
Beispiel #3
0
        public void CanCreateBagsTest()
        {
            int numBags = 5;
            var bags    = PropertyHelpers.CreateBags(numBags);

            Assert.AreEqual(bags.Count, numBags);
        }
Beispiel #4
0
        private void UpdateBuffer()
        {
            uint packSize = AnnotationVariable.DataType.GetPackSizeScalar();

            if (AnnotationVariable.IsMatrix && Values[0] is SerializableColor)
            {
                for (int i = 0; i < Values.Count; ++i)
                {
                    uint stepOffset = packSize * AnnotationVariable.Rows;
                    stepOffset = stepOffset.RoundUpMultiple16();
                    AnnotationVariable.CopyColorToBuffer((SerializableColor)Values.ElementAt(i), stepOffset, packSize * (uint)i);
                }
            }
            else
            {
                uint startOffset = 0;
                for (int column = 0; column < AnnotationVariable.Columns; ++column)
                {
                    for (int row = 0; row < AnnotationVariable.Rows; ++row)
                    {
                        if (Values[row * column + column] != null)
                        {
                            AnnotationVariable.CopyToBuffer(PropertyHelpers.ConvertToCorrectType(AnnotationVariable.DataType, Values[row * (int)AnnotationVariable.Columns + column]), startOffset);
                        }
                        startOffset += packSize;
                    }
                    startOffset = startOffset.RoundUpMultiple16();
                }
            }
            ITempHelper helper = ((App)Application.Current).ActiveViewport;

            AnnotationVariable.AnnotationGroup.MarshalBuffer(helper.ViewportHost, helper.IsStandardShaderActive);
        }
Beispiel #5
0
        public void Replace(Operation operation, object objectToApplyTo)
        {
            var removeResult = Remove(operation.path, objectToApplyTo, operation);

            if (removeResult.HasError)
            {
                // return => currently not applicable, will throw exception in Remove method
            }

            if (!removeResult.HasError && removeResult.ActualType == null)
            {
                // the remove operation completed succesfully, but we could not determine the type.
                throw new JsonPatchException(
                          new JsonPatchError(
                              objectToApplyTo,
                              operation,
                              string.Format("Patch failed: could not determine type of property at location {0}", operation.path)),
                          422);
            }

            var conversionResult = PropertyHelpers.ConvertToActualType(removeResult.ActualType, operation.value);

            if (!conversionResult.CanBeConverted)
            {
                throw new JsonPatchException(
                          new JsonPatchError(
                              objectToApplyTo,
                              operation,
                              string.Format("Patch failed: property value cannot be converted to type of path location {0}", operation.path)),
                          422);
            }

            Add(operation.path, conversionResult.ConvertedInstance, objectToApplyTo, operation);
        }
Beispiel #6
0
        /// <summary>
        /// Data property name that DataTables will use to set tr element DOM IDs.
        /// </summary>
        /// <param name="rowId"></param>
        /// <returns></returns>
        public TableOptionsFactory <TModel> RowId <T>(Expression <Func <TModel, T> > expression)
        {
            var propertyInfo = PropertyHelpers.GetPropertyInfo(expression);

            _jObject.Add("rowId", new JValue(propertyInfo.Name));
            return(this);
        }
Beispiel #7
0
 public void Process(SchemaProcessorContext context)
 {
     if (context.Type == typeof(ExternalRequirement))
     {
         var schema = context.Schema.Properties.Where(s => s.Key == PropertyHelpers.GetPropertyName(() => new ExternalRequirement().Heading)).FirstOrDefault().Value;
         using (var db = new CSET_Context())
         {
             var categories = db.QUESTION_GROUP_HEADING.Select(s => s.Question_Group_Heading1).Distinct().OrderBy(s => s).ToList();
             categories.ForEach(s => schema.Enumeration.Add(s));
         }
         schema = context.Schema.Properties.Where(s => s.Key == PropertyHelpers.GetPropertyName(() => new ExternalRequirement().Subheading)).FirstOrDefault().Value;
         using (var db = new CSET_Context())
         {
             var tempSchema    = new JsonSchema();
             var subCategories = db.UNIVERSAL_SUB_CATEGORIES.Select(s => s.Universal_Sub_Category).Distinct().OrderBy(s => s).ToList();
             subCategories.ForEach(s => tempSchema.Enumeration.Add(s));
             schema.AnyOf.Add(tempSchema);
             schema.AnyOf.Add(new JsonSchema()
             {
                 Type = JsonObjectType.String
             });
         }
         schema = context.Schema.Properties.Where(s => s.Key == PropertyHelpers.GetPropertyName(() => new ExternalRequirement().SecurityAssuranceLevel)).FirstOrDefault().Value;
         using (var db = new CSET_Context())
         {
             var subCategories = db.UNIVERSAL_SAL_LEVEL.Select(s => s.Sal_Level_Order).Distinct().OrderBy(s => s).ToList();
             subCategories.ForEach(s => schema.Enumeration.Add(s));
         }
     }
     else
     {
         throw new InvalidOperationException("Wrong type");
     }
 }
        public void Test()
        {
            var items = new[]
            {
                new PartySettings
                {
                    Id      = Guid.NewGuid().ToString(),
                    ScopeId = Guid.NewGuid().ToString(),
                    LastModificationDateTime = DateTime.UtcNow,
                },
                new PartySettings
                {
                    Id = Guid.NewGuid().ToString(), ScopeId = Guid.NewGuid().ToString(),
                    PartyBoxesSettings = new PartyBoxesSettings {
                        SupplierBoxSelectionStrategy = SupplierBoxSelectionStrategy.ShipperField
                    },
                }
            };

            var properties  = new List <string>();
            var gettersList = new List <Func <object?, object?> >();

            PropertyHelpers.BuildGettersForProperties(typeof(PartySettings), "", x => x, properties, gettersList, new CustomPropertyConfigurationProvider());

            var getters = properties.Zip(gettersList, (name, getter) => (name, getter)).ToDictionary(x => x.name, x => x.getter);

            getters["Id"](items[0]).Should().Be(items[0].Id);
            getters["ScopeId"](items[0]).Should().Be(items[0].ScopeId);
            getters["PartyBoxesSettings.SupplierBoxSelectionStrategy"](items[0]).Should().BeNull();
            getters["LastModificationDateTime"](items[0]).Should().Be(items[0].LastModificationDateTime);

            getters["Id"](items[1]).Should().Be(items[1].Id);
            getters["ScopeId"](items[1]).Should().Be(items[1].ScopeId);
            getters["PartyBoxesSettings.SupplierBoxSelectionStrategy"](items[1]).Should().Be(SupplierBoxSelectionStrategy.ShipperField);
        }
        public void PostAddItemTest()
        {
            var store  = PropertyHelpers.SamplePropertiesStore();
            var bag1   = store.Find("GUID1");
            var bagBad = store.Find("InvalidGUID");

            // Validate our objects
            Assert.IsNotNull(bag1);
            Assert.IsNull(bagBad);

            // Attempt to add after the fact
            bag1.Add("A-NewKey3", "A-NewValue3");

            // Output data
            var json = JsonConvert.SerializeObject(store, Formatting.Indented);

            Log.Debug(json);

            var tempBag1 = store.Find("GUID1");

            json = JsonConvert.SerializeObject(tempBag1, Formatting.Indented);
            Log.Debug(json);

            var value = tempBag1.Items["A-NewKey3"];

            Assert.IsNotNull(value);
            Assert.AreEqual("A-NewValue3", value);
        }
Beispiel #10
0
        private static void ParseRequiredParameters <TOptions>(string[] args, int offsetInArray, ArgumentGroupInfo TypeArgumentInfo, TOptions options, ref int currentLogicalPosition) where TOptions : new()
        {
            if (args.Length == 0)
            {
                throw new ArgumentException("Required parameters have not been specified");
            }

            int matchedRequiredParameters = 0;

            do
            {
                //set the required property
                PropertyInfo propInfo;
                if (!TypeArgumentInfo.RequiredArguments.TryGetValue(currentLogicalPosition, out propInfo))
                {
                    break;
                }

                //make sure that we don't run out of array
                if (offsetInArray + currentLogicalPosition >= args.Length)
                {
                    throw new ArgumentException("Required parameters have not been specified");
                }
                var value = PropertyHelpers.GetValueFromArgsArray(args, offsetInArray, ref currentLogicalPosition, propInfo);

                propInfo.SetValue(options, value);
                matchedRequiredParameters++;
            } while (currentLogicalPosition < args.Length);

            // no more? do we have any properties that we have not yet set?
            if (TypeArgumentInfo.RequiredArguments.Count != matchedRequiredParameters)
            {
                throw new ArgumentException("Not all required arguments have been specified");
            }
        }
Beispiel #11
0
        /// <summary>
        /// The "replace" operation replaces the value at the target location
        /// with a new value.  The operation object MUST contain a "value" member
        /// whose content specifies the replacement value.
        ///
        /// The target location MUST exist for the operation to be successful.
        ///
        /// For example:
        ///
        /// { "op": "replace", "path": "/a/b/c", "value": 42 }
        ///
        /// This operation is functionally identical to a "remove" operation for
        /// a value, followed immediately by an "add" operation at the same
        /// location with the replacement value.
        /// </summary>
        /// <param name="operation">The replace operation</param>
        /// <param name="objectApplyTo">Object to apply the operation to</param>
        public void Replace(Operation <T> operation, T objectToApplyTo)
        {
            var removeResult = Remove(operation.path, objectToApplyTo, operation);

            if (removeResult.HasError)
            {
                // return => currently not applicable, will throw exception in Remove method
            }

            if (!removeResult.HasError && removeResult.ActualType == null)
            {
                // the remove operation completed succesfully, but we could not determine the type.
                throw new JsonPatchException(
                          new JsonPatchError(
                              objectToApplyTo,
                              operation,
                              string.Format("Patch failed: could not determine type of property at location {0}", operation.path)),
                          422);
            }
            ConversionResult conversionResult;
            var propType = removeResult.ActualType;
            var value    = operation.value;

            if (!propType.IsValueType && propType != typeof(string) && value != null && value.GetType() == typeof(string))
            {
                object newObj;
                if (CustomDeserializationHandler != null)
                {
                    newObj = CustomDeserializationHandler(value.ToString(), propType);
                }
                else
                {
                    newObj = JsonConvert.DeserializeObject(value.ToString(), propType);
                }
                conversionResult = new ConversionResult(true, newObj);
            }
            else
            {
                conversionResult = PropertyHelpers.ConvertToActualType(removeResult.ActualType, operation.value);
            }

            if (!conversionResult.CanBeConverted)
            {
                throw new JsonPatchException(
                          new JsonPatchError(
                              objectToApplyTo,
                              operation,
                              string.Format("Patch failed: property value cannot be converted to type of path location {0}", operation.path)),
                          422);
            }

            Add(operation.path, conversionResult.ConvertedInstance, objectToApplyTo, operation);
        }
Beispiel #12
0
        public ObjectDescription GetMeta(string objectIdentifier)
        {
            var type     = schemaRegistry.GetTypeByTypeIdentifier(objectIdentifier);
            var schema   = schemaRegistry.GetSchemaByTypeIdentifier(objectIdentifier);
            var typeMeta = PropertyHelpers.BuildTypeMetaInformation(null, type, type, schema.PropertyDescriptionBuilder, schema.CustomPropertyConfigurationProvider);

            return(new ObjectDescription
            {
                Identifier = objectIdentifier,
                SchemaDescription = schema.Description,
                TypeMetaInformation = typeMeta,
            });
        }
Beispiel #13
0
        public static PropertyComponent?GetComponentsFromLine(string line)
        {
            if (PropertyHelpers.IsRowVersion(line))
            {
                return(null);
            }

            if (PropertyHelpers.IsNameSpace(line))
            {
                return(null);
            }

            PropertyComponent propertyComponent = new PropertyComponent {
                IsArray = PropertyHelpers.IsArray(line)
            };

            string[] components = line.Trim().Split(" ");
            foreach (string component in components)
            {
                if (PropertyHelpers.IsAccessModifiers(component) || PropertyHelpers.IsGetOrSet(component))
                {
                    continue;
                }

                if (PropertyHelpers.IsPropertyType(component))
                {
                    propertyComponent.PropertyType       = PropertyHelpers.GetPropertyTypeFromComponent(component);
                    propertyComponent.PropertyTypeString = component;
                }
                else if (PropertyHelpers.IsVirtual(component))
                {
                    propertyComponent.PropertyType = PropertyType.PartOutput;
                }
                else
                {
                    if (PropertyHelpers.IsArray(component))
                    {
                        propertyComponent.ArrayType = PropertyHelpers.GetArrayTypeFromLine(component);
                    }

                    propertyComponent.Name = component;

                    if (string.IsNullOrEmpty(propertyComponent.PropertyTypeString))
                    {
                        propertyComponent.PropertyTypeString = component;
                    }
                }
            }

            return(propertyComponent);
        }
        public override void ShowTypeView(Type type, object instance = null)
        {
            if (type is null)
            {
                return;
            }
            m_InstancePropertys = new List <PropertyInfo>(PropertyHelpers.GetInstancePropertys(type));
            m_InstancePropertys.Sort(Comparison);

            m_StaticPropertys = new List <PropertyInfo>(PropertyHelpers.GetStaticPropertys(type));
            m_StaticPropertys.Sort(Comparison);

            base.ShowTypeView(type, instance);
        }
Beispiel #15
0
        public async Task <DownloadResult> DownloadObjects([NotNull] string objectIdentifier, [NotNull][FromBody] ObjectSearchRequest query)
        {
            var type          = schemaRegistry.GetTypeByTypeIdentifier(objectIdentifier);
            var schema        = schemaRegistry.GetSchemaByTypeIdentifier(objectIdentifier);
            var downloadLimit = schema.Description.DownloadLimit;
            var count         = await schemaRegistry.GetConnector(objectIdentifier).Count(query.GetFilters(), downloadLimit + 1).ConfigureAwait(false);

            if (count > downloadLimit)
            {
                return new DownloadResult
                       {
                           File       = null,
                           Count      = (int)count,
                           CountLimit = downloadLimit,
                       }
            }
            ;

            var results = await schemaRegistry.GetConnector(objectIdentifier).Search(query.GetFilters(), query.GetSorts(), 0, downloadLimit).ConfigureAwait(false);

            var properties = new List <string>();
            var getters    = new List <Func <object, object> >();

            PropertyHelpers.BuildGettersForProperties(type, "", x => x, properties, getters);

            var excludedIndices    = properties.Select((x, i) => (x, i)).Where(x => query.ExcludedFields.Contains(x.x)).Select(x => x.i).ToArray();
            var filteredProperties = properties.Where((x, i) => !excludedIndices.Contains(i)).ToArray();
            var filteredGetters    = getters.Where((x, i) => !excludedIndices.Contains(i)).ToArray();

            var csvWriter = new CsvWriter(filteredProperties);

            foreach (var item in results)
            {
                csvWriter.AddRow(filteredGetters.Select(f => PropertyHelpers.ToString(f, item)).ToArray());
            }

            return(new DownloadResult
            {
                Count = count ?? 0,
                CountLimit = downloadLimit,
                File = new FileInfo
                {
                    Content = csvWriter.GetBytes(),
                    ContentType = "text/csv",
                    Name = $"{objectIdentifier}-{DateTime.UtcNow:yyyy-MM-dd-HHmm}.csv"
                }
            });
        }
Beispiel #16
0
        /// <summary>
        /// Copy values from one object to another, as long as they are the same type.
        /// </summary>
        /// <example>
        /// This sample shows how to use <see cref="ValuesFrom{T}(T, T, bool, string[])"/> to copy all values excluding <paramref name="properties"/>
        /// from one model to another.
        ///
        /// <code>
        /// user.ValuesFrom(model, true,
        ///    nameof(model.DoNotCopyMe)
        /// );
        /// </code>
        /// </example>
        /// <typeparam name="T">Type of object you are copying.</typeparam>
        /// <param name="targetObject">Target object for copying values to.</param>
        /// <param name="sourceObject">Source object for copying values from.</param>
        /// <param name="isExclusionList">Whether <paramref name="properties"/> is a list of properties to exclude or include.</param>
        /// <param name="properties">Properties to include or exclude from the copy.</param>
        public static void ValuesFrom <T>(this T targetObject, T sourceObject, bool isExclusionList, params string[] properties)
        {
            var type          = typeof(T);
            var allProperties = !isExclusionList ? properties : type.GetProperties().Where(m => !properties.Contains(m.Name)).Select(m => m.Name);

            if (allProperties == null || allProperties.Count() == 0)
            {
                return;
            }

            foreach (var property in properties)
            {
                var newVal = PropertyHelpers.GetProperty(sourceObject, property);
                PropertyHelpers.SetPropertyValue(targetObject, property, newVal);
            }
        }
Beispiel #17
0
        static void SingletonClass(
            ref ClusterDict classCluster,
            ClusterSubDict allClass)
        {
            classCluster.Add("Singleton##Class", NewClassDict());

            bool added = false;

            foreach (var class2type in allClass)
            {
                added = false;

                if (class2type.Value.IsEnum)
                {
                    continue;
                }

                PropertyInfo[] propertyInfos = PropertyHelpers.GetStaticPropertys(class2type.Value);
                FieldInfo[]    fieldInfos    = FieldHelpers.GetStaticFields(class2type.Value);

                //Seach propertys singleton
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    if (propertyInfo.PropertyType.FullName == class2type.Value.FullName)
                    {
                        classCluster["Singleton##Class"].Add(class2type.Key, class2type.Value);
                        added = true;
                        break;
                    }
                }

                if (added)
                {
                    continue;
                }

                //Seach fields singleton
                foreach (FieldInfo fieldInfo in fieldInfos)
                {
                    if (fieldInfo.FieldType.FullName == class2type.Value.FullName)
                    {
                        classCluster["Singleton##Class"].Add(class2type.Key, class2type.Value);
                        break;
                    }
                }
            }
        }
Beispiel #18
0
        /// <summary>
        /// 统计Class的引用和静态成员
        /// </summary>
        static int CountClassInclude(
            Type type,
            ClusterSubDict allClass
            )
        {
            HashSet <Type> types = new HashSet <Type>();
            int            bias  = 0; //


            PropertyInfo[] propertyInfos = PropertyHelpers.GetAllPropertys(type);
            FieldInfo[]    fieldInfos    = FieldHelpers.GetAllFields(type);

            //count field class include number
            foreach (FieldInfo fieldInfo in fieldInfos)
            {
                Caller.Try(() =>
                {
                    if (allClass.ContainsKey(fieldInfo.FieldType.Name))
                    {
                        //static class field
                        if (fieldInfo.IsStatic && fieldInfo.FieldType.IsEnum == false)
                        {
                            bias += 1;
                        }
                        types.Add(fieldInfo.FieldType);
                    }
                });
            }

            //count property class include number
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                if (allClass.ContainsKey(propertyInfo.PropertyType.Name))
                {
                    //static class property
                    if (propertyInfo.GetAccessors().Length > 0 &&
                        propertyInfo.GetAccessors()[0].IsStatic &&
                        propertyInfo.PropertyType.IsEnum == false)
                    {
                        bias += 1;
                    }
                    types.Add(propertyInfo.PropertyType);
                }
            }

            return(types.Count + bias);
        }
        public void UpdateBuffer(bool marshalBuffer = true)
        {
            ITempHelper helper = ((App)Application.Current).ActiveViewport;

            if (helper == null || helper.ViewportHost == null)
            {
                return;
            }

            if (IsTexture)
            {
                if (helper.IsStandardShaderActive)
                {
                    helper.ViewportHost.UpdateShaderImage(uint.Parse(Regex.Match(AnnotationGroup.Register, @"\d+").Value), (int)AnnotationGroup.AnnotationShaderGroup.Type, Value?.ToString() ?? "");
                }
                else
                {
                    helper.ViewportHost.UpdatePPShaderImage(uint.Parse(Regex.Match(AnnotationGroup.Register, @"\d+").Value), Value?.ToString() ?? "");
                }
                return;
            }

            if (Value == null)
            {
                return;
            }
            if (IsScalar)
            {
                if (IsScalar)
                {
                    CopyToBuffer(PropertyHelpers.ConvertToCorrectType(DataType, Value));
                }
            }
            else if (IsVector)
            {
                if (Value is SerializableColor)
                {
                    CopyColorToBuffer((SerializableColor)Value, DataType.GetPackSizeScalar());
                }
            }
            if (marshalBuffer)
            {
                AnnotationGroup.MarshalBuffer(helper.ViewportHost, helper.IsStandardShaderActive);
            }
        }
Beispiel #20
0
        public void Create2PropertiesAndSerializationTest()
        {
            var bag1 = PropertyHelpers.CreateBag("GUID-1");
            var bag2 = PropertyHelpers.CreateBag("GUID-2");
            var bag3 = PropertyHelpers.CreateBag("GUID-3");

            var bags1 = new List <Properties>()
            {
                bag1, bag2, bag3
            };
            var json  = JsonConvert.SerializeObject(bags1, Formatting.Indented);
            var bags2 = JsonConvert.DeserializeObject <List <Properties> >(json);

            Log.Debug(json);

            Assert.IsNotNull(bag2);
            Assert.AreEqual(bags1.Count, bags2.Count);
        }
        public void SaveClearAndLoadPropertiesFileTest()
        {
            Log.Debug($"Tmp Path: {_settings.SettingsFilePath}");

            var store = PropertyHelpers.SamplePropertiesStore();

            _settings.PropertiesStore = store;

            _settings.SaveFile();
            store.ClearAll();
            Assert.AreEqual(store.PropertyBags.Count, 0);

            _settings.LoadFile();
            Assert.AreNotEqual(store.PropertyBags.Count, 0);

            string json = JsonConvert.SerializeObject(store.PropertyBags, Formatting.Indented);

            Log.Debug(json);
        }
        public void CreateUI()
        {
            AnnotationValue.PropertyChanged += new PropertyChangedEventHandler(OnResourcePropertyChanged);

            if (IsTexture)
            {
                UIElement = new ImagePicker(this);
            }
            else if (DataType.IsBool() && IsScalar)
            {
                UIElement = PropertyHelpers.CreateCheckBox(this, "Value", Value);
            }
            else if (!DataType.IsBool() && IsScalar && (IsSNorm || IsUNorm ||
                                                        (Annotations?.Contains(new KeyValuePair <string, string>("UIWidget", "Slider")) ?? false)))
            {
                object val = Value;
                if (val == null)
                {
                    if (DataType.IsIntegral())
                    {
                        Value = 0;
                    }
                    else
                    {
                        Value = 0.0;
                    }
                }
                UIElement = PropertyHelpers.CreateSlider(this, "Value", this, val);
            }
            else if (!IsMatrix && (Columns == 3 || Columns == 4) &&
                     (Annotations?.Contains(new KeyValuePair <string, string>("UIWidget", "Color")) ?? false))
            {
                UIElement = PropertyHelpers.CreateColorPicker(this, "Value", (Columns == 4) ? true : false, Value);
            }
            else if (IsScalar)
            {
                UIElement = PropertyHelpers.CreateSpinner(this, "Value", this, Value);
            }
            else
            {
                UIElement = new DropdownVecMatProperty(this);
            }
        }
Beispiel #23
0
        public async Task <ObjectDetails> ReadObject(string objectIdentifier, ObjectReadRequest query)
        {
            var type   = schemaRegistry.GetTypeByTypeIdentifier(objectIdentifier);
            var schema = schemaRegistry.GetSchemaByTypeIdentifier(objectIdentifier);
            var result = await schemaRegistry.GetConnector(objectIdentifier).Read(query.Conditions).ConfigureAwait(false);

            var typeMeta = PropertyHelpers.BuildTypeMetaInformation(result, type, type, schema.PropertyDescriptionBuilder, schema.CustomPropertyConfigurationProvider);
            var obj      = ObjectsConverter.StoredToApiDeep(result, schema.CustomPropertyConfigurationProvider);

            return(new ObjectDetails
            {
                Object = obj,
                Meta = new ObjectDescription
                {
                    Identifier = objectIdentifier,
                    SchemaDescription = schema.Description,
                    TypeMetaInformation = typeMeta,
                }
            });
        }
Beispiel #24
0
        public async Task <ObjectDetails> ReadObject([NotNull] string objectIdentifier, [NotNull][FromBody] ObjectSearchRequest query)
        {
            var type     = schemaRegistry.GetTypeByTypeIdentifier(objectIdentifier);
            var schema   = schemaRegistry.GetSchemaByTypeIdentifier(objectIdentifier);
            var typeMeta = PropertyHelpers.BuildTypeMetaInformation(type, schema.PropertyDescriptionBuilder, schema.CustomPropertyConfigurationProvider);
            var result   = await schemaRegistry.GetConnector(objectIdentifier).Read(query.GetFilters()).ConfigureAwait(false);

            var typeInfo = TypeInfoExtractor.Extract(result, type, schema.PropertyDescriptionBuilder, schema.CustomPropertyConfigurationProvider);
            var obj      = ObjectsConverter.StoredToApi(typeInfo, type, result, schema.CustomPropertyConfigurationProvider);

            return(new ObjectDetails
            {
                Object = obj,
                Meta = new ObjectDescription
                {
                    Identifier = objectIdentifier,
                    SchemaDescription = schema.Description,
                    TypeMetaInformation = typeMeta,
                }
            });
        }
Beispiel #25
0
        ///// <summary>
        ///// Add a column to the factory
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <returns></returns>
        //public DataTableColumnBuilder Add<T>()
        //{
        //    DataTableColumnBuilder column = new DataTableColumnBuilder();
        //    this.Columns.Add(column);
        //    return column;
        //}


        /// <summary>
        /// Add a column to the factory
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public DataTableColumnBuilder ColumnFor <T>(Expression <Func <TModel, T> > expression)
        {
            var propertyInfo = PropertyHelpers.GetPropertyInfo(expression);

            if (IndexesDic.ContainsKey(propertyInfo.Name))
            {
                throw new Exception($"Column {propertyInfo.Name} is already Set.");
            }
            IndexesDic[propertyInfo.Name] = _currentColumnIndex++;
            DataTableColumnBuilder column = new DataTableColumnBuilder(propertyInfo)
            {
                Expression = expression, // TODO: try use  InputExtensions.HiddenFor()
            };

            //ViewContext viewContext = htmlHelper.ViewContext;
            // viewContext.ViewData.Model =
            //System.Web.Mvc.HtmlHelper<TModel> htmlHelper2 = new HtmlHelper<TModel>(htmlHelper.ViewContext, htmlHelper.ViewDataContainer);// htmlHelper;
            //var result=InputExtensions.HiddenFor(htmlHelper2, expression).ToHtmlString();
            column.Type(GetType(propertyInfo));
            this.Columns.Add(column);
            return(column);
        }
Beispiel #26
0
 public void Process(SchemaProcessorContext context)
 {
     if (context.Type == typeof(ExternalStandard))
     {
         var schema = context.Schema.Properties.Where(s => s.Key == PropertyHelpers.GetPropertyName(() => new ExternalStandard().Category)).FirstOrDefault().Value;
         using (var db = new CSET_Context())
         {
             var categories = db.SETS_CATEGORY.Select(s => s.Set_Category_Name).Distinct().OrderBy(s => s).ToList();
             categories.ForEach(s => schema.Enumeration.Add(s));
             var setNames  = db.SETS.Select(s => s.Set_Name).ToList().Union(db.SETS.Select(s => s.Short_Name).ToList()).Distinct().OrderBy(s => s).ToList();
             var newSchema = new JsonSchema();
             setNames.ForEach(s => newSchema.Enumeration.Add(s));
             context.Schema.Properties.Where(s => s.Key == PropertyHelpers.GetPropertyName(() => new ExternalStandard().ShortName)).FirstOrDefault().Value.Not = newSchema;
             var reqs = context.Schema.Properties.Where(s => s.Key == PropertyHelpers.GetPropertyName(() => new ExternalStandard().Requirements)).FirstOrDefault().Value;
             reqs.MinLength = 1;
         }
     }
     else
     {
         throw new InvalidOperationException("Wrong type");
     }
 }
        private static TOptions InternalParse <TOptions>(string[] args, int offsetInArray, ArgumentGroupInfo arguments, ParserOptions parseOptions)
            where TOptions : new()
        {
            TOptions options = new TOptions();
            int      currentLogicalPosition = 0;

            // let's match them to actual required args, in positional
            if (arguments.RequiredArguments.Count > 0)
            {
                ParseRequiredParameters(args, offsetInArray, arguments, options, ref currentLogicalPosition);
            }

            // we are going to keep track of any properties that have not been specified so that we can set their default value.
            var unmatchedOptionalProperties = ParseOptionalParameters(args, offsetInArray, arguments, options, ref currentLogicalPosition);

            // for all the remaining optional properties, set their default value.
            foreach (var property in unmatchedOptionalProperties)
            {
                //get the default value..
                var    value        = property.GetCustomAttribute <OptionalArgumentAttribute>();
                object defaultValue = value.DefaultValue;

                // If we want to read values from the environment, try to get the value
                if (parseOptions.ReadFromEnvironment && !value.IsCollection && parseOptions.VariableNamePrefix != null)
                {
                    var envVar = Environment.GetEnvironmentVariable($"{parseOptions.VariableNamePrefix}{value.Name}");

                    if (!string.IsNullOrEmpty(envVar))
                    {
                        defaultValue = PropertyHelpers.GetValueForProperty(envVar, property);
                    }
                }

                property.SetValue(options, Convert.ChangeType(defaultValue, property.PropertyType));
            }

            return(options);
        }
 public void CopyColorToBuffer(SerializableColor color, uint stepOffset, uint startOffset = 0)
 {
     if (DataType.IsIntegral())
     {
         CopyToBuffer(PropertyHelpers.ConvertToCorrectType(DataType, color.R), startOffset);
         CopyToBuffer(PropertyHelpers.ConvertToCorrectType(DataType, color.G), startOffset + stepOffset);
         CopyToBuffer(PropertyHelpers.ConvertToCorrectType(DataType, color.B), startOffset + stepOffset * 2);
         if (Columns == 4)
         {
             CopyToBuffer(PropertyHelpers.ConvertToCorrectType(DataType, color.A), startOffset + stepOffset * 3);
         }
     }
     else
     {
         CopyToBuffer(PropertyHelpers.ConvertToCorrectType(DataType, color.scR), startOffset);
         CopyToBuffer(PropertyHelpers.ConvertToCorrectType(DataType, color.scG), startOffset + stepOffset);
         CopyToBuffer(PropertyHelpers.ConvertToCorrectType(DataType, color.scB), startOffset + stepOffset * 2);
         if (Columns == 4)
         {
             CopyToBuffer(PropertyHelpers.ConvertToCorrectType(DataType, color.scA), startOffset + stepOffset * 3);
         }
     }
 }
Beispiel #29
0
        private void InitializeItemsSource()
        {
            DataType type = AnnotationVariable.DataType;

            if (type.IsBool())
            {
                if (Values == null || Values.Count != AnnotationVariable.Rows * AnnotationVariable.Columns)
                {
                    Values = new ObservableCollection <object>(new object[AnnotationVariable.Rows * AnnotationVariable.Columns]);
                }

                for (int row = 0; row < AnnotationVariable.Rows; ++row)
                {
                    StackPanel panel = new StackPanel();
                    panel.Orientation = Orientation.Horizontal;
                    for (int column = 0; column < AnnotationVariable.Columns; ++column)
                    {
                        UIElement element = PropertyHelpers.CreateCheckBox(this, $"Values[{row * (int)AnnotationVariable.Columns + column}]", Values[row * (int)AnnotationVariable.Columns + column]);
                        panel.Children.Add(element);
                    }
                    Items.Add(panel);
                }
            }
            else if ((AnnotationVariable.Columns == 3 || AnnotationVariable.Columns == 4) &&
                     (AnnotationVariable.Annotations?.Contains(new KeyValuePair <string, string>("UIWidget", "Color")) ?? false))
            {
                if (Values == null || Values.Count != AnnotationVariable.Rows)
                {
                    Values = new ObservableCollection <object>(new object[AnnotationVariable.Rows]);
                }

                for (int row = 0; row < AnnotationVariable.Rows; ++row)
                {
                    UIElement element = PropertyHelpers.CreateColorPicker(this, $"Values[{row}]", (AnnotationVariable.Columns == 4) ? true : false, Values[row]);
                    Items.Add(element);
                }
            }
            else if (AnnotationVariable.Columns == 1 &&
                     (AnnotationVariable.Annotations?.Contains(new KeyValuePair <string, string>("UIWidget", "Slider")) ?? false))
            {
                if (Values == null || Values.Count != AnnotationVariable.Rows)
                {
                    Values = new ObservableCollection <object>(new object[AnnotationVariable.Rows]);
                }

                for (int row = 0; row < AnnotationVariable.Rows; ++row)
                {
                    object val = Values[row];
                    if (val == null)
                    {
                        if (AnnotationVariable.DataType.IsIntegral())
                        {
                            Values[row] = 0;
                        }
                        else
                        {
                            Values[row] = 0.0;
                        }
                    }
                    UIElement element = PropertyHelpers.CreateSlider(this, $"Values[{row}]", AnnotationVariable, val);
                    Items.Add(element);
                }
            }
            else
            {
                if (Values == null || Values.Count != AnnotationVariable.Rows * AnnotationVariable.Columns)
                {
                    Values = new ObservableCollection <object>(new object[AnnotationVariable.Rows * AnnotationVariable.Columns]);
                }
                for (int row = 0; row < AnnotationVariable.Rows; ++row)
                {
                    StackPanel panel = new StackPanel();
                    panel.Orientation = Orientation.Horizontal;
                    for (int column = 0; column < AnnotationVariable.Columns; ++column)
                    {
                        UIElement element = PropertyHelpers.CreateSpinner(this, $"Values[{row * (int)AnnotationVariable.Columns + column}]", AnnotationVariable, Values[row * (int)AnnotationVariable.Columns + column]);
                        panel.Children.Add(element);
                    }
                    Items.Add(panel);
                }
            }
        }
Beispiel #30
0
        private GetValueResult GetValueAtLocation(string location, object objectToGetValueFrom, Operation operationToReport)
        {
            // get value from "objectToGetValueFrom" at location "location"
            object valueAtLocation = null;

            var pathResult = PropertyHelpers.GetActualPropertyPath(
                location,
                objectToGetValueFrom,
                operationToReport, false);

            var positionAsInteger  = pathResult.NumericEnd;
            var actualFromProperty = pathResult.PathToProperty;

            // first, analyze the tree.
            var result = new ObjectTreeAnalysisResult(objectToGetValueFrom, actualFromProperty, ContractResolver);

            if (result.UseDynamicLogic)
            {
                // find the property
                if (result.Container.ContainsCaseInsensitiveKey(result.PropertyPathInParent))
                {
                    if (positionAsInteger > -1)
                    {
                        // get the actual type
                        var typeOfPathProperty = result.Container
                                                 .GetValueForCaseInsensitiveKey(result.PropertyPathInParent).GetType();

                        if (PropertyHelpers.IsNonStringArray(typeOfPathProperty))
                        {
                            // now, get the generic type of the enumerable
                            var genericTypeOfArray = PropertyHelpers.GetIListType(typeOfPathProperty);

                            // get value
                            var array = result.Container.GetValueForCaseInsensitiveKey(result.PropertyPathInParent) as IList;

                            if (positionAsInteger >= array.Count)
                            {
                                throw new JsonPatchException(
                                          new JsonPatchError(
                                              objectToGetValueFrom,
                                              operationToReport,
                                              string.Format("Patch failed: property at location from: {0} does not exist", location)),
                                          422);
                            }

                            valueAtLocation = array[positionAsInteger];
                        }
                        else
                        {
                            throw new JsonPatchException(
                                      new JsonPatchError(
                                          objectToGetValueFrom,
                                          operationToReport,
                                          string.Format("Patch failed: provided from path is invalid for array property type at location from: {0}: expected array", location)),
                                      422);
                        }
                    }
                    else
                    {
                        // get the value
                        valueAtLocation =
                            result.Container.GetValueForCaseInsensitiveKey(result.PropertyPathInParent);
                    }
                }
                else
                {
                    throw new JsonPatchException(
                              new JsonPatchError(
                                  objectToGetValueFrom,
                                  operationToReport,
                                  string.Format("Patch failed: property at location from: {0} does not exist.", location)),
                              422);
                }
            }
            else
            {
                // not dynamic.
                var patchProperty = result.JsonPatchProperty;

                // is the path an array (but not a string (= char[]))?  In this case,
                // the path must end with "/position" or "/-", which we already determined before.
                if (positionAsInteger > -1)
                {
                    if (PropertyHelpers.IsNonStringArray(patchProperty.Property.PropertyType))
                    {
                        // now, get the generic type of the enumerable
                        if (patchProperty.Property.Readable)
                        {
                            var array = (IList)patchProperty.Property.ValueProvider
                                        .GetValue(patchProperty.Parent);

                            if (positionAsInteger >= array.Count)
                            {
                                throw new JsonPatchException(
                                          new JsonPatchError(
                                              objectToGetValueFrom,
                                              operationToReport,
                                              string.Format("Patch failed: property at location from: {0} does not exist", location)),
                                          422);
                            }

                            valueAtLocation = array[positionAsInteger];
                        }
                        else
                        {
                            throw new JsonPatchException(
                                      new JsonPatchError(
                                          objectToGetValueFrom,
                                          operationToReport,
                                          string.Format("Patch failed: cannot get property at location from from: {0}. Possible cause: the property doesn't have an accessible getter.", location)),
                                      422);
                        }
                    }
                    else
                    {
                        throw new JsonPatchException(
                                  new JsonPatchError(
                                      objectToGetValueFrom,
                                      operationToReport,
                                      string.Format("Patch failed: provided from path is invalid for array property type at location from: {0}: expected array", location)),
                                  422);
                    }
                }
                else
                {
                    if (!patchProperty.Property.Readable)
                    {
                        throw new JsonPatchException(
                                  new JsonPatchError(
                                      objectToGetValueFrom,
                                      operationToReport,
                                      string.Format("Patch failed: cannot get property at location from from: {0}. Possible cause: the property doesn't have an accessible getter.", location)),
                                  422);
                    }
                    valueAtLocation = patchProperty.Property.ValueProvider
                                      .GetValue(patchProperty.Parent);
                }
            }
            return(new GetValueResult(valueAtLocation, false));
        }