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));
        }
Exemple #3
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");
            }
        }
Exemple #4
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 async Task ProcessEventsAsync(PartitionContext context, IEnumerable <EventData> messages)
        {
            var batch = new TableBatchOperation();

            foreach (var msg in messages)
            {
                var snap = await JsonConvert.DeserializeObjectAsync <BusSnapshotInfo>(Encoding.UTF8.GetString(msg.GetBytes()));

                var entity = new DynamicTableEntity(snap.RouteShortName, snap.VehicleId.ToString());

                entity.Properties.Add("RouteShortName", EntityProperty.GeneratePropertyForString(snap.RouteShortName));
                entity.Properties.Add("VehicleId", EntityProperty.GeneratePropertyForInt(snap.VehicleId));
                entity.Properties.Add("TripId", EntityProperty.GeneratePropertyForInt(snap.TripId));
                entity.Properties.Add("Latitude", EntityProperty.GeneratePropertyForDouble(snap.Latitude));
                entity.Properties.Add("Longitude", EntityProperty.GeneratePropertyForDouble(snap.Longitude));
                entity.Properties.Add("DirectionOfTravel", EntityProperty.GeneratePropertyForString(snap.DirectionOfTravel.ToString()));
                entity.Properties.Add("NextStopId", EntityProperty.GeneratePropertyForInt(snap.NextStopId));
                entity.Properties.Add("Timeliness", EntityProperty.GeneratePropertyForString(snap.Timeliness.ToString()));
                entity.Properties.Add("TimelinessOffset", EntityProperty.GeneratePropertyForInt(snap.TimelinessOffset));
                entity.Properties.Add("Timestamp", EntityProperty.GeneratePropertyForDateTimeOffset(snap.Timestamp));

                batch.Add(TableOperation.InsertOrReplace(entity));
            }

            var tableClient = _account.CreateCloudTableClient();

            var table = tableClient.GetTableReference("snapshots");

            await table.CreateIfNotExistsAsync();

            await table.ExecuteBatchAsync(batch);

            await context.CheckpointAsync();
        }
        public void Create_Double_ConvertThrowsIfNullValue()
        {
            // Act
            IConverter <EntityProperty, double> converter = EntityPropertyToTConverterFactory.Create <double>();

            // Assert
            AssertConvertThrowsIfNullValue(converter, EntityProperty.GeneratePropertyForDouble(null));
        }
        public void Create_NullableDouble_CanConvertNullValue()
        {
            // Act
            IConverter <EntityProperty, double?> converter = EntityPropertyToTConverterFactory.Create <double?>();

            // Assert
            AssertCanConvertNullValue(converter, EntityProperty.GeneratePropertyForDouble(null));
        }
        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);
        }
        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);
        }
Exemple #10
0
        /// <summary>
        /// Updates the data cache status.
        /// </summary>
        /// <param name="partitionKey">The partition key.</param>
        /// <param name="rowKey">The row key.</param>
        /// <param name="timeTaken">The time taken.</param>
        private void UpdateDataCacheStatus(string partitionKey, string rowKey, TimeSpan timeTaken)
        {
            DynamicTableEntity dataCacheDetail = new DynamicTableEntity();

            dataCacheDetail.PartitionKey = partitionKey;
            dataCacheDetail.RowKey       = rowKey;
            dataCacheDetail.Properties.Add("status", EntityProperty.GeneratePropertyForInt(1));
            dataCacheDetail.Properties.Add("TotalTime_InSec", EntityProperty.GeneratePropertyForDouble(timeTaken.TotalSeconds));

            //true value will make sure cached data will be updated in specified time
            dataCacheDetail.Properties.Add("NeedsUpdate", EntityProperty.GeneratePropertyForBool(true));

            this.DalcCommon.InsertEntity(Utils.GetRegionalTableName(Constants.DataCacheUpdateStatusTableName), dataCacheDetail);
        }
Exemple #11
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));
            }
        }
Exemple #12
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);
            }
        public void ProcessMigrate(IdentityCloudContext targetContext,
                                   IdentityCloudContext sourceContext,
                                   IList <DynamicTableEntity> claimResults,
                                   int maxDegreesParallel,
                                   Action updateComplete       = null,
                                   Action <string> updateError = null)
        {
            const string KeyVersion = "KeyVersion";

            var claims = claimResults
                         .Where(UserWhereFilter)
                         .ToList();


            var result2 = Parallel.ForEach(claims, new ParallelOptions()
            {
                MaxDegreeOfParallelism = maxDegreesParallel
            }, (claim) =>
            {
                //Add the new claim index
                try
                {
                    var claimNew = new DynamicTableEntity(claim.PartitionKey,
                                                          _keyHelper.GenerateRowKeyIdentityUserClaim(claim.Properties["ClaimType"].StringValue, claim.Properties["ClaimValue"].StringValue),
                                                          Constants.ETagWildcard,
                                                          claim.Properties);
                    if (claimNew.Properties.ContainsKey(KeyVersion))
                    {
                        claimNew.Properties[KeyVersion].DoubleValue = _keyHelper.KeyVersion;
                    }
                    else
                    {
                        claimNew.Properties.Add(KeyVersion, EntityProperty.GeneratePropertyForDouble(_keyHelper.KeyVersion));
                    }

                    var taskExecute = targetContext.UserTable.ExecuteAsync(TableOperation.InsertOrReplace(claimNew));
                    taskExecute.Wait();

                    updateComplete?.Invoke();
                }
                catch (Exception ex)
                {
                    updateError?.Invoke(string.Format("{0}\t{1}", claim.PartitionKey, ex.Message));
                }
            });
        }
Exemple #14
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);
        }
        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));
        }
Exemple #16
0
            public void SetEntityItem(DateTimeOffset dateTime, dynamic item)
            {
                char[] nums  = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
                string name  = (string)item.Name;
                int    pos   = name.IndexOfAny(nums);
                int    ch    = int.Parse(name.Substring(pos));
                int    index = ch / ENTITE_NUMS + 1;
                var    prop  = string.Format("C{0:D4}", ch);

                DataKey = dateTime.UtcDateTime.ToString("DyyyyMMddHHmmssfff");
                DynamicTableEntity nameTableEntity = NameEntityManager.GetTableEntity(index, "Name");
                DynamicTableEntity dataTableEntity = DataEntityManager.GetTableEntity(index, DataKey);

                SetEntityValue(nameTableEntity, "ADATE", EntityProperty.GeneratePropertyForString("Date Time"));
                SetEntityValue(dataTableEntity, "ADATE", EntityProperty.GeneratePropertyForString(dateTime.ToString(DATETIMEOFFSET_FORMAT)));

                SetEntityValue(nameTableEntity, prop, EntityProperty.GeneratePropertyForString(item.Name));
                SetEntityValue(dataTableEntity, prop, EntityProperty.GeneratePropertyForDouble((double)item.Value));
            }
Exemple #17
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);
        }
        public void TestMonthlyCarSalesDecoding()
        {
            ReflectionMapper reflectionMapper = new ReflectionMapper(typeof(MonthlyCountryEVCarSales));

            Dictionary <string, EntityProperty> properties = new Dictionary <string, EntityProperty>();

            properties["Sources"] = EntityProperty.GeneratePropertyForString(
                "http://testsource.com, http://anothersource.com"
                );

            properties["SalesPercent"] = EntityProperty.GeneratePropertyForDouble(34.6);
            MonthlyCountryEVCarSales sales = reflectionMapper.Convert <MonthlyCountryEVCarSales>(typeof(MonthlyCountryEVCarSales), "Norway", "2019_1", properties);

            Assert.IsNotNull(sales);
            Assert.AreEqual(sales.Country, "Norway");
            Assert.AreEqual(sales.Year, 2019);
            Assert.AreEqual(sales.Month, 1);
            Assert.AreEqual(sales.SalesPercent, 34.6m);
            Assert.AreEqual(sales.Sources, new string[] { "http://testsource.com", "http://anothersource.com" }.ToList());
        }
Exemple #19
0
        public IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            var retorno = new Dictionary <string, EntityProperty>
            {
                { nameof(PartitionKey), EntityProperty.GeneratePropertyForString(PartitionKey) },
                { nameof(RowKey), EntityProperty.GeneratePropertyForString(RowKey) },
                { nameof(Timestamp), EntityProperty.GeneratePropertyForDateTimeOffset(Timestamp) },
                { nameof(ETag), EntityProperty.GeneratePropertyForString(ETag) },
                { nameof(Email), EntityProperty.GeneratePropertyForString(Email) },
                { nameof(Biotipo), EntityProperty.GeneratePropertyForString(Biotipo) },
                { nameof(Genero), EntityProperty.GeneratePropertyForString(Genero) },
                { nameof(Idade), EntityProperty.GeneratePropertyForInt(Idade) },
                { nameof(Altura), EntityProperty.GeneratePropertyForInt(Altura) },
                { nameof(Peso), EntityProperty.GeneratePropertyForInt(Peso) },
                { nameof(FrequenciaTreino), EntityProperty.GeneratePropertyForString(FrequenciaTreino) },
                { nameof(MetaCalorica), EntityProperty.GeneratePropertyForDouble(MetaCalorica) },
                { nameof(MetaProteica), EntityProperty.GeneratePropertyForDouble(MetaProteica) }
            };

            return(retorno);
        }
Exemple #20
0
        private static EntityProperty CreateEntityPropertyFromJProperty(JProperty property)
        {
            switch (property.Value.Type)
            {
            case JTokenType.String:
                return(EntityProperty.GeneratePropertyForString((string)property.Value));

            case JTokenType.Integer:
                return(EntityProperty.GeneratePropertyForInt((int)property.Value));

            case JTokenType.Boolean:
                return(EntityProperty.GeneratePropertyForBool((bool)property.Value));

            case JTokenType.Guid:
                return(EntityProperty.GeneratePropertyForGuid((Guid)property.Value));

            case JTokenType.Float:
                return(EntityProperty.GeneratePropertyForDouble((double)property.Value));

            default:
                return(EntityProperty.CreateEntityPropertyFromObject((object)property.Value));
            }
        }
        public void ConvertTableEntityToDictionary()
        {
            var ahora  = DateTimeOffset.FromFileTime(129000000000000000).UtcDateTime;
            var entity = new DynamicTableEntity("ali", "ostad", "eTag", new Dictionary <string, EntityProperty> {
                { "whah??", EntityProperty.GeneratePropertyForDateTimeOffset(ahora) },
                { "inty", EntityProperty.GeneratePropertyForInt(123) },
                { "doubly", EntityProperty.GeneratePropertyForDouble(123.23) },
                { "booly", EntityProperty.GeneratePropertyForBool(false) },
                { "stringy", EntityProperty.GeneratePropertyForString("magical unicorns") },
                { "ignored1", EntityProperty.GeneratePropertyForString(",") },
                { "ignored2", EntityProperty.GeneratePropertyForString("") }
            })
            {
                Timestamp = ahora.Subtract(TimeSpan.FromDays(42))
            };

            var source = new DiagnosticsSourceSummary {
                TypeName = "typename"
            };

            source.DynamicProperties[ConveyorBeltConstants.TimestampFieldName] = "whah??";

            var dict = entity.ToDictionary(source);

            Assert.Equal("typename", dict["cb_type"]);
            Assert.Equal("ali", dict["PartitionKey"]);
            Assert.Equal("ostad", dict["RowKey"]);
            Assert.Equal(ahora.ToString("s"), dict["whah??"]);
            Assert.Equal("123", dict["inty"]);
            Assert.Equal("123.23", dict["doubly"]);
            Assert.Equal("false", dict["booly"]);
            Assert.Equal("magical unicorns", dict["stringy"]);
            Assert.Equal(ahora.ToString("s"), dict["@timestamp"]);
            Assert.False(dict.ContainsKey("ignored1"));
            Assert.False(dict.ContainsKey("ignored2"));
            Assert.Equal(9, dict.Count);
        }
Exemple #22
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);
        }
Exemple #23
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);
        }
Exemple #25
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);
        }