static EntityPropertyResolvers()
 {
     // ReSharper disable PossibleInvalidOperationException
     DefaultInternal = new Dictionary <Type, IEntityPropertyResolver>
     {
         { typeof(bool), new EntityPropertyResolver <bool>(member => EntityProperty.GeneratePropertyForBool(member), entityProperty => entityProperty.BooleanValue.Value) },
         { typeof(bool?), new EntityPropertyResolver <bool?>(EntityProperty.GeneratePropertyForBool, entityProperty => entityProperty.BooleanValue) },
         { typeof(int), new EntityPropertyResolver <int>(member => EntityProperty.GeneratePropertyForInt(member), entityProperty => entityProperty.Int32Value.Value) },
         { typeof(int?), new EntityPropertyResolver <int?>(EntityProperty.GeneratePropertyForInt, entityProperty => entityProperty.Int32Value) },
         { typeof(long), new EntityPropertyResolver <long>(member => EntityProperty.GeneratePropertyForLong(member), entityProperty => entityProperty.Int64Value.Value) },
         { typeof(long?), new EntityPropertyResolver <long?>(EntityProperty.GeneratePropertyForLong, entityProperty => entityProperty.Int64Value) },
         { typeof(double), new EntityPropertyResolver <double>(member => EntityProperty.GeneratePropertyForDouble(member), entityProperty => entityProperty.DoubleValue.Value) },
         { typeof(double?), new EntityPropertyResolver <double?>(EntityProperty.GeneratePropertyForDouble, entityProperty => entityProperty.DoubleValue) },
         { typeof(decimal), new EntityPropertyResolver <decimal>(member => EntityProperty.GeneratePropertyForString(member.ToString(CultureInfo.InvariantCulture)), entityProperty => decimal.Parse(entityProperty.StringValue)) },
         { typeof(decimal?), new EntityPropertyResolver <decimal?>(member => EntityProperty.GeneratePropertyForString(member?.ToString(CultureInfo.InvariantCulture)), entityProperty => entityProperty.StringValue == null ? (decimal?)null : decimal.Parse(entityProperty.StringValue)) },
         { typeof(Guid), new EntityPropertyResolver <Guid>(member => EntityProperty.GeneratePropertyForGuid(member), entityProperty => entityProperty.GuidValue.Value) },
         { typeof(Guid?), new EntityPropertyResolver <Guid?>(EntityProperty.GeneratePropertyForGuid, entityProperty => entityProperty.GuidValue) },
         { typeof(DateTime), new EntityPropertyResolver <DateTime>(member => EntityProperty.GeneratePropertyForDateTimeOffset(member), entityProperty => entityProperty.DateTime.Value) },
         { typeof(DateTime?), new EntityPropertyResolver <DateTime?>(member => EntityProperty.GeneratePropertyForDateTimeOffset(member), entityProperty => entityProperty.DateTime) },
         { typeof(DateTimeOffset), new EntityPropertyResolver <DateTimeOffset>(member => EntityProperty.GeneratePropertyForDateTimeOffset(member), entityProperty => entityProperty.DateTimeOffsetValue.Value) },
         { typeof(DateTimeOffset?), new EntityPropertyResolver <DateTimeOffset?>(EntityProperty.GeneratePropertyForDateTimeOffset, entityProperty => entityProperty.DateTimeOffsetValue) },
         { typeof(string), new EntityPropertyResolver <string>(EntityProperty.GeneratePropertyForString, entityProperty => entityProperty.StringValue) },
         { typeof(byte[]), new EntityPropertyResolver <byte[]>(EntityProperty.GeneratePropertyForByteArray, entityProperty => entityProperty.BinaryValue) },
         { typeof(Uri), new EntityPropertyResolver <Uri>(member => EntityProperty.GeneratePropertyForString(member?.ToString()), entityProperty => entityProperty.StringValue == null ? null : new Uri(entityProperty.StringValue)) }
     };
     // ReSharper restore PossibleInvalidOperationException
 }
        public void TableEntityPropertyGenerator()
        {
            string pk = Guid.NewGuid().ToString();
            string rk = Guid.NewGuid().ToString();
            Dictionary <string, EntityProperty> properties = new Dictionary <string, EntityProperty>();
            EntityProperty boolEntity = EntityProperty.GeneratePropertyForBool(true);

            properties.Add("boolEntity", boolEntity);
            EntityProperty timeEntity = EntityProperty.GeneratePropertyForDateTimeOffset(DateTimeOffset.UtcNow);

            properties.Add("timeEntity", timeEntity);
            EntityProperty doubleEntity = EntityProperty.GeneratePropertyForDouble(0.1);

            properties.Add("doubleEntity", doubleEntity);
            EntityProperty guidEntity = EntityProperty.GeneratePropertyForGuid(Guid.NewGuid());

            properties.Add("guidEntity", guidEntity);
            EntityProperty intEntity = EntityProperty.GeneratePropertyForInt(1);

            properties.Add("intEntity", intEntity);
            EntityProperty longEntity = EntityProperty.GeneratePropertyForLong(1);

            properties.Add("longEntity", longEntity);
            EntityProperty stringEntity = EntityProperty.GeneratePropertyForString("string");

            properties.Add("stringEntity", stringEntity);

            DynamicReplicatedTableEntity ent = new DynamicReplicatedTableEntity(pk, rk, "*", properties);

            this.repTable.Execute(TableOperation.Insert(ent));
        }
Example #3
0
 IDictionary <string, EntityProperty> ITableEntity.WriteEntity(OperationContext operationContext)
 {
     return(new Dictionary <string, EntityProperty>
     {
         { CountPropertyName, EntityProperty.GeneratePropertyForLong(Count) }
     });
 }
Example #4
0
        private EntityProperty CreateEntityPropertyWithNullValue(EdmType edmType)
        {
            switch (edmType)
            {
            case EdmType.String:
                return(EntityProperty.GeneratePropertyForString(null));

            case EdmType.Binary:
                return(EntityProperty.GeneratePropertyForByteArray(null));

            case EdmType.Boolean:
                return(EntityProperty.GeneratePropertyForBool(null));

            case EdmType.DateTime:
                return(EntityProperty.GeneratePropertyForDateTimeOffset(null));

            case EdmType.Double:
                return(EntityProperty.GeneratePropertyForDouble(null));

            case EdmType.Guid:
                return(EntityProperty.GeneratePropertyForGuid(null));

            case EdmType.Int32:
                return(EntityProperty.GeneratePropertyForInt(null));

            case EdmType.Int64:
                return(EntityProperty.GeneratePropertyForLong(null));

            default:
                throw new InvalidOperationException("Unexpected EdmType");
            }
        }
Example #5
0
        /// <inheritdoc />
        public override IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            var result = new Dictionary <string, EntityProperty>();

            foreach (var prop in Fields)
            {
                var name = prop.Key;
                var val  = prop.Value;
                switch (val)
                {
                case string str:
                    result.Add(name, EntityProperty.GeneratePropertyForString(str));
                    break;

                case bool bl:
                    result.Add(name, EntityProperty.GeneratePropertyForBool(bl));
                    break;

                case DateTimeOffset dt:
                    result.Add(name, EntityProperty.GeneratePropertyForDateTimeOffset(dt));
                    break;

                case DateTime dt:
                    result.Add(name, EntityProperty.GeneratePropertyForDateTimeOffset(new DateTimeOffset(dt)));
                    break;

                case float db:
                    result.Add(name, EntityProperty.GeneratePropertyForDouble(db));
                    break;

                case double db:
                    result.Add(name, EntityProperty.GeneratePropertyForDouble(db));
                    break;

                case Guid gd:
                    result.Add(name, EntityProperty.GeneratePropertyForGuid(gd));
                    break;

                case int it:
                    result.Add(name, EntityProperty.GeneratePropertyForInt(it));
                    break;

                case short it:
                    result.Add(name, EntityProperty.GeneratePropertyForInt(it));
                    break;

                case long lg:
                    result.Add(name, EntityProperty.GeneratePropertyForLong(lg));
                    break;

                case null:
                    break;

                default:
                    throw new NotSupportedException("Field is not supported: " + val.GetType());
                }
            }

            return(result);
        }
        public void Create_Int64_ConvertThrowsIfNullValue()
        {
            // Act
            IConverter <EntityProperty, long> converter = EntityPropertyToTConverterFactory.Create <long>();

            // Assert
            AssertConvertThrowsIfNullValue(converter, EntityProperty.GeneratePropertyForLong(null));
        }
        public void Create_NullableInt64_CanConvertNullValue()
        {
            // Act
            IConverter <EntityProperty, long?> converter = EntityPropertyToTConverterFactory.Create <long?>();

            // Assert
            AssertCanConvertNullValue(converter, EntityProperty.GeneratePropertyForLong(null));
        }
Example #8
0
            public void SetTdsStatus(string key, long value)
            {
                CloudTable _table0 = GetTable(0);

                DynamicTableEntity tdsPropEntity = new DynamicTableEntity("Prop", key);

                tdsPropEntity.Properties.Add("N001", EntityProperty.GeneratePropertyForLong(value));
                _table0.ExecuteAsync(TableOperation.InsertOrMerge(tdsPropEntity)).Wait();
            }
        private static EntityProperty CreateEntityProperty(JsonSerializer serializer, JProperty property)
        {
            if (property != null)
            {
                return(null !);
            }

            var            list    = JObject.Parse(property !.Value.ToString()).Properties().ToList();
            var            edmType = (EdmType)Enum.Parse(typeof(EdmType), list[1].Value.ToString(), true);
            EntityProperty entityProperty;

            switch ((int)edmType)
            {
            case 0:
                entityProperty =
                    EntityProperty.GeneratePropertyForString(list[0].Value.ToObject <string>(serializer));
                break;

            case 1:
                entityProperty =
                    EntityProperty.GeneratePropertyForByteArray(list[0].Value.ToObject <byte[]>(serializer));
                break;

            case 2:
                entityProperty = EntityProperty.GeneratePropertyForBool(list[0].Value.ToObject <bool>(serializer));
                break;

            case 3:
                entityProperty =
                    EntityProperty.GeneratePropertyForDateTimeOffset(list[0].Value
                                                                     .ToObject <DateTimeOffset>(serializer));
                break;

            case 4:
                entityProperty =
                    EntityProperty.GeneratePropertyForDouble(list[0].Value.ToObject <double>(serializer));
                break;

            case 5:
                entityProperty = EntityProperty.GeneratePropertyForGuid(list[0].Value.ToObject <Guid>(serializer));
                break;

            case 6:
                entityProperty = EntityProperty.GeneratePropertyForInt(list[0].Value.ToObject <int>(serializer));
                break;

            case 7:
                entityProperty = EntityProperty.GeneratePropertyForLong(list[0].Value.ToObject <long>(serializer));
                break;

            default:
                throw new NotSupportedException($"Unsupported EntityProperty.PropertyType:{edmType} detected during deserialization");
            }

            return(entityProperty);
        }
Example #10
0
 public IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext) =>
 new Dictionary <string, EntityProperty>
 {
     [nameof(Id)]           = EntityProperty.GeneratePropertyForLong(Id),
     [nameof(Name)]         = EntityProperty.GeneratePropertyForString(Name),
     [nameof(IsRunning)]    = EntityProperty.GeneratePropertyForBool(IsRunning),
     [nameof(PartitionKey)] = EntityProperty.GeneratePropertyForString(PartitionKey),
     [nameof(RowKey)]       = EntityProperty.GeneratePropertyForString(RowKey),
     [nameof(Timestamp)]    = EntityProperty.GeneratePropertyForDateTimeOffset(Timestamp),
     [nameof(ETag)]         = EntityProperty.GeneratePropertyForString(ETag)
 };
Example #11
0
        public IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            var dict = new Dictionary <string, EntityProperty>
            {
                [PayloadKeyName]  = EntityProperty.GeneratePropertyForByteArray(Payload),
                [ManifestKeyName] = EntityProperty.GeneratePropertyForString(Manifest),
                [SeqNoKeyName]    = EntityProperty.GeneratePropertyForLong(SeqNo)
            };

            return(dict);
        }
Example #12
0
        /// <summary>
        /// Generates a record in the jobstable and initializes the currentBlob
        /// </summary>
        private static bool InitializeJob()
        {
            //Initialize Job
            jobInfo = new DynamicTableEntity()
            {
                PartitionKey = conf.BatchId,
                RowKey       = jobId
            };
            jobInfo.Properties.Add("WorkerId", EntityProperty.GeneratePropertyForString(workerId));
            jobInfo.Properties.Add("BlobUrl", EntityProperty.GeneratePropertyForString(currentBlobUrl));
            jobInfo.Properties.Add("Status", EntityProperty.GeneratePropertyForString("Started"));
            jobInfo.Properties.Add("DownStarted", EntityProperty.GeneratePropertyForString(Utilities.Now2Log));



            //preparing entity for inserting the job info in the jobs table
            var blobName = Utilities.BlobNameByUrl(currentBlobUrl);

            srcContainer = srcBlobClient.GetContainerReference(conf.SrcContainerName);
            bool sourceExists;

            if (sourceExists = srcContainer.ExistsAsync().Result) //Checking existence of source blob
            {
                var blobReference = srcContainer.GetBlobReference(blobName);
                if (sourceExists = blobReference.ExistsAsync().Result)
                {
                    //checking existence of destiny blog. If it exists, the line parameter checking overwrites is evaluated
                    var destBlobReference = destContainer.GetBlobReference(blobName);
                    var destinyExists     = destBlobReference.ExistsAsync().Result;
                    var okToUpload        = !destinyExists || conf.OverwriteIfExists;
                    if (okToUpload)
                    {
                        currentBlob = (CloudBlob)srcBlobClient.GetBlobReferenceFromServerAsync(new Uri(currentBlobUrl)).Result;
                        _           = currentBlob.FetchAttributesAsync();
                        jobInfo.Properties.Add("Size", EntityProperty.GeneratePropertyForLong(currentBlob.Properties.Length));
                        UpdateJobInfo();
                        return(true);
                    }
                    else
                    {
                        UpdateJobInfo("DestBlobExists");
                        LogUpdate($"Destiny {blobName} blob already exists and overwriting has not been declared in the batch parameter. Job will be removed from queue.");
                    }
                }
            }
            if (!sourceExists)
            {
                UpdateJobInfo("SrcBlobMissing");
                LogUpdate($"Source {blobName} blob missing. Job will be removed from queue.");
            }
            jobsQueue.DeleteMessageAsync(jobMessage);
            return(false);
        }
Example #13
0
        public IDictionary <string, EntityProperty> WriteEntity(
            OperationContext operationContext)
        {
            var dict =
                new Dictionary <string, EntityProperty>
            {
                [HighestSequenceNrKey] = EntityProperty.GeneratePropertyForLong(HighestSequenceNr),
                [ManifestKeyName]      = EntityProperty.GeneratePropertyForString(Manifest),
            };

            return(dict);
        }
        public void GetEventDateTimeOffset_UsesEventTickCount()
        {
            var entity = new DynamicTableEntity("foo", "bar")
            {
                Timestamp = _date
            };

            var itsYesterday = _date.Subtract(TimeSpan.FromDays(1));

            entity.Properties.Add("EventTickCount", EntityProperty.GeneratePropertyForLong(itsYesterday.Ticks));

            Assert.Equal(itsYesterday, entity.GetEventDateTimeOffset());
        }
        private static EntityProperty CreateEntityProperty(
            JsonSerializer serializer,
            JProperty property)
        {
            if (property == null)
            {
                return((EntityProperty)null);
            }
            List <JProperty> list    = JObject.Parse(((object)property.Value).ToString()).Properties().ToList <JProperty>();
            EdmType          edmType = (EdmType)Enum.Parse(typeof(EdmType), ((object)list[1].Value).ToString(), true);
            EntityProperty   entityProperty;

            switch ((int)edmType)
            {
            case 0:
                entityProperty = EntityProperty.GeneratePropertyForString((string)list[0].Value.ToObject <string>(serializer));
                break;

            case 1:
                entityProperty = EntityProperty.GeneratePropertyForByteArray((byte[])list[0].Value.ToObject <byte[]>(serializer));
                break;

            case 2:
                entityProperty = EntityProperty.GeneratePropertyForBool(new bool?((bool)list[0].Value.ToObject <bool>(serializer)));
                break;

            case 3:
                entityProperty = EntityProperty.GeneratePropertyForDateTimeOffset(new DateTimeOffset?((DateTimeOffset)list[0].Value.ToObject <DateTimeOffset>(serializer)));
                break;

            case 4:
                entityProperty = EntityProperty.GeneratePropertyForDouble(new double?((double)list[0].Value.ToObject <double>(serializer)));
                break;

            case 5:
                entityProperty = EntityProperty.GeneratePropertyForGuid(new Guid?((Guid)list[0].Value.ToObject <Guid>(serializer)));
                break;

            case 6:
                entityProperty = EntityProperty.GeneratePropertyForInt(new int?((int)list[0].Value.ToObject <int>(serializer)));
                break;

            case 7:
                entityProperty = EntityProperty.GeneratePropertyForLong(new long?((long)list[0].Value.ToObject <long>(serializer)));
                break;

            default:
                throw new NotSupportedException(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Unsupported EntityProperty.PropertyType:{0} detected during deserialization.", (object)edmType));
            }
            return(entityProperty);
        }
Example #16
0
        /// <summary>
        ///     Function member to validate field type.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>EntityProperty converted from object</returns>
        /// <exception cref="System.ArgumentException">Type not supported</exception>
        public static EntityProperty WriteEntityProperty(object value)
        {
            ////******************* WCF Data Services type ************************/
            ////Edm.Binary ->     byte[], An array of bytes up to 64 KB in size.
            ////Edm.Boolean ->    bool, A Boolean value.
            ////Edm.DateTime ->   DateTime, A 64-bit value expressed as Coordinated Universal Time (UTC).
            ////The supported DateTime range begins from 12:00 midnight, January 1, 1601 A.D. (C.E.), UTC. The range ends at December 31, 9999.
            ////Edm.Double ->     double, A 64-bit floating point value.
            ////Edm.Guid ->       Guid, A 128-bit globally unique identifier.
            ////Edm.Int32 ->      Int32 or int, A 32-bit integer.
            ////Edm.Int64 ->      Int64 or long, A 64-bit integer.
            ////Edm.String ->     String, A UTF-16-encoded value. String values may be up to 64 KB in size.

            Type type = value.GetType();

            switch (type.Name)
            {
            // WCF Data Services type
            case "Byte[]":
                return(EntityProperty.GeneratePropertyForByteArray((byte[])value));

            case "Boolean":
                return(EntityProperty.GeneratePropertyForBool((bool)value));

            case "DateTime":
                return(EntityProperty.GeneratePropertyForDateTimeOffset(new DateTimeOffset((DateTime)value)));

            case "DateTimeOffset":
                return(EntityProperty.GeneratePropertyForDateTimeOffset((DateTimeOffset)value));

            case "Double":
                return(EntityProperty.GeneratePropertyForDouble((double)value));

            case "Guid":
                return(EntityProperty.GeneratePropertyForGuid((Guid)value));

            case "Int32":
                return(EntityProperty.GeneratePropertyForInt((int)value));

            case "Int64":
                return(EntityProperty.GeneratePropertyForLong((long)value));

            case "String":
                return(EntityProperty.GeneratePropertyForString((string)value));

            default:
                throw new ArgumentException(string.Format("Type \"{0}\" is not supported.", type.FullName));
            }
        }
Example #17
0
            public IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
            {
                //Azure Lib calls this when it wants to transform this entity to a writeable one

                var dic = new Dictionary <string, EntityProperty>();

                foreach (KeyValuePair <string, DynamicValue> cell in _row)
                {
                    EntityProperty ep;

                    Type t = cell.Value.OriginalType;

                    if (t == typeof(bool))
                    {
                        ep = EntityProperty.GeneratePropertyForBool(cell.Value);
                    }
                    else if (t == typeof(DateTime) || t == typeof(DateTimeOffset))
                    {
                        ep = EntityProperty.GeneratePropertyForDateTimeOffset(((DateTime)cell.Value).ToUniversalTime());
                    }
                    else if (t == typeof(int))
                    {
                        ep = EntityProperty.GeneratePropertyForInt(cell.Value);
                    }
                    else if (t == typeof(long))
                    {
                        ep = EntityProperty.GeneratePropertyForLong(cell.Value);
                    }
                    else if (t == typeof(double))
                    {
                        ep = EntityProperty.GeneratePropertyForDouble(cell.Value);
                    }
                    else if (t == typeof(Guid))
                    {
                        ep = EntityProperty.GeneratePropertyForGuid(cell.Value);
                    }
                    else if (t == typeof(byte[]))
                    {
                        ep = EntityProperty.GeneratePropertyForByteArray(cell.Value);
                    }
                    else
                    {
                        ep = EntityProperty.GeneratePropertyForString(cell.Value);
                    }

                    dic[cell.Key] = ep;
                }
                return(dic);
            }
Example #18
0
 static DynamicTableEntity ToTableEntity(this Expense expense, string email) =>
 new DynamicTableEntity(email + "+" + expense.Account,
                        expense.Id.Coalesce(Guid.NewGuid()).ToString(),
                        "*",
                        new Dictionary <string, EntityProperty>
 {
     [nameof(Expense.Account)]     = EntityProperty.GeneratePropertyForString(expense.Account),
     [nameof(Expense.Payee)]       = EntityProperty.GeneratePropertyForString(expense.Payee),
     [nameof(Expense.Description)] = EntityProperty.GeneratePropertyForString(expense.Description),
     [nameof(Expense.Status)]      = EntityProperty.GeneratePropertyForString(expense.Status),
     [nameof(Expense.Type)]        = EntityProperty.GeneratePropertyForString(expense.Type),
     [nameof(Expense.Date)]        = EntityProperty.GeneratePropertyForDateTimeOffset(expense.Date),
     [nameof(Expense.Amount)]      = EntityProperty.GeneratePropertyForLong((long)(expense.Amount * 100L)),
     [nameof(Expense.Tags)]        = EntityProperty.GeneratePropertyForString(expense.Tags)
 });
        public IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            var dict =
                new Dictionary <string, EntityProperty>
            {
                [ManifestKeyName]        = EntityProperty.GeneratePropertyForString(Manifest),
                [PayloadKeyName]         = EntityProperty.GeneratePropertyForByteArray(Payload),
                [UtcTicksKeyName]        = EntityProperty.GeneratePropertyForLong(UtcTicks),
                [IdxPartitionKeyKeyName] = EntityProperty.GeneratePropertyForString(IdxPartitionKey),
                [IdxRowKeyKeyName]       = EntityProperty.GeneratePropertyForString(IdxRowKey),
                [IdxTagKeyName]          = EntityProperty.GeneratePropertyForString(IdxTag)
            };

            return(dict);
        }
Example #20
0
        public void Should_ReadEntity()
        {
            var entity  = new Entity();
            var tEntity = (ITableEntity)entity;

            tEntity.ReadEntity(new Dictionary <string, EntityProperty>
            {
                { nameof(Entity.IntValue), EntityProperty.GeneratePropertyForInt(123) },
                { nameof(Entity.LongValue), EntityProperty.GeneratePropertyForLong(null) },
                { nameof(Entity.StringValue), EntityProperty.GeneratePropertyForString("Abc") },
                { nameof(Entity.DateTimeOffsetValue), EntityProperty.GeneratePropertyForDateTimeOffset(DateTimeOffset.Now) },
            }, new OperationContext());

            entity.IntValue.Should().Be(123);
            entity.LongValue.Should().BeNull();
            entity.StringValue.Should().Be("Abc");
            entity.DateTimeOffsetValue.Should().BeOnOrBefore(DateTimeOffset.Now);
        }
Example #21
0
        public static DynamicTableEntity ToEntity(this MetricModel metric, string sourceName, DateTimeOffset timeCaptured)
        {
            var minuteOffset = new DateTimeOffset(DateTime.Parse(timeCaptured.UtcDateTime.ToString("yyyy-MM-dd HH:mm:00")), TimeSpan.Zero);
            var shardKey     = (DateTimeOffset.MaxValue.Ticks - minuteOffset.Ticks).ToString("D19");

            var entity = new DynamicTableEntity(shardKey,
                                                string.Format("{0}_{1}", sourceName, metric.Name));

            entity.Properties.Add("Name", EntityProperty.GeneratePropertyForString(metric.Name));
            entity.Properties.Add("TimeStamp", EntityProperty.GeneratePropertyForDateTimeOffset(metric.TimeStamp));
            entity.Properties.Add("Average", EntityProperty.GeneratePropertyForDouble(metric.Average));
            entity.Properties.Add("Count", EntityProperty.GeneratePropertyForLong(metric.Count));
            entity.Properties.Add("Maximum", EntityProperty.GeneratePropertyForDouble(metric.Maximum));
            entity.Properties.Add("Minimum", EntityProperty.GeneratePropertyForDouble(metric.Minimum));
            entity.Properties.Add("Total", EntityProperty.GeneratePropertyForDouble(metric.Total));

            return(entity);
        }
Example #22
0
        public static DynamicTableEntity ToEntity(
            this EventVersion version, string aggregateId, long commitId)
        {
            Ensure.ArgumentNotNull(version, nameof(version));
            Ensure.ArgumentNotNullOrWhiteSpace(aggregateId, nameof(aggregateId));

            var dte = new DynamicTableEntity(aggregateId, StorageConstants.EventStore.VersionRowValue);

            dte.Properties = new Dictionary <string, EntityProperty>();
            dte.Properties.Add(StorageConstants.EventStore.VersionColumn,
                               EntityProperty.GeneratePropertyForLong(version.Version));
            dte.Properties.Add(StorageConstants.EventStore.LatestCommitID,
                               EntityProperty.GeneratePropertyForLong(commitId));
            // Most important thing here
            dte.ETag = version.ETag;

            return(dte);
        }
        public void TableEntityPropertySetter()
        {
            string pk = Guid.NewGuid().ToString();
            string rk = Guid.NewGuid().ToString();
            Dictionary <string, EntityProperty> properties = new Dictionary <string, EntityProperty>();
            EntityProperty boolEntity = EntityProperty.GeneratePropertyForBool(null);

            boolEntity.BooleanValue = true;
            properties.Add("boolEntity", boolEntity);

            EntityProperty timeEntity = EntityProperty.GeneratePropertyForDateTimeOffset(null);

            timeEntity.DateTimeOffsetValue = DateTimeOffset.UtcNow;
            properties.Add("timeEntity", timeEntity);

            EntityProperty doubleEntity = EntityProperty.GeneratePropertyForDouble(null);

            doubleEntity.DoubleValue = 0.1;
            properties.Add("doubleEntity", doubleEntity);

            EntityProperty guidEntity = EntityProperty.GeneratePropertyForGuid(null);

            guidEntity.GuidValue = Guid.NewGuid();
            properties.Add("guidEntity", guidEntity);

            EntityProperty intEntity = EntityProperty.GeneratePropertyForInt(null);

            intEntity.Int32Value = 1;
            properties.Add("intEntity", intEntity);

            EntityProperty longEntity = EntityProperty.GeneratePropertyForLong(null);

            longEntity.Int64Value = 1;
            properties.Add("longEntity", longEntity);

            EntityProperty stringEntity = EntityProperty.GeneratePropertyForString(null);

            stringEntity.StringValue = "string";
            properties.Add("stringEntity", stringEntity);

            DynamicReplicatedTableEntity ent = new DynamicReplicatedTableEntity(pk, rk, "*", properties);

            this.repTable.Execute(TableOperation.Insert(ent));
        }
Example #24
0
        protected EntityProperty GenerateProperty(EdmType propertyValueType, object propertyValueStr)
        {
            EntityProperty propertyValue;

            switch (propertyValueType)
            {
            case EdmType.String:
                propertyValue = EntityProperty.GeneratePropertyForString((string)propertyValueStr);
                break;

            case EdmType.Binary:
                propertyValue = EntityProperty.GeneratePropertyForByteArray(Convert.FromBase64String(propertyValueStr.ToString()));
                break;

            case EdmType.Boolean:
                propertyValue = EntityProperty.GeneratePropertyForBool(Convert.ToBoolean(propertyValueStr));
                break;

            case EdmType.DateTime:
                propertyValue = EntityProperty.GeneratePropertyForDateTimeOffset((DateTime)propertyValueStr);
                break;

            case EdmType.Double:
                propertyValue = EntityProperty.GeneratePropertyForDouble(Convert.ToDouble(propertyValueStr));
                break;

            case EdmType.Guid:
                propertyValue = EntityProperty.GeneratePropertyForGuid(Guid.Parse(propertyValueStr.ToString()));
                break;

            case EdmType.Int32:
                propertyValue = EntityProperty.GeneratePropertyForInt(Convert.ToInt32(propertyValueStr));
                break;

            case EdmType.Int64:
                propertyValue = EntityProperty.GeneratePropertyForLong(Convert.ToInt64(propertyValueStr));
                break;

            default: throw new ArgumentException($"Can't create table property with Type {string.Join(", ", propertyValueType)} and value {propertyValueStr}");
            }
            return(propertyValue);
        }
Example #25
0
        public static DynamicTableEntity ToEntity(this BusPeckResult result)
        {
            var minuteOffset = new DateTimeOffset(DateTime.Parse(result.TimeCaptured.UtcDateTime.ToString("yyyy-MM-dd HH:mm:00")), TimeSpan.Zero);
            var shardKey     = (DateTimeOffset.MaxValue.Ticks - minuteOffset.Ticks).ToString("D19");

            var entity = new DynamicTableEntity(shardKey,
                                                string.Format("{0}_{1}", result.SourceName, result.QueueName));

            entity.Properties.Add("ActiveMessageCount", EntityProperty.GeneratePropertyForLong(result.ActiveMessageCount));
            entity.Properties.Add("DeadLetterMessageCount", EntityProperty.GeneratePropertyForLong(result.DeadLetterMessageCount));
            entity.Properties.Add("MaxSizeInMB", EntityProperty.GeneratePropertyForLong(result.MaxSizeInMB));
            entity.Properties.Add("ScheduledMessageCount", EntityProperty.GeneratePropertyForLong(result.ScheduledMessageCount));
            entity.Properties.Add("SizeInMB", EntityProperty.GeneratePropertyForLong(result.SizeInMB));
            entity.Properties.Add("QueueName", EntityProperty.GeneratePropertyForString(result.QueueName));
            entity.Properties.Add("SourceName", EntityProperty.GeneratePropertyForString(result.SourceName));
            entity.Properties.Add("TimeCaptured", EntityProperty.GeneratePropertyForDateTimeOffset(result.TimeCaptured));
            entity.Properties.Add("QueueType", EntityProperty.GeneratePropertyForString(result.QueueType));

            return(entity);
        }
Example #26
0
        public override IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            var properties = new Dictionary <string, EntityProperty>();

            foreach (var getter in Getters)
            {
                var value = getter.Value.Item2(Entity);
                if (value == null)
                {
                    continue;
                }
                var            type           = getter.Value.Item1;
                EntityProperty entityProperty = null;
                if (type == typeof(bool) || type == typeof(bool?))
                {
                    entityProperty = EntityProperty.GeneratePropertyForBool((bool?)value);
                }
                else if (type == typeof(int) || type == typeof(int?))
                {
                    entityProperty = EntityProperty.GeneratePropertyForInt((int?)value);
                }
                else if (type == typeof(long) || type == typeof(long?))
                {
                    entityProperty = EntityProperty.GeneratePropertyForLong((long?)value);
                }
                else if (type == typeof(double) || type == typeof(double?))
                {
                    entityProperty = EntityProperty.GeneratePropertyForDouble((double?)value);
                }
                else if (type == typeof(float) || type == typeof(float?))
                {
                    entityProperty = EntityProperty.GeneratePropertyForDouble((float?)value);
                }
                else if (type == typeof(DateTime) || type == typeof(DateTime?))
                {
                    entityProperty = EntityProperty.GeneratePropertyForDateTimeOffset((DateTime?)value);
                }
                else if (type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?))
                {
                    entityProperty = EntityProperty.GeneratePropertyForDateTimeOffset((DateTimeOffset?)value);
                }
                else if (type == typeof(Guid) || type == typeof(Guid?))
                {
                    entityProperty = EntityProperty.GeneratePropertyForGuid((Guid?)value);
                }
                else if (type == typeof(byte[]))
                {
                    entityProperty = EntityProperty.GeneratePropertyForByteArray(value as byte[]);
                }
                else if (type == typeof(string))
                {
                    entityProperty = EntityProperty.GeneratePropertyForString(value as string);
                }

                if (entityProperty != null)
                {
                    properties[getter.Key] = entityProperty;
                }
            }
            return(properties);
        }
Example #27
0
        IDictionary <string, EntityProperty> ITableEntity.WriteEntity(OperationContext operationContext)
        {
            var getter  = getPropertyGetter(GetType());
            var results = new Dictionary <string, EntityProperty>();

            foreach (var(key, item) in _binder.GetValues(this))
            {
                if (key == _rowKey || key == _partitionKey)
                {
                    continue;
                }
                if (key == nameof(PartitionKey) || key == nameof(RowKey))
                {
                    continue;
                }
                EntityProperty entityProperty = null;

                switch (item.Type)
                {
                case JTokenType.Null:
                    entityProperty = new EntityProperty((string)null);
                    break;

                case JTokenType.Boolean:
                    entityProperty = EntityProperty.GeneratePropertyForBool(item.Value <bool>());
                    break;

                case JTokenType.Date:
                    entityProperty = EntityProperty.GeneratePropertyForDateTimeOffset(item.Value <DateTimeOffset>());
                    break;

                case JTokenType.Guid:
                    entityProperty = EntityProperty.GeneratePropertyForGuid(item.Value <Guid>());
                    break;

                case JTokenType.Integer:
                    switch (item.Value)
                    {
                    case short s:
                        entityProperty = EntityProperty.GeneratePropertyForInt(s);
                        break;

                    case int i:
                        entityProperty = EntityProperty.GeneratePropertyForInt(i);
                        break;

                    case long l:
                        entityProperty = EntityProperty.GeneratePropertyForLong(l);
                        break;
                    }
                    break;

                case JTokenType.Float:
                    switch (item.Value)
                    {
                    case float f:
                        entityProperty = EntityProperty.GeneratePropertyForDouble(f);
                        break;

                    case double d:
                        entityProperty = EntityProperty.GeneratePropertyForDouble(d);
                        break;

                    case decimal _:
                        entityProperty = EntityProperty.GeneratePropertyForString(item.Value <string>());
                        break;
                    }
                    break;

                default:
                    if (TryGetPropertyType(getter, GetType(), key, out var _))
                    {
                        var context = getter.Get(this, key);

                        switch (context)
                        {
                        case null:
                            entityProperty = new EntityProperty((string)null);
                            break;

                        case Instant instant:
                            entityProperty = EntityProperty.GeneratePropertyForDateTimeOffset(instant.ToDateTimeOffset());
                            break;

                        case LocalDate localDate:
                            entityProperty = EntityProperty.GeneratePropertyForDateTimeOffset(localDate.ToDateTimeUnspecified());
                            break;

                        case LocalDateTime localDateTime:
                            entityProperty = EntityProperty.GeneratePropertyForDateTimeOffset(localDateTime.ToDateTimeUnspecified());
                            break;

                        case OffsetDateTime offsetDateTime:
                            entityProperty = EntityProperty.GeneratePropertyForDateTimeOffset(offsetDateTime.ToDateTimeOffset());
                            break;

                        case ZonedDateTime zonedDateTime:
                            entityProperty = EntityProperty.GeneratePropertyForDateTimeOffset(zonedDateTime.ToDateTimeOffset());
                            break;

                        default:
                            entityProperty = EntityProperty.GeneratePropertyForString(item.Value <string>());
                            break;
                        }
                    }
                    else
                    {
                        entityProperty = EntityProperty.GeneratePropertyForString(item.Value <string>());
                    }
                    break;
                }

                results.Add(key, entityProperty);
            }
            return(results);
        }
Example #28
0
        static List <PropertyConverter> GetPropertyConvertersForType(Type type)
        {
            var          propertyConverters = new List <PropertyConverter>();
            BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;

            // Loop through the type hierarchy to find all [DataMember] attributes which belong to [DataContract] classes.
            while (type != null && type.GetCustomAttribute <DataContractAttribute>() != null)
            {
                foreach (MemberInfo member in type.GetMembers(flags))
                {
                    DataMemberAttribute dataMember = member.GetCustomAttribute <DataMemberAttribute>();
                    if (dataMember == null)
                    {
                        continue;
                    }

                    PropertyInfo property = member as PropertyInfo;
                    FieldInfo    field    = member as FieldInfo;
                    if (property == null && field == null)
                    {
                        throw new InvalidDataContractException("Only fields and properties can be marked as [DataMember].");
                    }
                    else if (property != null && (!property.CanWrite || !property.CanRead))
                    {
                        throw new InvalidDataContractException("[DataMember] properties must be both readable and writeable.");
                    }

                    // Timestamp is a reserved property name in Table Storage, so the name needs to be changed.
                    string propertyName = dataMember.Name ?? member.Name;
                    if (string.Equals(propertyName, "Timestamp", StringComparison.OrdinalIgnoreCase))
                    {
                        propertyName = "_Timestamp";
                    }

                    Func <object, EntityProperty>   getEntityPropertyFunc;
                    Action <object, EntityProperty> setObjectPropertyFunc;

                    Type memberValueType = property != null ? property.PropertyType : field.FieldType;
                    if (typeof(string).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForString((string)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.StringValue);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForString((string)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.StringValue);
                        }
                    }
                    else if (memberValueType.IsEnum)
                    {
                        // Enums are serialized as strings for readability.
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForString(property.GetValue(o).ToString());
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, Enum.Parse(memberValueType, e.StringValue));
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForString(field.GetValue(o).ToString());
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, Enum.Parse(memberValueType, e.StringValue));
                        }
                    }
                    else if (typeof(int?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForInt((int?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.Int32Value);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForInt((int?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.Int32Value);
                        }
                    }
                    else if (typeof(long?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForLong((long?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.Int64Value);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForLong((long?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.Int64Value);
                        }
                    }
                    else if (typeof(bool?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForBool((bool?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.BooleanValue);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForBool((bool?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.BooleanValue);
                        }
                    }
                    else if (typeof(DateTime?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForDateTimeOffset((DateTime?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.DateTime);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForDateTimeOffset((DateTime?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.DateTime);
                        }
                    }
                    else if (typeof(DateTimeOffset?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForDateTimeOffset((DateTimeOffset?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.DateTimeOffsetValue);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForDateTimeOffset((DateTimeOffset?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.DateTimeOffsetValue);
                        }
                    }
                    else if (typeof(Guid?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForGuid((Guid?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.GuidValue);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForGuid((Guid?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.GuidValue);
                        }
                    }
                    else if (typeof(double?).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForDouble((double?)property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.DoubleValue);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForDouble((double?)field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.DoubleValue);
                        }
                    }
                    else if (typeof(byte[]).IsAssignableFrom(memberValueType))
                    {
                        if (property != null)
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForByteArray((byte[])property.GetValue(o));
                            setObjectPropertyFunc = (o, e) => property.SetValue(o, e.BinaryValue);
                        }
                        else
                        {
                            getEntityPropertyFunc = o => EntityProperty.GeneratePropertyForByteArray((byte[])field.GetValue(o));
                            setObjectPropertyFunc = (o, e) => field.SetValue(o, e.BinaryValue);
                        }
                    }
                    else // assume a serializeable object
                    {
                        getEntityPropertyFunc = o =>
                        {
                            object value = property != null?property.GetValue(o) : field.GetValue(o);

                            string json = value != null?JsonConvert.SerializeObject(value) : null;

                            return(EntityProperty.GeneratePropertyForString(json));
                        };

                        setObjectPropertyFunc = (o, e) =>
                        {
                            string json  = e.StringValue;
                            object value = json != null?JsonConvert.DeserializeObject(json, memberValueType) : null;

                            if (property != null)
                            {
                                property.SetValue(o, value);
                            }
                            else
                            {
                                field.SetValue(o, value);
                            }
                        };
                    }

                    propertyConverters.Add(new PropertyConverter(propertyName, getEntityPropertyFunc, setObjectPropertyFunc));
                }

                type = type.BaseType;
            }

            return(propertyConverters);
        }
        /// <inheritdoc />
        public override IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            var result = new Dictionary <string, EntityProperty>();

            foreach (var prop in GetType().GetRuntimeProperties().Where(p => p.CanWrite && !Excluded.Contains(p.Name)))
            {
                var name = prop.Name;
                var val  = prop.GetValue(this);
                if (prop.GetCustomAttribute <IgnorePropertyAttribute>() != null)
                {
                    continue;
                }

                if (prop.GetCustomAttribute <BooleanColumns>() != null &&
                    typeof(IEnumerable <string>).IsAssignableFrom(prop.PropertyType))
                {
                    var set = (IEnumerable <string>)prop.GetValue(this);
                    foreach (var setval in set)
                    {
                        result.Add($"{name}_{EscapeColumnName(setval)}", EntityProperty.GeneratePropertyForBool(true));
                    }

                    continue;
                }

                switch (val)
                {
                case string str:
                    result.Add(name, EntityProperty.GeneratePropertyForString(str));
                    break;

                case bool bl:
                    result.Add(name, EntityProperty.GeneratePropertyForBool(bl));
                    break;

                case DateTimeOffset dt:
                    result.Add(name, EntityProperty.GeneratePropertyForDateTimeOffset(dt));
                    break;

                case DateTime dt:
                    result.Add(name, EntityProperty.GeneratePropertyForDateTimeOffset(new DateTimeOffset(dt)));
                    break;

                case float db:
                    result.Add(name, EntityProperty.GeneratePropertyForDouble(db));
                    break;

                case double db:
                    result.Add(name, EntityProperty.GeneratePropertyForDouble(db));
                    break;

                case Guid gd:
                    result.Add(name, EntityProperty.GeneratePropertyForGuid(gd));
                    break;

                case int it:
                    result.Add(name, EntityProperty.GeneratePropertyForInt(it));
                    break;

                case short it:
                    result.Add(name, EntityProperty.GeneratePropertyForInt(it));
                    break;

                case long lg:
                    result.Add(name, EntityProperty.GeneratePropertyForLong(lg));
                    break;

                case null:
                    break;

                default:
                    result.Add(
                        name,
                        EntityProperty.GeneratePropertyForString(
                            val?.GetType().IsEnum == true ? GetEnumValue(val) : JsonSerializer.Serialize(val)));
                    break;
                }
            }

            return(result);
        }