public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var dict = value as IDictionary<PropertyName, IProperty>;
			if (dict == null) return;
			var settings = serializer.GetConnectionSettings();
			var props = new Properties();
			foreach (var kv in dict)
			{
				var v = kv.Value as IPropertyWithClrOrigin;
				if (v?.ClrOrigin == null)
				{
					props.Add(kv.Key, kv.Value);
					continue;
				}
				//We do not have to take .Name into account from serializer PropertyName (kv.Key) already handles this
				var serializerMapping = settings.Serializer?.CreatePropertyMapping(v.ClrOrigin);
				if (serializerMapping == null || !serializerMapping.Ignore) 
					props.Add(kv.Key, kv.Value);
			}
			_dictionaryConverter.WriteJson(writer, props, serializer);
		}
        public StructureObjectArray(PsdReader reader)
        {
            int version = reader.ReadInt32();
            this.Add("Name", reader.ReadString());
            this.Add("ClassID", reader.ReadKey());

            int count = reader.ReadInt32();

            List<Properties> items = new List<Properties>();

            for (int i = 0; i < count; i++)
            {
                Properties props = new Properties();
                props.Add("Type1", reader.ReadKey());
                props.Add("EnumName", reader.ReadType());

                props.Add("Type2", PsdUtility.ToUnitType(reader.ReadType()));
                int d4 = reader.ReadInt32();
                props.Add("Values", reader.ReadDoubles(d4));

                items.Add(props);
            }
            this.Add("items", items.ToArray());
        }
		public IProperties GetProperties(ConcurrentDictionary<Type, int> seenTypes = null, int maxRecursion = 0)
		{
			var properties = new Properties();

			int seen;
			if (seenTypes != null && seenTypes.TryGetValue(_type, out seen) && seen > maxRecursion)
				return properties;

			foreach (var propertyInfo in _type.GetProperties())
			{
				var attribute = ElasticsearchPropertyAttribute.From(propertyInfo);
				if (attribute != null && attribute.Ignore)
					continue;
				var property = GetProperty(propertyInfo, attribute);
				properties.Add(propertyInfo, property);
			}

			return properties;
		}
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var r = new Properties();
			JObject o = JObject.Load(reader);

			foreach (var p in o.Properties())
			{
				var name = p.Name;
				var po = p.First as JObject;
				if (po == null)
					continue;

				var mapping = _elasticTypeConverter.ReadJson(po.CreateReader(), objectType, existingValue, serializer)
				as IProperty;
				if (mapping == null)
					continue;
				mapping.Name = name;

				r.Add(name, mapping);

			}
			return r;
		}
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jToken = JToken.ReadFrom(reader);

            if (jToken.Type == JTokenType.Array)
            {
                return new Properties();
            }

            if (jToken.Type == JTokenType.Object)
            {
                var properties = new Properties();
                foreach (var property in ((JObject)jToken).Properties())
                {
                    if(property.Name == "headers")
                    {
                        if (property.Value.Type == JTokenType.Object)
                        {
                            var headers = (JObject) property.Value;
                            foreach (var header in headers.Properties())
                            {
                                properties.headers.Add(header.Name, header.Value.ToString());
                            }
                        }
                    }
                    else
                    {
                        properties.Add(property.Name, property.Value.ToString());
                    }
                }
                return properties;
            }

            throw new JsonException(
                string.Format("Expected array or object for properties, but was {0}", jToken.Type), null);
        }
Beispiel #6
0
 private void initializeRegistrationProperties()
 {
     Properties.Add("username", "");
     Properties.Add("duplicated_password", "");
 }
Beispiel #7
0
 public LengthException(string input, int inputLength) : base(typeof(LengthException))
 {
     Properties.Add(nameof(input), input);
     Properties.Add(nameof(inputLength), inputLength);
 }
        static void ReadTileset(XmlNode node, ref Map map, string base_path)
        {
            TileSet r    = new TileSet();
            r.FirstGid   = node.ReadInt("firstgid");
            r.Source     = node.ReadTag("source");
            r.Name       = node.ReadTag("name");
            r.TileWidth  = node.ReadInt("tilewidth");
            r.TileHeight = node.ReadInt("tileheight");
            r.Spacing    = node.ReadInt("spacing");
            r.Margin     = node.ReadInt("margin");

            Console.Out.WriteLine (r.Source);

            if (r.Source != "") {

                String filename = Path.Combine (base_path, r.Source);

                Console.Out.WriteLine (r.Source);

                try {

                XmlDocument extTileset = new XmlDocument ();
                extTileset.Load (File.OpenRead (filename));
                foreach (XmlNode extNode in extTileset.ChildNodes) {

                    if (extNode.Name == "tileset")
                        node = extNode;
                }

                r.Name       = node.ReadTag("name");
                r.TileWidth  = node.ReadInt("tilewidth");
                r.TileHeight = node.ReadInt("tileheight");
                r.Spacing    = node.ReadInt("spacing");
                r.Margin     = node.ReadInt("margin");

                FileInfo fi = new FileInfo (filename);
                base_path = fi.DirectoryName;

                } catch (Exception e) {
                    Console.Out.WriteLine (e.Message);
                    return;
                }
            }

            if (node.HasChildNodes)
            {
                foreach (XmlNode child in node.ChildNodes)
                {

                    if (child.Name == "image") {
                        string c = child.ReadTag ("trans", "FFFFFF");
                        if (c.Length == 6 && !c.StartsWith ("#")) {
                            c = "#" + c;
                        }
                        Color t = ColorTranslator.FromHtml (c);

                        if (child.Attributes ["trans"] != null) {
                            r.Images.Add (new Image () {
                                Source = child.ReadTag ("source"),
                                TransColor = t,
                                UseTransColor = true
                            });
                        } else {
                            r.Images.Add (new Image () {
                                Source = child.ReadTag ("source"),
                                TransColor = t,
                                UseTransColor = false
                            });
                        }
                    } else if (child.Name == "tile") {
                        int id = child.ReadInt ("id");
                        Properties tileprops = new Properties();
                        XmlNode data = child.FirstChild; // Should be a properties tag.
                        foreach (XmlNode property in data.ChildNodes) {
                            tileprops.Add (property.ReadTag ("name"), property.ReadTag ("value"));
                        }
                        r.TileProperties.Add (id, tileprops);
                    }
                }
            }

            //r.ReadBitmaps(base_path);

            map.TileSets.Add(r);
        }
        public GeneratedUClass(Type reflectedClass)
        {
            reflectedClassType = reflectedClass;

            Name = reflectedClass.Name;
            Type = reflectedClass.GetCustomAttribute <GenerateApiAttribute>().ClassType;

            if (Type == UClassType.Request)
            {
                foreach (var requesDataField in reflectedClass.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
                         .Where(property => property.GetCustomAttributes <ApiRequestDataAttribute>(true).Any()))
                {
                    RequestArguments.Add(new UProperty(requesDataField, true));
                }

                if (reflectedClass.GetCustomAttributes <RequireServerAuthAttribute>(true).Any())
                {
                    RequestArguments.Add(new UProperty()
                    {
                        Name = "ServerAuthKey", Type = PropertyType.String, IsArgument = true
                    });
                    if (RequestArguments.Count >= 2)
                    {
                        RequestArguments.Swap(0, RequestArguments.Count - 1);
                    }
                }
                else if (reflectedClass.GetCustomAttributes <RequireAuthAttribute>(true).Any())
                {
                    if (!RequestArguments.Exists(a => a.Name.Equals("PlayerId", StringComparison.OrdinalIgnoreCase)))
                    {
                        RequestArguments.Add(new UProperty()
                        {
                            Name = "PlayerId", Type = PropertyType.String, IsArgument = true
                        });
                        if (RequestArguments.Count >= 2)
                        {
                            RequestArguments.Swap(0, RequestArguments.Count - 1);
                        }
                    }
                    RequestArguments.Add(new UProperty()
                    {
                        Name = "SessionToken", Type = PropertyType.String, IsArgument = true
                    });
                    if (RequestArguments.Count >= 3)
                    {
                        RequestArguments.Swap(1, RequestArguments.Count - 1);
                    }
                }

                foreach (var responseDataField in reflectedClass.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
                         .Where(property => property.GetCustomAttributes <ApiResponseDataAttribute>(true).Any()))
                {
                    Properties.Add(new UProperty(responseDataField));
                }
            }
            else if (Type == UClassType.Enum)
            {
                foreach (var enumValue in reflectedClass.GetEnumNames())
                {
                    EnumValues.Add(enumValue);
                }
            }
            else
            {
                foreach (var reflectedProperty in reflectedClass.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
                         .Where(property => !property.GetCustomAttributes <IgnorePropertyAttribute>(true).Any() && property.CanWrite))
                {
                    Properties.Add(new UProperty(reflectedProperty));
                }
            }
        }
 public void AddProperty(string name)
 {
     Properties.Add(name);
 }
 /// <summary>
 /// Sets a value for an attribute.
 /// </summary>
 /// <param name="name">the iText tagname</param>
 /// <param name="value">the default value for this tag</param>
 public void AddValue(string name, string value)
 {
     AttributeValues.Add(name, value);
 }
Beispiel #12
0
		public void Add(string propName, RavenJToken token)
		{
			Properties.Add(propName, token);
		}
Beispiel #13
0
 /// <summary>
 /// To set the property based on Property name and value.
 /// </summary>
 /// <param name="name">Name (String) of the record property.</param>
 /// <param name="value">value (Object) of the record property.</param>
 public void SetProperty(string name, object value)
 {
     Properties.Add(name, value);
 }
Beispiel #14
0
        private void GetRelated()
        {
            // Clear related
            Regions.Clear();
            Properties.Clear();
            AttachedContent.Clear();

            // Get group parents
            DisableGroups = SysGroup.GetParents(Page.GroupId);
            DisableGroups.Reverse();

            // Get template & permalink
            Template  = PageTemplate.GetSingle("pagetemplate_id = @0", Page.TemplateId);
            Permalink = Permalink.GetSingle(Page.PermalinkId);
            if (Permalink == null)
            {
                // Get the site tree
                using (var db = new DataContext()) {
                    var sitetree = db.SiteTrees.Where(s => s.Id == Page.SiteTreeId).Single();

                    Permalink = new Permalink()
                    {
                        Id = Guid.NewGuid(), Type = Permalink.PermalinkType.PAGE, NamespaceId = sitetree.NamespaceId
                    };
                    Page.PermalinkId = Permalink.Id;
                }
            }

            // Get placement ref title
            if (!IsSite)
            {
                if (Page.ParentId != Guid.Empty || Page.Seqno > 1)
                {
                    Page refpage = null;
                    if (Page.Seqno > 1)
                    {
                        if (Page.ParentId != Guid.Empty)
                        {
                            refpage = Page.GetSingle("page_parent_id = @0 AND page_seqno = @1", Page.ParentId, Page.Seqno - 1);
                        }
                        else
                        {
                            refpage = Page.GetSingle("page_parent_id IS NULL AND page_seqno = @0 AND page_sitetree_id = @1", Page.Seqno - 1, Page.SiteTreeId);  //ÖS 2015-03-18 added siteid to the query
                        }
                    }
                    else
                    {
                        refpage = Page.GetSingle(Page.ParentId, true);
                    }
                    PlaceRef = refpage.Title;
                }
            }

            if (Template != null)
            {
                // Only load regions & properties if this is an original
                if (Page.OriginalId == Guid.Empty)
                {
                    // Get regions
                    var regions = RegionTemplate.Get("regiontemplate_template_id = @0", Template.Id, new Params()
                    {
                        OrderBy = "regiontemplate_seqno"
                    });
                    foreach (var rt in regions)
                    {
                        var reg = Region.GetSingle("region_regiontemplate_id = @0 AND region_page_id = @1 and region_draft = @2",
                                                   rt.Id, Page.Id, Page.IsDraft);
                        if (reg != null)
                        {
                            Regions.Add(reg);
                        }
                        else
                        {
                            Regions.Add(new Region()
                            {
                                InternalId       = rt.InternalId,
                                Name             = rt.Name,
                                Type             = rt.Type,
                                PageId           = Page.Id,
                                RegiontemplateId = rt.Id,
                                IsDraft          = Page.IsDraft,
                                IsPageDraft      = Page.IsDraft
                            });
                        }
                    }

                    // Get Properties
                    foreach (string name in Template.Properties)
                    {
                        Property prp = Property.GetSingle("property_name = @0 AND property_parent_id = @1 AND property_draft = @2",
                                                          name, Page.Id, Page.IsDraft);
                        if (prp != null)
                        {
                            Properties.Add(prp);
                        }
                        else
                        {
                            Properties.Add(new Property()
                            {
                                Name = name, ParentId = Page.Id, IsDraft = Page.IsDraft
                            });
                        }
                    }
                }
            }
            else
            {
                throw new ArgumentException("Could not find page template for page {" + Page.Id.ToString() + "}");
            }

            // Only load attachments if this is an original
            if (Page.OriginalId == Guid.Empty)
            {
                // Get attached content
                if (Page.Attachments.Count > 0)
                {
                    // Content meta data is actually memcached, so this won't result in multiple queries
                    Page.Attachments.ForEach(a => {
                        Models.Content c = Models.Content.GetSingle(a, true);
                        if (c != null)
                        {
                            AttachedContent.Add(c);
                        }
                    });
                }
            }

            // Get page position
            Parents = BuildParentPages(Sitemap.GetStructure(Page.SiteTreeInternalId, false), Page);
            Parents.Insert(0, new PagePlacement()
            {
                Level = 1, IsSelected = Page.ParentId == Guid.Empty
            });
            Siblings = BuildSiblingPages(Page.Id, Page.ParentId, Page.Seqno, Page.ParentId, Page.SiteTreeInternalId);

            // Only load extensions if this is an original
            if (Page.OriginalId == Guid.Empty)
            {
                // Get extensions
                Extensions = Page.GetExtensions(true);
            }

            // Initialize regions
            foreach (var reg in Regions)
            {
                reg.Body.InitManager(this);
            }

            // Get whether comments should be enabled
            EnableComments = Areas.Manager.Models.CommentSettingsModel.Get().EnablePages;
            if (!Page.IsNew && EnableComments)
            {
                using (var db = new DataContext()) {
                    Comments = db.Comments.
                               Include("CreatedBy").
                               Where(c => c.ParentId == Page.Id && c.ParentIsDraft == false).
                               OrderByDescending(c => c.Created).ToList();
                }
            }

            // Get the site if this is a site page
            if (Permalink.Type == Models.Permalink.PermalinkType.SITE)
            {
                using (var db = new DataContext()) {
                    SiteTree = db.SiteTrees.Where(s => s.Id == Page.SiteTreeId).Single();
                }
            }

            // Check if the page can be published
            if (Page.OriginalId != Guid.Empty)
            {
                CanPublish = Page.GetScalar("SELECT count(*) FROM page WHERE page_id=@0 AND page_draft=0", Page.OriginalId) > 0;
            }
        }
 public virtual void SetMarkupAttribute(String key, String value)
 {
     markupAttributes.Add(key, value);
 }
        public virtual void TryInheritFrom(IEntity parent)
        {
            if (parent is IHasProperties hasProperties)
            {
                //Properties inheritance
                foreach (var parentProperty in hasProperties.Properties ?? Array.Empty <Property>())
                {
                    if (Properties == null)
                    {
                        Properties = new List <Property>();
                    }
                    var existProperty = Properties.FirstOrDefault(x => x.IsSame(parentProperty, PropertyType.Product, PropertyType.Variation));
                    if (existProperty == null)
                    {
                        existProperty = AbstractTypeFactory <Property> .TryCreateInstance();

                        Properties.Add(existProperty);
                    }
                    existProperty.TryInheritFrom(parentProperty);

                    existProperty.IsReadOnly = existProperty.Type != PropertyType.Variation && existProperty.Type != PropertyType.Product;
                }
                //Restore sorting order after changes
                if (Properties != null)
                {
                    Properties = Properties.OrderBy(x => x.Name).ToList();
                }
            }

            if (parent is IHasTaxType hasTaxType)
            {
                //TODO: prevent saving the inherited simple values
                //TaxType  inheritance
                if (TaxType == null)
                {
                    TaxType = hasTaxType.TaxType;
                }
            }

            if (parent is CatalogProduct parentProduct)
            {
                var isVariation = GetType().IsAssignableFrom(typeof(Variation));
                //Inherit images from parent product (if its not set)
                if (Images.IsNullOrEmpty() && !parentProduct.Images.IsNullOrEmpty())
                {
                    Images = new List <Image>();
                    foreach (var parentImage in parentProduct.Images)
                    {
                        var image = AbstractTypeFactory <Image> .TryCreateInstance();

                        image.TryInheritFrom(parentImage);
                        Images.Add(image);
                    }
                }

                //Inherit assets from parent product (if its not set)
                if (Assets.IsNullOrEmpty() && !parentProduct.Assets.IsNullOrEmpty())
                {
                    Assets = new List <Asset>();
                    foreach (var parentAsset in parentProduct.Assets)
                    {
                        var asset = AbstractTypeFactory <Asset> .TryCreateInstance();

                        asset.TryInheritFrom(parentAsset);
                        Assets.Add(asset);
                    }
                }

                //inherit editorial reviews from main product and do not inherit if variation loaded within product
                if (!isVariation && Reviews.IsNullOrEmpty() && parentProduct.Reviews != null)
                {
                    Reviews = new List <EditorialReview>();
                    foreach (var parentReview in parentProduct.Reviews)
                    {
                        var review = AbstractTypeFactory <EditorialReview> .TryCreateInstance();

                        review.TryInheritFrom(parentReview);
                        Reviews.Add(review);
                    }
                }
                //inherit not overridden property values from main product
                foreach (var parentProductProperty in parentProduct.Properties ?? Array.Empty <Property>())
                {
                    var existProperty = Properties.FirstOrDefault(x => x.IsSame(parentProductProperty, PropertyType.Product, PropertyType.Variation));
                    if (existProperty == null)
                    {
                        existProperty = AbstractTypeFactory <Property> .TryCreateInstance();

                        Properties.Add(existProperty);
                    }
                    existProperty.TryInheritFrom(parentProductProperty);
                    existProperty.IsReadOnly = existProperty.Type != PropertyType.Variation && existProperty.Type != PropertyType.Product;

                    //Inherit only parent Product properties  values if own values aren't set
                    if (parentProductProperty.Type == PropertyType.Product)
                    {
                        if (existProperty.Values.IsNullOrEmpty() && !parentProductProperty.Values.IsNullOrEmpty())
                        {
                            existProperty.Values = new List <PropertyValue>();
                            foreach (var parentPropValue in parentProductProperty.Values)
                            {
                                var propValue = AbstractTypeFactory <PropertyValue> .TryCreateInstance();

                                propValue.TryInheritFrom(parentPropValue);
                                existProperty.Values.Add(propValue);
                            }
                        }
                    }
                }
                //TODO: prevent saving the inherited simple values
                Width       = parentProduct.Width ?? Width;
                Height      = parentProduct.Height ?? Height;
                Length      = parentProduct.Length ?? Length;
                MeasureUnit = parentProduct.MeasureUnit ?? MeasureUnit;
                Weight      = parentProduct.Weight ?? Weight;
                WeightUnit  = parentProduct.WeightUnit ?? WeightUnit;
                PackageType = parentProduct.PackageType ?? PackageType;

                if (!Variations.IsNullOrEmpty())
                {
                    foreach (var variation in Variations)
                    {
                        variation.TryInheritFrom(this);
                    }
                }
            }
        }
 /// <summary>
 /// Register the property we want to provider a design time version of.
 /// </summary>
 public TabControlDesignModeValueProvider()
 {
     Properties.Add(MyPlatformTypes.TabControl.SelectedIndexProperty);
 }
Beispiel #18
0
 /// <summary>
 /// See <see cref="M:iTextSharp.text.IMarkupAttributes.setMarkupAttribute(System.String,System.String)"/>
 /// </summary>
 /// <param name="name">attribute name</param>
 /// <param name="value">attribute value</param>
 public void setMarkupAttribute(string name, string value)
 {
     markupAttributes = (markupAttributes == null) ? new Properties() : markupAttributes;
     markupAttributes.Add(name, value);
 }
Beispiel #19
0
        public ClientConfiguration(ClientConfigurationList parentList)
        {
            _parentList = parentList;

            // Client properties
            PrivateKeyProperty.TargetTypes.Add(GetType());
            DnsProperty.TargetTypes.Add(GetType());
            AddressProperty.TargetTypes.Add(GetType());

            // Server properties
            PresharedKeyProperty.TargetTypes.Add(typeof(ServerConfiguration));
            PublicKeyProperty.TargetTypes.Add(typeof(ServerConfiguration));
            ServerPersistentKeepaliveProperty.TargetTypes.Add(typeof(ServerConfiguration));

            var    serverConfiguration = new ServerConfiguration().Load <ServerConfiguration>(Configuration.LoadFromFile(ServerConfigurationPrerequisite.ServerDataPath));
            string serverIp            = serverConfiguration.AddressProperty.Value;

            // Add support for generating client IP
            AddressProperty.Action = new ConfigurationPropertyAction(this)
            {
                Name                    = nameof(Resources.GenerateFromServerAction),
                Description             = string.Format(Resources.GenerateClientAddressActionDescription, serverIp),
                DependentProperty       = serverConfiguration.AddressProperty,
                DependencySatisfiedFunc = prop => string.IsNullOrEmpty(prop.Validation?.Validate?.Invoke(prop)),
                Action                  = (conf, prop) =>
                {
                    IPNetwork serverNetwork     = IPNetwork.Parse(serverConfiguration.AddressProperty.Value);
                    var       possibleAddresses = serverNetwork.ListIPAddress().Skip(2).SkipLast(1).ToList(); // Skip reserved .0 and .1 and .255.

                    // If the current address is already in range, we're done
                    if (possibleAddresses.Select(a => a.ToString()).Contains(prop.Value))
                    {
                        return;
                    }

                    WaitCursor.SetOverrideCursor(Cursors.Wait);

                    var existingAddresses = parentList.List.Select(c => c.AddressProperty.Value);

                    // Find the first address that isn't used by another client
                    prop.Value = possibleAddresses.FirstOrDefault(a => existingAddresses.Contains(a.ToString()) == false)?.ToString();

                    WaitCursor.SetOverrideCursor(null);
                }
            };

            // Do custom validation on the Address (we want a specific IP or a CIDR with /32)
            AddressProperty.Validation = new ConfigurationPropertyValidation
            {
                Validate = obj =>
                {
                    string result = default;

                    // First, try parsing with IPNetwork to see if it's in CIDR format
                    if (IPNetwork.TryParse(obj.Value, out var network))
                    {
                        // At this point, we know it's a valid network. Let's see how many addresses are in range
                        if (network.Usable > 1)
                        {
                            // It's CIDR, but it defines more than one address.
                            // However, IPNetwork has a quirk that parses single addresses (without mask) as a range.
                            // So now let's see if it's a single address
                            if (IPAddress.TryParse(obj.Value, out _) == false)
                            {
                                // If we get here, it passed CIDR parsing, but it defined more than one address (i.e., had a mask). It's bad!
                                result = Resources.ClientAddressValidationError;
                            }
                            // Else, it's a single address as parsed by IPAddress, so we're good!
                        }
                        // Else
                        // It's in CIDR notation and only defines a single address (/32) so we're good!
                    }
                    else
                    {
                        // Not even IPNetwork could parse it, so it's really bad!
                        result = Resources.ClientAddressValidationError;
                    }

                    return(result);
                }
            };

            // The client generates the PSK
            PresharedKeyProperty.Action = new ConfigurationPropertyAction(this)
            {
                Name   = $"{nameof(PresharedKeyProperty)}{nameof(ConfigurationProperty.Action)}",
                Action = (conf, prop) =>
                {
                    WaitCursor.SetOverrideCursor(Cursors.Wait);
                    prop.Value = new WireGuardExe().ExecuteCommand(new GeneratePresharedKeyCommand());
                    WaitCursor.SetOverrideCursor(null);
                }
            };

            // Allowed IPs is special, because for the server, it's the same as the Address property for the client
            var allowedIpsProperty = new ConfigurationProperty(this)
            {
                PersistentPropertyName = "AllowedIPs",
                Value    = AddressProperty.Value,
                IsHidden = true
            };

            allowedIpsProperty.TargetTypes.Add(typeof(ServerConfiguration));
            AddressProperty.PropertyChanged += (_, args) =>
            {
                if (args.PropertyName == nameof(AddressProperty.Value))
                {
                    allowedIpsProperty.Value = AddressProperty.Value;
                }
            };
            Properties.Add(allowedIpsProperty);

            // Adjust index of properties and resort
            AddressProperty.Index = 1;
            DnsProperty.Index     = 2;
            SortProperties();

            Properties.ForEach(p => p.PropertyChanged += (_, args) =>
            {
                if (args.PropertyName == nameof(p.Value))
                {
                    GenerateQrCodeAction.RaisePropertyChanged(nameof(GenerateQrCodeAction.DependencySatisfied));
                    ExportConfigurationFileAction.RaisePropertyChanged(nameof(ExportConfigurationFileAction.DependencySatisfied));
                }
            });
        }
        /// <summary>
        /// Replaces the contents of the APP1 section with the Exif properties.
        /// </summary>
        private bool WriteExifApp1(bool preserveMakerNote)
        {
            // Zero out IFD field offsets. We will fill those as we write the IFD sections
            exifIFDFieldOffset    = 0;
            gpsIFDFieldOffset     = 0;
            interopIFDFieldOffset = 0;
            firstIFDFieldOffset   = 0;
            // We also do not know the location of the embedded thumbnail yet
            thumbOffsetLocation = 0;
            thumbOffsetValue    = 0;
            thumbSizeLocation   = 0;
            thumbSizeValue      = 0;
            // Write thumbnail tags if they are missing, remove otherwise
            if (Thumbnail == null)
            {
                Properties.Remove(ExifTag.ThumbnailJPEGInterchangeFormat);
                Properties.Remove(ExifTag.ThumbnailJPEGInterchangeFormatLength);
            }
            else
            {
                if (!Properties.ContainsKey(ExifTag.ThumbnailJPEGInterchangeFormat))
                {
                    Properties.Add(new ExifUInt(ExifTag.ThumbnailJPEGInterchangeFormat, 0));
                }
                if (!Properties.ContainsKey(ExifTag.ThumbnailJPEGInterchangeFormatLength))
                {
                    Properties.Add(new ExifUInt(ExifTag.ThumbnailJPEGInterchangeFormatLength, 0));
                }
            }

            // Which IFD sections do we have?
            Dictionary <ExifTag, ExifProperty> ifdzeroth  = new Dictionary <ExifTag, ExifProperty>();
            Dictionary <ExifTag, ExifProperty> ifdexif    = new Dictionary <ExifTag, ExifProperty>();
            Dictionary <ExifTag, ExifProperty> ifdgps     = new Dictionary <ExifTag, ExifProperty>();
            Dictionary <ExifTag, ExifProperty> ifdinterop = new Dictionary <ExifTag, ExifProperty>();
            Dictionary <ExifTag, ExifProperty> ifdfirst   = new Dictionary <ExifTag, ExifProperty>();

            foreach (ExifProperty prop in Properties)
            {
                switch (prop.IFD)
                {
                case IFD.Zeroth:
                    ifdzeroth.Add(prop.Tag, prop);
                    break;

                case IFD.EXIF:
                    ifdexif.Add(prop.Tag, prop);
                    break;

                case IFD.GPS:
                    ifdgps.Add(prop.Tag, prop);
                    break;

                case IFD.Interop:
                    ifdinterop.Add(prop.Tag, prop);
                    break;

                case IFD.First:
                    ifdfirst.Add(prop.Tag, prop);
                    break;
                }
            }

            // Add IFD pointers if they are missing
            // We will write the pointer values later on
            if (ifdexif.Count != 0 && !ifdzeroth.ContainsKey(ExifTag.EXIFIFDPointer))
            {
                ifdzeroth.Add(ExifTag.EXIFIFDPointer, new ExifUInt(ExifTag.EXIFIFDPointer, 0));
            }
            if (ifdgps.Count != 0 && !ifdzeroth.ContainsKey(ExifTag.GPSIFDPointer))
            {
                ifdzeroth.Add(ExifTag.GPSIFDPointer, new ExifUInt(ExifTag.GPSIFDPointer, 0));
            }
            if (ifdinterop.Count != 0 && !ifdexif.ContainsKey(ExifTag.InteroperabilityIFDPointer))
            {
                ifdexif.Add(ExifTag.InteroperabilityIFDPointer, new ExifUInt(ExifTag.InteroperabilityIFDPointer, 0));
            }

            // Remove IFD pointers if IFD sections are missing
            if (ifdexif.Count == 0 && ifdzeroth.ContainsKey(ExifTag.EXIFIFDPointer))
            {
                ifdzeroth.Remove(ExifTag.EXIFIFDPointer);
            }
            if (ifdgps.Count == 0 && ifdzeroth.ContainsKey(ExifTag.GPSIFDPointer))
            {
                ifdzeroth.Remove(ExifTag.GPSIFDPointer);
            }
            if (ifdinterop.Count == 0 && ifdexif.ContainsKey(ExifTag.InteroperabilityIFDPointer))
            {
                ifdexif.Remove(ExifTag.InteroperabilityIFDPointer);
            }

            if (ifdzeroth.Count == 0 && ifdgps.Count == 0 && ifdinterop.Count == 0 && ifdfirst.Count == 0 && Thumbnail == null)
            {
                // Nothing to write
                return(false);
            }

            // We will need these bitconverter to write byte-ordered data
            BitConverterEx bceExif = new BitConverterEx(BitConverterEx.SystemByteOrder, ByteOrder);

            // Create a memory stream to write the APP1 section to
            MemoryStream ms = new MemoryStream();

            // Exif identifer
            ms.Write(Encoding.ASCII.GetBytes("Exif\0\0"), 0, 6);

            // TIFF header
            // Byte order
            long tiffoffset = ms.Position;

            ms.Write((ByteOrder == BitConverterEx.ByteOrder.LittleEndian ? new byte[] { 0x49, 0x49 } : new byte[] { 0x4D, 0x4D }), 0, 2);
            // TIFF ID
            ms.Write(bceExif.GetBytes((ushort)42), 0, 2);
            // Offset to 0th IFD
            ms.Write(bceExif.GetBytes((uint)8), 0, 4);

            // Write IFDs
            WriteIFD(ms, ifdzeroth, IFD.Zeroth, tiffoffset, preserveMakerNote);
            uint exififdrelativeoffset = (uint)(ms.Position - tiffoffset);

            WriteIFD(ms, ifdexif, IFD.EXIF, tiffoffset, preserveMakerNote);
            uint gpsifdrelativeoffset = (uint)(ms.Position - tiffoffset);

            WriteIFD(ms, ifdgps, IFD.GPS, tiffoffset, preserveMakerNote);
            uint interopifdrelativeoffset = (uint)(ms.Position - tiffoffset);

            WriteIFD(ms, ifdinterop, IFD.Interop, tiffoffset, preserveMakerNote);
            uint firstifdrelativeoffset = (uint)(ms.Position - tiffoffset);

            WriteIFD(ms, ifdfirst, IFD.First, tiffoffset, preserveMakerNote);

            // Now that we now the location of IFDs we can go back and write IFD offsets
            if (exifIFDFieldOffset != 0)
            {
                ms.Seek(exifIFDFieldOffset, SeekOrigin.Begin);
                ms.Write(bceExif.GetBytes(exififdrelativeoffset), 0, 4);
            }
            if (gpsIFDFieldOffset != 0)
            {
                ms.Seek(gpsIFDFieldOffset, SeekOrigin.Begin);
                ms.Write(bceExif.GetBytes(gpsifdrelativeoffset), 0, 4);
            }
            if (interopIFDFieldOffset != 0)
            {
                ms.Seek(interopIFDFieldOffset, SeekOrigin.Begin);
                ms.Write(bceExif.GetBytes(interopifdrelativeoffset), 0, 4);
            }
            if (firstIFDFieldOffset != 0)
            {
                ms.Seek(firstIFDFieldOffset, SeekOrigin.Begin);
                ms.Write(bceExif.GetBytes(firstifdrelativeoffset), 0, 4);
            }
            // We can write thumbnail location now
            if (thumbOffsetLocation != 0)
            {
                ms.Seek(thumbOffsetLocation, SeekOrigin.Begin);
                ms.Write(bceExif.GetBytes(thumbOffsetValue), 0, 4);
            }
            if (thumbSizeLocation != 0)
            {
                ms.Seek(thumbSizeLocation, SeekOrigin.Begin);
                ms.Write(bceExif.GetBytes(thumbSizeValue), 0, 4);
            }

            ms.Close();

            // Return APP1 header
            exifApp1.Header = ms.ToArray();
            return(true);
        }
 public DataProviderElement()
 {
     Properties.Add(_propTypeName);
     Properties.Add(_propName);
     Properties.Add(_propDefault);
 }
 /// <summary>
 /// Sets an alias for an attribute.
 /// </summary>
 /// <param name="name">the iText tagname</param>
 /// <param name="alias">the custom tagname</param>
 public virtual void AddAlias(string name, string alias)
 {
     AttributeAliases.Add(alias, name);
 }
Beispiel #23
0
 private void OnAddPropertyExecuted(string obj)
 {
     Properties.Add(new MenuItemPropertyViewModel(MenuItem.AddDefaultMenuItemProperty(Model)));
 }
Beispiel #24
0
        /// <summary>
        ///  Load value from <property>...</property> tag. Null returned if value cannot be determined.
        /// </summary>
        private Object loadValue(XmlNode e, String key, int type)
        {
            String text = XMLUtils.GetText(e);

            switch (type)
            {
                case PropertySet_Fields.BOOLEAN:
                    return TextUtils.ParseBoolean(text);

                case PropertySet_Fields.INT:
                    return TextUtils.ParseInt(text);

                case PropertySet_Fields.LONG:
                    return  TextUtils.ParseLong(text);

                case PropertySet_Fields.DOUBLE:
                    return TextUtils.ParseDouble(text);

                case PropertySet_Fields.STRING:
                case PropertySet_Fields.TEXT:
                    return text;

                case PropertySet_Fields.DATE:

                    try
                    {
                        return DateTime.Parse(text, new DateTimeFormatInfo());
                    }
                    catch (FormatException )
                    {
                        return null; // if the date cannot be parsed, ignore it.
                    }
                    //return null;
                case PropertySet_Fields.OBJECT:

                    try
                    {
                        return TextUtils.decodeObject(text);
                    }
                    catch (Exception )
                    {
                        return null; // if Object cannot be decoded, ignore it.
                    }

                case PropertySet_Fields.XML:

                    try
                    {
                        XmlDocument doc=new XmlDocument();
                            doc.LoadXml(text);
                        return doc;

                    }
                    catch (Exception )
                    {
                        return null; // if XML cannot be parsed, ignore it.
                    }

                case PropertySet_Fields.DATA:

                    try
                    {
                        return new Data(TextUtils.DecodeBytes(text));
                    }
                    catch (IOException )
                    {
                        return null; // if data cannot be decoded, ignore it.
                    }
                    //return null;

                case PropertySet_Fields.PROPERTIES:

                    try
                    {

                        Properties props = new Properties();
                        XmlNodeList pElements = e.SelectNodes( "properties/property");

                        foreach(XmlNode pElement in pElements)
                        {

                            props.Add(XMLUtils.GetAttribute(pElement,"key"), XMLUtils.GetElementText(pElement));
                        }

                        return props;
                    }
                    catch (Exception )
                    {
                        return null; // could not get nodes via x-path
                    }

                default:
                    return null;

            }
        }
Beispiel #25
0
 public void AddProperty(string propertyName, object propertyValue)
 {
     Properties.Add(propertyName, propertyValue);
 }
Beispiel #26
0
        private void ReadProperties(PsdReader reader, Int32 level, Properties props)
        {
            reader.Skip('\t', level);
            Char c = reader.ReadChar();

            if (c == ']')
            {
                return;
            }
            else if (c == '<')
            {
                reader.Skip('<');
            }
            reader.Skip('\n');
            //Properties props = new Properties();
            while (true)
            {
                reader.Skip('\t', level);
                c = reader.ReadChar();
                if (c == '>')
                {
                    reader.Skip('>');
                    return;
                }
                else
                {
                    //assert c == 9;
                    c = reader.ReadChar();
                    //assert c == '/' : "unknown char: " + c + " on level: " + level;
                    String name = String.Empty;
                    while (true)
                    {
                        c = reader.ReadChar();
                        if (c == ' ' || c == 10)
                        {
                            break;
                        }
                        name += c;
                    }
                    if (c == 10)
                    {
                        Properties p = new Properties();
                        this.ReadProperties(reader, level + 1, p);
                        if (p.Count > 0)
                        {
                            props.Add(name, p);
                        }
                        reader.Skip('\n');
                    }
                    else if (c == ' ')
                    {
                        Object value = this.ReadValue(reader, level + 1);
                        props.Add(name, value);
                    }
                    else
                    {
                        //assert false;
                    }
                }
            }
        }
Beispiel #27
0
 public CustomSection()
 {
     Properties.Add(IntDefaultCapacity);
 }
Beispiel #28
0
 protected override bool OnDeserializeUnrecognizedAttribute(string name, string value)
 {
     Properties.Add(new ConfigurationProperty(name, typeof(String)));
     this[name] = value;
     return(true);
 }
 private void ReadProperties(PsdReader reader, int level, Properties props)
 {
     reader.Skip('\t', level);
     char c = reader.ReadChar();
     if (c == ']')
     {
         return;
     }
     else if (c == '<')
     {
         reader.Skip('<');
     }
     reader.Skip('\n');
     //Properties props = new Properties();
     while (true)
     {
         reader.Skip('\t', level);
         c = reader.ReadChar();
         if (c == '>')
         {
             reader.Skip('>');
             return;
         }
         else
         {
             //assert c == 9;
             c = reader.ReadChar();
             //assert c == '/' : "unknown char: " + c + " on level: " + level;
             string name = string.Empty;
             while (true)
             {
                 c = reader.ReadChar();
                 if (c == ' ' || c == 10)
                 {
                     break;
                 }
                 name += c;
             }
             if (c == 10)
             {
                 Properties p = new Properties();
                 this.ReadProperties(reader, level + 1, p);
                 if (p.Count > 0)
                     props.Add(name, p);
                 reader.Skip('\n');
             }
             else if (c == ' ')
             {
                 object value = this.ReadValue(reader, level + 1);
                 props.Add(name, value);
             }
             else
             {
                 //assert false;
             }
         }
     }
 }
 public void AddProperty(IdentifierExpression property)
 {
     Properties.Add(property);
 }
Beispiel #31
0
 /// <summary>
 /// Optimized version of [[Put]] when the property is known to be undeclared already
 /// </summary>
 /// <param name="name"></param>
 /// <param name="value"></param>
 /// <param name="writable"></param>
 /// <param name="configurable"></param>
 /// <param name="enumerable"></param>
 public void FastAddProperty(string name, JsValue value, bool writable, bool enumerable, bool configurable)
 {
     Properties.Add(name, new PropertyDescriptor(value, writable, enumerable, configurable));
 }
Beispiel #32
0
        public SyntheticType(IType baseType)
        {
            if (!ShouldBeSyntheticType(baseType))
            {
                throw new ArgumentException("{0} is not a valid type for SyntheticType", baseType.ToString());
            }

            // gosdk: Ensure the generated name does not collide with existing type names
            BaseType = baseType;

            IType elementType = getElementType(baseType);

            if (elementType is PrimaryType)
            {
                var type = (elementType as PrimaryType).Type;
                if (type == KnownPrimaryType.Boolean)
                {
                    Name += "Bool";
                }
                else if (type == KnownPrimaryType.ByteArray)
                {
                    Name += "ByteArray";
                }
                else if (type == KnownPrimaryType.Double)
                {
                    Name += "Float64";
                }
                else if (type == KnownPrimaryType.Int)
                {
                    Name += "Int32";
                }
                else if (type == KnownPrimaryType.Long)
                {
                    Name += "Int64";
                }
                else if (type == KnownPrimaryType.Stream)
                {
                    Name += "ReadCloser";
                }
                else if (type == KnownPrimaryType.String)
                {
                    Name += "String";
                }
                else if (type == KnownPrimaryType.TimeSpan)
                {
                    Name += "TimeSpan";
                }
                else if (type == KnownPrimaryType.Base64Url)
                {
                    Name += "Base64Url";
                }
                else if (type == KnownPrimaryType.UnixTime)
                {
                    Name += "UnixTime";
                }
            }
            else if (elementType is InterfaceType)
            {
                Name += "Object";
            }
            else if (elementType is PackageType)
            {
                Name += (elementType as PackageType).Member;
            }
            else if (elementType is EnumType)
            {
                Name += "String";
            }
            else
            {
                Name += elementType.Name;
            }

            Property p = new Property();

            p.SerializedName = "value";
            p.Name           = "Value";
            p.Type           = baseType;
            Properties.Add(p);
        }
		/// <summary>
		/// Sends the exception's message and stacktrace, plus additional information the
		/// program thinks may be relevant. Limitted to MAX_EXCEPTION_REPORTS_PER_RUN
		/// </summary>
		public static void ReportException(Exception e, Dictionary<string, string> moreProperties)
		{
			if (!AllowTracking)
				return;

			_exceptionCount++;

			// we had an incident where some problem caused a user to emit hundreds of thousands of exceptions,
			// in the background, blowing through our Analytics service limits and getting us kicked off.
			if (_exceptionCount > MAX_EXCEPTION_REPORTS_PER_RUN)
			{
				return;
			}

			var props = new Properties()
			{
				{ "Message", e.Message },
				{ "Stack Trace", e.StackTrace }
			};
			if (moreProperties != null)
			{
				foreach (var key in moreProperties.Keys)
				{
					props.Add(key, moreProperties[key]);
				}
			}
			TrackWithApplicationProperties("Exception", props);
		}
Beispiel #34
0
 /// <summary>
 /// Default constructor to add the property for design time translation.
 /// </summary>
 public TreeViewItemIsExpandedDesignModeValueProvider()
 {
     Debug.Assert(!_propertyIdentifier.IsEmpty, "Static constructor should have been called!");
     Properties.Add(_propertyIdentifier);
 }
Beispiel #35
0
        /// <summary>
        /// Loads all properties from database into objects. If this method is re-called, it will re-query the database.
        /// </summary>
        /// <remarks>
        /// This optimizes sql calls. This will first check if all of the properties have been loaded. If not, 
        /// then it will query for all property types for the current version from the db. It will then iterate over each
        /// cmdPropertyData row and store the id and propertyTypeId in a list for lookup later. Once the records have been 
        /// read, we iterate over the cached property types for this ContentType and create a new property based on
        /// our stored list of proeprtyTypeIds. We then have a cached list of Property objects which will get returned
        /// on all subsequent calls and is also used to return a property with calls to getProperty.
        /// </remarks>
        private void InitializeProperties()
        {
            m_LoadedProperties = new Properties();

            if (ContentBase != null)
            {
                //NOTE: we will not load any properties where HasIdentity = false - this is because if properties are 
                // added to the property collection that aren't persisted we'll get ysods
                m_LoadedProperties.AddRange(ContentBase.Properties.Where(x => x.HasIdentity).Select(x => new Property(x)));
                return;
            }

            if (this.ContentType == null)
                return;

            //Create anonymous typed list with 2 props, Id and PropertyTypeId of type Int.
            //This will still be an empty list since the props list is empty.
            var propData = m_LoadedProperties.Select(x => new { Id = 0, PropertyTypeId = 0 }).ToList();

            string sql = @"select id, propertyTypeId from cmsPropertyData where versionId=@versionId";

            using (IRecordsReader dr = SqlHelper.ExecuteReader(sql,
                SqlHelper.CreateParameter("@versionId", Version)))
            {
                while (dr.Read())
                {
                    //add the item to our list
                    propData.Add(new { Id = dr.Get<int>("id"), PropertyTypeId = dr.Get<int>("propertyTypeId") });
                }
            }

            foreach (PropertyType pt in this.ContentType.PropertyTypes)
            {
                if (pt == null)
                    continue;

                //get the propertyId
                var property = propData.LastOrDefault(x => x.PropertyTypeId == pt.Id);
                if (property == null)
                {
                    continue;
                    //var prop = Property.MakeNew(pt, this, Version);
                    //property = new {Id = prop.Id, PropertyTypeId = pt.Id};
                }
                var propertyId = property.Id;

                Property p = null;
                try
                {
                    p = new Property(propertyId, pt);
                }
                catch
                {
                    continue; //this remains from old code... not sure why we would do this?
                }

                m_LoadedProperties.Add(p);
            }
        }
Beispiel #36
0
        public TestAmendment()
        {
            #region Methods

            // Modify Multiply to also set the Result property to the resulting value
            Methods
            .Named("Multiply")
            .WithParams <int, int>()
            .Before((T instance, ref int x, ref int y) => instance.Result = x * y);

            // Modify SlowSum to measure the method execution time
            Methods
            .Named("SlowSum")
            .WithParams <int[]>()
            .Before((T instance, ref int[] values)
                    => { var s = new Stopwatch(); s.Start(); return(s); })
            .Catch <Exception>((instance, exception, stopwatch, values) => values.Sum())
            .Finally((instance, stopwatch, values)
                     => instance.Result = (int)stopwatch.ElapsedMilliseconds);

            // Modify Multiply to also set the Result property to the resulting value
            Methods
            .Named("Add")
            .WithParams <int, int>()
            .Implement((instance, x, y) => x + y);

            // Modify Multiply2 to also set the Result property to the resulting value
            // Demonstrates use of array syntax
            Methods
            .Named("Multiply2")
            .Before((instance, methodName, parameters)
                    => instance.Result = (int)parameters[0] * (int)parameters[1]);

            // Modify Divide to change the second parameter value to 1 every time
            Methods
            .Named("Divide")
            .WithParams <int, int>()
            .Before((T instance, ref int x, ref int y)
                    => y = 1);


            // Modify Divide2 to change the second parameter value to 1 every time
            Methods
            .Named("Divide2")
            .Before((instance, methodName, parameters)
                    => parameters[1] = 1);

            // Replace implementation of Square to correct coding error
            Methods
            .Named("Square")
            .WithParams <int>()
            .Implement((instance, x)
                       => x * x);

            // Modify Double to double each of the input values
            Methods
            .Named("Double")
            .WithParams <int[]>()
            .After((instance, set) =>
            {
                for (int i = 0; i < set.Length; i++)
                {
                    set[i] = set[i] * 2;
                }
            });

            // Modify Double to double each of the input values
            Methods
            .Named("Double2")
            .After((instance, methodName, parameters) =>
            {
                for (int i = 0; i < ((int[])parameters[0]).Length; i++)
                {
                    ((int[])parameters[0])[i] = ((int[])parameters[0])[i] * 2;
                }
            });

            // Modify Sum to return the sum of the input values
            Methods
            .Named("Sum")
            .WithParams <int[]>()
            .After <long>((instance, set, result)
                          => set.Sum());

            // Modify Sum2 to return the sum of the input values
            Methods
            .Named("Sum2")
            .After((instance, methodName, parameters, result)
                   => (long)((int[])parameters[0]).Sum());


            // Modify the input values but ignore the return value
            Methods
            .Named("Sum3")
            .After((instance, methodName, parameters) =>
            {
                for (int i = 1; i < ((int[])parameters[0]).Length; i++)
                {
                    ((int[])parameters[0])[i] = ((int[])parameters[0])[i - 1] + ((int[])parameters[0])[i];
                }
            });

            #endregion

            #region Properties

            // public int Count { get; set; }
            Properties
            .Add <int>("Count");

            // public int Three { get { return One + Two; } }
            Properties
            .Add <int>("Three")
            .Get((instance, property) => instance.One + instance.Two);

            // public string LazyRandomName { get { if (lazyRandomName == null) lazyRandomName = "r" + new Random().Next(); return lazyRandomName; } }
            Properties
            .Add <string>("LazyRandomName", (instance, property) => "r" + new Random().Next());

            // public int SetResult { set { Result = value; } }
            Properties
            .Add <int>("SetResult")
            .Set((instance, property, value) => instance.Result = value);

            // public int InitiallyTwelve { get; set; } = 12
            Properties
            .Add <int>("InitiallyTwelve")
            .Initialize((instance, property) => 12);

            // Modify Random1 getter set value of Random1 to GetRandom(1) before returning the underlying property value
            Properties
            .Named("Random1")
            .BeforeGet((instance, propertyName) => instance.Random1 = instance.GetRandom(1));

            // Modify Random2 to calculate a random number based on an assigned seed value
            Properties
            .Named("Random2")
            .OfType <int>()
            .AfterGet((instance, propertyName, result) => instance.GetRandom(result));

            // Modify ILog.e property
            Properties
            .Named("Afterthought.UnitTest.Target.ILog.e")
            .OfType <decimal>()
            .Get((instance, propertyName) => 2.71828m);

            // Modify Random5 to be just a simple getter/setter using Result property as the backing store
            Properties
            .Named("Random5")
            .OfType <int>()
            .Get((instance, propertyName) => instance.Result)
            .Set((instance, propertyName, value) => instance.Result = value);

            // Update Result to equal the value assigned to CopyToResult
            Properties
            .Named("CopyToResult")
            .OfType <int>()
            .BeforeSet((instance, propertyName, oldValue, value) => { instance.Result = value; return(value); });

            // Modify Add to add the old value to the value being assigned
            Properties
            .Named("Add")
            .OfType <int>()
            .BeforeSet((instance, propertyName, oldValue, value) => oldValue + value);

            // Initialize InitiallyThirteen to 13
            Properties
            .Named("InitiallyThirteen")
            .OfType <int>()
            .Initialize((instance, propertyName) => 13);

            // Initialize ExistingLazyRandomName
            Properties
            .Named("ExistingLazyRandomName")
            .OfType <string>()
            .LazyInitialize((instance, propertyName) => "r" + new Random().Next());

            #endregion

            #region Interfaces

            // Implement IMath interface
            Implement <IMath>(

                // Pi
                Properties.Add <decimal>("Pi").Get((instance, property) => 3.14159m),

                // Subtract(x, y)
                Methods.Add("Subtract", (T instance, decimal x, decimal y) => x - y)
                );

            #endregion

            #region Attributes

            // Type Attributes
            Attributes.Add <TestAttribute, Type>(typeof(string));
            Attributes.Add <TestAttribute>();
            Attributes.Add <TestAttribute, int>(5);
            Attributes.Add <TestAttribute, string[]>(new string[] { "Testing", "Two" });

            // Field Attributes
            Fields
            .Named("holding1")
            .AddAttribute <TestAttribute, Type>(typeof(string))
            .AddAttribute <TestAttribute>()
            .AddAttribute <TestAttribute, int>(5)
            .AddAttribute <TestAttribute, string[]>(new string[] { "Testing", "Two" });

            // Constructor Attributes
            Constructors
            .WithParams()
            .AddAttribute <TestAttribute, Type>(typeof(string))
            .AddAttribute <TestAttribute>()
            .AddAttribute <TestAttribute, int>(5)
            .AddAttribute <TestAttribute, string[]>(new string[] { "Testing", "Two" });

            // Property Attributes
            Properties
            .Named("Random1")
            .AddAttribute <TestAttribute, Type>(typeof(string))
            .AddAttribute <TestAttribute>()
            .AddAttribute <TestAttribute, int>(5)
            .AddAttribute <TestAttribute, string[]>(new string[] { "Testing", "Two" });

            // Method Attributes
            Methods
            .Named("Multiply")
            .AddAttribute <TestAttribute, Type>(typeof(string))
            .AddAttribute <TestAttribute>()
            .AddAttribute <TestAttribute, int>(5)
            .AddAttribute <TestAttribute, string[]>(new string[] { "Testing", "Two" });

            // EventAttributes
            Events
            .Named("Calculate")
            .AddAttribute <TestAttribute, Type>(typeof(string))
            .AddAttribute <TestAttribute>()
            .AddAttribute <TestAttribute, int>(5)
            .AddAttribute <TestAttribute, string[]>(new string[] { "Testing", "Two" });

            #endregion
        }
        /// <summary>
        /// Reads the APP1 section containing Exif metadata.
        /// </summary>
        private void ReadExifAPP1()
        {
            // Find the APP1 section containing Exif metadata
            exifApp1 = Sections.Find(a => (a.Marker == JPEGMarker.APP1) &&
                                     a.Header.Length >= 6 &&
                                     (Encoding.ASCII.GetString(a.Header, 0, 6) == "Exif\0\0"));

            // If there is no APP1 section, add a new one after the last APP0 section (if any).
            if (exifApp1 == null)
            {
                int insertionIndex = Sections.FindLastIndex(a => a.Marker == JPEGMarker.APP0);
                if (insertionIndex == -1)
                {
                    insertionIndex = 0;
                }
                insertionIndex++;
                exifApp1 = new JPEGSection(JPEGMarker.APP1);
                Sections.Insert(insertionIndex, exifApp1);
                if (BitConverterEx.SystemByteOrder == BitConverterEx.ByteOrder.LittleEndian)
                {
                    ByteOrder = BitConverterEx.ByteOrder.LittleEndian;
                }
                else
                {
                    ByteOrder = BitConverterEx.ByteOrder.BigEndian;
                }
                return;
            }

            byte[] header = exifApp1.Header;
            SortedList <int, IFD> ifdqueue = new SortedList <int, IFD>();

            makerNoteOffset = 0;

            // TIFF header
            int tiffoffset = 6;

            if (header[tiffoffset] == 0x49 && header[tiffoffset + 1] == 0x49)
            {
                ByteOrder = BitConverterEx.ByteOrder.LittleEndian;
            }
            else if (header[tiffoffset] == 0x4D && header[tiffoffset + 1] == 0x4D)
            {
                ByteOrder = BitConverterEx.ByteOrder.BigEndian;
            }
            else
            {
                throw new NotValidExifFileException();
            }

            // TIFF header may have a different byte order
            BitConverterEx.ByteOrder tiffByteOrder = ByteOrder;
            if (BitConverterEx.LittleEndian.ToUInt16(header, tiffoffset + 2) == 42)
            {
                tiffByteOrder = BitConverterEx.ByteOrder.LittleEndian;
            }
            else if (BitConverterEx.BigEndian.ToUInt16(header, tiffoffset + 2) == 42)
            {
                tiffByteOrder = BitConverterEx.ByteOrder.BigEndian;
            }
            else
            {
                throw new NotValidExifFileException();
            }

            // Offset to 0th IFD
            int ifd0offset = (int)BitConverterEx.ToUInt32(header, tiffoffset + 4, tiffByteOrder, BitConverterEx.SystemByteOrder);

            ifdqueue.Add(ifd0offset, IFD.Zeroth);

            BitConverterEx conv        = new BitConverterEx(ByteOrder, BitConverterEx.SystemByteOrder);
            int            thumboffset = -1;
            int            thumblength = 0;
            int            thumbtype   = -1;

            // Read IFDs
            while (ifdqueue.Count != 0)
            {
                int ifdoffset  = tiffoffset + ifdqueue.Keys[0];
                IFD currentifd = ifdqueue.Values[0];
                ifdqueue.RemoveAt(0);

                // Field count
                ushort fieldcount = conv.ToUInt16(header, ifdoffset);
                for (short i = 0; i < fieldcount; i++)
                {
                    // Read field info
                    int    fieldoffset = ifdoffset + 2 + 12 * i;
                    ushort tag         = conv.ToUInt16(header, fieldoffset);
                    ushort type        = conv.ToUInt16(header, fieldoffset + 2);
                    uint   count       = conv.ToUInt32(header, fieldoffset + 4);
                    byte[] value       = new byte[4];
                    Array.Copy(header, fieldoffset + 8, value, 0, 4);

                    // Fields containing offsets to other IFDs
                    if (currentifd == IFD.Zeroth && tag == 0x8769)
                    {
                        int exififdpointer = (int)conv.ToUInt32(value, 0);
                        ifdqueue.Add(exififdpointer, IFD.EXIF);
                    }
                    else if (currentifd == IFD.Zeroth && tag == 0x8825)
                    {
                        int gpsifdpointer = (int)conv.ToUInt32(value, 0);
                        ifdqueue.Add(gpsifdpointer, IFD.GPS);
                    }
                    else if (currentifd == IFD.EXIF && tag == 0xa005)
                    {
                        int interopifdpointer = (int)conv.ToUInt32(value, 0);
                        ifdqueue.Add(interopifdpointer, IFD.Interop);
                    }

                    // Save the offset to maker note data
                    if (currentifd == IFD.EXIF && tag == 37500)
                    {
                        makerNoteOffset = conv.ToUInt32(value, 0);
                    }

                    // Calculate the bytes we need to read
                    uint baselength = 0;
                    if (type == 1 || type == 2 || type == 7)
                    {
                        baselength = 1;
                    }
                    else if (type == 3)
                    {
                        baselength = 2;
                    }
                    else if (type == 4 || type == 9)
                    {
                        baselength = 4;
                    }
                    else if (type == 5 || type == 10)
                    {
                        baselength = 8;
                    }
                    uint totallength = count * baselength;

                    // If field value does not fit in 4 bytes
                    // the value field is an offset to the actual
                    // field value
                    int fieldposition = 0;
                    if (totallength > 4)
                    {
                        fieldposition = tiffoffset + (int)conv.ToUInt32(value, 0);
                        value         = new byte[totallength];
                        Array.Copy(header, fieldposition, value, 0, totallength);
                    }

                    // Compressed thumbnail data
                    if (currentifd == IFD.First && tag == 0x201)
                    {
                        thumbtype   = 0;
                        thumboffset = (int)conv.ToUInt32(value, 0);
                    }
                    else if (currentifd == IFD.First && tag == 0x202)
                    {
                        thumblength = (int)conv.ToUInt32(value, 0);
                    }

                    // Uncompressed thumbnail data
                    if (currentifd == IFD.First && tag == 0x111)
                    {
                        thumbtype = 1;
                        // Offset to first strip
                        if (type == 3)
                        {
                            thumboffset = (int)conv.ToUInt16(value, 0);
                        }
                        else
                        {
                            thumboffset = (int)conv.ToUInt32(value, 0);
                        }
                    }
                    else if (currentifd == IFD.First && tag == 0x117)
                    {
                        thumblength = 0;
                        for (int j = 0; j < count; j++)
                        {
                            if (type == 3)
                            {
                                thumblength += (int)conv.ToUInt16(value, 0);
                            }
                            else
                            {
                                thumblength += (int)conv.ToUInt32(value, 0);
                            }
                        }
                    }

                    // Create the exif property from the interop data
                    ExifProperty prop = ExifPropertyFactory.Get(tag, type, count, value, ByteOrder, currentifd, Encoding);
                    Properties.Add(prop);
                }

                // 1st IFD pointer
                int firstifdpointer = (int)conv.ToUInt32(header, ifdoffset + 2 + 12 * fieldcount);
                if (firstifdpointer != 0)
                {
                    ifdqueue.Add(firstifdpointer, IFD.First);
                }
                // Read thumbnail
                if (thumboffset != -1 && thumblength != 0 && Thumbnail == null)
                {
                    if (thumbtype == 0)
                    {
                        using (MemoryStream ts = new MemoryStream(header, tiffoffset + thumboffset, thumblength))
                        {
                            Thumbnail = ImageFile.FromStream(ts);
                        }
                    }
                }
            }
        }
Beispiel #38
0
        /// <summary>
        /// Loads all properties from database into objects. If this method is re-called, it will re-query the database.
        /// </summary>
        /// <remarks>
        /// This optimizes sql calls. This will first check if all of the properties have been loaded. If not, 
        /// then it will query for all property types for the current version from the db. It will then iterate over each
        /// cmdPropertyData row and store the id and propertyTypeId in a list for lookup later. Once the records have been 
        /// read, we iterate over the cached property types for this ContentType and create a new property based on
        /// our stored list of proeprtyTypeIds. We then have a cached list of Property objects which will get returned
        /// on all subsequent calls and is also used to return a property with calls to getProperty.
        /// </remarks>
        private void InitializeProperties()
        {
            m_LoadedProperties = new Properties();

            if (this.ContentType == null)
                return;

            //Create anonymous typed list with 2 props, Id and PropertyTypeId of type Int.
            //This will still be an empty list since the props list is empty.
            var propData = m_LoadedProperties.Select(x => new { Id = 0, PropertyTypeId = 0 }).ToList();

            string sql = @"select id, propertyTypeId from cmsPropertyData where versionId=@versionId";

            using (IRecordsReader dr = SqlHelper.ExecuteReader(sql,
                SqlHelper.CreateParameter("@versionId", Version)))
            {
                while (dr.Read())
                {
                    //add the item to our list
                    propData.Add(new { Id = dr.Get<int>("id"), PropertyTypeId = dr.Get<int>("propertyTypeId") });
                }
            }

            foreach (PropertyType pt in this.ContentType.PropertyTypes)
            {
                if (pt == null)
                    continue;

                //get the propertyId
                var property = propData
                    .Where(x => x.PropertyTypeId == pt.Id)
                    .SingleOrDefault();
                if (property == null)
                    continue;
                var propertyId = property.Id;

                Property p = null;
                try
                {
                    p = new Property(propertyId, pt);
                }
                catch
                {
                    continue; //this remains from old code... not sure why we would do this?
                }

                m_LoadedProperties.Add(p);
            }
        }
Beispiel #39
0
        public override PropertyDescriptor GetOwnProperty(string propertyName)
        {
            PropertyDescriptor x;

            if (Properties.TryGetValue(propertyName, out x))
            {
                return(x);
            }

            var type = Target.GetType();

            // look for a property
            var property = type
                           .GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public)
                           .FirstOrDefault(p => EqualsIgnoreCasing(p.Name, propertyName));

            if (property != null)
            {
                var descriptor = new PropertyInfoDescriptor(Engine, property, Target);
                Properties.Add(propertyName, descriptor);
                return(descriptor);
            }

            // look for a field
            var field = type
                        .GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public)
                        .FirstOrDefault(f => EqualsIgnoreCasing(f.Name, propertyName));

            if (field != null)
            {
                var descriptor = new FieldInfoDescriptor(Engine, field, Target);
                Properties.Add(propertyName, descriptor);
                return(descriptor);
            }

            // if no properties were found then look for a method
            var methods = type.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public)
                          .Where(m => EqualsIgnoreCasing(m.Name, propertyName))
                          .ToArray();

            if (methods.Any())
            {
                var descriptor = new PropertyDescriptor(new MethodInfoFunctionInstance(Engine, methods), false, true, false);
                Properties.Add(propertyName, descriptor);
                return(descriptor);
            }

            // if no methods are found check if target implemented indexing
            if (type.GetProperties().FirstOrDefault(p => p.GetIndexParameters().Length != 0) != null)
            {
                return(new IndexDescriptor(Engine, propertyName, Target));
            }

            var interfaces = type.GetInterfaces();

            // try to find a single explicit property implementation
            var explicitProperties = (from iface in interfaces
                                      from iprop in iface.GetProperties()
                                      where EqualsIgnoreCasing(iprop.Name, propertyName)
                                      select iprop).ToArray();

            if (explicitProperties.Length == 1)
            {
                var descriptor = new PropertyInfoDescriptor(Engine, explicitProperties[0], Target);
                Properties.Add(propertyName, descriptor);
                return(descriptor);
            }

            // try to find explicit method implementations
            var explicitMethods = (from iface in interfaces
                                   from imethod in iface.GetMethods()
                                   where EqualsIgnoreCasing(imethod.Name, propertyName)
                                   select imethod).ToArray();

            if (explicitMethods.Length > 0)
            {
                var descriptor = new PropertyDescriptor(new MethodInfoFunctionInstance(Engine, explicitMethods), false, true, false);
                Properties.Add(propertyName, descriptor);
                return(descriptor);
            }

            // try to find explicit indexer implementations
            var explicitIndexers =
                (from iface in interfaces
                 from iprop in iface.GetProperties()
                 where iprop.GetIndexParameters().Length != 0
                 select iprop).ToArray();

            if (explicitIndexers.Length == 1)
            {
                return(new IndexDescriptor(Engine, explicitIndexers[0].DeclaringType, propertyName, Target));
            }

            return(PropertyDescriptor.Undefined);
        }
Beispiel #40
0
 /// <summary>
 /// Adds a property to the collection
 /// </summary>
 /// <param name="key">Property key</param>
 /// <param name="value">Property value</param>
 public void AddProperty(string key, string value)
 {
     Properties.Add(new ItemProperty(key, value));
 }
Beispiel #41
0
 public ActivePlatformsAttribute(params Platform[] platforms)
 {
     Properties.Add("ActivePlatforms", platforms);
 }
		private static Properties MakeSegmentIOProperties(Dictionary<string, string> properties)
		{
			var prop = new Properties();
			foreach (var key in properties.Keys)
			{
				prop.Add(key, properties[key]);
			}
			return prop;
			return prop;
		}
		/// <summary>
		/// Sends the exception's message and stacktrace, plus additional information the
		/// program thinks may be relevant.
		/// </summary>
		public static void ReportException(Exception e, Dictionary<string, string> moreProperties)
		{
			if (!AllowTracking)
				return;

			var props = new Properties()
			{
				{ "Message", e.Message },
				{ "Stack Trace", e.StackTrace }
			};
			if (moreProperties != null)
			{
				foreach (var key in moreProperties.Keys)
				{
					props.Add(key, moreProperties[key]);
				}
			}
			TrackWithDefaultProperties("Exception", props);
		}