Example #1
0
 public static void SelectDropDown(string element, string value, PropertyType elementtype)
 {
     if (elementtype == PropertyType.Id)
         new SelectElement(PropertiesCollection.driver.FindElement(By.Id(element))).SelectByText(value);
     if (elementtype == PropertyType.Name)
         new SelectElement(PropertiesCollection.driver.FindElement(By.Name(element))).SelectByText(value);
 }
		public XmlBamlPropertyElement(XmlBamlElement parent, PropertyType propertyType, PropertyDeclaration propertyDeclaration)
			: base(parent)
		{
			_propertyType = propertyType;
			this.propertyDeclaration = propertyDeclaration;
			this.TypeDeclaration = propertyDeclaration.DeclaringType;
		}
        private void AddHomeOnlyBannerTextArea()
        {
            var migrationName = MethodBase.GetCurrentMethod().Name;

            try
            {
                var path = HostingEnvironment.MapPath(MigrationMarkersPath + migrationName + ".txt");
                if (File.Exists(path))
                    return;

                var contentTypeService = UmbracoContext.Current.Application.Services.ContentTypeService;
                var communityContentType = contentTypeService.GetContentType("Community");
                var propertyTypeAlias = "homeOnlyBanner";
                if (communityContentType.PropertyTypeExists(propertyTypeAlias) == false)
                {
                    var textarea = new DataTypeDefinition("Umbraco.TextboxMultiple");
                    var textareaPropertyType = new PropertyType(textarea, propertyTypeAlias) { Name = "Banner (only shown on home)" };
                    communityContentType.AddPropertyType(textareaPropertyType, "Banners");
                    communityContentType.MovePropertyType("mainNotification", "Banners");
                    contentTypeService.Save(communityContentType);
                }

                string[] lines = { "" };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                LogHelper.Error<MigrationsHandler>(string.Format("Migration: '{0}' failed", migrationName), ex);
            }
        }
Example #4
0
 public PropertyInfo(PropertyData propertyData, PropertyType type, bool canAuto, bool extended)
 {
     this.canAuto = canAuto;
     this.extended = extended;
     this.propertyData = propertyData;
     this.type = type;
 }
Example #5
0
 public BizTalkContextProperty(string ns, string name, object value, PropertyType propertyType)
 {
     this.Namespace = ns;
     this.Name = name;
     this.Value = value;
     this.PropertyType = propertyType;
 }
 public UtilProperty(string desc, int data, Func<UtilProperty, bool> OnUpdate = null)
 {
     this.Description = desc;
     this.Data = OriginalData = data;
     this.Type = PropertyType.Integer;
     this.OnUpdate = OnUpdate;
 }
Example #7
0
 public Property(int id, Guid version, PropertyType propertyType, object value)
 {
     Id = id;
     _propertyType = propertyType;
     _version = version;
     Value = value;
 }
 public AddNewPropertyToForm(Guid formId, Guid propertyId, PropertyType type, string name)
 {
     FormId = formId;
     PropertyId = propertyId;
     Type = type;
     Name = name;
 }
Example #9
0
 public PropertyData(Guid formId, Guid propertyId, string name, PropertyType type)
 {
     FormId     = formId;
     PropertyId = propertyId;
     Name       = name;
     Type       = type;
 }
Example #10
0
 public void SetType(string typeName)
 {
   switch (typeName)
   {
     case "string":
     case "text":
     case "sequence":
       this.Type = PropertyType.text;
       break;
     case "integer":
     case "float":
     case "decimal":
       this.Type = PropertyType.number;
       break;
     case "date":
       this.Type = PropertyType.date;
       break;
     case "item":
       this.Type = PropertyType.item;
       break;
     case "list":
     case "filter list":
       this.Type = PropertyType.list;
       break;
     default:
       this.Type = PropertyType.unknown;
       break;
   }
 }
 public RuleParameterAttribute(string key, PropertyType type, string description, string defaultValue)
 {
     Key = key;
     Description = description;
     Type = type;
     DefaultValue = defaultValue;
 }
        public Property createProperty(String name, PropertyType type, String country, String street, int number, bool savePropertyToFile)
        {
            Address address;
            Property property;

            if (number >= 0)
            {
                address = new Address(country, street, number);
            }
            else
            {
                address = new Address(country, street);
            }

            property = new Property(name, type, address);

            try
            {
                if (savePropertyToFile)
                {
                    propertyRepository.save(property);
                }

                return property;
            }
            catch (ValidationException)
            {
                log.Info("Property validation exception");
            }

            return null;
        }
Example #13
0
        public List<PropertyInfo> SearchProperties(PropertyType propertyType, string address, int? minPrice, int? maxPrice)
        {
            using (var connection = GetOpenConnection())
            {
                var sql = @"select * from PropertyInfo
                               where 1 = 1";
                if (propertyType == PropertyType.Rent || propertyType == PropertyType.Sale)
                {
                    sql += @" and PropertyType = @propertyType";
                }
                if (!String.IsNullOrWhiteSpace(address))
                {
                    sql += @" and Address like CONCAT('%', @address, '%')";
                }
                if (minPrice.HasValue && maxPrice.HasValue)
                {
                    sql += @" and Price between @minPrice and @maxPrice";
                }
                sql += @" select * from Photo";

                List<PropertyInfo> propertyInfos;
                using (var multi = connection.QueryMultiple(sql, new { propertyType=propertyType, address = address, minPrice = minPrice, maxPrice = maxPrice }))
                {
                    propertyInfos = multi.Read<PropertyInfo>().ToList();
                    var photos = multi.Read<Photo>();
                    propertyInfos.ForEach((p) =>
                    {
                        p.Photos = photos.Where(photo => photo.PropertyId == p.Id).ToList();
                    });
                };
                return propertyInfos;
            }
        }
        private static bool PropertyRead(ConfigResource resource, PropertyType propertyType, Queue<string> keyQueue, string key, string val)
        {
            bool success = false;
            if (config != null)
            {
                switch (propertyType)
                {
                    case PropertyType.Property:
                        success = true;
                        ApplyProperty(keyQueue, key, val);
                        break;
                    case PropertyType.If:
                        if (config.Properties.ContainsKey(val))
                        {
                            success = !Convert.ToBoolean(config.Properties[val]);
                        }
                        break;
                    case PropertyType.Import:
                        ConfigResource res = resource.GetLocalConfigResource(string.Format(@"{0}.properties", val));
                        success = res.Exists;
                        break;
                }
            }

            return success;
        }
Example #15
0
 private static string PropertyTypeToRmValue(PropertyType pt)
 {
     switch (pt)
     {
         case PropertyType.Bungalow:
             return "12";
         case PropertyType.Flat:
             return "8";
         case PropertyType.Studio:
             return "9";
         case PropertyType.House://This is depreciated
             return "3";//treat all properties using the legacy "House" type as semi-detatched
         case PropertyType.Unknown:
             return "0";
         case PropertyType.TerracedHouse:
             return "1";
         case PropertyType.EndOfTerraceHouse:
             return "2";
         case PropertyType.SemiDetachedHouse:
             return "3";
         case PropertyType.DetachedHouse:
             return "4";
         default:
             return "0";//Unknown
     }
 }
        /// <summary>
        /// Performs the package action during package installation
        /// </summary>
        /// <param name="packageName">
        /// The package name.
        /// </param>
        /// <param name="xmlData">
        /// The xml data.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/> indicating success of failure.
        /// </returns>
        public bool Execute(string packageName, XmlNode xmlData)
        {
            var dtd = _services.DataTypeService.GetDataTypeDefinitionById(-88);

            // Create the MerchelloCustomer MemberType
            var mt = new MemberType(-1)
            {
                Alias = MemberTypeName,
                Name = MemberTypeName,
                AllowedAsRoot = true
            };

            var fn = new PropertyType(dtd) { Alias = "firstName", Name = "First name" };
            var ln = new PropertyType(dtd) { Alias = "lastName", Name = "Last name" };

            mt.AddPropertyType(fn);
            mt.AddPropertyType(ln);

            mt.SetMemberCanEditProperty("firstName", true);
            mt.SetMemberCanEditProperty("lastName", true);
            mt.SetMemberCanViewProperty("firstName", true);
            mt.SetMemberCanViewProperty("lastName", true);

            _services.MemberTypeService.Save(mt);

            // Add the MemberGroup
            var mg = new MemberGroup() { Name = MemberGroupName };

            _services.MemberGroupService.Save(mg);

            return true;
        }
Example #17
0
        public Property(PropertyType propertyType, IntPtr value)
        {
            assignValues();

            this.propertyType = propertyType;
            this.IntPtrValue = value;
        }
        public string GetImportValue(PropertyType propType, string content)
        {
            LogHelper.Debug<ContentDataTypeMapper>("Mapping a datatype: {0} {1}", () => propType.DataTypeDefinitionId, () => content);

            var prevalues =
                ApplicationContext.Current.Services.DataTypeService.GetPreValuesCollectionByDataTypeId(propType.DataTypeDefinitionId)
                                  .PreValuesAsDictionary;

            if (prevalues != null && prevalues.Count > 0)
            {
                var importValue = "";

                var values = content.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                foreach(var alias in values)
                {
                    string preValue = prevalues.Where(kvp => kvp.Key == alias)
                                        .Select(kvp => kvp.Value.Id.ToString())
                                        .SingleOrDefault();

                    if (!String.IsNullOrWhiteSpace(preValue))
                    {
                        importValue = string.Format("{0}{1},", importValue, preValue);
                    }
                    else
                    {
                        importValue = string.Format("{0}{1},", alias, preValue);
                    }
                }
                LogHelper.Debug<ContentDataTypeMapper>("Setting value {0} to {1}", () => content, () => importValue.Trim(","));
                return importValue.Trim(",");
            }
            return content;
        }
Example #19
0
        public Property(PropertyType propertyType, String value)
        {
            assignValues();

            this.propertyType = propertyType;
            this.StringValue = value;
        }
 public UtilProperty(string desc, SolidBrush data, Func<UtilProperty, bool> OnUpdate = null)
 {
     this.OnUpdate = OnUpdate;
     this.Description = desc;
     this.Data = OriginalData = data;
     this.Type = PropertyType.Brush;
 }
Example #21
0
        public Property(PropertyType propertyType, uint value)
        {
            assignValues();

            this.propertyType = propertyType;
            this.UintValue = value;
        }
 public void WhenINeedCompanyToHaveProperty(string companyName, PropertyType type, string propertyName)
 {
     context.For<Company>(companyName)
            .Exists(propertyName, company => company.CompanyProperty);
     context.For<CompanyProperty>(propertyName)
            .IsTrue(property => property.Type == type);
 }
            public override object ConvertDbToEditor(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
            {
                if(property.Value == null || property.Value.ToString() == "")
                    return string.Empty;

                var archetype = ArchetypeHelper.Instance.DeserializeJsonToArchetype(property.Value.ToString(), propertyType.DataTypeDefinitionId);

                foreach (var fieldset in archetype.Fieldsets)
                {
                    foreach (var propDef in fieldset.Properties.Where(p => p.DataTypeGuid != null))
                    {
                        try
                        {
                            var dtd = ArchetypeHelper.Instance.GetDataTypeByGuid(Guid.Parse(propDef.DataTypeGuid));
                            var propType = new PropertyType(dtd) {Alias = propDef.Alias};
                            var prop = new Property(propType, propDef.Value);
                            var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias);
                            propDef.Value = propEditor.ValueEditor.ConvertDbToEditor(prop, propType, dataTypeService);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error<ArchetypePropertyValueEditor>(ex.Message, ex);
                        }
                    }
                }

                return archetype;
            }
Example #24
0
 public static void Replace(PropertyInstance propertyInstance, PropertyType newType)
 {
     TerrainInstance t = propertyInstance.terrainInstance;
     Destroy( t.property.gameObject );
     t.property = null;
     Create( t, newType );
 }
 /// <summary>
 /// Defines a property in a frame.
 /// </summary>
 /// <param name="byteCount">Set to zero to read all bytes until the end of the buffer / write all bytes in the array.</param>
 /// <param name="propertyName">The name of the property. Set to empty to ignore this property.</param>
 /// <param name="propertyType">The type of this property.</param>
 /// <param name="readOnly"></param>
 public PropertyDescriptor(byte byteCount, string propertyName, PropertyType propertyType, bool readOnly)
 {
     ByteCount = byteCount;
     PropertyName = propertyName;
     PropertyType = propertyType;
     ReadOnly = readOnly;
 }
        public static Property FindByPropertyType(Entity entity, PropertyType propertyType)
        {
            if (entity == null) throw new ArgumentNullException("entity");

            foreach (var property in entity.AllProperties)
            {
                if (property.GetAttributeValue("propertyType", Constants.NamespaceUri, PropertyType.None) == propertyType)
                {
                    return property;
                }
            }

            PropertyTypeCompatibility compatibility = (PropertyTypeCompatibility) propertyType;
            foreach (var property in entity.AllProperties)
            {
                var value = property.GetAttributeValue("propertyType", Constants.NamespaceUri, PropertyTypeCompatibility.None);
                if (value == compatibility ||
                    (value == PropertyTypeCompatibility.User && propertyType == PropertyType.UserClaimUser) ||
                    (value == PropertyTypeCompatibility.User && propertyType == PropertyType.UserLoginUser))
                {
                    return property;
                }
            }

            return null;
        }
Example #27
0
 public static void EnterText(string element, string value, PropertyType elementtype)
 {
     if (elementtype == PropertyType.Id)
         PropertiesCollection.driver.FindElement(By.Id(element)).SendKeys(value);
     if (elementtype == PropertyType.Name)
         PropertiesCollection.driver.FindElement(By.Name(element)).SendKeys(value);
 }
        public void ParsePropertyType_ReturnsCorrectString(PropertyType propertyType, string expected)
        {
            //act
            var result = EnumFactory.ParsePropertyType(propertyType);

            //assert
            result.Should().Be(expected);
        }
            /// <summary>
            /// Format the data for the editor
            /// </summary>
            /// <param name="property"></param>
            /// <param name="propertyType"></param>
            /// <param name="dataTypeService"></param>
            /// <returns></returns>
            public override object ConvertDbToEditor(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
            {
                if (property.Value == null)
                    return null;

                var parsed = MacroTagParser.FormatRichTextPersistedDataForEditor(property.Value.ToString(), new Dictionary<string, string>());
                return parsed;
            }
 /// <summary>
 /// Initializes a new instance of the PropertyNameObject class.
 /// </summary>
 /// <param name="displayName">A string value indicates the name of property.</param>
 /// <param name="longId">A unsigned integer value indicates property long ID (LID) of specified property.</param>
 /// <param name="propertySet">A string indicates property set of specified property.</param>
 /// <param name="dataType">The date type of specified property.</param>
 public PropertyNameObject(PropertyNames displayName, uint longId, string propertySet, PropertyType dataType)
 {
     this.displayName = displayName;
     this.propertyName.Kind = 0x00;
     this.propertyName.Guid = new Guid(propertySet).ToByteArray();
     this.propertyName.LID = longId;
     this.propertyType = dataType;
 }
 public void Delete(PropertyType entity)
 {
     _context.PropertyTypes.Attach(entity);
     _context.Entry <PropertyType>(entity).State = System.Data.EntityState.Deleted;
     _context.SaveChanges();
 }
Example #32
0
 private static uint ComposeRawValue(PropertyType type, uint value)
 {
     InternalDebug.Assert(value <= ValueMask);
     return(((uint)type << TypeShift) | value);
 }
        private void Init()
        {
            Current.Reset();
            Current.UnlockConfigs();
            Current.Configs.Add(SettingsForTests.GenerateMockUmbracoSettings);
            Current.Configs.Add <IGlobalSettings>(() => new GlobalSettings());
            var globalSettings = Current.Configs.Global();

            // create a content node kit
            var kit = new ContentNodeKit
            {
                ContentTypeId = 2,
                Node          = new ContentNode(1, Guid.NewGuid(), 0, "-1,1", 0, -1, DateTime.Now, 0),
                DraftData     = new ContentData
                {
                    Name        = "It Works2!",
                    Published   = false,
                    TemplateId  = 0,
                    VersionId   = 2,
                    VersionDate = DateTime.Now,
                    WriterId    = 0,
                    Properties  = new Dictionary <string, PropertyData[]> {
                        { "prop", new[]
                          {
                              new PropertyData {
                                  Culture = "", Segment = "", Value = "val2"
                              },
                              new PropertyData {
                                  Culture = "fr-FR", Segment = "", Value = "val-fr2"
                              },
                              new PropertyData {
                                  Culture = "en-UK", Segment = "", Value = "val-uk2"
                              },
                              new PropertyData {
                                  Culture = "dk-DA", Segment = "", Value = "val-da2"
                              },
                              new PropertyData {
                                  Culture = "de-DE", Segment = "", Value = "val-de2"
                              }
                          } }
                    },
                    CultureInfos = new Dictionary <string, CultureVariation>
                    {
                        // draft data = everything, and IsDraft indicates what's edited
                        { "fr-FR", new CultureVariation {
                              Name = "name-fr2", IsDraft = true, Date = new DateTime(2018, 01, 03, 01, 00, 00)
                          } },
                        { "en-UK", new CultureVariation {
                              Name = "name-uk2", IsDraft = true, Date = new DateTime(2018, 01, 04, 01, 00, 00)
                          } },
                        { "dk-DA", new CultureVariation {
                              Name = "name-da2", IsDraft = true, Date = new DateTime(2018, 01, 05, 01, 00, 00)
                          } },
                        { "de-DE", new CultureVariation {
                              Name = "name-de1", IsDraft = false, Date = new DateTime(2018, 01, 02, 01, 00, 00)
                          } }
                    }
                },
                PublishedData = new ContentData
                {
                    Name        = "It Works1!",
                    Published   = true,
                    TemplateId  = 0,
                    VersionId   = 1,
                    VersionDate = DateTime.Now,
                    WriterId    = 0,
                    Properties  = new Dictionary <string, PropertyData[]> {
                        { "prop", new[]
                          {
                              new PropertyData {
                                  Culture = "", Segment = "", Value = "val1"
                              },
                              new PropertyData {
                                  Culture = "fr-FR", Segment = "", Value = "val-fr1"
                              },
                              new PropertyData {
                                  Culture = "en-UK", Segment = "", Value = "val-uk1"
                              }
                          } }
                    },
                    CultureInfos = new Dictionary <string, CultureVariation>
                    {
                        // published data = only what's actually published, and IsDraft has to be false
                        { "fr-FR", new CultureVariation {
                              Name = "name-fr1", IsDraft = false, Date = new DateTime(2018, 01, 01, 01, 00, 00)
                          } },
                        { "en-UK", new CultureVariation {
                              Name = "name-uk1", IsDraft = false, Date = new DateTime(2018, 01, 02, 01, 00, 00)
                          } },
                        { "de-DE", new CultureVariation {
                              Name = "name-de1", IsDraft = false, Date = new DateTime(2018, 01, 02, 01, 00, 00)
                          } }
                    }
                }
            };

            // create a data source for NuCache
            var dataSource = new TestDataSource(kit);

            var runtime = Mock.Of <IRuntimeState>();

            Mock.Get(runtime).Setup(x => x.Level).Returns(RuntimeLevel.Run);

            // create data types, property types and content types
            var dataType = new DataType(new VoidEditor("Editor", Mock.Of <ILogger>()))
            {
                Id = 3
            };

            var dataTypes = new[]
            {
                dataType
            };

            _propertyType = new PropertyType("Umbraco.Void.Editor", ValueStorageType.Nvarchar)
            {
                Alias = "prop", DataTypeId = 3, Variations = ContentVariation.Culture
            };
            _contentType = new ContentType(-1)
            {
                Id = 2, Alias = "alias-ct", Variations = ContentVariation.Culture
            };
            _contentType.AddPropertyType(_propertyType);

            var contentTypes = new[]
            {
                _contentType
            };

            var contentTypeService = Mock.Of <IContentTypeService>();

            Mock.Get(contentTypeService).Setup(x => x.GetAll()).Returns(contentTypes);
            Mock.Get(contentTypeService).Setup(x => x.GetAll(It.IsAny <int[]>())).Returns(contentTypes);

            var contentTypeServiceBaseFactory = Mock.Of <IContentTypeBaseServiceProvider>();

            Mock.Get(contentTypeServiceBaseFactory).Setup(x => x.For(It.IsAny <IContentBase>())).Returns(contentTypeService);

            var dataTypeService = Mock.Of <IDataTypeService>();

            Mock.Get(dataTypeService).Setup(x => x.GetAll()).Returns(dataTypes);

            // create a service context
            var serviceContext = ServiceContext.CreatePartial(
                dataTypeService: dataTypeService,
                memberTypeService: Mock.Of <IMemberTypeService>(),
                memberService: Mock.Of <IMemberService>(),
                contentTypeService: contentTypeService,
                localizationService: Mock.Of <ILocalizationService>()
                );

            // create a scope provider
            var scopeProvider = Mock.Of <IScopeProvider>();

            Mock.Get(scopeProvider)
            .Setup(x => x.CreateScope(
                       It.IsAny <IsolationLevel>(),
                       It.IsAny <RepositoryCacheMode>(),
                       It.IsAny <IEventDispatcher>(),
                       It.IsAny <bool?>(),
                       It.IsAny <bool>(),
                       It.IsAny <bool>()))
            .Returns(Mock.Of <IScope>);

            // create a published content type factory
            var contentTypeFactory = new PublishedContentTypeFactory(
                Mock.Of <IPublishedModelFactory>(),
                new PropertyValueConverterCollection(Array.Empty <IPropertyValueConverter>()),
                dataTypeService);

            // create a variation accessor
            _variationAccesor = new TestVariationContextAccessor();

            // at last, create the complete NuCache snapshot service!
            var options = new PublishedSnapshotService.Options {
                IgnoreLocalDb = true
            };

            _snapshotService = new PublishedSnapshotService(options,
                                                            null,
                                                            runtime,
                                                            serviceContext,
                                                            contentTypeFactory,
                                                            null,
                                                            new TestPublishedSnapshotAccessor(),
                                                            _variationAccesor,
                                                            Mock.Of <IUmbracoContextAccessor>(),
                                                            Mock.Of <ILogger>(),
                                                            scopeProvider,
                                                            Mock.Of <IDocumentRepository>(),
                                                            Mock.Of <IMediaRepository>(),
                                                            Mock.Of <IMemberRepository>(),
                                                            new TestDefaultCultureAccessor(),
                                                            dataSource,
                                                            globalSettings,
                                                            new SiteDomainHelper(),
                                                            Mock.Of <IEntityXmlSerializer>(),
                                                            Mock.Of <IPublishedModelFactory>(),
                                                            new UrlSegmentProviderCollection(new[] { new DefaultUrlSegmentProvider() }));

            // invariant is the current default
            _variationAccesor.VariationContext = new VariationContext();
        }
Example #34
0
        internal object GetConstantValue(bool raw)
        {
            object?defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw);

            if (defaultValue == DBNull.Value)
            {
                // Arg_EnumLitValueNotFound -> "Literal value was not found."
                throw new InvalidOperationException(SR.Arg_EnumLitValueNotFound);
            }

            return(defaultValue !);
        }
Example #35
0
 public static uint GetRawType(PropertyType type)
 {
     return((uint)type << TypeShift);
 }
Example #36
0
 public override object GetValue(string culture = null, string segment = null) => PropertyType.ConvertInterToObject(_owner, ReferenceCacheLevel, InterValue, _preview);
Example #37
0
        /// <summary>
        /// Creates the specific CustomDocumentProperty from the given propertyType with the given value
        /// </summary>
        /// <returns>returns null if property is not set</returns>
        public CustomDocumentProperty CreateProperty(object propertyValue, PropertyType propertyType)
        {
            if (propertyValue == null)
            {
                throw new ArgumentNullException(nameof(propertyValue));
            }

            var returnedProperty = new CustomDocumentProperty();
            var propSet          = false;

            // Calculate the correct type:
            switch (propertyType)
            {
            case PropertyType.DateTime:
                // Make sure you were passed a real date,
                // and if so, format in the correct way.
                // The date/time value passed in should
                // represent a UTC date/time.
                if (propertyValue is DateTime)
                {
                    returnedProperty.VTFileTime = new VTFileTime($"{Convert.ToDateTime(propertyValue):s}Z");
                    propSet = true;
                }

                break;

            case PropertyType.NumberInteger:
                if (propertyValue is int)
                {
                    returnedProperty.VTInt32 = new VTInt32(propertyValue.ToString());
                    propSet = true;
                }

                break;

            case PropertyType.NumberDouble:
                if (propertyValue is double)
                {
                    returnedProperty.VTFloat = new VTFloat(propertyValue.ToString());
                    propSet = true;
                }

                break;

            case PropertyType.Text:
                returnedProperty.VTLPWSTR = new VTLPWSTR(propertyValue.ToString());
                propSet = true;

                break;

            case PropertyType.YesNo:
                if (propertyValue is bool)
                {
                    returnedProperty.VTBool = new VTBool(Convert.ToBoolean(propertyValue).ToString().ToLower());
                    propSet = true;
                }
                break;

            default:
                throw new ArgumentException($"unknown {nameof(propertyType)} [{propertyType}]");
            }

            return(propSet ? returnedProperty : null);
        }
Example #38
0
 public Property(string name, PropertyType type, object value)
 {
     Name  = name;
     Type  = type;
     Value = value;
 }
 virtual protected void DeserializeExtraProperties(TObject item, PropertyType property, XElement node)
 {
     // no op.
 }
Example #40
0
        public void TestGetLinkedEntitesForContent()
        {
            // arrange
            var content = new Mock <IContent>();

            var propTypeCp1 = new PropertyType(
                Constants.PropertyEditors.ContentPickerAlias,
                DataTypeDatabaseType.Integer,
                "contentPicker")
            {
                Name = "Content picker"
            };

            var propTypeCp2 = new PropertyType(
                Constants.PropertyEditors.ContentPickerAlias,
                DataTypeDatabaseType.Integer,
                "contentPicker2")
            {
                Name = "Content picker 2"
            };

            var propTypeText = new PropertyType(
                Constants.PropertyEditors.TextboxAlias,
                DataTypeDatabaseType.Nvarchar,
                "textbox")
            {
                Name = "Text box"
            };

            var propTypeCp3 = new PropertyType(
                Constants.PropertyEditors.ContentPickerAlias,
                DataTypeDatabaseType.Integer,
                "contentPicker")
            {
                Name = "Content picker"
            };

            content.SetupGet(x => x.PropertyTypes)
            .Returns(
                new List <PropertyType>()
            {
                propTypeCp1,
                propTypeText,
                propTypeCp2,
                propTypeCp3
            });

            var prop1 = new Property(propTypeCp1, 1500);
            var prop2 = new Property(propTypeCp2, 1500);
            var prop3 = new Property(propTypeCp3, 2000);

            content.SetupGet(x => x.Properties)
            .Returns(
                new PropertyCollection(
                    new List <Property>()
            {
                prop1,
                new Property(propTypeText, "Foo"),
                prop2,
                prop3,
            }));

            content.SetupGet(x => x.Id).Returns(1234);
            content.SetupGet(x => x.Name).Returns("Foo content");

            var parser = new Mock <IPropertyParser>();

            parser.Setup(x => x.GetLinkedEntities(prop1.Value))
            .Returns(new List <ILinkedEntity> {
                new LinkedDocumentEntity(1500)
            });

            parser.Setup(x => x.GetLinkedEntities(prop2.Value))
            .Returns(new List <ILinkedEntity> {
                new LinkedDocumentEntity(1500)
            });

            parser.Setup(x => x.GetLinkedEntities(prop3.Value))
            .Returns(new List <ILinkedEntity> {
                new LinkedDocumentEntity(2000)
            });

            this.serviceMock.Setup(x => x.GetParsablePropertiesForContent(content.Object))
            .Returns(
                new List <PropertyWithParser>
            {
                new PropertyWithParser(prop1, parser.Object, "Content"),
                new PropertyWithParser(prop2, parser.Object, "Meta"),
                new PropertyWithParser(prop3, parser.Object, "Content"),
            });

            // act
            var result = this.service.GetLinkedEntitesForContent(content.Object);

            // verify
            this.serviceMock.Verify(x => x.GetParsablePropertiesForContent(content.Object), Times.Once);
            Assert.IsNotNull(result);

            var linkedEntities = result;

            Assert.AreEqual(2, linkedEntities.Count);

            Assert.IsTrue(result.ContainsKey("Content picker [[Content]]"));
            Assert.IsTrue(result.ContainsKey("Content picker 2 [[Meta]]"));
            Assert.IsTrue(
                result["Content picker [[Content]]"].ToList().Exists(x => x.LinkedEntityType == LinkedEntityType.Document && x.Id == 1500));
            Assert.IsTrue(
                result["Content picker [[Content]]"].ToList().Exists(x => x.LinkedEntityType == LinkedEntityType.Document && x.Id == 2000));
            Assert.IsTrue(
                result["Content picker 2 [[Meta]]"].ToList().Exists(x => x.LinkedEntityType == LinkedEntityType.Document && x.Id == 1500));
        }
Example #41
0
        public void TestGetParsablePropertiesForContent()
        {
            // arrange
            var content = new Mock <IContent>();

            var dataTypeContentPicker = new DataTypeDefinition(Constants.PropertyEditors.ContentPickerAlias)
            {
                Id = 15
            };
            var dataTypeTextBox = new DataTypeDefinition(Constants.PropertyEditors.TextboxAlias)
            {
                Id = 16
            };

            var propTypeCp1 =
                new PropertyType(
                    dataTypeContentPicker,
                    "contentPicker");

            var propTypeCp2 =
                new PropertyType(
                    dataTypeContentPicker,
                    "contentPicker2");

            var propTypeText =
                new PropertyType(dataTypeTextBox, "textbox");


            var contentType = new Mock <IContentType>();

            contentType.SetupGet(x => x.CompositionPropertyGroups)
            .Returns(
                new List <PropertyGroup>
            {
                new PropertyGroup
                {
                    Name          = "Content",
                    PropertyTypes =
                        new PropertyTypeCollection(
                            new List <PropertyType> {
                        propTypeCp1, propTypeCp2, propTypeText
                    })
                },
            });

            content.SetupGet(x => x.PropertyTypes)
            .Returns(
                new List <PropertyType>()
            {
                propTypeCp1,
                propTypeText,
                propTypeCp2
            });


            content.SetupGet(x => x.Properties)
            .Returns(
                new PropertyCollection(
                    new List <Property>()
            {
                new Property(propTypeCp1, 1500),
                new Property(propTypeText, "Foo"),
                new Property(propTypeCp2, 1500)
            }));

            content.SetupGet(x => x.ContentType).Returns(contentType.Object);

            this.dataTypeService.Setup(x => x.GetDataTypeDefinitionById(15)).Returns(dataTypeContentPicker);
            this.dataTypeService.Setup(x => x.GetDataTypeDefinitionById(16)).Returns(dataTypeTextBox);

            var contetPickerParser = new Mock <IPropertyParser>();

            contetPickerParser.Setup(x => x.IsParserFor(dataTypeContentPicker)).Returns(true);
            contetPickerParser.Setup(x => x.IsParserFor(dataTypeTextBox)).Returns(false);

            this.serviceMock.Setup(x => x.GetAllPropertyParsers())
            .Returns(new List <IPropertyParser> {
                contetPickerParser.Object
            });

            // act
            var result = this.service.GetParsablePropertiesForContent(content.Object);

            // verify
            this.serviceMock.Verify(x => x.GetAllPropertyParsers(), Times.Once);
            this.dataTypeService.Verify(x => x.GetDataTypeDefinitionById(It.IsAny <int>()), Times.Exactly(3));

            Assert.IsNotNull(result);

            Assert.AreEqual(2, result.Count());
        }
Example #42
0
 internal CLRIPropertyValueImpl(PropertyType type, Object data)
 {
     _type = type;
     _data = data;
 }
Example #43
0
 public PropertyDescriptor(string name, PropertyType type, AccessLevels accessLevel)
 {
     Name        = name;
     Type        = type;
     AccessLevel = accessLevel;
 }
Example #44
0
 public virtual double OnDataFix(SkillObj self, PropertyType pType, double pValue, BuffInfo_New buffInfo, BuffConfig_New buffConfig)
 {
     return(pValue);
 }
        private PropertyType GetOrCreateProperty(TObject item,
                                                 Guid key,
                                                 string alias,
                                                 Guid definitionKey,
                                                 string propertyEditorAlias,
                                                 out bool IsNew)
        {
            logger.Debug(serializerType, "GetOrCreateProperty {0} [{1}]", key, alias);

            IsNew = false;

            var property = default(PropertyType);

            if (key != Guid.Empty)
            {
                // should we throw - not a valid sync file ?
                // or carry on with best endevours ?
                property = item.PropertyTypes.SingleOrDefault(x => x.Key == key);
            }

            if (property == null)
            {
                // we should really say if we don't have the key!
                // but lets lookup by alias.
                property = item.PropertyTypes.SingleOrDefault(x => x.Alias == alias);
            }

            var editorAlias = propertyEditorAlias;

            IDataType dataType = default(IDataType);

            if (definitionKey != Guid.Empty)
            {
                dataType = dataTypeService.GetDataType(definitionKey);
            }

            if (dataType == null && !string.IsNullOrEmpty(propertyEditorAlias))
            {
                dataType = dataTypeService.GetDataType(propertyEditorAlias);
            }

            if (dataType == null)
            {
                return(null);
            }

            // we set it here, this means if the file is in conflict (because its changed in the datatype),
            // we shouldn't reset it later on should we set the editor alias value.
            editorAlias = dataType.EditorAlias;

            // if it's null then it doesn't exist (so it's new)
            if (property == null)
            {
                if (PropertyExistsOnComposite(item, alias))
                {
                    logger.Debug(serializerType, "Cannot create property here {0} as it exist on Composition", item.Name);
                    // can't create here, its on a composite
                    return(null);
                }
                else
                {
                    property = new PropertyType(dataType, alias);
                    IsNew    = true;
                }
            }


            // thing that could break if they where blank.
            // update, only set this if its not already set (because we don't want to break things!)
            // also update it if its not the same as the datatype, (because that has to match)
            if (!property.PropertyEditorAlias.Equals(editorAlias))
            {
                logger.Debug(serializerType, "Property Editor Alias mismatch {0} != {1} fixing...", property.PropertyEditorAlias, editorAlias);
                property.PropertyEditorAlias = editorAlias;
            }

            if (property.DataTypeId != dataType.Id)
            {
                property.DataTypeId = dataType.Id;
            }

            return(property);
        }
Example #46
0
        private void UpdateDocumentType()
        {
            const string
                svgViewerEditorAlias         = "svgCustomView",
                svgViewerPropertyAlias       = "pageCustomSvgIcon",
                svgViewerPropertyName        = "Page Custom Svg Icon",
                svgViewerPropertyDescription = "Displays the page icon from the strip-menu svg file",
                svgViewerDataTypeName        = "Page Custom Svg Icon";

            try
            {
                var container   = dataTypeService.GetContainers(CONTAINER, 1).FirstOrDefault();
                var containerId = -1;

                if (container != null)
                {
                    containerId = container.Id;
                }

                var contentType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS);
                if (contentType != null)
                {
                    var exists = dataTypeService.GetDataType(svgViewerDataTypeName) != null;
                    if (!exists)
                    {
                        var notCreated = Web.Composing.Current.PropertyEditors.TryGet(svgViewerEditorAlias, out IDataEditor editor);
                        if (notCreated)
                        {
                            DataType svgDataType = new DataType(editor, containerId)
                            {
                                Name = svgViewerDataTypeName
                            };
                            dataTypeService.Save(svgDataType);
                        }
                        else
                        {
                            var firstEmbeddedResource = new SvgViewerEmbeddedResources().Resources[0];
                            if (!ContentHelper.AssetAlreadyExists(firstEmbeddedResource.FileName, firstEmbeddedResource.OutputDirectory))
                            {
                                ContentHelper.CopyPhysicalAssets(new SvgViewerEmbeddedResources());
                                ConnectorContext.AuditService.Add(AuditType.Save, 1, contentType.Id, "Resources", "Embedded Resources Copied");
                            }
                            // will need to restart the app, in order to force a refresh to attempt to create the data type again
                            throw new DataTypeNotCreatedException("In order to create the Data Type, a Reload is required");
                        }
                    }

                    if (!contentType.PropertyTypeExists(svgViewerPropertyAlias))
                    {
                        var          svgDataType     = dataTypeService.GetDataType(svgViewerPropertyName);
                        PropertyType svgPropertyType = new PropertyType(svgDataType, svgViewerPropertyAlias)
                        {
                            Name        = svgViewerPropertyName,
                            Description = svgViewerPropertyDescription,
                            Variations  = ContentVariation.Nothing
                        };
                        contentType.AddPropertyType(svgPropertyType, TAB);

                        contentTypeService.Save(contentType);
                        ConnectorContext.AuditService.Add(AuditType.Save, -1, contentType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_ALIAS}' has been updated");
                    }
                }
            }
            catch (System.Exception ex)
            {
                logger.Error(typeof(_15_UpdateGenericDocumentTypeForSvgIcons), ex.Message);
                logger.Error(typeof(_15_UpdateGenericDocumentTypeForSvgIcons), ex.StackTrace);
            }
        }
Example #47
0
            public override object ConvertDbToEditor(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
            {
                if (string.IsNullOrEmpty(property.Value?.ToString()))
                {
                    return(new object[0]);
                }

                using (_profilingLogger.DebugDuration <EmbeddedContentPropertyEditor>($"ConvertDbToEditor({property.Alias})"))
                {
                    JArray source = NestedContentHelper.ConvertFromNestedContent(JArray.Parse(property.Value.ToString()));

                    List <IContentType> contentTypes = _contentTypeService.GetAllContentTypes().ToList();
                    PreValueCollection  preValues    = dataTypeService.GetPreValuesCollectionByDataTypeId(propertyType.DataTypeDefinitionId);

                    PreValue configPreValue = preValues.PreValuesAsDictionary["embeddedContentConfig"];
                    var      config         = JsonConvert.DeserializeObject <EmbeddedContentConfig>(configPreValue.Value);

                    var items = source.ToObject <EmbeddedContentItem[]>();

                    return((from indexedItem in items.Select((item, index) => new { item, index })
                            let item = indexedItem.item
                                       let index = indexedItem.index
                                                   let configDocType = config.DocumentTypes.FirstOrDefault(x => x.DocumentTypeAlias == item.ContentTypeAlias)
                                                                       where configDocType != null
                                                                       let contentType = contentTypes.FirstOrDefault(x => x.Alias == item.ContentTypeAlias)
                                                                                         let tabs = (from pg in contentType.CompositionPropertyGroups
                                                                                                     orderby pg.SortOrder
                                                                                                     group pg by pg.Name into groupedByTabName
                                                                                                     let firstTab = groupedByTabName.First()
                                                                                                                    let propertyTypes = groupedByTabName.SelectMany(x => x.PropertyTypes)
                                                                                                                                        select new TabWithKey <EmbeddedContentPropertyDisplay>()
                    {
                        Id = firstTab.Id,
                        Key = firstTab.Key,
                        Label = UmbracoDictionaryTranslate(firstTab.Name),
                        Alias = firstTab.Key.ToString(),
                        Properties = from pt in propertyTypes
                                     orderby pt.SortOrder
                                     let value = GetPropertyValue(item.Properties, pt.Alias)
                                                 let p = GetProperty(pt, value)
                                                         where p != null
                                                         select p
                    }).ToList()
                                                                                                    where contentType != null
                                                                                                    select new EmbeddedContentItemDisplay
                    {
                        Key = item.Key,
                        AllowEditingName = configDocType.AllowEditingName == "1",
                        ContentTypeAlias = item.ContentTypeAlias,
                        ContentTypeName = UmbracoDictionaryTranslate(contentType.Name),
                        Description = UmbracoDictionaryTranslate(contentType.Description),
                        CreateDate = item.CreateDate,
                        UpdateDate = item.UpdateDate,
                        CreatorId = item.CreatorId,
                        WriterId = item.WriterId,
                        Icon = contentType.Icon,
                        Name = item.Name,
                        Published = item.Published,
                        SettingsTab = configDocType.SettingsTabKey.HasValue ? tabs.FirstOrDefault(x => x.Key == configDocType.SettingsTabKey) : null,
                        Tabs = configDocType.SettingsTabKey.HasValue ? tabs.Where(x => x.Key != configDocType.SettingsTabKey) : tabs
                    }).ToList());
                }
            }
Example #48
0
        private static T CoerceScalarValue <T>(PropertyType type, object value)
        {
            // If the property type is neither one of the coercable numeric types nor IInspectable, we
            // should not attempt coersion, even if the underlying value is technically convertable
            if (!IsCoercable(type, value) && type != PropertyType.Inspectable)
            {
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
            }

            try {
                // Try to coerce:
                //  * String <--> Guid
                //  * Numeric scalars
                if (type == PropertyType.String && typeof(T) == typeof(Guid))
                {
                    return((T)(object)Guid.Parse((string)value));
                }
                else if (type == PropertyType.Guid && typeof(T) == typeof(String))
                {
                    return((T)(object)((Guid)value).ToString("D", System.Globalization.CultureInfo.InvariantCulture));
                }
                else
                {
                    // Iterate over the numeric scalars, to see if we have a match for one of the known conversions
                    foreach (Tuple <Type, PropertyType> numericScalar in NumericScalarTypes)
                    {
                        if (numericScalar.Item1 == typeof(T))
                        {
                            return((T)Convert.ChangeType(value, typeof(T), System.Globalization.CultureInfo.InvariantCulture));
                        }
                    }
                }
            }
            catch (FormatException) {
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
            }
            catch (InvalidCastException) {
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
            }
            catch (OverflowException) {
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueCoersion", type, value, typeof(T).Name), __HResults.DISP_E_OVERFLOW);
            }

            // If the property type is IInspectable, and we have a nested IPropertyValue, then we need
            // to pass along the request to coerce the value.
            IPropertyValue ipv = value as IPropertyValue;

            if (type == PropertyType.Inspectable && ipv != null)
            {
                if (typeof(T) == typeof(Byte))
                {
                    return((T)(object)ipv.GetUInt8());
                }
                else if (typeof(T) == typeof(Int16))
                {
                    return((T)(object)ipv.GetInt16());
                }
                else if (typeof(T) == typeof(UInt16))
                {
                    return((T)(object)ipv.GetUInt16());
                }
                else if (typeof(T) == typeof(Int32))
                {
                    return((T)(object)ipv.GetUInt32());
                }
                else if (typeof(T) == typeof(UInt32))
                {
                    return((T)(object)ipv.GetUInt32());
                }
                else if (typeof(T) == typeof(Int64))
                {
                    return((T)(object)ipv.GetInt64());
                }
                else if (typeof(T) == typeof(UInt64))
                {
                    return((T)(object)ipv.GetUInt64());
                }
                else if (typeof(T) == typeof(Single))
                {
                    return((T)(object)ipv.GetSingle());
                }
                else if (typeof(T) == typeof(Double))
                {
                    return((T)(object)ipv.GetDouble());
                }
                else
                {
                    BCLDebug.Assert(false, "T in coersion function wasn't understood as a type that can be coerced - make sure that CoerceScalarValue and NumericScalarTypes are in sync");
                }
            }

            // Otherwise, this is an invalid coersion
            throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
        }
 protected virtual void SerializeExtraProperties(XElement node, TObject item, PropertyType property)
 {
     // when something has extra properties that the others don't (memberTypes at the moment)
 }
Example #50
0
        /// <summary>
        /// Deletes resource from the netowrk model.
        /// </summary>
        /// <param name="rd">Description of the resource that should be deleted</param>
        private void DeleteEntity(ResourceDescription rd)
        {
            if (rd == null)
            {
                CommonTrace.WriteTrace(CommonTrace.TraceInfo, "Delete entity is not done because update operation is empty.");
                return;
            }

            try
            {
                long globalId = rd.Id;

                CommonTrace.WriteTrace(CommonTrace.TraceVerbose, "Deleting entity with GID ({0:x16}).", globalId);

                // check if entity exists
                if (!this.EntityExists(globalId))
                {
                    string message = String.Format("Failed to delete entity because entity with specified GID ({0:x16}) does not exist in network model.", globalId);
                    CommonTrace.WriteTrace(CommonTrace.TraceError, message);
                    throw new Exception(message);
                }

                // get entity to be deleted
                IdentifiedObject io = GetEntity(globalId);

                // check if entity could be deleted (if it is not referenced by any other entity)
                if (io.IsReferenced)
                {
                    Dictionary <ModelCode, List <long> > references = new Dictionary <ModelCode, List <long> >();
                    io.GetReferences(references, TypeOfReference.Target);

                    StringBuilder sb = new StringBuilder();

                    foreach (KeyValuePair <ModelCode, List <long> > kvp in references)
                    {
                        foreach (long referenceGlobalId in kvp.Value)
                        {
                            sb.AppendFormat("0x{0:x16}, ", referenceGlobalId);
                        }
                    }

                    string message = String.Format("Failed to delete entity (GID = 0x{0:x16}) because it is referenced by entities with GIDs: {1}.", globalId, sb.ToString());
                    CommonTrace.WriteTrace(CommonTrace.TraceError, message);
                    throw new Exception(message);
                }

                // find property ids
                List <ModelCode> propertyIds = resourcesDescs.GetAllSettablePropertyIdsForEntityId(io.GlobalId);

                // remove references
                Property property = null;
                foreach (ModelCode propertyId in propertyIds)
                {
                    PropertyType propertyType = Property.GetPropertyType(propertyId);

                    if (propertyType == PropertyType.Reference)
                    {
                        property = io.GetProperty(propertyId);

                        if (propertyType == PropertyType.Reference)
                        {
                            // get target entity and remove reference to another entity
                            long targetGlobalId = property.AsReference();

                            if (targetGlobalId != 0)
                            {
                                // get target entity
                                IdentifiedObject targetEntity = GetEntity(targetGlobalId);

                                // remove reference to another entity
                                targetEntity.RemoveReference(propertyId, globalId);
                            }
                        }
                    }
                }

                // remove entity form netowrk model
                DMSType   type      = (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(globalId);
                Container container = GetContainer(type);
                container.RemoveEntity(globalId);

                CommonTrace.WriteTrace(CommonTrace.TraceVerbose, "Deleting entity with GID ({0:x16}) successfully finished.", globalId);
            }
            catch (Exception ex)
            {
                string message = String.Format("Failed to delete entity (GID = 0x{0:x16}) from model. {1}", rd.Id, ex.Message);
                CommonTrace.WriteTrace(CommonTrace.TraceError, message);
                throw new Exception(message);
            }
        }
 public static bool IsComputed(this PropertyType propertyType)
 {
     return(propertyType == PropertyType.LinkingObjects);
 }
Example #52
0
 /// <summary>
 /// Determines whether the property type varies by culture.
 /// </summary>
 /// <param name="propertyType">The property type.</param>
 /// <returns>
 /// A value indicating whether the property type varies by culture.
 /// </returns>
 public static bool VariesByCulture(this PropertyType propertyType) => propertyType.Variations.VariesByCulture();
 public ISyncMapper GetSyncMapper(PropertyType propertyType)
 => this.FirstOrDefault(x => x.IsMapper(propertyType));
Example #54
0
 /// <summary>
 /// Determines whether the property type is invariant.
 /// </summary>
 /// <param name="propertyType">The property type.</param>
 /// <returns>
 /// A value indicating whether the property type is invariant.
 /// </returns>
 public static bool VariesByNothing(this PropertyType propertyType) => propertyType.Variations.VariesByNothing();
Example #55
0
 /// <summary>
 /// Sets or removes the property type variation depending on the specified value.
 /// </summary>
 /// <param name="propertyType">The property type.</param>
 /// <param name="variation">The variation to set or remove.</param>
 /// <param name="value">If set to <c>true</c> sets the variation; otherwise, removes the variation.</param>
 /// <remarks>
 /// This method does not support setting the variation to nothing.
 /// </remarks>
 public static void SetVariesBy(this PropertyType propertyType, ContentVariation variation, bool value = true) => propertyType.Variations = propertyType.Variations.SetFlag(variation, value);
Example #56
0
 /// <summary>
 /// Determines whether the property type varies by culture and segment.
 /// </summary>
 /// <param name="propertyType">The property type.</param>
 /// <returns>
 /// A value indicating whether the property type varies by culture and segment.
 /// </returns>
 public static bool VariesByCultureAndSegment(this PropertyType propertyType) => propertyType.Variations.VariesByCultureAndSegment();
Example #57
0
        private static uint ComposeRawValue(PropertyType type, float value)
        {
            InternalDebug.Assert(type == PropertyType.Fractional || type == PropertyType.Percentage);

            return(GetRawType(type) | ((uint)(value * 10000.0f) & ValueMask));
        }
Example #58
0
 public CLRIReferenceImpl(PropertyType type, T obj)
     : base(type, obj)
 {
     BCLDebug.Assert(obj != null, "Must not be null");
     _value = obj;
 }
Example #59
0
 public ReadOnlyReferenceSerializer(PropertyInfo property, PropertyType type) : base(property, type)
 {
 }
        public void SetValueTest()
        {
            var dataTypeService = Mock.Of <IDataTypeService>();

            var vortoDataType = new DataTypeDefinition("vortoEditorAlias")
            {
                Id           = 1,
                Key          = Guid.Parse("ebd71353-206e-4df6-8a4c-e194519f7794"),
                DatabaseType = DataTypeDatabaseType.Ntext
            };

            var innerDataType = new DataTypeDefinition("innerEditorAlias")
            {
                Id           = 2,
                Key          = Guid.Parse("92897bc6-a5f3-4ffe-ae27-f2e7e33dda49"),
                DatabaseType = DataTypeDatabaseType.Integer // for true/false
            };

            var dataTypes = new[] { vortoDataType, innerDataType };

            Mock.Get(dataTypeService)
            .Setup(x => x.GetDataTypeDefinitionById(It.IsAny <Guid>()))
            .Returns <Guid>(id => dataTypes.FirstOrDefault(x => x.Key == id));

            var preValues = new Dictionary <int, PreValueCollection>
            {
                { 1, new PreValueCollection(new Dictionary <string, PreValue>
                    {
                        { "dataType", new PreValue("{\"guid\":\"92897bc6-a5f3-4ffe-ae27-f2e7e33dda49\",\"name\":\"True/False\",\"propertyEditorAlias\":\"innerEditorAlias\"}") }
                    }) }
            };

            Mock.Get(dataTypeService)
            .Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny <int>()))
            .Returns <int>(id => preValues.TryGetValue(id, out var collection) ? collection : null);

            ValueConnectorCollection connectors = null;
            var defaultConnector = new DefaultValueConnector();
            var vortoConnector   = new VortoValueConnector(dataTypeService, new Lazy <ValueConnectorCollection>(() => connectors));

            connectors = new ValueConnectorCollection(new Dictionary <string, IValueConnector>
            {
                { "innerEditorAlias", defaultConnector },
                { "vortoEditorAlias", vortoConnector }
            });

            var input = "{\"values\":{\"da-DK\":\"i0\",\"de-DE\":\"i0\",\"en-GB\":\"i0\",\"en\":\"i0\"},\"dtdGuid\":\"ebd71353-206e-4df6-8a4c-e194519f7794\"}";

            UmbracoConfig.For.SetUmbracoSettings(GenerateMockSettings());

            var vortoPropertyType = new PropertyType(vortoDataType, "vortoProperty");
            var vortoProperty     = new Property(vortoPropertyType, null); // value is going to be replaced
            var vortoContent      = new Content("mockContent", -1, new ContentType(-1), new PropertyCollection(new List <Property> {
                vortoProperty
            }));

            vortoConnector.SetValue(vortoContent, "vortoProperty", input);

            var output = vortoContent.GetValue("vortoProperty");

            // fixme - why strings and not integers?!
            // so "i0" is sent to default connector, but it sets value to "0" not 0 - wtf?

            Assert.IsInstanceOf <string>(output);

            Console.WriteLine(output);
            Assert.AreEqual("{\"values\":{\"da-DK\":0,\"de-DE\":0,\"en-GB\":0,\"en\":0},\"dtdGuid\":\"ebd71353-206e-4df6-8a4c-e194519f7794\"}", output);
        }