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));
        }
Ejemplo n.º 2
0
        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();
        }
 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
 }
Ejemplo n.º 4
0
 IDictionary <string, EntityProperty> ITableEntity.WriteEntity(OperationContext operationContext)
 {
     return(new Dictionary <string, EntityProperty>
     {
         { PlaceHolderPropertyName, EntityProperty.GeneratePropertyForInt(1) }
     });
 }
Ejemplo n.º 5
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");
            }
        }
Ejemplo n.º 6
0
        private async Task <DynamicTableEntity> TryInsertTableEntityAsync(CloudTableClient client, DynamicTableEntity entity, int index, bool addProperty = false)
        {
            try
            {
                DynamicTableEntity clonedEntity = Helpers.Clone(entity);
                if (addProperty)
                {
                    clonedEntity.Properties["regionId"] = EntityProperty.GeneratePropertyForInt(index);
                    clonedEntity.Properties["region"]   = EntityProperty.GeneratePropertyForString(client.ConnectionPolicy.PreferredLocations[0]);
                }

                Console.WriteLine("\tInserting entity with Partition Key :{0}, Row Key: {1} to region: {2}", entity.PartitionKey, entity.RowKey, client.ConnectionPolicy.PreferredLocations[0]);
                TableResult result = await client.GetTableReference(this.tableName).ExecuteAsync(TableOperation.Insert(clonedEntity));

                return(entity);
            }
            catch (StorageException exception)
            {
                if (exception.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict)
                {
                    return(null);
                }

                throw;
            }
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        public virtual DynamicTableEntity Write(T data)
        {
            if (data == null)
            {
                return(null);
            }
            DynamicTableEntity e = new DynamicTableEntity(data.PartitionKey, data.RowKey);

            foreach (var propInfo in typeof(T).GetProperties())
            {
                var tblColumnAttr = propInfo.GetCustomAttribute <TableColumnAttribute>();
                if (tblColumnAttr != null)
                {
                    var columnName = tblColumnAttr.Name;
                    var val        = propInfo.GetValue(data);
                    if (propInfo.PropertyType.IsEnum)
                    {
                        var intval = (int)val;
                        e.Properties[columnName] = EntityProperty.GeneratePropertyForInt(intval);
                    }
                    else
                    {
                        e.Properties[columnName] = EntityProperty.CreateEntityPropertyFromObject(val);
                    }
                }
            }

            return(e);
        }
        public override IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            var entity = base.WriteEntity(operationContext);

            entity.Add(nameof(BatchState), EntityProperty.GeneratePropertyForInt((int)BatchState));

            return(entity);
        }
        public void Create_Int32_ConvertThrowsIfNullValue()
        {
            // Act
            IConverter <EntityProperty, int> converter = EntityPropertyToTConverterFactory.Create <int>();

            // Assert
            AssertConvertThrowsIfNullValue(converter, EntityProperty.GeneratePropertyForInt(null));
        }
        public void Create_NullableInt32_CanConvertNullValue()
        {
            // Act
            IConverter <EntityProperty, int?> converter = EntityPropertyToTConverterFactory.Create <int?>();

            // Assert
            AssertCanConvertNullValue(converter, EntityProperty.GeneratePropertyForInt(null));
        }
Ejemplo n.º 12
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 PmseSyncStatus(string partitionKey, string rowKey, TimeSpan timeTaken)
        {
            DynamicTableEntity pmseSyncDetail = new DynamicTableEntity();

            pmseSyncDetail.PartitionKey = partitionKey;
            pmseSyncDetail.RowKey       = rowKey;
            pmseSyncDetail.Properties.Add("status", EntityProperty.GeneratePropertyForInt(1));
            this.PmseSync.InsertEntity(Utils.GetRegionalTableName(Constants.PmseSyncStatusTableName), pmseSyncDetail);
        }
        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);
        }
        public DynamicTableEntity ConvertToDynamicEntity(SerializedClefLog log)
        {
            var properties = DistributeDataByProperties(log.Data);

            properties[VERSION] = EntityProperty.GeneratePropertyForInt(1);
            return(new DynamicTableEntity
            {
                Properties = properties
            });
        }
        public void CanConvertFromSourceToSummary_WithAlternateTypeName()
        {
            var entity = new DynamicTableEntity("pk", "rk");

            entity.Properties["dpi"] = EntityProperty.GeneratePropertyForInt(2);
            entity.Properties["AlternateTypeName"] = EntityProperty.GeneratePropertyForString("vahshi");
            var source = new DiagnosticsSource(entity);

            var summary = source.ToSummary();

            Assert.Equal(summary.TypeName, source.ToTypeKey());
        }
Ejemplo n.º 16
0
        public IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            IDictionary <string, EntityProperty> ret = new Dictionary <string, EntityProperty>();

            // Add the custom properties here
            ret.Add(nameof(LastSequence), EntityProperty.GeneratePropertyForInt(LastSequence));
            ret.Add(nameof(Context), EntityProperty.GeneratePropertyForString(Context));
            ret.Add(nameof(DomainName), EntityProperty.GeneratePropertyForString(DomainName));
            ret.Add(nameof(EntityTypeName), EntityProperty.GeneratePropertyForString(EntityTypeName));
            ret.Add(nameof(InstanceKey), EntityProperty.GeneratePropertyForString(InstanceKey));
            return(ret);
        }
        public IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            var result = new Dictionary <string, EntityProperty>
            {
                { "Id", EntityProperty.GeneratePropertyForGuid(this.ID) },
                { nameof(this.Tenant), EntityProperty.GeneratePropertyForString(this.Tenant) },
                { nameof(this.Username), EntityProperty.GeneratePropertyForString(this.Username) },
                { nameof(this.Email), EntityProperty.GeneratePropertyForString(this.Email) },
                { nameof(this.Created), EntityProperty.GeneratePropertyForDateTimeOffset(this.Created) },
                { nameof(this.LastUpdated), EntityProperty.GeneratePropertyForDateTimeOffset(this.LastUpdated) },
                { nameof(this.IsAccountClosed), EntityProperty.GeneratePropertyForBool(this.IsAccountClosed) },
                { nameof(this.AccountClosed), EntityProperty.GeneratePropertyForDateTimeOffset(this.AccountClosed) },
                { nameof(this.IsLoginAllowed), EntityProperty.GeneratePropertyForBool(this.IsLoginAllowed) },
                { nameof(this.LastLogin), EntityProperty.GeneratePropertyForDateTimeOffset(this.LastLogin) },
                { nameof(this.LastFailedLogin), EntityProperty.GeneratePropertyForDateTimeOffset(this.LastFailedLogin) },
                { nameof(this.FailedLoginCount), EntityProperty.GeneratePropertyForInt(this.FailedLoginCount) },
                { nameof(this.PasswordChanged), EntityProperty.GeneratePropertyForDateTimeOffset(this.PasswordChanged) },
                { nameof(this.RequiresPasswordReset), EntityProperty.GeneratePropertyForBool(this.RequiresPasswordReset) },
                { nameof(this.IsAccountVerified), EntityProperty.GeneratePropertyForBool(this.IsAccountVerified) },
                { nameof(this.LastFailedPasswordReset), EntityProperty.GeneratePropertyForDateTimeOffset(this.LastFailedPasswordReset) },
                { nameof(this.FailedPasswordResetCount), EntityProperty.GeneratePropertyForInt(this.FailedPasswordResetCount) },

                { nameof(this.MobileCode), EntityProperty.GeneratePropertyForString(this.MobileCode) },
                { nameof(this.MobileCodeSent), EntityProperty.GeneratePropertyForDateTimeOffset(this.MobileCodeSent) },
                { nameof(this.MobilePhoneNumber), EntityProperty.GeneratePropertyForString(this.MobilePhoneNumber) },
                { nameof(this.MobilePhoneNumberChanged), EntityProperty.GeneratePropertyForDateTimeOffset(this.MobilePhoneNumberChanged) },

                { nameof(this.AccountTwoFactorAuthMode), EntityProperty.GeneratePropertyForString(this.AccountTwoFactorAuthMode.ToString()) },
                { nameof(this.CurrentTwoFactorAuthStatus), EntityProperty.GeneratePropertyForString(this.CurrentTwoFactorAuthStatus.ToString()) },
                { nameof(this.VerificationKey), EntityProperty.GeneratePropertyForString(this.VerificationKey) },
                { nameof(this.VerificationPurpose), EntityProperty.GeneratePropertyForString(this.VerificationPurpose?.ToString()) },
                { nameof(this.VerificationKeySent), EntityProperty.GeneratePropertyForDateTimeOffset(this.VerificationKeySent) },
                { nameof(this.VerificationStorage), EntityProperty.GeneratePropertyForString(this.VerificationStorage) },
                { nameof(this.HashedPassword), EntityProperty.GeneratePropertyForString(this.HashedPassword) },
                { nameof(this.Claims), GeneratePropertyForClaims(this.Claims) },
                { nameof(this.LinkedAccounts), GeneratePropertyForLinkedAccounts(this.LinkedAccounts) },
                { nameof(this.LinkedAccountClaims), GeneratePropertyForLinkedAccountClaims(this.LinkedAccountClaims) },
                //{ nameof(this.Certificates), GeneratePropertyForCertificates(this.Certificates) },
                //{ nameof(this.TwoFactorAuthTokens), GeneratePropertyForTwoFactorAuthTokens(this.TwoFactorAuthTokens) },
                { nameof(this.PasswordResetSecrets), GeneratePropertyForPasswordResetSecrets(this.PasswordResetSecrets) },
            };

            this.WriteProperties(result);

            // Ideally, we'd only update these values when we were certain the entity was
            // persisted to storage.
            this.OriginalUserName        = this.Username;
            this.OriginalEmail           = this.Email;
            this.OriginalPhoneNumber     = this.MobilePhoneNumber;
            this.OriginalVerificationKey = this.VerificationKey;

            return(result);
        }
        public IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            IDictionary <string, EntityProperty> ret = new Dictionary <string, EntityProperty>();

            // Add the custom properties here
            ret.Add(nameof(DomainName), EntityProperty.GeneratePropertyForString(DomainName));
            ret.Add(nameof(EntityTypeName), EntityProperty.GeneratePropertyForString(EntityTypeName));
            ret.Add(nameof(InstanceKey), EntityProperty.GeneratePropertyForString(InstanceKey));
            ret.Add(nameof(WasEverIncluded), EntityProperty.GeneratePropertyForBool(WasEverIncluded));
            ret.Add(nameof(WasEverExcluded), EntityProperty.GeneratePropertyForBool(WasEverExcluded));
            ret.Add(nameof(CurrentClassification), EntityProperty.GeneratePropertyForInt((int)CurrentClassification));
            return(ret);
        }
        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);
        }
Ejemplo n.º 20
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);
        }
Ejemplo n.º 21
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);
            }
Ejemplo n.º 22
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));
            }
        }
Ejemplo n.º 23
0
            public void SetTdsDataStatus(string body)
            {
                CloudTable         _table0       = GetTable(0);
                IList <int>        useTabels     = DataEntityManager.UseTabels();
                DynamicTableEntity tdsPropEntity = new DynamicTableEntity("Data", DataKey);

                foreach (int i in useTabels)
                {
                    tdsPropEntity.Properties.Add(string.Format("N{0,3:D3}", i), EntityProperty.GeneratePropertyForInt(i));
                }
                if (body != "")
                {
                    tdsPropEntity.Properties.Add("Body", EntityProperty.GeneratePropertyForString(body));
                }
                _table0.ExecuteAsync(TableOperation.InsertOrMerge(tdsPropEntity)).Wait();
            }
Ejemplo n.º 24
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);
        }
        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));
        }
Ejemplo n.º 26
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);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Save the DTT square to batch.
        /// </summary>
        /// <param name="tableName">Name of the table.</param>
        /// <param name="square">The square.</param>
        private void SaveDTTSquareToBatch(string tableName, DTTSquare square)
        {
            try
            {
                byte[] block = new byte[square.DttValues.Length * sizeof(int)];
                Buffer.BlockCopy(square.DttValues, 0, block, 0, block.Length);

                var stream = new MemoryStream();
                using (Stream ds = new GZipStream(stream, CompressionMode.Compress))
                {
                    ds.Write(block, 0, square.DttValues.Count() * sizeof(int));
                }

                byte[] compressed = stream.ToArray();

                DynamicTableEntity entity = new DynamicTableEntity();
                entity.Properties.Add("DataRecord", EntityProperty.GeneratePropertyForByteArray(compressed));
                entity.Properties.Add("Easting", EntityProperty.GeneratePropertyForInt(square.Easting));
                entity.Properties.Add("Northing", EntityProperty.GeneratePropertyForInt(square.Northing));
                entity.RowKey       = square.Northing.ToString().PadLeft(7, '0');
                entity.PartitionKey = square.Easting.ToString().PadLeft(7, '0');

                if (!batches.ContainsKey(entity.PartitionKey))
                {
                    batches[entity.PartitionKey] = new TableBatchOperation();
                }

                TableBatchOperation batchOperations = batches[entity.PartitionKey];
                batchOperations.Add(TableOperation.Insert(entity));

                if (batchOperations.Count >= 50)
                {
                    this.FlushBatch(tableName, batchOperations);
                    batchOperations.Clear();
                }
            }
            catch (Exception ex)
            {
                this.Logger.Log(TraceEventType.Error, LoggingMessageId.DttSyncGenericMessage, string.Format("Exception Occured in Table: {0}, Exception :{1}", tableName, ex.ToString()));
            }
        }
        public void CanConvertFromSourceToSummary()
        {
            var entity = new DynamicTableEntity("pk", "rk");

            entity.Properties["dpi"] = EntityProperty.GeneratePropertyForInt(2);
            entity.Properties["dps"] = EntityProperty.GeneratePropertyForString("man");
            entity.Properties["dpd"] = EntityProperty.GeneratePropertyForDateTimeOffset(DateTime.UtcNow);
            entity.Properties["dpb"] = EntityProperty.GeneratePropertyForBool(true);
            var source = new DiagnosticsSource(entity);

            var summary = source.ToSummary();

            Assert.Equal(summary.ConnectionString, source.ConnectionString);
            Assert.Equal(summary.PartitionKey, source.PartitionKey);
            Assert.Equal(summary.RowKey, source.RowKey);
            Assert.Equal(summary.DynamicProperties["dpd"], source.GetProperty <DateTime>("dpd"));
            Assert.Equal(summary.DynamicProperties["dpi"], source.GetProperty <int>("dpi"));
            Assert.Equal(summary.DynamicProperties["dps"], source.GetProperty <string>("dps"));
            Assert.Equal(summary.DynamicProperties["dpb"], source.GetProperty <bool>("dpb"));
            Assert.Equal(summary.TypeName, source.ToTypeKey());
        }
Ejemplo n.º 29
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);
        }
        public void BetweenAnHourWithGraceOf3ThereIs57()
        {
            var lockStore = new Mock <ILockStore>();

            lockStore.Setup(
                x => x.TryLockAsync(It.IsAny <LockToken>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <int>())).Returns(Task.FromResult(true));
            var config    = new Mock <IConfigurationValueProvider>();
            var scheduler = new MinuteTableShardScheduler(config.Object);
            var entity    = new DynamicTableEntity("dd", "fff");

            entity.Properties.Add("GracePeriodMinutes", EntityProperty.GeneratePropertyForInt(3));
            entity.Properties.Add("IsActive", EntityProperty.GeneratePropertyForBool(true));
            var source = new DiagnosticsSource(entity);

            source.LastOffsetPoint = DateTimeOffset.UtcNow.AddHours(-1).DropSecondAndMilliseconds().ToString("O");
            source.LastScheduled   = DateTimeOffset.UtcNow.AddDays(-1);

            var result = scheduler.TryScheduleAsync(source).Result;

            Assert.Equal(57, result.Item1.Count());
        }