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));
        }
 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
 }
Example #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");
            }
        }
Example #4
0
 private static void FillDynaConfig()
 {
     dynaConfig.Properties.Add("SrcAccountConnectionString",
                               EntityProperty.GeneratePropertyForString(conf.SrcAccountConnectionString));
     dynaConfig.Properties.Add("SrcContainerName",
                               EntityProperty.GeneratePropertyForString(conf.SrcContainerName));
     dynaConfig.Properties.Add("DestAccountConnectionString",
                               EntityProperty.GeneratePropertyForString(conf.DestAccountConnectionString));
     dynaConfig.Properties.Add("DestContainerName",
                               EntityProperty.GeneratePropertyForString(conf.DestContainerName));
     dynaConfig.Properties.Add("SrcBlobName",
                               EntityProperty.GeneratePropertyForString(conf.SrcPattern)); //* for all the blobs in the container
     dynaConfig.Properties.Add("DeleteFromSource",
                               EntityProperty.GeneratePropertyForBool(conf.DeleteFromSource));
     dynaConfig.Properties.Add("SafeDeleteFromSource",
                               EntityProperty.GeneratePropertyForBool(conf.SafeDeleteFromSource));
     dynaConfig.Properties.Add("DestTier",
                               EntityProperty.GeneratePropertyForString(conf.DestTier));
     dynaConfig.Properties.Add("LocalTempPath",
                               EntityProperty.GeneratePropertyForString(conf.LocalTempPath));
     dynaConfig.Properties.Add("DeleteFromLocalTemp",
                               EntityProperty.GeneratePropertyForBool(conf.DeleteFromLocalTemp));
     dynaConfig.Properties.Add("AzCopyPath",
                               EntityProperty.GeneratePropertyForString(conf.AzCopyPath));
     dynaConfig.Properties.Add("CustomerId",
                               EntityProperty.GeneratePropertyForString(conf.CustomerId));
     dynaConfig.Properties.Add("OverwriteIfExists",
                               EntityProperty.GeneratePropertyForBool(conf.OverwriteIfExists));
 }
Example #5
0
        /// <inheritdoc />
        public override IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            var result = new Dictionary <string, EntityProperty>();

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

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

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

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

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

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

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

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

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

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

                case null:
                    break;

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

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

            // Assert
            AssertConvertThrowsIfNullValue(converter, EntityProperty.GeneratePropertyForBool(null));
        }
        public void Create_NullableBoolean_CanConvertNullValue()
        {
            // Act
            IConverter <EntityProperty, bool?> converter = EntityPropertyToTConverterFactory.Create <bool?>();

            // Assert
            AssertCanConvertNullValue(converter, EntityProperty.GeneratePropertyForBool(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);
        }
Example #9
0
 public IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext) =>
 new Dictionary <string, EntityProperty>
 {
     [nameof(Id)]           = EntityProperty.GeneratePropertyForLong(Id),
     [nameof(Name)]         = EntityProperty.GeneratePropertyForString(Name),
     [nameof(IsRunning)]    = EntityProperty.GeneratePropertyForBool(IsRunning),
     [nameof(PartitionKey)] = EntityProperty.GeneratePropertyForString(PartitionKey),
     [nameof(RowKey)]       = EntityProperty.GeneratePropertyForString(RowKey),
     [nameof(Timestamp)]    = EntityProperty.GeneratePropertyForDateTimeOffset(Timestamp),
     [nameof(ETag)]         = EntityProperty.GeneratePropertyForString(ETag)
 };
        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);
        }
        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));
            ret.Add(nameof(Deleting), EntityProperty.GeneratePropertyForBool(Deleting));
            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);
        }
Example #14
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);
        }
Example #15
0
            public IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
            {
                //Azure Lib calls this when it wants to transform this entity to a writeable one

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

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

                    Type t = cell.Value.OriginalType;

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

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

            Type type = value.GetType();

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

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

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

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

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

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

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

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

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

            default:
                throw new ArgumentException(string.Format("Type \"{0}\" is not supported.", type.FullName));
            }
        }
        public void TableEntityPropertySetter()
        {
            string pk = Guid.NewGuid().ToString();
            string rk = Guid.NewGuid().ToString();
            Dictionary <string, EntityProperty> properties = new Dictionary <string, EntityProperty>();
            EntityProperty boolEntity = EntityProperty.GeneratePropertyForBool(null);

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

            EntityProperty timeEntity = EntityProperty.GeneratePropertyForDateTimeOffset(null);

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

            EntityProperty doubleEntity = EntityProperty.GeneratePropertyForDouble(null);

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

            EntityProperty guidEntity = EntityProperty.GeneratePropertyForGuid(null);

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

            EntityProperty intEntity = EntityProperty.GeneratePropertyForInt(null);

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

            EntityProperty longEntity = EntityProperty.GeneratePropertyForLong(null);

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

            EntityProperty stringEntity = EntityProperty.GeneratePropertyForString(null);

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

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

            this.repTable.Execute(TableOperation.Insert(ent));
        }
Example #18
0
 /// <inheritdoc />
 public IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
 {
     return(new Dictionary <string, EntityProperty>
     {
         { nameof(EventbriteId), EntityProperty.GeneratePropertyForString(EventbriteId) },
         { nameof(Name), EntityProperty.GeneratePropertyForString(Name) },
         { nameof(Submission.TimeToComplete), EntityProperty.GeneratePropertyForString(Submission?.TimeToComplete?.ToString("G", new NumberFormatInfo())) },
         { nameof(Submission.Verified), EntityProperty.GeneratePropertyForBool(Submission?.Verified) },
         { nameof(Submission.Show), EntityProperty.GeneratePropertyForBool(Submission?.Show) },
         { nameof(Submission.Locked), EntityProperty.GeneratePropertyForBool(Submission?.Locked) },
         { nameof(Submission.DisplayImgUrl), EntityProperty.GeneratePropertyForString(Submission?.DisplayImgUrl?.ToString()) },
         { nameof(Submission.VerifyingImgUrl), EntityProperty.GeneratePropertyForString(Submission?.VerifyingImgUrl?.ToString()) },
         { nameof(Submission.DisplayName), EntityProperty.GeneratePropertyForString(Submission?.DisplayName) },
         { nameof(Email), EntityProperty.GeneratePropertyForString(Email) },
         { nameof(Address), EntityProperty.GeneratePropertyForString(JsonSerializer.Serialize(Address)) },
         { nameof(BioGender), EntityProperty.GeneratePropertyForString(BioGender.ToString("G")) },
         { nameof(SoftDelete), EntityProperty.GeneratePropertyForBool(SoftDelete) }
     });
 }
Example #19
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 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());
        }
        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());
        }
Example #22
0
        private void RetrieveOrInsert(string SourceRepo, string branch, string sha, string TargetRepo)
        {
            TableQuery rangeQuery = new TableQuery().Where(TableQuery.CombineFilters(
                                                               TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, sha),
                                                               TableOperators.And,
                                                               TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, TargetRepo)));

            var commits = s_table.ExecuteQuery(rangeQuery);

            if (commits.Count() == 0)
            {
                DynamicTableEntity entity = new DynamicTableEntity(TargetRepo, sha);
                entity.Properties.Add("Branch", EntityProperty.GeneratePropertyForString(branch));
                entity.Properties.Add("PR", EntityProperty.GeneratePropertyForString(string.Empty));
                entity.Properties.Add("SourceRepo", EntityProperty.GeneratePropertyForString(SourceRepo));
                entity.Properties.Add("Mirrored", EntityProperty.GeneratePropertyForBool(false));

                TableOperation insertOperation = TableOperation.Insert(entity);
                s_table.Execute(insertOperation);
            }
        }
Example #23
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);
        }
Example #25
0
        public override IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            var properties = new Dictionary <string, EntityProperty>();

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

                if (entityProperty != null)
                {
                    properties[getter.Key] = entityProperty;
                }
            }
            return(properties);
        }
Example #26
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);
        }
Example #27
0
        public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }

            var    message            = formatter(state, exception);
            string exceptionText      = exception?.ToString();
            bool   hasMessageOverflow = message.Length > overflowThreshold;

            var properties = new Dictionary <string, EntityProperty>
            {
                ["LogLevel"]            = EntityProperty.GeneratePropertyForString(logLevel.ToString()),
                ["Message"]             = EntityProperty.GeneratePropertyForString(hasMessageOverflow ? message.Substring(0, overflowThreshold) : message),
                ["ExceptionText"]       = EntityProperty.GeneratePropertyForString(exceptionText),
                ["EventId"]             = EntityProperty.GeneratePropertyForInt(eventId.Id),
                ["EventName"]           = EntityProperty.GeneratePropertyForString(eventId.Name),
                ["Date"]                = EntityProperty.GeneratePropertyForDateTimeOffset(DateTimeOffset.Now),
                ["LoggerName"]          = EntityProperty.GeneratePropertyForString(this.Name),
                ["IsMessageOverflowed"] = EntityProperty.GeneratePropertyForBool(hasMessageOverflow),
            };

            string requestId = null;
            var    current   = AzureScope.Current;

            while (current != null)
            {
                foreach (var item in current.Values)
                {
                    properties.Add($"Scope{current.StateName}{item.Key}", EntityProperty.CreateEntityPropertyFromObject(item.Value));
                    if (item.Key == "RequestId")
                    {
                        requestId = (string)item.Value;
                    }
                }

                current = current.Parent;
            }

            properties["RequestId"] = EntityProperty.GeneratePropertyForString(requestId);

            var id        = timeBasedId.NewId();
            var partition = (requestId ?? id).Substring(0, 5);

            if (message != null || exceptionText != null)
            {
                var entity = new DynamicTableEntity(
                    partition,
                    id, null, properties);

                this.sink.Post(entity);
                if (hasMessageOverflow)
                {
                    this.overflowSink.Post(new KeyValuePair <string, string>(id, message));
                }
            }
        }
        /// <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);
        }
Example #29
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);
        }