public void property_factory_cached() { IPropertyFactory notCached = new PropertyFactory(); notCached.Create <string>("Test").Should().NotBeSameAs(notCached.Create <string>("Test")); IPropertyFactory cached = new PropertyFactory().Cached(); cached.Create <string>("Test").Should().BeSameAs(cached.Create <string>("Test")); }
public void property_factory() { PropertyFactory propertyFactory = new PropertyFactory(); IProperty property = propertyFactory.Create <int>("Test"); property.Type.Should().Be(typeof(int)); property.Name.Should().Be("Test"); property = propertyFactory.Create(typeof(int), "Test"); property.Type.Should().Be(typeof(int)); property.Name.Should().Be("Test"); }
public SubtypingProperty(Type baseType, PropertyFactory modelFactory, Type[] availableTypes) { AvailableTypes = availableTypes.Select(x => { var attr = x.GetCustomAttribute <PwSubtypeAttribute>(); return(new SubTypeInfo(x, attr.Name)); }).ToArray(); ValueType = baseType; SelectedType.Where(x => x != null) .Subscribe(x => { try { Model.Value = modelFactory.Create(x.Type, Title.Value); } catch (Exception e) { Debugger.Log(1, "Error", $"Error from SubtypingProperty:\n{e}\n"); OnErrorSubject.OnNext(e); } }); Value = Model.Where(x => x != null) .SelectMany(x => x.Value) .ToReactiveProperty(mode: ReactivePropertyMode.RaiseLatestValueOnSubscribe); Model.Where(x => x != null) .SelectMany(x => x.OnError) .Subscribe(x => OnErrorSubject.OnNext(x)); }
public void SubtypingPropagateTest() { bool isCalled = false; var factory = new PropertyFactory(); factory.GetStructure(Assembly.GetExecutingAssembly(), typeof(SubtypeProject), new Project[0]); var prop = factory.Create(typeof(A), "SubtypeA") as SubtypingProperty; var vm = new ViewModelFactory(factory).Create(prop, false) as SubtypingViewModel; vm.OnChanged.Subscribe(x => isCalled = true); T GetMember <T>(IStructureProperty model, string name) => (T)model.Members.First(x => x.PropertyInfo.Name == name); prop.SelectedType.Value = prop.AvailableTypes.First(); var memberB = GetMember <SubtypingProperty>(prop.Model.Value as ClassProperty, nameof(AX.B)); memberB.SelectedType.Value = memberB.AvailableTypes.First(); var memberC = GetMember <ClassProperty>(memberB.Model.Value as ClassProperty, nameof(BX.C)); var memberX = GetMember <IntProperty>(memberC, nameof(C.Z)); memberX.IntValue.Value = 999; isCalled.IsTrue(); }
public Property GetProperty(string deviceId, string nodeId, string propertyId) { var propertyBase = GetPropertyBase(deviceId, nodeId, propertyId); var property = PropertyFactory.Create(propertyBase); return(property); }
internal NotifyPropertyChangedRecordedElement(IUndoRedoService undoRedoService, INotifyPropertyChanged objAsNotifyPropertyChanged) : base(objAsNotifyPropertyChanged) { if (undoRedoService == null) { throw new ArgumentNullException("undoRedoService"); } if (objAsNotifyPropertyChanged == null) { throw new ArgumentNullException("objAsNotifyPropertyChanged"); } _objAsNotifyPropertyChanged = objAsNotifyPropertyChanged; _objAsNotifyPropertyChanged.PropertyChanged += OnPropertyChanged; foreach (var propertyInfo in objAsNotifyPropertyChanged.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) { var getMethod = propertyInfo.GetGetMethod(); if (getMethod != null && getMethod.GetParameters().Any()) { continue; } var attributes = propertyInfo.GetCustomAttributes(typeof(IsRecordableAttribute), true); if (attributes.Length <= 0) { continue; } var property = PropertyFactory.Create(undoRedoService, objAsNotifyPropertyChanged, (IsRecordableAttribute)attributes[0], propertyInfo); _properties.Add(property.Name, property); } }
/// <summary> /// Возвращает описание контрола Image /// </summary> private ControlTypeDescription GetSampleImageDescription() { var standardCssClass = PropertyFactory.GetStandardCssClassProperty(); standardCssClass.DefaultValue = "sample-image"; var bindingProperty = PropertyFactory.GetBindingProperty(); bindingProperty.GetBindingLoader = () => new CustomBindingLoader(Constants.SampleImage.Slider, Constants.SampleImage.SliderConverter); var sampleImage = new ControlTypeDescription(Constants.SampleImage.ClassName) { DisplayName = Resources.ControlTypes_SampleImage, ControlGroupDisplayName = Resources.ControlGroup_Samples, PropertyDescriptions = { standardCssClass, PropertyFactory.GetNameProperty(), PropertyFactory.GetVisibilityProperty(), PropertyFactory.GetCustomCssClassesProperty(), PropertyFactory.Create(Constants.SampleImage.ImageHeight), PropertyFactory.Create(Constants.SampleImage.ImageWidth), PropertyFactory.Create(Constants.SampleImage.Slider), PropertyFactory.Create(Constants.SampleImage.Description), PropertyFactory.Create(UrlPropertyDesignerExtension.Extension.Constants.CommonProperties.UrlAddress), bindingProperty, PropertyFactory.GetClickEvent(), PropertyFactory.GetMouseOverEvent(), PropertyFactory.GetMouseOutEvent(), } }; return(sampleImage); }
/// <summary> /// Возвращает описание контрола SampleTextBox /// </summary> private ControlTypeDescription GetSampleTextBoxDescription() { var standardCssClass = PropertyFactory.GetStandardCssClassProperty(); standardCssClass.DefaultValue = "sample-textbox"; var sampleTextBox = new ControlTypeDescription(Constants.SampleTextBox.ClassName) { DisplayName = Resources.ControlTypes_SampleTextBox, ControlGroupDisplayName = Resources.ControlGroup_Samples, PropertyDescriptions = { standardCssClass, PropertyFactory.GetNameProperty(), PropertyFactory.GetVisibilityProperty(), PropertyFactory.GetCustomCssClassesProperty(), PropertyFactory.GetTipProperty(), PropertyFactory.GetLabelTextProperty(), PropertyFactory.GetTabStopProperty(), PropertyFactory.GetDefaultProperty(), PropertyFactory.Create(Constants.CommonProperties.UrlAddress), PropertyFactory.GetClickEvent(), PropertyFactory.GetMouseOverEvent(), PropertyFactory.GetMouseOutEvent(), PropertyFactory.GetFocusEvent(), PropertyFactory.GetBlurEvent(), PropertyFactory.GetDataChangedEvent(), PropertyFactory.CreateEvent("ImageClick", "ControlTypes_ImageClickEventProperty"), }, GetAllowedOperations = AllowedOperationsStorage.GetAllowedOperations(Constants.AllowedOperations.AllowCreateInEditLayoutsOnly) }; PropertyFactory.AddSimpleBinding(sampleTextBox, editOperation: true); return(sampleTextBox); }
public void can_make_nested_property() { var animal = new Animal(); var property = PropertyFactory.Create(typeof(Animal), "Color.Red"); Assert.DoesNotThrow(() => Assert.Equal(animal.Color.Red, property.Get(animal))); Assert.DoesNotThrow(() => property.Set(animal, 20)); Assert.Equal(20, animal.Color.Red); }
public void should_allow_set_when_property_is_writeable() { var property = PropertyFactory.Create(typeof(Animal), "Name"); var animal = new Animal { Name = "before" }; Assert.True(property.CanWrite); Assert.DoesNotThrow(() => property.Set(animal, "after")); Assert.Equal("after", animal.Name); }
public void test_property() { //create instance of factory PropertyFactory f = new PropertyFactory(); //create instance from factory Property p = f.Create("Property"); //check that it is right type Type t = new Property().GetType(); Assert.IsInstanceOfType(t, p); }
public PropertyCollection GetProperties(Instance instance) { var properties = new PropertyCollection(); foreach (var propertyPairs in ReflectionMappingManager.PropertyCache[instance.GetType()]) { var value = GetPropertyValue(instance, propertyPairs.Value.Item1, propertyPairs.Value.Item2); var robloxProperty = PropertyFactory.Create(propertyPairs.Key, propertyPairs.Value.Item2, value); properties.Add(robloxProperty); } return(properties); }
public void Create_Valid_ReturnsInitialized() { var propertyFactory = new PropertyFactory(); var propertyNumber = 1; var propertySquareMeters = 30d; var propertyRooms = 1d; var property = propertyFactory.Create(propertyNumber, propertySquareMeters, propertyRooms); Assert.Equal(property.Number, propertyNumber); Assert.Equal(property.SquareMeters, propertySquareMeters); Assert.Equal(property.Rooms, propertyRooms); }
public void CreateProperties() { var resFactory = new ResidentialFactory(); var transFactory = new TransportFactory(); var utilFactory = new UtilityFactory(); var genericFactory = new PropertyFactory(); var luckFactory = new LuckFactory(); try { var propertyDetails = _fileReader.ReadPropertyDetailsFromCSV(); // Add the properties to the board foreach (var propertyDetail in propertyDetails) { switch (propertyDetail.Type.ToLower()) { case "luck": Board.Access() .AddProperty(luckFactory.create(propertyDetail.Name, propertyDetail.IsPenalty, propertyDetail.Amount)); break; case "residential": Board.Access() .AddProperty(resFactory.create(propertyDetail.Name, propertyDetail.Price, propertyDetail.Rent, propertyDetail.HouseCost, propertyDetail.HouseColour)); break; case "transport": Board.Access().AddProperty(transFactory.create(propertyDetail.Name)); break; case "utility": Board.Access().AddProperty(utilFactory.create(propertyDetail.Name)); break; case "generic": Board.Access().AddProperty(genericFactory.Create(propertyDetail.Name)); break; } } Console.WriteLine("Properties have been setup"); } catch (Exception ex) { Console.WriteLine("Oops, something went wrong setting up the properties: {0}", ex.Message); } }
/// <summary> /// Возвращает описание контрола SampleCheckBox /// </summary> private ControlTypeDescription GetSampleCheckBoxDescription() { var standardCssClass = PropertyFactory.GetStandardCssClassProperty(); // Получаем свойство StandardCssClass standardCssClass.DefaultValue = "sample-checkbox"; // Изменяем значение по умолчанию var dataFieldProperty = PropertyFactory.GetDataFieldProperty(); dataFieldProperty.Editor = typeof(BooleanMetadataEditor); // Создаем описание контрола, который будет доступен по имени PartnerCheckBox var partnerCheckBox = new ControlTypeDescription(Constants.SampleCheckBox.ClassName) { DisplayName = Resources.ControlTypes_SampleCheckBox, // Отображаемое наименование контрола в окне конструктора разметок ControlGroupDisplayName = Resources.ControlGroup_Samples, // Название группы в конструкторе разметок PropertyDescriptions = // Содержит перечень свойств, которыми обладает контрол { PropertyFactory.GetNameProperty(), // Наименование экземпляра контрола PropertyFactory.GetTipProperty(), // Текст подсказки при наведении на контрол PropertyFactory.GetLabelTextProperty(), // Текст метки PropertyFactory.GetVisibilityProperty(), // Видимость контрола PropertyFactory.GetCustomCssClassesProperty(), // Пользовательские css классы PropertyFactory.GetTabStopProperty(), // Переход по tab standardCssClass, // Базовый css класс контрола PropertyFactory.GetDisabledProperty(), // Редактирование контрола // Блок свойств Binding PropertyFactory.GetDataSourceProperty(), // Источник данных (отображается только в конструкторе) dataFieldProperty, // Поле данных (отображается только в конструкторе) PropertyFactory.GetBindingProperty(), // Свойство binding (не отображается в конструкторе) PropertyFactory.GetEditOperationProperty(), // Режим редактирования (отображается только в конструкторе) PropertyFactory.Create(Constants.SampleCheckBox.DefaultValue), // Свойство DefaultValue (было добавлено ранее этим расширением) PropertyFactory.CreateEvent(Constants.SampleCheckBox.EventChecked, "ControlTypes_EventCheckedProperty"), // Событие EventChecked, отображаемое наименование свойства содержится в файле ресурсов по ключу ControlTypes_EventCheckedProperty PropertyFactory.CreateEvent(Constants.SampleCheckBox.EventUnchecked, "ControlTypes_EventUncheckedProperty") // Событие EventUnchecked }, // GetAllowedOperations = AllowedOperationsStorage.GetAllowedOperations(Constants.AllowedOperations.AllowCreateInEditLayoutsOnly) // Указывает, что контрол доступен только в разметках редактирования }; return(partnerCheckBox); }
public void DictionaryPropertyTest() { var factory = new PropertyFactory(); var model = factory.Create(typeof(Hoge), "Root"); model.IsInstanceOf <ClassProperty>(); var classModel = model as ClassProperty; var dicModel = classModel.Members.First(x => x.PropertyInfo.Name == nameof(Hoge.Ints)); dicModel.IsInstanceOf <ComplicateCollectionProperty>(); var collectionModel = dicModel as ComplicateCollectionProperty; var prop = collectionModel.AddNewElement(); Assert.AreEqual(typeof(KeyValuePair <string, int>), prop.ValueType); prop.IsInstanceOf <StructProperty>(); var kvpModel = prop as StructProperty; //kvpModel.Members.First(x => x.PropertyInfo.Name == "Key").Value.Value = "Hash"; //kvpModel.Members.First(x => x.PropertyInfo.Name == "Value").Value.Value = 123; }
public void RoutingTest() { var factory = new PropertyFactory(); var model = (ClassProperty)factory.Create(typeof(Hoge), "Hoge"); var xProp = (IntProperty)model.Members.First(x => x.PropertyInfo.Name == "X"); var fugaProp = (ClassProperty)model.Members.First(x => x.PropertyInfo.Name == "Fuga"); var yProp = (IntProperty)fugaProp.Members.First(x => x.PropertyInfo.Name == "Y"); var fooProp = (ClassProperty)fugaProp.Members.First(x => x.PropertyInfo.Name == "Foo"); var zProp = (IntProperty)fooProp.Members.First(x => x.PropertyInfo.Name == "Z"); xProp.IntValue.Value = 16; yProp.IntValue.Value = 64; zProp.IntValue.Value = 256; var router = new ViewModelRouter(new ViewModelFactory(factory)); Assert.AreEqual(xProp.IntValue.Value, router.GetIntProperty(model, "X").Value); Assert.AreEqual(yProp.IntValue.Value, router.GetIntProperty(model, "Fuga.Y").Value); Assert.AreEqual(zProp.IntValue.Value, router.GetIntProperty(model, "Fuga.Foo.Z").Value); }
// Возвращает описание контрола SampleCheckBox private ControlTypeDescription GetHyperCommentsDescription() { var standardCssClass = PropertyFactory.GetStandardCssClassProperty(); // Получаем свойство StandardCssClass standardCssClass.DefaultValue = "hyper-comments"; // Изменяем значение по умолчанию var hyperComments = new ControlTypeDescription(Constants.HyperComments.ClassName) { DisplayName = Resources.ControlTypes_HyperComments, // Отображаемое наименование контрола в окне конструктора разметок ControlGroupDisplayName = Resources.ControlGroup_Samples, PropertyDescriptions = // Содержит перечень свойств, которыми обладает контрол { PropertyFactory.GetNameProperty(), // Наименование экземпляра контрола standardCssClass, // Базовый css класс контрола PropertyFactory.Create(Constants.HyperComments.WidgetId), // Свойство WidgetId (было добавлено ранее этим расширением) }, GetAllowedOperations = AllowedOperationsStorage.GetAllowedOperations(Constants.AllowedOperations.AllowCreateInViewLayoutsOnly) // Указывает, что контрол доступен только в разметках просмотра }; return(hyperComments); }
public IProperty GetByPin(string pin) { FVCP.Persistence.EF.Property dbProperty = null; using (var db = new PropertyEntities()) { dbProperty = db.Properties .Include(x => x.PropertyAddress) .Include(x => x.PropertyClass) .Include(x => x.PropertyTags) .Include(x => x.Township) .FirstOrDefault(x => x.Pin == pin); } if (dbProperty == null) { return(null); } PropertyDTO dto = PropertyRepository.MapFieldValues(dbProperty); PropertyFactory myFact = new PropertyFactory(); IProperty retVal = myFact.Create(dto); return(retVal); }
private void TestCreateInstance <Expected>(Type type) { var factory = new PropertyFactory(); factory.Create(type, "Test").IsInstanceOf <Expected>(); }
public void OnInternalProjectType() { var factory = new PropertyFactory(); var obj = factory.Create(typeof(InternalProject), "Test1"); }
public void should_throw_if_path_empty() { Assert.Throws <ArgumentException>(() => PropertyFactory.Create(typeof(Animal), "")); }
public void should_throw_if_type_is_null() { Assert.Throws <ArgumentNullException>(() => PropertyFactory.Create(null, "Nothing")); }
internal static void Build() { if (readProps != null) { return; // completely built and ready for use } #if CF // no wait option on CF if (!Monitor.TryEnter(lockToken)) #else // give it a few seconds on regular .NET if (!Monitor.TryEnter(lockToken, 5000)) #endif { throw new InvalidOperationException("Possible deadlock detected preparing serializer for " + typeof(T).Name + "; try using Serializer.PrepareSerializer to initialize this type at application startup."); } try { if (readProps != null || subclasses != null) { // readProps != null : double-checked locking // readProps == null, but subclasses != null : // this scenario means that we are in the process of building the // serializer; since we hold the lock, this must be re-entrancy, so simply ignore //Trace.WriteLine("Re-entrant short-circuit: " + typeof(T).FullName, "ProtoBuf.Serializer:Build"); return; } //Trace.WriteLine("Building: " + typeof(T).FullName, "ProtoBuf.Serializer:Build"); // otherwise we are building the serializer for the first time; initialize // subclasses as a marker that we are in-progress subclasses = new KeyValuePair <Type, Property <T, T> > [0]; // use this to prevent recursion if (!Serializer.IsEntityType(typeof(T))) { throw new InvalidOperationException("Only data-contract classes can be processed (error processing " + typeof(T).Name + ")"); } BuildCallbacks(); List <Property <T> > readPropList = new List <Property <T> >(), writePropList = new List <Property <T> >(); List <int> tagsInUse = new List <int>(); foreach (MemberInfo prop in Serializer.GetProtoMembers(typeof(T))) { string name; DataFormat format; int tag; MemberSerializationOptions options; if (!Serializer.TryGetTag(prop, out tag, out name, out format, out options)) { continue; // didn't recognise this as a usable property } // check for duplicates if (tagsInUse.Contains(tag)) { throw new InvalidOperationException( string.Format("Duplicate tag {0} detected in {1}", tag, name)); } tagsInUse.Add(tag); Property <T> actualProp = PropertyFactory.Create <T>(prop); writePropList.Add(actualProp); readPropList.Add(actualProp); foreach (Property <T> altProp in actualProp.GetCompatibleReaders()) { if (altProp.Tag != actualProp.Tag) { throw new ProtoException("Alternative readers must handle the same tag"); } foreach (Property <T> tmp in readPropList) { if (tmp.FieldPrefix == altProp.FieldPrefix) { throw new ProtoException("Alternative readers must handle different wire-types"); } } readPropList.Add(altProp); } } #if CF2 CrapSort(readPropList, delegate(Property <T> x, Property <T> y) { return(x.FieldPrefix.CompareTo(y.FieldPrefix)); }); CrapSort(writePropList, delegate(Property <T> x, Property <T> y) { return(x.FieldPrefix.CompareTo(y.FieldPrefix)); }); #else readPropList.Sort(delegate(Property <T> x, Property <T> y) { return(x.FieldPrefix.CompareTo(y.FieldPrefix)); }); writePropList.Sort(delegate(Property <T> x, Property <T> y) { return(x.FieldPrefix.CompareTo(y.FieldPrefix)); }); #endif List <KeyValuePair <Type, Property <T, T> > > subclassList = new List <KeyValuePair <Type, Property <T, T> > >(); foreach (ProtoIncludeAttribute pia in Attribute.GetCustomAttributes(typeof(T), typeof(ProtoIncludeAttribute), false)) { Type subclassType = pia.ResolveKnownType(typeof(T).Assembly); if (subclassType == null) { throw new ProtoException("Unable to identify known-type for ProtoIncludeAttribute: " + pia.KnownTypeName); } if (subclassType.BaseType != typeof(T)) { throw new ProtoException(string.Format( "Known-type {0} for ProtoIncludeAttribute must be a direct subclass of {1}", subclassType.Name, typeof(T).Name)); } Property <T, T> prop; switch (pia.DataFormat) { case DataFormat.Default: prop = (Property <T, T>) PropertyUtil <T> .CreateTypedProperty("CreatePropertyMessageString", typeof(T), typeof(T), subclassType); break; case DataFormat.Group: prop = (Property <T, T>) PropertyUtil <T> .CreateTypedProperty("CreatePropertyMessageGroup", typeof(T), typeof(T), subclassType); break; default: throw new ProtoException("Invalid ProtoIncludeAttribute data-format: " + pia.DataFormat); } // check for duplicates if (tagsInUse.Contains(pia.Tag)) { throw new InvalidOperationException( string.Format("Duplicate tag {0} detected in sub-type {1}", pia.Tag, subclassType.Name)); } tagsInUse.Add(pia.Tag); prop.Init(pia.Tag, pia.DataFormat, PropertyFactory.GetPassThru <T>(), null, true, null); subclassList.Add(new KeyValuePair <Type, Property <T, T> >(subclassType, prop)); } subclasses = subclassList.ToArray(); writeProps = writePropList.ToArray(); readProps = readPropList.ToArray(); // this must be last; this lets other threads see the data } catch (Exception ex) { readProps = writeProps = null; subclasses = null; Debug.WriteLine("Build() failed for type: " + typeof(T).AssemblyQualifiedName); Debug.WriteLine(ex); throw; } finally { Monitor.Exit(lockToken); } }