Example #1
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");
            }
        }
        private async Task <List <TableOperation> > BuildTableOperationUpsert(T entity)
        {
            var entityId        = EntityDefinition.GetIdValues(entity);
            var serializedField = EntityProperty.GeneratePropertyForByteArray(BSonConvert.SerializeObject(entity));
            var fields          = GetEntityFilterableFields(entity).ToList();
            var record          = GenerateRecordMainPartition(entity, serializedField, fields);

            List <TableOperation> operations = new List <TableOperation>
            {
                TableOperation.InsertOrReplace(record)
            };

            operations.AddRange(GeneratePersistPartitionData(entity, serializedField, fields)
                                .Select(TableOperation.InsertOrReplace));
            var idValue = string.Join(StorageQueryBuilder.PARTITION_FIELD_SEPARATOR,
                                      entityId.Select(StorageQueryBuilder.NormalizeStringValue));

            var old = await GetById(StorageQueryBuilder.GetTableKeyNormalizedValue(idValue)).ConfigureAwait(false);

            if (old != null)
            {
                var oldFields = GetEntityFilterableFields(old);
                IEnumerable <TableOperation> deleteOperations = GeneratePersistPartitionData(old, null, oldFields)
                                                                .Select(TableOperation.Delete)
                                                                .Where(d => !operations.Any(o =>
                                                                                            o.Entity.PartitionKey == d.Entity.PartitionKey && o.Entity.RowKey == d.Entity.RowKey))
                                                                .ToList();
                operations.AddRange(deleteOperations);
            }
            return(operations);
        }
        private async Task <List <TableOperation> > BuildTableOperationUpdate(T entity)
        {
            var entityIdValues = EntityDefinition.GetIdValues(entity);
            var idString       = string.Join(StorageQueryBuilder.PARTITION_FIELD_SEPARATOR,
                                             entityIdValues.Select(StorageQueryBuilder.NormalizeStringValue));

            var serializedField = EntityProperty.GeneratePropertyForByteArray(BSonConvert.SerializeObject(entity));

            var fields = GetEntityFilterableFields(entity);

            var record = GenerateRecordMainPartition(entity, serializedField, fields);

            List <TableOperation> operations = new List <TableOperation>
            {
                TableOperation.Replace(record)
            };

            var old = await GetById(idString).ConfigureAwait(false);

            if (old != null)
            {
                var oldFields = GetEntityFilterableFields(old);
                operations.AddRange(GeneratePersistPartitionData(old, null, oldFields).Select(TableOperation.Delete));
            }
            return(operations);
        }
        private static EntityProperty CreateEntityProperty(JsonSerializer serializer, JProperty property)
        {
            if (property != null)
            {
                return(null !);
            }

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

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

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

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

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

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

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

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

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

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

            return(entityProperty);
        }
        private void WriteSchema(CloudTable table)
        {
            DeleteSchema(table);

            DynamicTableEntity schema = new DynamicTableEntity(SCHEMA_CONSTANT_STRING, DateTime.UtcNow.ToString("s"));
            var hashData        = ComputeDefinitionHash();
            var serializedField = EntityProperty.GeneratePropertyForByteArray(hashData);

            schema.Properties.Add("Content", serializedField);
            table.Execute(TableOperation.InsertOrReplace(schema));
        }
Example #6
0
        public IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            var dict = new Dictionary <string, EntityProperty>
            {
                [PayloadKeyName]  = EntityProperty.GeneratePropertyForByteArray(Payload),
                [ManifestKeyName] = EntityProperty.GeneratePropertyForString(Manifest),
                [SeqNoKeyName]    = EntityProperty.GeneratePropertyForLong(SeqNo)
            };

            return(dict);
        }
        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 #8
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 #9
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 IDictionary <string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            var dict =
                new Dictionary <string, EntityProperty>
            {
                [ManifestKeyName]        = EntityProperty.GeneratePropertyForString(Manifest),
                [PayloadKeyName]         = EntityProperty.GeneratePropertyForByteArray(Payload),
                [UtcTicksKeyName]        = EntityProperty.GeneratePropertyForLong(UtcTicks),
                [IdxPartitionKeyKeyName] = EntityProperty.GeneratePropertyForString(IdxPartitionKey),
                [IdxRowKeyKeyName]       = EntityProperty.GeneratePropertyForString(IdxRowKey),
                [IdxTagKeyName]          = EntityProperty.GeneratePropertyForString(IdxTag)
            };

            return(dict);
        }
Example #11
0
        public static DynamicTableEntity ToEntity(
            this EventBase @event, string partitionkey, long eventVersion)
        {
            Ensure.ArgumentNotNull(@event, nameof(@event));
            var dte = new DynamicTableEntity(partitionkey, eventVersion.FormatLong());

            dte.Properties = new Dictionary <string, EntityProperty>();
            dte.Properties.Add(StorageConstants.EventStore.EventType,
                               EntityProperty.GeneratePropertyForString(@event.GetType().AssemblyQualifiedName));

            var bytes = Encoding.Default.GetBytes(JsonConvert.SerializeObject(@event));

            // var compressed = Brotli.CompressBuffer(bytes, 0, bytes.Length);

            dte.Properties.Add(StorageConstants.EventStore.EventData,
                               EntityProperty.GeneratePropertyForByteArray(bytes));

            return(dte);
        }
        private List <TableOperation> BuildTableOperationInsert(T entity)
        {
            List <KeyValuePair <string, EntityProperty> > fields = GetEntityFilterableFields(entity).ToList();

            EntityProperty serializedField = EntityProperty.GeneratePropertyForByteArray(BSonConvert.SerializeObject(entity));

            var record = GenerateRecordMainPartition(entity, serializedField, fields);
            List <TableOperation> operations = new List <TableOperation>
            {
                TableOperation.Insert(record)
            };

            foreach (var partitionRecord in GeneratePersistPartitionData(entity, serializedField, fields))
            {
                operations.Add(TableOperation.Insert(partitionRecord));
            }

            return(operations);
        }
Example #13
0
        protected EntityProperty GenerateProperty(EdmType propertyValueType, object propertyValueStr)
        {
            EntityProperty propertyValue;

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

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

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

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

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

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

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

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

            default: throw new ArgumentException($"Can't create table property with Type {string.Join(", ", propertyValueType)} and value {propertyValueStr}");
            }
            return(propertyValue);
        }
Example #14
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 TableBatchEntityOver1MBShouldThrow()
        {
            TableBatchOperation batch = new TableBatchOperation();
            string pk = Guid.NewGuid().ToString();

            DynamicReplicatedTableEntity ent = GenerateRandomEnitity(pk);

            ent.Properties.Add("binary", EntityProperty.GeneratePropertyForByteArray(new byte[1024 * 1024]));
            batch.Insert(ent);

            OperationContext opContext = new OperationContext();

            try
            {
                this.repTable.ExecuteBatch(batch, null, opContext);
                Assert.Fail();
            }
            catch (StorageException)
            {
                TestHelper.ValidateResponse(opContext, 2, (int)HttpStatusCode.BadRequest, new string[] { "EntityTooLarge" }, "The entity is larger than the maximum allowed size (1MB).");
            }
        }
        public void TableBatchOver4MBShouldThrow()
        {
            TableBatchOperation batch = new TableBatchOperation();
            string pk = Guid.NewGuid().ToString();

            for (int m = 0; m < 65; m++)
            {
                DynamicReplicatedTableEntity ent = GenerateRandomEnitity(pk);

                // Maximum Entity size is 64KB
                ent.Properties.Add("binary", EntityProperty.GeneratePropertyForByteArray(new byte[64 * 1024]));
                batch.Insert(ent);
            }

            OperationContext opContext = new OperationContext();

            try
            {
                this.repTable.ExecuteBatch(batch, null, opContext);
                Assert.Fail();
            }
            catch (StorageException)
            {
                //
                // ###XXX: NEW SOURCE CODES: The commented out codes were the original codes
                //
                //TestHelper.ValidateResponse(opContext, 1, (int)HttpStatusCode.BadRequest, new string[] { "ContentLengthExceeded" }, "The content length for the requested operation has exceeded the limit (4MB).");
                TestHelper.ValidateResponse(
                    opContext,
                    2,
                    (int)HttpStatusCode.RequestEntityTooLarge,
                    new string[] { "RequestBodyTooLarge" },
                    "The request body is too large and exceeds the maximum permissible limit"
                    );
            }
        }
Example #17
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 #18
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);
        }