Beispiel #1
0
        /// <summary>
        /// This is the default constructor.
        /// </summary>
        /// <param name="mediaType">The media type string.</param>
        /// <param name="converterType">The type for </param>
        public MediaTypeConverterAttribute(Type converterType, Type entityType = null, string mediaType = null, double priority = 0.1)
        {
            if (converterType == null)
            {
                throw new ArgumentNullException("converterType");
            }

            if (!converterType.IsSubclassOf(typeof(TransportSerializer)))
            {
                throw new ArgumentOutOfRangeException("converterType", "Type should be a subclass of TransportSerializerBase");
            }

            if (priority > 1)
            {
                throw new ArgumentOutOfRangeException("priority", "priority can not be greater than 1");
            }

            ConverterType = converterType;
            TransportSerializer serializer = null;

            bool instantiate = entityType == null || mediaType == null;

            if (instantiate)
            {
                serializer = (TransportSerializer)Activator.CreateInstance(converterType);
            }

            EntityType = entityType ?? serializer.EntityType;
            MediaType  = mediaType ?? serializer.MediaType;
            Priority   = priority;
        }
Beispiel #2
0
        /// <summary>
        /// This is the default constructor.
        /// </summary>
        protected ApiProviderAsyncV2(
            IKeyMapper <K> keyMapper = null
            , TransportSerializer <E> primaryTransport        = null
            , IEnumerable <IApiProviderAuthBase> authHandlers = null
            , bool useDefaultJsonSerializer = true
            ) : base(authHandlers)
        {
            mKeyMapper = keyMapper ?? ResolveKeyMapper();

            ResolveTransport(primaryTransport, useDefaultJsonSerializer);
        }
Beispiel #3
0
        /// <summary>
        /// This is the default constructor.
        /// </summary>
        public ApiProviderAsyncV2(Uri rootUri
                                  , IKeyMapper <K> keyMapper = null
                                  , TransportSerializer <E> primaryTransport        = null
                                  , IEnumerable <IApiProviderAuthBase> authHandlers = null
                                  , bool useDefaultJsonSerializer = true)
            : this(keyMapper, primaryTransport, authHandlers, useDefaultJsonSerializer)
        {
            if (rootUri == null)
            {
                throw new ArgumentNullException("You must set rootUri for the API");
            }

            mUriMapper = CreateUriMapper(rootUri);
        }
Beispiel #4
0
        /// <summary>
        /// This is the default constructor.
        /// </summary>
        public ApiProviderAsyncV2(TransportUriMapper <K> uriMapper                  = null
                                  , IKeyMapper <K> keyMapper                        = null
                                  , TransportSerializer <E> primaryTransport        = null
                                  , IEnumerable <IApiProviderAuthBase> authHandlers = null
                                  , bool useDefaultJsonSerializer                   = true)
            : this(keyMapper, primaryTransport, authHandlers, useDefaultJsonSerializer)
        {
            if (uriMapper == null)
            {
                throw new ArgumentNullException("You must set uriMapper");
            }

            mUriMapper = uriMapper;
        }
Beispiel #5
0
        /// <summary>
        /// This constructors sets the underlying respository.
        /// </summary>
        /// <param name="respository">The aynsc repository.</param>
        protected ApiPersistenceControllerAsyncBase(IRepositoryAsync <K, E> respository)
        {
            mRespository = respository;
            mSerializers = TransportSerializer.GetSerializers <E>(GetType())
                           .ToDictionary((p) => p.MediaType.ToLowerInvariant());

            //If we have no serializers set on this controller, check the entity.
            if (mSerializers == null || mSerializers.Count == 0)
            {
                mSerializers = TransportSerializer.GetSerializers <E>(typeof(E))
                               .ToDictionary((p) => p.MediaType.ToLowerInvariant());
            }

            mKeyMapper = (KeyMapper <K>)KeyMapper.Resolve <K>();

            mODataValidate = ODataValidationSettingsCreate();
        }
Beispiel #6
0
        /// <summary>
        /// This method resolves the specific serializer for the entity transport.
        /// </summary>
        protected virtual TransportSerializer <E> ResolveSerializer()
        {
            mTransports = TransportSerializer.GetSerializers <E>(GetType()).ToDictionary((s) => s.MediaType.ToLowerInvariant());

            if (mTransports == null || mTransports.Count == 0)
            {
                mTransports = TransportSerializer.GetSerializers <E>(typeof(E)).ToDictionary((s) => s.MediaType.ToLowerInvariant());
            }

            if (mTransports == null || mTransports.Count == 0)
            {
                throw new TransportSerializerResolutionException("The default TransportSerializer cannot be resolved.");
            }

            //Get the transport serializer with the highest priority.
            return(mTransports.Values.OrderByDescending((t) => t.Priority).First());
        }
Beispiel #7
0
        /// <summary>
        /// This method resolves the appropriate transport serialzer from the incoming accept header.
        /// </summary>
        /// <param name="rq">The incoming request.</param>
        /// <param name="transport">The resolve transport serializer.</param>
        /// <returns>Returns true if the serializer can be resolved.</returns>
        protected virtual bool ResolveDeserializer(ApiRequest rq, out TransportSerializer <E> transport)
        {
            transport = null;

            try
            {
                string mediaType = rq.BodyType.MediaType.ToLowerInvariant();
                if (mSerializers.ContainsKey(mediaType))
                {
                    transport = mSerializers[mediaType];
                    return(true);
                }
            }
            catch (Exception ex)
            {
                LogException(rq, ex);
            }

            return(false);
        }
Beispiel #8
0
        /// <summary>
        /// This method resolves the specific serializer for the entity transport.
        /// </summary>
        protected virtual void ResolveTransport(TransportSerializer <E> primaryTransport, bool useDefaultJsonSerializer)
        {
            var transportSerializers = TransportSerializer.GetSerializers <E>(GetType()).ToDictionary((s) => s.MediaType.ToLowerInvariant());

            if (transportSerializers == null || transportSerializers.Count == 0)
            {
                transportSerializers = TransportSerializer.GetSerializers <E>(typeof(E)).ToDictionary((s) => s.MediaType.ToLowerInvariant());
            }

            if (transportSerializers == null || transportSerializers.Count == 0)
            {
                if (primaryTransport == null && !useDefaultJsonSerializer)
                {
                    throw new TransportSerializerResolutionException("No TransportSerializers can be resolved for the entity.");
                }

                transportSerializers = new Dictionary <string, TransportSerializer <E> >();

                if (primaryTransport == null)
                {
                    primaryTransport = new JsonTransportSerializer <E>();
                }
            }

            if (primaryTransport != null && !transportSerializers.ContainsKey(primaryTransport.MediaType))
            {
                transportSerializers.Add(primaryTransport.MediaType, primaryTransport);
            }

            mTransportSerializers = transportSerializers;

            //Get the transport serializer with the highest priority.
            if (primaryTransport != null)
            {
                mPrimaryTransport = primaryTransport.MediaType;
            }
            else
            {
                mPrimaryTransport = mTransportSerializers.OrderByDescending((t) => t.Value.Priority).First().Key;
            }
        }
Beispiel #9
0
        /// <summary>
        /// This is the default constructor.
        /// </summary>
        public ApiProviderAsyncBase(TransportUriMapper <K> uriMapper = null
                                    , bool useHttps            = true, string entityName = null
                                    , IKeyMapper <K> keyMapper = null
                                    , TransportSerializer <E> primaryTransport = null)
        {
            // Get the types assembly version to add to the request headers
            mAssemblyVersion = GetType().Assembly.GetName().Version.ToString();

            mKeyMapper = keyMapper ?? ResolveKeyMapper();

            mUriMapper = uriMapper ?? ResolveUriMapper(uriMapper, entityName);

            if (entityName != null)
            {
                EntityName = entityName;
            }

            mPrimaryTransport = primaryTransport ?? ResolveSerializer();

            UseHttps = useHttps;
        }
Beispiel #10
0
        /// <summary>
        /// This method resolves the transport serializer for the outgoing response using the accept header.
        /// </summary>
        /// <param name="rq">The incoming request.</param>
        /// <param name="transport">The resolve transport serializer.</param>
        /// <returns>Returns true if the serializer can be resolved.</returns>
        protected virtual bool ResolveSerializer(ApiRequest rq, out TransportSerializer <E> transport)
        {
            transport = null;
            var accepts = rq.Accept ?? new List <MediaTypeWithQualityHeaderValue>();

            if (accepts.Count == 0)
            {
                accepts.Add(new MediaTypeWithQualityHeaderValue(WildcardMediaType));
            }

            if (mSerializers.Count == 0)
            {
                return(false);
            }

            try
            {
                foreach (var accept in accepts.OrderByDescending(a => a.Quality))
                {
                    var mediaType = accept.MediaType.ToLowerInvariant();
                    if (mSerializers.ContainsKey(mediaType))
                    {
                        transport = mSerializers[mediaType];
                        return(true);
                    }
                    if (mediaType.Equals(WildcardMediaType) || mediaType.EndsWith("*"))
                    {
                        transport = mSerializers.OrderByDescending(s => s.Value.Priority).First().Value;
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                LogException(rq, ex);
            }

            return(false);
        }
Beispiel #11
0
        /// <summary>
        /// This method processes the outgoing response.
        /// </summary>
        /// <typeparam name="KT">The key type.</typeparam>
        /// <typeparam name="ET">The entity type.</typeparam>
        /// <param name="responseHolder">The response message.</param>
        /// <param name="entitySerializer">The optional serializer.</param>
        /// <returns>Returns the relevant result.</returns>
        protected virtual IHttpActionResult ResponseFormat <KT, ET>(RepositoryHolder <KT, ET> responseHolder
                                                                    , TransportSerializer <ET> entitySerializer = null)
        {
            ApiResponse response = null;

            switch (responseHolder.ResponseCode)
            {
            case 200:
                response = new ApiResponse(HttpStatusCode.OK);
                break;

            case 201:
                response = new ApiResponse(HttpStatusCode.Created);
                break;

            case 202:
                response = new ApiResponse(HttpStatusCode.Accepted);
                break;

            case 204:
                response = new ApiResponse(HttpStatusCode.NoContent);
                break;

            case 400:
                return(BadRequest(responseHolder.ResponseMessage ?? string.Empty));

            case 404:
                return(StatusCode(HttpStatusCode.NotFound));

            case 405:
                return(StatusCode(HttpStatusCode.MethodNotAllowed));

            case 408:
                return(StatusCode(HttpStatusCode.RequestTimeout));

            case 409:
                return(StatusCode(HttpStatusCode.Conflict));

            case 412:
                return(StatusCode(HttpStatusCode.PreconditionFailed));

            case 417:
                return(StatusCode(HttpStatusCode.ExpectationFailed));

            case 442:
                return(StatusCode(HttpStatusCode.UnsupportedMediaType));

            case 502:
                return(StatusCode(HttpStatusCode.BadGateway));

            case 504:
                return(StatusCode(HttpStatusCode.GatewayTimeout));

            default:
                LogMessage(LoggingLevel.Error, $"Unexpected error occurred {responseHolder}");
                return(StatusCode(HttpStatusCode.InternalServerError));
            }

            if (entitySerializer != null && responseHolder.Entity != null)
            {
                response.MediaType = entitySerializer.MediaType;
                response.Data      = entitySerializer.GetData(responseHolder.Entity);
            }

            if (responseHolder.KeyReference != null)
            {
                response.ContentId = responseHolder.KeyReference.Item1;
                response.VersionId = responseHolder.KeyReference.Item2;
            }

            if (responseHolder.IsCached)
            {
                response.IsCached = true;
            }

            return(response);
        }