Esempio n. 1
0
        /// <summary>Implements basic check and convertion logic for ConvertToJson method.</summary>
        protected static JsonObject CheckAndConvertToJson(
            object sourceEntity, IEntityConfig entityConfig, bool throwOnError, Func <JsonObject> convert)
        {
            if (entityConfig.EntityType != sourceEntity.GetType())
            {
                return(LogAndThrowInvalidOperationExceptionIfNeeded <JsonObject>(
                           throwOnError,
                           "Serializing type {0} does not match type {1} in configuration.",
                           sourceEntity.GetType(),
                           entityConfig.EntityType
                           ));
            }

            var entityId = entityConfig.GetId(sourceEntity);

            if (String.IsNullOrWhiteSpace(entityId))
            {
                return(LogAndThrowInvalidOperationExceptionIfNeeded <JsonObject>(
                           throwOnError, "Entity ID should be set prior calling deserializer."));
            }

            var documentId = entityConfig.ConvertEntityIdToDocumentId(entityId);

            if (String.IsNullOrWhiteSpace(documentId))
            {
                return(LogAndThrowInvalidOperationExceptionIfNeeded <JsonObject>(
                           throwOnError,
                           "IEntityConfig.ConvertEntityIdToDocumentId() should not ever return null, empty or whitespace string."));
            }

            var documentRevision = entityConfig.IsRevisionPresent
                                ? entityConfig.GetRevision(sourceEntity)
                                : null;

            var documentType = entityConfig.DocumentType;

            if (String.IsNullOrWhiteSpace(documentType))
            {
                return(LogAndThrowInvalidOperationExceptionIfNeeded <JsonObject>(
                           throwOnError, "IEntityConfig.DocumentType should not ever be null, empty or whitespace string."));
            }

            var jsonObject = convert();

            if (jsonObject == null)
            {
                return(null);
            }

            // The only way simple to place special properties at the top is to write object again
            // Should investigate this as potential perf botleneck.
            var properties = new List <KeyValuePair <string, JsonValue> > {
                new KeyValuePair <string, JsonValue>(Document.IdPropertyName, documentId)
            };

            if (!string.IsNullOrWhiteSpace(documentRevision))
            {
                properties.Add(new KeyValuePair <string, JsonValue>(Document.RevisionPropertyName, documentRevision));
            }
            properties.Add(new KeyValuePair <string, JsonValue>(Document.TypePropertyName, documentType));
            properties.AddRange(jsonObject);

            return(new JsonObject(properties));
        }