Beispiel #1
0
        private static void DynamicProperty1()
        {
            var props = new DynamicProperty[]
            {
                new DynamicProperty("Name", typeof(string)),
                new DynamicProperty("Age", typeof(int))
            };

            Type type = DynamicClassFactory.CreateType(props);

            var dynamicClass = Activator.CreateInstance(type) as DynamicClass;

            dynamicClass.SetDynamicPropertyValue("Name", "Abhik");
            dynamicClass.SetDynamicPropertyValue("Age", 40);

            var dynamicClass1 = Activator.CreateInstance(type) as DynamicClass;

            dynamicClass1.SetDynamicPropertyValue("Name", "Pamli");
            dynamicClass1.SetDynamicPropertyValue("Age", 35);

            List <DynamicClass> customer = new List <DynamicClass>()
            {
                dynamicClass,
                dynamicClass1
            };

            var cust = customer.AsQueryable().Where("GetDynamicPropertyValue(Age)>20");

            foreach (DynamicClass item in cust)
            {
                Console.WriteLine(item.GetDynamicPropertyValue("Name"));
            }

            Console.Read();
        }
        public void It_Raises_CanExecute_When_Property_Changes()
        {
            var canExecute   = true;
            var property     = new DynamicProperty <bool>(DefaultPropertyName, false);
            var testStrategy = new TestCommandStrategy();

            var strategy = new CanExecuteCommandStrategy(property)
            {
                InnerStrategy = testStrategy
            };

            var command = new DynamicCommand(DefaultCommandName, strategy);

            command.CanExecuteChanged += OnCanExecuteChanged;

            canExecute = command.CanExecute(null);
            canExecute.Should().BeFalse();

            property.Value = true;
            canExecute.Should().BeTrue();

            property.Value = false;
            canExecute.Should().BeFalse();

            void OnCanExecuteChanged(object sender, EventArgs e)
            {
                canExecute = command.CanExecute(null);
            }
        }
Beispiel #3
0
        public CastSpellAction()
        {
            _spamControl            = new Stopwatch();
            QueueIsRunning          = false;
            Properties["Casted"]    = new MetaProp("Casted", typeof(int), new ReadOnlyAttribute(true));
            Properties["SpellName"] = new MetaProp("SpellName", typeof(string), new ReadOnlyAttribute(true));
            Properties["Repeat"]    = new MetaProp("Repeat", typeof(DynamicProperty <int>),
                                                   new TypeConverterAttribute(typeof(DynamicProperty <int> .DynamivExpressionConverter)));
            Properties["Entry"]      = new MetaProp("Entry", typeof(uint));
            Properties["CastOnItem"] = new MetaProp("CastOnItem", typeof(bool), new DisplayNameAttribute("Cast on Item"));
            Properties["ItemType"]   = new MetaProp("ItemType", typeof(InventoryType), new DisplayNameAttribute("Item Type"));
            Properties["ItemId"]     = new MetaProp("ItemId", typeof(uint));
            Properties["RepeatType"] = new MetaProp("RepeatType", typeof(RepeatCalculationType), new DisplayNameAttribute("Repeat Type"));
            // Properties["Recipe"] = new MetaProp("Recipe", typeof(Recipe), new TypeConverterAttribute(typeof(RecipeConverter)));

            Casted = 0;
            Repeat = new DynamicProperty <int>(this, "1");
            RegisterDynamicProperty("Repeat");
            Entry      = 0u;
            RepeatType = RepeatCalculationType.Craftable;
            Recipe     = null;
            CastOnItem = false;
            ItemType   = InventoryType.Chest;
            ItemId     = 0u;
            Properties["SpellName"].Value = SpellName;

            //Properties["Recipe"].Show = false;
            Properties["ItemType"].Show           = false;
            Properties["ItemId"].Show             = false;
            Properties["Casted"].PropertyChanged += OnCounterChanged;
            CheckTradeskillList();
            Properties["RepeatType"].PropertyChanged += CastSpellActionPropertyChanged;
            Properties["Entry"].PropertyChanged      += OnEntryChanged;
            Properties["CastOnItem"].PropertyChanged += CastOnItemChanged;
        }
 public void GetValue_PropertyIsValueType_GetsBoxedAndReturnsCorrectValue()
 {
     _target = DynamicProperty.Create(typeof(Person), "Age");
     _person.Age = 100;
     object age = _target.GetValue(_person);
     Assert.AreEqual(100, age);
 }
Beispiel #5
0
        public static DynamicProperty ToWebModel(this VirtoCommercePlatformCoreDynamicPropertiesDynamicObjectProperty dto)
        {
            var webModel = new DynamicProperty();

            webModel.InjectFrom <NullableAndEnumValueInjecter>(dto);

            if (dto.DisplayNames != null)
            {
                webModel.DisplayNames = dto.DisplayNames.Select(x => new LocalizedString(new Language(x.Locale), x.Name)).ToList();
            }
            if (dto.Values != null)
            {
                if (webModel.IsDictionary)
                {
                    var dictValues = dto.Values.Where(x => x.Value != null).Select(x => x.Value)
                                     .Cast <JObject>()
                                     .Select(x => x.ToObject <VirtoCommercePlatformCoreDynamicPropertiesDynamicPropertyDictionaryItem>())
                                     .ToArray();

                    webModel.DictionaryValues = dictValues.Select(x => x.ToWebModel()).ToList();
                }
                else
                {
                    webModel.Values = dto.Values.Select(x => x.ToWebModel()).ToList();
                }
            }

            return(webModel);
        }
        public BuyItemFromAhAction()
        {
            Properties["ItemID"]    = new MetaProp("ItemID", typeof(string));
            Properties["MaxBuyout"] = new MetaProp("MaxBuyout", typeof(PropertyBag.GoldEditor),
                                                   new DisplayNameAttribute("Max Buyout"), new TypeConverterAttribute(typeof(PropertyBag.GoldEditorConverter)));
            Properties["Amount"] = new MetaProp("Amount", typeof(DynamicProperty <int>),
                                                new TypeConverterAttribute(typeof(DynamicProperty <int> .DynamivExpressionConverter)));
            Properties["ItemListType"]  = new MetaProp("ItemListType", typeof(ItemType), new DisplayNameAttribute("Buy ..."));
            Properties["AutoFindAh"]    = new MetaProp("AutoFindAh", typeof(bool), new DisplayNameAttribute("Auto find AH"));
            Properties["BuyAdditively"] = new MetaProp("BuyAdditively", typeof(bool), new DisplayNameAttribute("Buy Additively"));

            Properties["BidOnItem"] = new MetaProp("BidOnItem", typeof(bool), new DisplayNameAttribute("Bid on Item"));
            Properties["Location"]  = new MetaProp("Location", typeof(string), new EditorAttribute(typeof(PropertyBag.LocationEditor), typeof(UITypeEditor)));

            ItemID = "";
            Amount = new DynamicProperty <int>(this, "1");
            RegisterDynamicProperty("Amount");
            ItemListType  = ItemType.Item;
            AutoFindAh    = true;
            _loc          = WoWPoint.Zero;
            Location      = _loc.ToInvariantString();
            MaxBuyout     = new PropertyBag.GoldEditor("100g0s0c");
            BidOnItem     = false;
            BuyAdditively = true;

            Properties["AutoFindAh"].PropertyChanged   += AutoFindAHChanged;
            Properties["ItemListType"].PropertyChanged += BuyItemFromAhActionPropertyChanged;
            Properties["Location"].PropertyChanged     += LocationChanged;
            Properties["Amount"].Show   = true;
            Properties["Location"].Show = false;
        }
        public static DynamicProperty ToWebModel(this OrderModule.Client.Model.DynamicObjectProperty dto)
        {
            var result = new DynamicProperty();

            result.InjectFrom <NullableAndEnumValueInjecter>(dto);

            if (dto.DisplayNames != null)
            {
                result.DisplayNames = dto.DisplayNames.Select(x => new LocalizedString(new Language(x.Locale), x.Name)).ToList();
            }

            if (dto.Values != null)
            {
                if (result.IsDictionary)
                {
                    var dictValues = dto.Values.Where(x => x.Value != null)
                                     .Select(x => x.Value)
                                     .Cast <JObject>()
                                     .Select(x => x.ToObject <Platform.Client.Model.DynamicPropertyDictionaryItem>())
                                     .ToArray();

                    result.DictionaryValues = dictValues.Select(x => x.ToWebModel()).ToList();
                }
                else
                {
                    result.Values = dto.Values.Select(x => x.ToWebModel()).ToList();
                }
            }

            return(result);
        }
        private static string GetPropertyTypeName(DynamicProperty property, Field field)
        {
            string typeName = string.Empty;

            switch (property)
            {
            // 基础资料类型属性、单选辅助资料属性
            case IComplexProperty _:
            {
                string lookUpObjectId = GetFieldLookUpObjectId(field);
                typeName = lookUpObjectId;
                break;
            }

            // 单据体
            case ICollectionProperty collectionProperty:
                typeName = GetICollectionPropertyTypeName(collectionProperty);
                break;

            // 普通属性
            case ISimpleProperty _:
                typeName = GetBaseTypeName(property.PropertyType);
                break;
            }

            return(typeName);
        }
Beispiel #9
0
        private ValueValidationInfo DIValidationInfo(SmartComponent smartComponent, DynamicProperty property, object newValue)
        {
            int diNumber = -1;

            int.TryParse(Right(property.Name, property.Name.Length - 11), out diNumber);
            if ((diNumber >= 0) && (diNumber < bDIO_AddressIsValid[(int)IO.Input].Length))
            {
                bDIO_AddressIsValid[(int)IO.Input][diNumber] = false;
                S7Client.S7DataItem item = new S7Client.S7DataItem();
                if (!GetS7DataItem((string)newValue, ref item))
                {
                    return(new ValueValidationInfo(ValueValidationResult.InvalidSyntax));
                }
                if (item.WordLen != S7Consts.S7WLBit)
                {
                    return(new ValueValidationInfo(ValueValidationResult.InvalidSyntax));
                }
                if ((item.Area != S7Consts.S7AreaPA) &&
                    (item.Area != S7Consts.S7AreaMK) &&
                    (item.Area != S7Consts.S7AreaDB)
                    )
                {
                    return(new ValueValidationInfo(ValueValidationResult.InvalidSyntax));
                }

                bDIO_AddressIsValid[(int)IO.Input][diNumber] = true;
                return(ValueValidationInfo.Valid);
            }
            else
            {
                return(new ValueValidationInfo(ValueValidationResult.InvalidProject));
            }
        }
        private IList <DynamicPropertyObjectValue> ToDynamicPropertyMultiValue(DynamicProperty dynamicProperty, Dictionary <string, IList <DynamicPropertyDictionaryItem> > dynamicPropertyDictionaryItems, string values)
        {
            var parsedValues    = values.Split(',').Select(value => value.Trim()).ToList();
            var convertedValues = parsedValues.Select(value => ToDynamicPropertyValue(dynamicProperty, dynamicPropertyDictionaryItems, value));

            return(convertedValues.ToList());
        }
        public ComponentTestingPropertyDataAdapter(OleDbDataReader dr, IList<string> dynamicList, int startColumn)
        {
            ControlSystemName = "";
            ComponentName = "";

            ControlSystemName = dr.SafeString((int) TestingPropertyColumn.ControlSystemName).Trim();
            ComponentName = dr.SafeString((int) TestingPropertyColumn.ComponentName).Trim();

            DynamicProperties = new List<DynamicProperty>();

            if (dynamicList != null && dynamicList.Any())
            {
                for (var d = 0; d < dynamicList.Count(); d++)
                {
                    var p = dynamicList[d];

                    var property = new DynamicProperty
                    {
                        PropertyName = p,
                        PropertyValue = dr.SafeString(startColumn + d)
                    };

                    DynamicProperties.Add(property);
                }
            }
        }
        public BuyItemAction()
        {
            Properties["Location"] = new MetaProp("Location", typeof(string),
                                                  new EditorAttribute(typeof(PropertyBag.LocationEditor),
                                                                      typeof(UITypeEditor)));
            Properties["NpcEntry"] = new MetaProp("NpcEntry", typeof(uint),
                                                  new EditorAttribute(typeof(PropertyBag.EntryEditor),
                                                                      typeof(UITypeEditor)));
            Properties["ItemID"] = new MetaProp("ItemID", typeof(string));
            Properties["Count"] = new MetaProp("Count", typeof(DynamicProperty<int>),
                                               new TypeConverterAttribute(typeof(DynamicProperty<int>.DynamivExpressionConverter)));
            Properties["BuyItemType"] = new MetaProp("BuyItemType", typeof(BuyItemActionType),
                                                     new DisplayNameAttribute("Buy"));
            Properties["BuyAdditively"] = new MetaProp("BuyAdditively", typeof(bool),
                                                       new DisplayNameAttribute("Buy Additively"));
            ItemID = "";
            Count = new DynamicProperty<int>(this, "0"); // dynamic expression
            RegisterDynamicProperty("Count");
            BuyItemType = BuyItemActionType.Material;
            _loc = WoWPoint.Zero;
            Location = _loc.ToInvariantString();
            NpcEntry = 0u;
            BuyAdditively = true;

            Properties["ItemID"].Show = false;
            Properties["Count"].Show = false;
            Properties["BuyAdditively"].Show = false;
            Properties["Location"].PropertyChanged += LocationChanged;
            Properties["BuyItemType"].PropertyChanged += BuyItemActionPropertyChanged;
        }
Beispiel #13
0
 private FieldInfo[] method_2(TypeBuilder typeBuilder_0, DynamicProperty[] dynamicProperty_0)
 {
     FieldInfo[] array = new FieldBuilder[dynamicProperty_0.Length];
     for (int i = 0; i < dynamicProperty_0.Length; i++)
     {
         DynamicProperty dynamicProperty = dynamicProperty_0[i];
         FieldBuilder    fieldBuilder    = typeBuilder_0.DefineField("_" + dynamicProperty.Name, dynamicProperty.Type, FieldAttributes.Private);
         PropertyBuilder propertyBuilder = typeBuilder_0.DefineProperty(dynamicProperty.Name, PropertyAttributes.HasDefault, dynamicProperty.Type, null);
         MethodBuilder   methodBuilder   = typeBuilder_0.DefineMethod("get_" + dynamicProperty.Name, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName, dynamicProperty.Type, Type.EmptyTypes);
         ILGenerator     iLGenerator     = methodBuilder.GetILGenerator();
         iLGenerator.Emit(OpCodes.Ldarg_0);
         iLGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
         iLGenerator.Emit(OpCodes.Ret);
         MethodBuilder methodBuilder2 = typeBuilder_0.DefineMethod("set_" + dynamicProperty.Name, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName, null, new Type[]
         {
             dynamicProperty.Type
         });
         ILGenerator iLGenerator2 = methodBuilder2.GetILGenerator();
         iLGenerator2.Emit(OpCodes.Ldarg_0);
         iLGenerator2.Emit(OpCodes.Ldarg_1);
         iLGenerator2.Emit(OpCodes.Stfld, fieldBuilder);
         iLGenerator2.Emit(OpCodes.Ret);
         propertyBuilder.SetGetMethod(methodBuilder);
         propertyBuilder.SetSetMethod(methodBuilder2);
         array[i] = fieldBuilder;
     }
     return(array);
 }
Beispiel #14
0
		private Type method_1(DynamicProperty[] dynamicProperty_0)
		{
			LockCookie lockCookie = this.readerWriterLock_0.UpgradeToWriterLock(-1);
			Type result;
			try
			{
				string name = "DynamicClass" + (this.int_0 + 1);
				try
				{
					TypeBuilder typeBuilder = this.moduleBuilder_0.DefineType(name, TypeAttributes.Public, typeof(DynamicClass));
					FieldInfo[] fieldInfo_ = this.method_2(typeBuilder, dynamicProperty_0);
					this.method_3(typeBuilder, fieldInfo_);
					this.method_4(typeBuilder, fieldInfo_);
					Type type = typeBuilder.CreateType();
					this.int_0++;
					result = type;
				}
				finally
				{
				}
			}
			finally
			{
				this.readerWriterLock_0.DowngradeFromWriterLock(ref lockCookie);
			}
			return result;
		}
Beispiel #15
0
        public void Should_Get_From_Cache()
        {
            var(cacheManager, dynamicPropertyStoreSubstitute, cacheSubstitute) = InitializeFakes();

            var testDynamicProperty = new DynamicProperty
            {
                Id           = -1,
                PropertyName = "Test123",
                InputType    = "TestType",
                TenantId     = AbpSession.TenantId
            };

            var cacheKey = testDynamicProperty.Id + "@" + (testDynamicProperty.TenantId ?? 0);

            cacheSubstitute
            .Get(cacheKey, Arg.Any <Func <string, object> >())
            .Returns(testDynamicProperty);

            var dynamicPropertyManager = Resolve <IDynamicPropertyManager>();

            var entity = dynamicPropertyManager.Get(testDynamicProperty.Id);

            CheckEquality(entity, testDynamicProperty);

            cacheManager.Received().GetCache(Arg.Any <string>());
            cacheSubstitute.Received().Get(cacheKey, Arg.Any <Func <string, object> >());
            dynamicPropertyStoreSubstitute.DidNotReceive().Get(testDynamicProperty.Id);
        }
        public override void PostInitialize()
        {
            EnsureRootFoldersExist(new[] { VirtoCommerce.MarketingModule.Web.Model.MarketingConstants.ContentPlacesRootFolderId, VirtoCommerce.MarketingModule.Web.Model.MarketingConstants.CotentItemRootFolderId });

            //Create standard dynamic properties for dynamic content item
            var dynamicPropertyService  = _container.Resolve <IDynamicPropertyService>();
            var contentItemTypeProperty = new DynamicProperty
            {
                Id           = "Marketing_DynamicContentItem_Type_Property",
                IsDictionary = true,
                Name         = "Content type",
                ObjectType   = typeof(DynamicContentItem).FullName,
                ValueType    = DynamicPropertyValueType.ShortText,
                CreatedBy    = "Auto",
            };

            dynamicPropertyService.SaveProperties(new[] { contentItemTypeProperty });

            var securityScopeService = _container.Resolve <IPermissionScopeService>();

            securityScopeService.RegisterSope(() => new MarketingSelectedStoreScope());


            //Next lines allow to use polymorph types in API controller methods
            var httpConfiguration = _container.Resolve <HttpConfiguration>();

            httpConfiguration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new PolymorphicPromoEvalContextJsonConverter());
        }
        private void OpenEditor([NotNull] DynamicProperty dynamicProperty, [NotNull] PropertyDescriptor propertyDescriptor, [NotNull] string editorTypeName)
        {
            Debug.ArgumentNotNull(dynamicProperty, nameof(dynamicProperty));
            Debug.ArgumentNotNull(propertyDescriptor, nameof(propertyDescriptor));
            Debug.ArgumentNotNull(editorTypeName, nameof(editorTypeName));

            var type = Type.GetType(editorTypeName);

            if (type == null)
            {
                return;
            }

            var editor = Activator.CreateInstance(type) as UITypeEditor;

            if (editor == null)
            {
                return;
            }

            var value   = dynamicProperty.Value;
            var context = new TypeDescriptorContext(propertyDescriptor, Rendering);
            IServiceProvider provider = null;

            // ReSharper disable once AssignNullToNotNullAttribute - this is OK
            dynamicProperty.Value = editor.EditValue(context, provider, value);
        }
Beispiel #18
0
        public async Task Should_Not_Add_If_Property_Name_Is_Null_Or_Empty_Async()
        {
            var testDynamicProperty = new DynamicProperty
            {
                PropertyName = string.Empty,
                InputType    = Resolve <IDynamicEntityPropertyDefinitionManager>().GetAllAllowedInputTypeNames().First()
            };

            var dynamicPropertyManager = Resolve <IDynamicPropertyManager>();

            var exception =
                await Should.ThrowAsync <ArgumentNullException>(() =>
                                                                dynamicPropertyManager.AddAsync(testDynamicProperty));

            exception.Message.ShouldContain(nameof(testDynamicProperty.PropertyName));

            var testDynamicProperty2 = new DynamicProperty
            {
                PropertyName = null,
                InputType    = Resolve <IDynamicEntityPropertyDefinitionManager>().GetAllAllowedInputTypeNames().First()
            };

            var exception2 =
                await Should.ThrowAsync <ArgumentNullException>(() =>
                                                                dynamicPropertyManager.AddAsync(testDynamicProperty2));

            exception2.Message.ShouldContain(nameof(testDynamicProperty.PropertyName));
        }
        public static DynamicProperty ToDynamicProperty(this coreDto.DynamicObjectProperty propertyDto)
        {
            var result = new DynamicProperty();

            result.InjectFrom<NullableAndEnumValueInjecter>(propertyDto);

            if (propertyDto.DisplayNames != null)
            {
                result.DisplayNames = propertyDto.DisplayNames.Select(x => new LocalizedString(new Language(x.Locale), x.Name)).ToList();
            }

            if (propertyDto.Values != null)
            {
                if (result.IsDictionary)
                {
                    var dictValues = propertyDto.Values
                        .Where(x => x.Value != null)
                        .Select(x => x.Value)
                        .Cast<JObject>()
                        .Select(x => x.ToObject<platformDto.DynamicPropertyDictionaryItem>())
                        .ToArray();

                    result.DictionaryValues = dictValues.Select(x => x.ToDictItem()).ToList();
                }
                else
                {
                    result.Values = propertyDto.Values
                        .Where(x => x.Value != null)
                        .Select(x => x.ToLocalizedString())
                        .ToList();
                }
            }

            return result;
        }
Beispiel #20
0
        public void DefaultNumberFormatTest()
        {
            var data = new[]
            {
                new { TextValue = "SomeText", DateValue = DateTime.Now, DoubleValue = 10.2, IntValue = 5 }
            };

            var dynamicProperties = new[]
            {
                DynamicProperty.Create(data, "DynamicColumn1", "Display Name 1", typeof(DateTime?), n => DateTime.Now.AddDays(n.IntValue - 4)),
                DynamicProperty.Create(data, "DynamicColumn2", "Display Name 2", typeof(double), n => n.DoubleValue - 0.2)
            };


            var excelPackage = EnumerableExporter.Create(data, dynamicProperties)
                               .DefaultNumberFormat(typeof(DateTime), "| yyyy-MM-dd")
                               .DefaultNumberFormat(typeof(DateTime?), "|| yyyy-MM-dd")
                               .DefaultNumberFormat(typeof(double), "0.00 $")
                               .DefaultNumberFormat(typeof(int), "00")
                               .CreateExcelPackage();
            var excelWorksheet = excelPackage.Workbook.Worksheets.First();

            //TestHelper.OpenDocument(excelPackage);

            string numberDecimalSeparator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;

            Assert.IsTrue(excelWorksheet.Cells[2, 2].Text == DateTime.Today.ToString("| yyyy-MM-dd"));             //DateValue
            Assert.IsTrue(excelWorksheet.Cells[2, 3].Text == $"10{numberDecimalSeparator}20 $");                   //DoubleValue
            Assert.IsTrue(excelWorksheet.Cells[2, 4].Text == "05");                                                //IntValue
            Assert.IsTrue(excelWorksheet.Cells[2, 5].Text == DateTime.Today.AddDays(1).ToString("|| yyyy-MM-dd")); //DynamicColumn1
            Assert.IsTrue(excelWorksheet.Cells[2, 6].Text == $"10{numberDecimalSeparator}00 $");                   //DynamicColumn2
        }
        public MailItemAction()
        {
            Properties["ItemID"]          = new MetaProp("ItemID", typeof(string));
            Properties["AutoFindMailBox"] = new MetaProp("AutoFindMailBox", typeof(bool), new DisplayNameAttribute("Automatically find Mailbox"));
            Properties["Location"]        = new MetaProp("Location", typeof(string), new EditorAttribute(typeof(PropertyBag.LocationEditor), typeof(UITypeEditor)));
            Properties["UseCategory"]     = new MetaProp("UseCategory", typeof(bool), new DisplayNameAttribute("Use Category"));
            Properties["Category"]        = new MetaProp("Category", typeof(WoWItemClass), new DisplayNameAttribute("Item Category"));
            Properties["SubCategory"]     = new MetaProp("SubCategory", typeof(WoWItemTradeGoodsClass), new DisplayNameAttribute("Item SubCategory"));
            Properties["Amount"]          = new MetaProp("Amount", typeof(DynamicProperty <int>),
                                                         new TypeConverterAttribute(typeof(DynamicProperty <int> .DynamivExpressionConverter)));

            ItemID          = "";
            AutoFindMailBox = true;
            _loc            = WoWPoint.Zero;
            Location        = _loc.ToInvariantString();
            UseCategory     = true;
            Category        = WoWItemClass.TradeGoods;
            SubCategory     = WoWItemTradeGoodsClass.None;
            Amount          = new DynamicProperty <int>(this, "0");
            RegisterDynamicProperty("Amount");

            Properties["Location"].Show = false;
            Properties["ItemID"].Show   = false;
            Properties["AutoFindMailBox"].PropertyChanged += AutoFindMailBoxChanged;
            Properties["Location"].PropertyChanged        += LocationChanged;
            Properties["UseCategory"].PropertyChanged     += UseCategoryChanged;
            Properties["Category"].PropertyChanged        += CategoryChanged;
        }
Beispiel #22
0
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (binder.Name.Equals("Parameter"))
            {
                //AddParameter會自動根據POST或GET自動擺放parameter
                result = new DynamicProperty <RestRequest>(Node, (node, k, v) => node.AddParameter(k, v.ToString()), null);
                return(true);
            }
            if (binder.Name.Equals("Header"))
            {
                result = new DynamicProperty <RestRequest>(Node, (node, k, v) => node.AddHeader(k, v.ToString()), null);
                return(true);
            }
            if (binder.Name.Equals("UrlSegment"))
            {
                result = new DynamicProperty <RestRequest>(Node, (node, k, v) => node.AddUrlSegment(k, v.ToString()), null);
                return(true);
            }

            if (binder.Name.Equals("File"))
            {
                result = new DynamicProperty <RestRequest>(Node, (node, k, v) => node.AddFile(k, v.ToString()), null);
                return(true);
            }
            result = null;
            return(false);
        }
        /// <summary>
        /// Display the dialog modally.
        /// </summary>
        /// <param name="parentWindow">
        /// The parent window to the dialog
        /// </param>
        /// <param name="domain">
        /// The DynamicProperty domain object to evaluate.
        /// </param>
        /// <returns>
        /// <c>true</c> if the user clicked OK.
        /// </returns>
        public virtual bool DoModal(Window parentWindow, Domain domain)
        {
            bool ok = false;

            dynProp = (DynamicProperty) domain;

            TransientFor = parentWindow;

            // DomainToControls(domain);
            tvDynPropCtl.Render(DomainRenderer.Render(domain, "Summary"));

            calSimEffectiveDate.Date = DateTime.Now;
            //            DateTime dtNow = DateTime.Now;
            //            calSimEffectiveDate.Date = dtNow;
            //            txtSimTime.Text = dtNow.ToString("HH:mm");

            int response = Run();
            if (response == Gtk.ResponseType.Ok.value__)
            {
                ok = true;
                // ControlsToDomain(domain);
            }

            Destroy();

            return ok;
        }
Beispiel #24
0
        public void Create_CalledTwiceWithPropertyInfo_ReturnsCachedProperty()
        {
            DynamicProperty one = DynamicProperty.Create(typeof(Person).GetProperty("Brother"));
            DynamicProperty two = DynamicProperty.Create(typeof(Person).GetProperty("Brother"));

            Assert.AreSame(one, two);
        }
Beispiel #25
0
 Type CreateDynamicClass(DynamicProperty[] properties)
 {
     LockCookie cookie = rwLock.UpgradeToWriterLock(Timeout.Infinite);
     try
     {
         string typeName = "DynamicClass" + (classCount + 1);
     #if ENABLE_LINQ_PARTIAL_TRUST
         new ReflectionPermission(PermissionState.Unrestricted).Assert();
     #endif
         try
         {
             TypeBuilder tb = this.module.DefineType(typeName, TypeAttributes.Class |
                                                               TypeAttributes.Public, typeof(DynamicClass));
             FieldInfo[] fields = GenerateProperties(tb, properties);
             GenerateEquals(tb, fields);
             GenerateGetHashCode(tb, fields);
             Type result = tb.CreateType();
             classCount++;
             return result;
         }
         finally
         {
     #if ENABLE_LINQ_PARTIAL_TRUST
             PermissionSet.RevertAssert();
     #endif
         }
     }
     finally
     {
         rwLock.DowngradeFromWriterLock(ref cookie);
     }
 }
Beispiel #26
0
        public override string get_dynamic_property_setter_cname(DynamicProperty prop)
        {
            if (prop.dynamic_type.data_type == null ||
                !prop.dynamic_type.data_type.is_subtype_of(gobject_type))
            {
                return(base.get_dynamic_property_setter_cname(prop));
            }

            string setter_cname = "_dynamic_set_%s%d".printf(prop.name, dynamic_property_id++);

            var func = new CCodeFunction(setter_cname, "void");

            func.modifiers |= CCodeModifiers.STATIC | CCodeModifiers.INLINE;
            func.add_parameter(new CCodeParameter("obj", get_ccode_name(prop.dynamic_type)));
            func.add_parameter(new CCodeParameter("value", get_ccode_name(prop.property_type)));

            push_function(func);

            var call = new CCodeFunctionCall(new CCodeIdentifier("g_object_set"));

            call.add_argument(new CCodeIdentifier("obj"));
            call.add_argument(get_property_canonical_cconstant(prop));
            call.add_argument(new CCodeIdentifier("value"));
            call.add_argument(new CCodeConstant("NULL"));

            ccode.add_expression(call);

            pop_function();

            // append to C source file
            cfile.add_function_declaration(func);
            cfile.add_function(func);

            return(setter_cname);
        }
        public void TestDynamicProperty()
        {
            Random rand   = new Random();
            Person person = new Person();

            person.Brother = new Person();

            TimeSpan duration;
            DateTime start;

            start = DateTime.Now;

            for (int i = 0; i < 100000; i++)
            {
                Person brother = person.Brother;
                brother.Age++;
            }

            duration = DateTime.Now - start;
            Console.WriteLine(duration.ToString());

            DynamicProperty brotherProperty = DynamicProperty.Create(typeof(Person), "Brother");

            start = DateTime.Now;

            for (int i = 0; i < 100000; i++)
            {
                Person brother = (Person)brotherProperty.GetValue(person);
                brother.Age++;
            }

            duration = DateTime.Now - start;
            Console.WriteLine(duration.ToString());
        }
        /// <summary>
        ///   Called when the value of a dynamic property value has changed.
        /// </summary>
        /// <param name="component"> Component that owns the changed property. </param>
        /// <param name="changedProperty"> Changed property. </param>
        /// <param name="oldValue"> Previous value of the changed property. </param>
        public override void OnPropertyValueChanged(SmartComponent component, DynamicProperty changedProperty, Object oldValue)
        {
            PointCloud p       = null;
            Station    station = Project.ActiveProject as Station;

            if (station == null)
            {
                return;
            }

            //Get last cloud
            for (int i = 0; i < station.PointClouds.Count; ++i)
            {
                if (station.PointClouds[i].Name == component.UniqueId)
                {
                    p = station.PointClouds[i];
                }
            }

            if (p == null)
            {
                return;
            }

            if (changedProperty.Name == "Transform")
            {
                p.Transform.GlobalMatrix = (Matrix4)changedProperty.Value;
            }

            if (changedProperty.Name == "Visible")
            {
                p.Visible = (bool)changedProperty.Value;
            }
        }
Beispiel #29
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);

            SetFlash();

            //change the css class for this page type
            Form.Attributes["class"] = "StartPage";

            if (CurrentPage["MainLinksCount"] != null)
            {
                MainPageList.MaxCount = (int)CurrentPage["MainLinksCount"];
            }

            if (CurrentPage["SecondaryLinksCount"] != null)
            {
                SecondaryPageList.MaxCount = (int)CurrentPage["SecondaryLinksCount"];
            }

            DynamicProperty property = DynamicProperty.Load(CurrentPageLink, "StartPage");

            if (property == null)
            {
                return;
            }

            PageReference reference = property.PropertyValue.Value as PageReference;

            if (PageReference.IsNullOrEmpty(reference) || (reference.ID != CurrentPageLink.ID))
            {
                property.PropertyValue.Value = CurrentPageLink;
                property.Save();
            }
        }
Beispiel #30
0
        public object GetPropertyValue(object obj)
        {
            if (_dynamicProperty == null)
                _dynamicProperty = DynamicProperty.Create(this.Property);

            return _dynamicProperty.GetValue(obj);
        }
        public EngineeringPropertyDataAdapter(OleDbDataReader dr, IList<string> dynamicList, int startColumn)
        {
            ControlSystemName = "";
            ComponentName = "";

            ControlSystemName = dr.SafeString((int)EngineeringPropertyColumn.ControlSystemName).Trim();
            ComponentName = dr.SafeString((int)EngineeringPropertyColumn.ComponentName).Trim();

            DynamicProperties = new List<DynamicProperty>();

            if (dynamicList != null && dynamicList.Any())
            {
                for (int d = 0; d < dynamicList.Count(); d++)
                {
                    string p = dynamicList[d];

                    DynamicProperty property = new DynamicProperty();

                    property.PropertyName = p;
                    property.PropertyValue = dr.SafeString(startColumn + d);

                    DynamicProperties.Add(property);
                }
            }
        }
Beispiel #32
0
		public void AddProperty(string propName, object propValue, string propDesc,
			string propCat, Type propType, bool isReadOnly, bool isExpandable)
		{
			DynamicProperty p = new DynamicProperty(propName, propValue, propDesc, propCat,
				propType, isReadOnly, isExpandable);
			m_propertyCollection.Add(p);
		}
Beispiel #33
0
        /// <summary>
        /// Called when the value of a dynamic property value has changed.
        /// </summary>
        /// <param name="component"> Component that owns the changed property. </param>
        /// <param name="changedProperty"> Changed property. </param>
        /// <param name="oldValue"> Previous value of the changed property. </param>
        public override void OnPropertyValueChanged(SmartComponent component, DynamicProperty changedProperty, Object oldValue)
        {
            if (changedProperty.Name == "Status")
            {
                return;
            }

            base.OnPropertyValueChanged(component, changedProperty, oldValue);
            if (bOnLoad)
            {
                UpdateComponentList(component);
                UpdateControllers(component);
                isOnPropertyValueChanged[component.UniqueId] = false;
                return;
            }
            if (!isOnPropertyValueChanged.ContainsKey(component.UniqueId))
            {
                isOnPropertyValueChanged[component.UniqueId] = false;
            }

            bool bIsOnPropertyValueChanged = isOnPropertyValueChanged[component.UniqueId];

            isOnPropertyValueChanged[component.UniqueId] = true;

            if (changedProperty.Name == "Controller")
            {
                if ((string)changedProperty.Value != "Update")
                {
                    if (GetController(component) != null)
                    {
                        Logger.AddMessage("RSMoveMecha: Connecting Component " + component.Name + " to " + (string)changedProperty.Value, LogMessageSeverity.Information);
                        component.Properties["Status"].Value = "Connected";
                    }
                }
            }
            if (changedProperty.Name == "CtrlMechanism")
            {
                GetController(component);
            }
            if (changedProperty.Name == "Mechanism")
            {
                Mechanism mecha = (Mechanism)component.Properties["Mechanism"].Value;
                if (mecha != null)
                {
                    int[] mechaAxes         = mecha.GetActiveJoints();
                    int   iMechNumberOfAxes = mechaAxes.Length;
                    component.Properties["MechSpecAxis"].Attributes["MaxValue"] = iMechNumberOfAxes.ToString();
                }
            }

            if (!bIsOnPropertyValueChanged)
            {
                //Update available controller
                UpdateControllers(component);
                //Save Modified Component for EventHandlers
                UpdateComponentList(component);
            }

            isOnPropertyValueChanged[component.UniqueId] = bIsOnPropertyValueChanged;
        }
Beispiel #34
0
 public override Object Clone()
 {
     var result = new DynamicProperty();
     result.InitProperty();
     Copy(result);
     return result;
 }
Beispiel #35
0
        //public virtual ObservableCollection<DynamicPropertyObjectValueEntity> ObjectValues { get; set; }


        public virtual DynamicProperty ToModel(DynamicProperty dynamicProp)
        {
            if (dynamicProp == null)
            {
                throw new ArgumentNullException(nameof(dynamicProp));
            }

            dynamicProp.Id             = Id;
            dynamicProp.CreatedBy      = CreatedBy;
            dynamicProp.CreatedDate    = CreatedDate;
            dynamicProp.ModifiedBy     = ModifiedBy;
            dynamicProp.ModifiedDate   = ModifiedDate;
            dynamicProp.Description    = Description;
            dynamicProp.DisplayOrder   = DisplayOrder;
            dynamicProp.IsArray        = IsArray;
            dynamicProp.IsDictionary   = IsDictionary;
            dynamicProp.IsMultilingual = IsMultilingual;
            dynamicProp.IsRequired     = IsRequired;
            dynamicProp.Name           = Name;
            dynamicProp.ObjectType     = ObjectType;

            dynamicProp.ValueType    = EnumUtility.SafeParse(ValueType, DynamicPropertyValueType.LongText);
            dynamicProp.DisplayNames = DisplayNames.Select(x => x.ToModel(AbstractTypeFactory <DynamicPropertyName> .TryCreateInstance())).ToArray();
            //if (dynamicProp is DynamicObjectProperty dynamicObjectProp)
            //{
            //    dynamicObjectProp.Values = ObjectValues.Select(x => x.ToModel(AbstractTypeFactory<DynamicPropertyObjectValue>.TryCreateInstance())).ToArray();
            //}
            return(dynamicProp);
        }
Beispiel #36
0
        /// <summary>
        /// Sets up the structure for a forum
        /// </summary>
        /// <remarks>
        /// Sets up three subpages to the forum page. One container for active threads, one for sticky threads and one for archived threads.
        /// </remarks>
        /// <param name="forumReference">The reference to the forum.</param>
        public static PageReference SetupForumStructure(PageReference forumReference)
        {
            PageData activeContainer  = DataFactory.Instance.GetDefaultPageData(forumReference, ThreadContainerPageTypeName);
            PageData archiveContainer = DataFactory.Instance.GetDefaultPageData(forumReference, ThreadContainerPageTypeName);
            PageData stickyContainer  = DataFactory.Instance.GetDefaultPageData(forumReference, ThreadContainerPageTypeName);

            PageData forum = DataFactory.Instance.GetPage(forumReference).CreateWritableClone();

            activeContainer.PageName               = "Active";
            archiveContainer.PageName              = "Archive";
            stickyContainer.PageName               = "Sticky";
            activeContainer.VisibleInMenu          = false;
            archiveContainer.VisibleInMenu         = false;
            stickyContainer.VisibleInMenu          = false;
            activeContainer["PageChildOrderRule"]  = FilterSortOrder.ChangedDescending;
            archiveContainer["PageChildOrderRule"] = FilterSortOrder.ChangedDescending;
            stickyContainer["PageChildOrderRule"]  = FilterSortOrder.ChangedDescending;

            forum["ActiveThreadContainer"]  = DataFactory.Instance.Save(activeContainer, SaveAction.Publish, AccessLevel.Administer);
            forum["ArchiveThreadContainer"] = DataFactory.Instance.Save(archiveContainer, SaveAction.Publish, AccessLevel.Administer);
            forum["StickyThreadContainer"]  = DataFactory.Instance.Save(stickyContainer, SaveAction.Publish, AccessLevel.Administer);
            DynamicProperty forumStart = DynamicProperty.Load(forum.PageLink, "ForumStart");

            forumStart.PropertyValue.Value = forum.PageLink;
            forumStart.Save();

            return(DataFactory.Instance.Save(forum, SaveAction.Publish, AccessLevel.Administer));
        }
Beispiel #37
0
		private FieldInfo[] GenerateProperties(TypeBuilder tb, DynamicProperty[] properties)
		{
			FieldInfo[] array = new FieldBuilder[properties.Length];
			for (int i = 0; i < properties.Length; i++)
			{
				DynamicProperty dynamicProperty = properties[i];
				FieldBuilder fieldBuilder = tb.DefineField("_" + dynamicProperty.Name, dynamicProperty.Type, FieldAttributes.Private);
				PropertyBuilder propertyBuilder = tb.DefineProperty(dynamicProperty.Name, PropertyAttributes.HasDefault, dynamicProperty.Type, null);
				MethodBuilder methodBuilder = tb.DefineMethod("get_" + dynamicProperty.Name, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName, dynamicProperty.Type, Type.EmptyTypes);
				ILGenerator iLGenerator = methodBuilder.GetILGenerator();
				iLGenerator.Emit(OpCodes.Ldarg_0);
				iLGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
				iLGenerator.Emit(OpCodes.Ret);
				MethodBuilder methodBuilder2 = tb.DefineMethod("set_" + dynamicProperty.Name, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName, null, new Type[]
				{
					dynamicProperty.Type
				});
				ILGenerator iLGenerator2 = methodBuilder2.GetILGenerator();
				iLGenerator2.Emit(OpCodes.Ldarg_0);
				iLGenerator2.Emit(OpCodes.Ldarg_1);
				iLGenerator2.Emit(OpCodes.Stfld, fieldBuilder);
				iLGenerator2.Emit(OpCodes.Ret);
				propertyBuilder.SetGetMethod(methodBuilder);
				propertyBuilder.SetSetMethod(methodBuilder2);
				array[i] = fieldBuilder;
			}
			return array;
		}
Beispiel #38
0
 Type CreateDynamicClass(DynamicProperty[] properties)
 {
     LockCookie cookie = rwLock.UpgradeToWriterLock(Timeout.Infinite);
     try
     {
         string typeName = "DynamicClass" + (classCount + 1);
         try
         {
             TypeBuilder tb = this.module.DefineType(typeName, TypeAttributes.Class |
                 TypeAttributes.Public, typeof(DynamicClass));
             FieldInfo[] fields = GenerateProperties(tb, properties);
             GenerateEquals(tb, fields);
             GenerateGetHashCode(tb, fields);
             Type result = tb.CreateType();
             classCount++;
             return result;
         }
         finally
         {
         }
     }
     finally
     {
         rwLock.DowngradeFromWriterLock(ref cookie);
     }
 }
Beispiel #39
0
        public async Task Should_Get_From_Cache_Async()
        {
            var(cacheManager, dynamicPropertyStoreSubstitute, cacheSubstitute) = InitializeFakes();

            var testDynamicProperty = new DynamicProperty
            {
                Id           = -1,
                PropertyName = "Test123",
                InputType    = "TestType"
            };

            cacheSubstitute
            .GetAsync(testDynamicProperty.Id.ToString(), Arg.Any <Func <string, Task <object> > >())
            .Returns(testDynamicProperty);

            var dynamicPropertyManager = Resolve <IDynamicPropertyManager>();

            var entity = await dynamicPropertyManager.GetAsync(testDynamicProperty.Id);

            CheckEquality(entity, testDynamicProperty);

            cacheManager.Received().GetCache(Arg.Any <string>());
            await cacheSubstitute.Received().GetAsync(testDynamicProperty.Id.ToString(), Arg.Any <Func <string, Task <object> > >());

            await dynamicPropertyStoreSubstitute.DidNotReceive().GetAsync(testDynamicProperty.Id);
        }
Beispiel #40
0
		private FieldInfo[] GenerateProperties( TypeBuilder tb , DynamicProperty[] properties ) {
			FieldInfo[] fields = new FieldBuilder[properties.Length];
			for ( int i = 0 ; i < properties.Length ; i++ ) {
				DynamicProperty dp = properties[i];
				FieldBuilder fb = tb.DefineField( "_" + dp.Name , dp.Type , FieldAttributes.Private );
				PropertyBuilder pb = tb.DefineProperty( dp.Name , PropertyAttributes.HasDefault , dp.Type , null );
				MethodBuilder mbGet = tb.DefineMethod( "get_" + dp.Name ,
				                                       MethodAttributes.Public | MethodAttributes.SpecialName |
				                                       MethodAttributes.HideBySig ,
				                                       dp.Type , Type.EmptyTypes );
				ILGenerator genGet = mbGet.GetILGenerator();
				genGet.Emit( OpCodes.Ldarg_0 );
				genGet.Emit( OpCodes.Ldfld , fb );
				genGet.Emit( OpCodes.Ret );
				MethodBuilder mbSet = tb.DefineMethod( "set_" + dp.Name ,
				                                       MethodAttributes.Public | MethodAttributes.SpecialName |
				                                       MethodAttributes.HideBySig ,
				                                       null , new[] { dp.Type } );
				ILGenerator genSet = mbSet.GetILGenerator();
				genSet.Emit( OpCodes.Ldarg_0 );
				genSet.Emit( OpCodes.Ldarg_1 );
				genSet.Emit( OpCodes.Stfld , fb );
				genSet.Emit( OpCodes.Ret );
				pb.SetGetMethod( mbGet );
				pb.SetSetMethod( mbSet );
				fields[i] = fb;
			}
			return fields;
		}
        public InterlockDataAdapter(OleDbDataReader dr ,IList<string> dynamicList, int startColumn)
        {
            ControlSystemName = string.Empty;
            InterlockTypeName =
            Number = string.Empty;
            Cause = string.Empty;
            Description = string.Empty;

            ControlSystemName = dr.SafeString((int)InterlockColumn.ControlSystemName).Trim();
            InterlockTypeName = dr.SafeString((int)InterlockColumn.InterlockType).Trim();
            Number = dr.SafeString((int)InterlockColumn.Number).Trim();
            Cause = dr.SafeString((int)InterlockColumn.Cause).Trim();
            Description = dr.SafeString((int)InterlockColumn.Description).Trim();

            DynamicProperties = new List<DynamicProperty>();

            if (dynamicList != null && dynamicList.Any())
            {
                for (int d = 0; d < dynamicList.Count(); d++)
                {
                    string p = dynamicList[d];

                    DynamicProperty property = new DynamicProperty();

                    property.PropertyName = p;
                    property.PropertyValue = dr.SafeString(startColumn + d);

                    DynamicProperties.Add(property);
                }
            }
        }
Beispiel #42
0
 public static List<PageControl> RecursiveCreatePageControl(XmlElement root)
 {
     var result = new List<PageControl>();
     var nodeList = root.SelectNodes("Children/Child");
     if (nodeList.Count <= 0)
     {
         nodeList = root.SelectNodes("Child");
     }
     foreach (XmlNode node in nodeList)
     {
         var element = node as XmlElement;
         var control = new PageControl();
         control.Id = XmlUtility.GetAttrValue(element, "Id");
         control.Type = XmlUtility.GetAttrValue(element, "Type");
         var dynamicProperty = new DynamicProperty();
         dynamicProperty.InitProperty();
         var flashProperty = new FlashProperty();
         flashProperty.InitProperty();
         EvaluateProperty(element, control, dynamicProperty, flashProperty);
         EvaluateEvent(element, control, dynamicProperty, flashProperty);
         if (dynamicProperty.FlashEvents.Count > 0
             || dynamicProperty.FlashPropertys.Count > 0)
         {
             control.Properties.Add(new Property()
             {
                 Name = PropertyUtility.DYNAMICNAME,
                 Type = PropertyValueType.str.ToString(),
                 Value = dynamicProperty.ToXml()
             });
         }
         control.Children = RecursiveCreatePageControl(element);
         result.Add(control);
     }
     return result;
 }
Beispiel #43
0
        public void ReadOnlyGet()
        {
            TestClass testClass = new TestClass();
            DynamicProperty <TestClass> nameProperty = DynamicType <TestClass> .CreateDynamicProperty("ReadOnlyName");

            Assert.AreEqual("SomeTestName", nameProperty.InvokeGetterOn(testClass));
        }
        public void It_Creates_With_Value()
        {
            var myValue  = new TestEntity();
            var property = new DynamicProperty <TestEntity>(DefaultPropertyName, myValue);

            property.Value.Should().Be(myValue);
        }
        public DynamicProperty[] SaveProperties(DynamicProperty[] properties)
        {
            if (properties == null)
                throw new ArgumentNullException("properties");

            using (var repository = _repositoryFactory())
            using (var changeTracker = GetChangeTracker(repository))
            {
                var sourceProperties = properties.Select(x => x.ToEntity()).ToList();
                var targetProperties = repository.GetDynamicPropertiesByIds(properties.Select(x => x.Id).ToArray()).ToList();
                sourceProperties.CompareTo(targetProperties, EqualityComparer<DynamicPropertyEntity>.Default, (state, source, target) =>
                    {
                        if (state == EntryState.Modified)
                        {
                            changeTracker.Attach(target);
                            source.Patch(target);
                        }
                        else if (state == EntryState.Added)
                        {
                            repository.Add(source);
                        }

                    });
                repository.UnitOfWork.Commit();

                var result = repository.GetDynamicPropertiesByIds(sourceProperties.Select(p => p.Id).ToArray())
                    .Select(p => p.ToModel())
                    .ToArray();
                return result;
            }
        }
Beispiel #46
0
        public async Task Should_Add_And_Change_Cache_Async()
        {
            var(cacheManager, dynamicPropertyStoreSubstitute, cacheSubstitute) = InitializeFakes();

            var dynamicPropertyManager = Resolve <IDynamicPropertyManager>();

            var testDynamicProperty = new DynamicProperty
            {
                PropertyName = "Test123",
                InputType    = GetRandomAllowedInputType()
            };

            var result = await dynamicPropertyManager.AddAsync(testDynamicProperty);

            await cacheSubstitute.Received().SetAsync(
                testDynamicProperty.Id + "@0", // @0 is added because this is a host entity
                testDynamicProperty,
                Arg.Any <TimeSpan?>(),
                Arg.Any <DateTimeOffset?>()
                );

            await dynamicPropertyStoreSubstitute.Received().AddAsync(testDynamicProperty);

            result.ShouldBe(testDynamicProperty);
        }
Beispiel #47
0
 private void Init()
 {
     Text = MultilingualUtility.GetString("Flash");
     btnSelect.Text = MultilingualUtility.GetString("Select");
     btnConfirm.Text = MultilingualUtility.GetString("OK");
     btnCancel.Text = MultilingualUtility.GetString("Cancel");
     FlashPropertys = new DynamicProperty();
 }
        public void GetValue_PropertyIsReferenceType_GetsBoxedAndReturnsCorrectValue()
        {
            Person brother = new Person();
            _person.Brother = brother;

            _target = DynamicProperty.Create(typeof(Person), "Brother");
            object brotherDynamic = _target.GetValue(_person);
            Assert.AreSame(brother, brotherDynamic);
        }
        public IHttpActionResult SaveProperties(string typeName, DynamicProperty[] properties)
        {
            foreach (var property in properties.Where(property => string.IsNullOrEmpty(property.ObjectType)))
            {
                property.ObjectType = typeName;
            }

            _service.SaveProperties(properties);
            return StatusCode(HttpStatusCode.NoContent);
        }
        public static DynamicProperty ToModel(this DynamicPropertyEntity entity)
        {
            var result = new DynamicProperty();
            result.InjectFrom(entity);

            result.ValueType = EnumUtility.SafeParse(entity.ValueType, DynamicPropertyValueType.Undefined);

            result.DisplayNames = entity.DisplayNames.Select(n => n.ToModel()).ToArray();

            return result;
        }
        public object GetPropertyValue(object obj)
        {
            if (_dynamicProperty == null) {
                if (_Expression != null)
                    _dynamicProperty = DynamicProperty.Create(_Expression);
                else
                    _dynamicProperty = DynamicProperty.Create(this.Property);
            }

            return _dynamicProperty.GetValue(obj);
        }
 public static DynamicProperty Create(MemberExpression expression)
 {
     DynamicProperty cached;
     var propertyInfo = (PropertyInfo)expression.Member;
     lock (_dynamicPropertyCache) {
         if (!_dynamicPropertyCache.TryGetValue(propertyInfo, out cached)) {
             cached = new DynamicProperty(expression);
             _dynamicPropertyCache.Add(propertyInfo, cached);
         }
     }
     return cached;
 }
        public static DynamicProperty Create(PropertyInfo propertyInfo)
        {
            DynamicProperty cached;

            lock (_dynamicPropertyCache)
            {
                if (!_dynamicPropertyCache.TryGetValue(propertyInfo, out cached))
                {
                    cached = new DynamicProperty(propertyInfo);
                    _dynamicPropertyCache.Add(propertyInfo, cached);
                }
            }
            return cached;
        }
Beispiel #54
0
        public override void PostInitialize()
        {
            base.PostInitialize();
            //Create EnableQuote dynamic propertiy for  Store 
            var dynamicPropertyService = _container.Resolve<IDynamicPropertyService>();
            var enableQuotesProperty = new DynamicProperty
            {
                Id = "Quote_Enable_Property",
                Name = "EnableQuotes",
                ObjectType = typeof(Store).FullName,
                ValueType = DynamicPropertyValueType.Boolean,
                CreatedBy = "Auto",
            };

            dynamicPropertyService.SaveProperties(new[] { enableQuotesProperty });
        }
 private Type CreateDynamicClass(DynamicProperty[] properties)
 {
     string name = "DynamicClass" + (this.classCount + 1);
     try
     {
         TypeBuilder tb = this.module.DefineType(name, TypeAttributes.Public, typeof(DynamicClass));
         FieldInfo[] fields = this.GenerateProperties(tb, properties);
         this.GenerateEquals(tb, fields);
         this.GenerateGetHashCode(tb, fields);
         Type type = tb.CreateType();
         this.classCount++;
         return type;
     }
     finally
     {
     }
 }
        public void ClassFactory_LoadTest()
        {
            //Arrange
            var rnd = new Random(1);

            var testPropertiesGroups = new DynamicProperty[][] {
                new DynamicProperty[] { 
                    new DynamicProperty("String1", typeof( string )), 
                },
                new DynamicProperty[] { 
                    new DynamicProperty("String1", typeof( string )), 
                    new DynamicProperty("String2", typeof( string )) 
                },
                new DynamicProperty[] { 
                    new DynamicProperty("String1", typeof( string )), 
                    new DynamicProperty("Int1", typeof( int )) 
                },
                new DynamicProperty[] { 
                    new DynamicProperty("Int1", typeof( int )), 
                    new DynamicProperty("Int2", typeof( int )) 
                },
                new DynamicProperty[] { 
                    new DynamicProperty("String1", typeof( string )), 
                    new DynamicProperty("String2", typeof( string )), 
                    new DynamicProperty("String3", typeof( string )), 
                },
            };

            Action<int> testActionSingle = i =>
            {
                ClassFactory.Instance.GetDynamicClass(testPropertiesGroups[0]);
            };

            Action<int> testActionMultiple = i => {
                var testProperties = testPropertiesGroups[rnd.Next(0, testPropertiesGroups.Length)];

                ClassFactory.Instance.GetDynamicClass(testProperties);
            };

            //Act
            Parallel.For(0, 100000, testActionSingle);

            Parallel.For(0, 100000, testActionMultiple);

        }
Beispiel #57
0
        public override void PostInitialize()
        {
            var promotionExtensionManager = _container.Resolve<IMarketingExtensionManager>();
            EnsureRootFoldersExist(new[] { VirtoCommerce.MarketingModule.Web.Model.MarketingConstants.ContentPlacesRootFolderId, VirtoCommerce.MarketingModule.Web.Model.MarketingConstants.CotentItemRootFolderId });

			//Create standard dynamic properties for dynamic content item
			var dynamicPropertyService = _container.Resolve<IDynamicPropertyService>();
			var contentItemTypeProperty = new DynamicProperty
			{
				Id = "Marketing_DynamicContentItem_Type_Property",
				IsDictionary = true,
				Name = "Content type",
				ObjectType = typeof(DynamicContentItem).FullName,
				ValueType = DynamicPropertyValueType.ShortText,
				CreatedBy = "Auto",
			};
		
			dynamicPropertyService.SaveProperties(new [] { contentItemTypeProperty });
		}
        public SellItemAction()
        {
            Properties["Location"] = new MetaProp("Location", typeof(string), new EditorAttribute(typeof(PropertyBag.LocationEditor), typeof(UITypeEditor)));
            Properties["NpcEntry"] = new MetaProp("NpcEntry", typeof(uint), new EditorAttribute(typeof(PropertyBag.EntryEditor), typeof(UITypeEditor)));
            Properties["ItemID"] = new MetaProp("ItemID", typeof(string));
            Properties["Count"] = new MetaProp("Count", typeof(DynamicProperty<int>),
                new TypeConverterAttribute(typeof(DynamicProperty<int>.DynamivExpressionConverter)));
            Properties["SellItemType"] = new MetaProp("SellItemType", typeof(SellItemActionType), new DisplayNameAttribute("Sell Item Type"));

            ItemID = "";
            Count = new DynamicProperty<int>(this,"0");
            RegisterDynamicProperty("Count");
            _loc = WoWPoint.Zero;
            Location = _loc.ToInvariantString();
            NpcEntry = 0u;

            Properties["Location"].PropertyChanged += LocationChanged;
            Properties["SellItemType"].Value = SellItemActionType.Specific;
            Properties["SellItemType"].PropertyChanged += SellItemActionPropertyChanged;
        }
Beispiel #59
0
        public override void PostInitialize()
        {
            base.PostInitialize();
            //Create EnableQuote dynamic propertiy for  Store 
            var dynamicPropertyService = _container.Resolve<IDynamicPropertyService>();

            var defaultThemeNameProperty = new DynamicProperty
            {
                Id = "Default_Theme_Name_Property",
                Name = "DefaultThemeName",
                ObjectType = typeof(Store).FullName,
                ValueType = DynamicPropertyValueType.ShortText,
                CreatedBy = "Auto"
            };

            dynamicPropertyService.SaveProperties(new[] { defaultThemeNameProperty });

            //Register bounded security scope types
            var securityScopeService = _container.Resolve<IPermissionScopeService>();
            securityScopeService.RegisterSope(() => new ContentSelectedStoreScope());
        }
Beispiel #60
0
		private Type CreateDynamicClass(DynamicProperty[] properties)
		{
			LockCookie lockCookie = this.rwLock.UpgradeToWriterLock(-1);
			Type result;
			try
			{
				string name = "DynamicClass" + (this.classCount + 1);
				TypeBuilder typeBuilder = this.module.DefineType(name, TypeAttributes.Public, typeof(DynamicClass));
				FieldInfo[] fields = this.GenerateProperties(typeBuilder, properties);
				this.GenerateEquals(typeBuilder, fields);
				this.GenerateGetHashCode(typeBuilder, fields);
				Type type = typeBuilder.CreateType();
				this.classCount++;
				result = type;
			}
			finally
			{
				this.rwLock.DowngradeFromWriterLock(ref lockCookie);
			}
			return result;
		}