Example #1
0
        /// <summary>
        /// Makes a restful call using supplied information.
        /// </summary>
        /// <typeparam name="TResult">Return type to convert response to (if you provide VoidResultType then null will be returned - basically a void call).</typeparam>
        /// <param name="uri">Uri to make the request against.</param>
        /// <param name="httpVerb">HTTP verb to use.</param>
        /// <param name="body">Optional body object to send (use null if not needed).</param>
        /// <param name="cookieJar">Optional cookie to use (use null if not needed).</param>
        /// <param name="headerJar">Optional headers to use (use null if not needed).</param>
        /// <param name="saveResponseHeadersAction">Optional action to use to save response headers (use null if not needed).</param>
        /// <param name="contentType">Content type to use for request.</param>
        /// <param name="acceptType">Content type to use for response.</param>
        /// <param name="timeout">Timeout to use.</param>
        /// <param name="serializer">Serializer to use.</param>
        /// <returns>Converted response to the specified type.</returns>
        public static TResult Call <TResult>(
            Uri uri,
            HttpVerb httpVerb,
            object body,
            CookieJar cookieJar,
            HeaderJar headerJar,
            Action <KeyValuePair <string, string>[]> saveResponseHeadersAction,
            ContentType contentType,
            ContentType acceptType,
            TimeSpan timeout,
            IStringSerializeAndDeserialize serializer)
            where TResult : class
        {
            var httpVerbAsString = httpVerb.ToString().ToUpperInvariant();

            return(Call <TResult>(
                       uri,
                       httpVerbAsString,
                       body,
                       cookieJar,
                       headerJar,
                       saveResponseHeadersAction,
                       contentType,
                       acceptType,
                       timeout,
                       serializer));
        }
Example #2
0
        /// <summary>
        /// Builds a <see cref="TypeToRegisterForJson"/> for a type using the most sensible settings,
        /// with a specified <see cref="IStringSerializeAndDeserialize"/> to use everywhere the type appears.
        /// </summary>
        /// <param name="type">The type to register.</param>
        /// <param name="stringSerializer">The string serializer to use for <paramref name="type"/>.</param>
        /// <returns>
        /// The type to register for JSON serialization.
        /// </returns>
        public static TypeToRegisterForJson ToTypeToRegisterForJsonUsingStringSerializer(
            this Type type,
            IStringSerializeAndDeserialize stringSerializer)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

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

            var canConvertTypeMatchStrategy = type.ResolveDefaultIntoActionableRelatedTypesToInclude().ToCanConvertTypeMatchStrategy();

            var jsonConverterBuilderId = Guid.NewGuid().ToString() + "-" + Guid.NewGuid().ToString();

            JsonConverter ConverterBuilderFunc() => new StringSerializerBackedJsonConverter(type, stringSerializer, canConvertTypeMatchStrategy);

            var jsonConverterBuilder = new JsonConverterBuilder(jsonConverterBuilderId, ConverterBuilderFunc, ConverterBuilderFunc);

            var result = new TypeToRegisterForJson(type, MemberTypesToInclude.None, RelatedTypesToInclude.Default, jsonConverterBuilder, stringSerializer);

            return(result);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="TypeToRegisterForJson{T}"/> class.
 /// </summary>
 /// <param name="memberTypesToInclude">Specifies which member types of <typeparamref name="T"/> that should also be registered.</param>
 /// <param name="relatedTypesToInclude">Specifies which types related to <typeparamref name="T"/> that should also be registered.</param>
 /// <param name="jsonConverterBuilder">Builds a serializing and deserializing <see cref="JsonConverter"/>.</param>
 /// <param name="keyInDictionaryStringSerializer">The serializer to use when dictionaries are keyed on <typeparamref name="T"/> and the keys should be written-to/read-from a string.</param>
 public TypeToRegisterForJson(
     MemberTypesToInclude memberTypesToInclude,
     RelatedTypesToInclude relatedTypesToInclude,
     JsonConverterBuilder jsonConverterBuilder,
     IStringSerializeAndDeserialize keyInDictionaryStringSerializer)
     : base(typeof(T), memberTypesToInclude, relatedTypesToInclude, jsonConverterBuilder, keyInDictionaryStringSerializer)
 {
 }
        /// <summary>
        /// Withes the serializer.
        /// </summary>
        /// <param name="serializer">The serializer.</param>
        /// <returns>ICallOnUriAll.</returns>
        /// <inheritdoc />
        public ICallOnUriAll WithSerializer(IStringSerializeAndDeserialize serializer)
        {
            new { serializer }.AsArg().Must().NotBeNull();

            this.UpdateCallListThrowIfAlreadyCalled(nameof(this.WithSerializer));

            this.serializerForPostBodyAndResponse = serializer;
            return(this);
        }
        /// <summary>
        /// Builds a <see cref="StringSerializerBackedBsonSerializer{T}"/> for the specified type and backing string serializer.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="backingSerializer">The backing string serializer.</param>
        /// <returns>
        /// A newly constructed <see cref="StringSerializerBackedBsonSerializer{T}"/> for the specified type and backing string serializer.
        /// </returns>
        public static IBsonSerializer Build(
            Type type,
            IStringSerializeAndDeserialize backingSerializer)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            var result = (IBsonSerializer)typeof(StringSerializerBackedBsonSerializer <>).MakeGenericType(type).Construct(backingSerializer);

            return(result);
        }
Example #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TypeToRegisterForJson"/> class, specifying the origin types.
        /// </summary>
        /// <param name="type">The type to register.</param>
        /// <param name="recursiveOriginType">The type whose recursive processing of <paramref name="memberTypesToInclude"/> and <paramref name="relatedTypesToInclude"/> resulted in the creation of this <see cref="TypeToRegisterForJson"/>.</param>
        /// <param name="directOriginType">The type whose processing of <paramref name="memberTypesToInclude"/> and <paramref name="relatedTypesToInclude"/> directly resulted in the creation of this <see cref="TypeToRegisterForJson"/>.</param>
        /// <param name="memberTypesToInclude">Specifies which member types of <paramref name="type"/> that should also be registered.</param>
        /// <param name="relatedTypesToInclude">Specifies which types related to <paramref name="type"/> that should also be registered.</param>
        /// <param name="jsonConverterBuilder">Builds a serializing and deserializing <see cref="JsonConverter"/>.</param>
        /// <param name="keyInDictionaryStringSerializer">The serializer to use when dictionaries are keyed on <paramref name="type"/> and the keys should be written-to/read-from a string.</param>
        public TypeToRegisterForJson(
            Type type,
            Type recursiveOriginType,
            Type directOriginType,
            MemberTypesToInclude memberTypesToInclude,
            RelatedTypesToInclude relatedTypesToInclude,
            JsonConverterBuilder jsonConverterBuilder,
            IStringSerializeAndDeserialize keyInDictionaryStringSerializer)
            : base(type, recursiveOriginType, directOriginType, memberTypesToInclude, relatedTypesToInclude)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

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

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

            if (jsonConverterBuilder != null)
            {
                if (memberTypesToInclude != MemberTypesToInclude.None)
                {
                    throw new ArgumentException(Invariant($"{nameof(jsonConverterBuilder)} is specified, but {nameof(Serialization.MemberTypesToInclude)} is not {MemberTypesToInclude.None}."));
                }

                if (type.IsGenericTypeDefinition)
                {
                    throw new NotSupportedException(Invariant($"{nameof(jsonConverterBuilder)} is specified, but underlying type to register is an open generic."));
                }
            }

            if (keyInDictionaryStringSerializer != null)
            {
                if (type.IsGenericTypeDefinition)
                {
                    throw new NotSupportedException(Invariant($"{nameof(keyInDictionaryStringSerializer)} is specified, but underlying type to register is an open generic."));
                }
            }

            this.JsonConverterBuilder            = jsonConverterBuilder;
            this.KeyInDictionaryStringSerializer = keyInDictionaryStringSerializer;
        }
Example #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ObcStringSerializerBackedSerializer"/> class.
        /// </summary>
        /// <param name="backingStringSerializer">Backing string serializer.</param>
        /// <param name="id">Optional identifier to be stored in metadata of <see cref="SerializerRepresentation"/>.  DEFAULT is null.</param>
        public ObcStringSerializerBackedSerializer(
            IStringSerializeAndDeserialize backingStringSerializer,
            string id = null)
        {
            if (backingStringSerializer == null)
            {
                throw new ArgumentNullException(nameof(backingStringSerializer));
            }

            this.BackingStringSerializer = backingStringSerializer;

            this.SerializerRepresentation = new SerializerRepresentation(SerializationKind.StringSerializerBacked, metadata: new Dictionary <string, string> {
                { nameof(id), id }
            });
        }
        /// <summary>
        /// Builds a <see cref="TypeToRegisterForPropertyBag"/> from a type using the most sensible settings,
        /// with a specified <see cref="IStringSerializeAndDeserialize"/> to use everywhere the type appears.
        /// </summary>
        /// <param name="type">The type to register.</param>
        /// <param name="stringSerializer">The string serializer to use for <paramref name="type"/>.</param>
        /// <returns>
        /// The type to register for property bag serialization.
        /// </returns>
        public static TypeToRegisterForPropertyBag ToTypeToRegisterForPropertyBagUsingStringSerializer(
            this Type type,
            IStringSerializeAndDeserialize stringSerializer)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

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

            var result = new TypeToRegisterForPropertyBag(type, MemberTypesToInclude.None, RelatedTypesToInclude.Default, () => stringSerializer);

            return(result);
        }
Example #9
0
        /// <summary>
        /// Builds a <see cref="TypeToRegisterForJson"/> for a type using the most sensible settings,
        /// with a specified <see cref="IStringSerializeAndDeserialize"/> to use when dictionaries are keyed on that type.
        /// </summary>
        /// <param name="type">The type to register.</param>
        /// <param name="stringSerializer">The string serializer to use when dictionaries are keyed on <paramref name="type"/>.</param>
        /// <returns>
        /// The type to register for JSON serialization.
        /// </returns>
        public static TypeToRegisterForJson ToTypeToRegisterForJsonUsingKeyInDictionaryStringSerializer(
            this Type type,
            IStringSerializeAndDeserialize stringSerializer)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

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

            var result = new TypeToRegisterForJson(type, MemberTypesToInclude.All, RelatedTypesToInclude.Default, null, stringSerializer);

            return(result);
        }
Example #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StringSerializerBackedJsonConverter"/> class.
        /// </summary>
        /// <param name="registeredType">The type that the converter is registered for.</param>
        /// <param name="backingSerializer">The backing serializer.</param>
        /// <param name="canConvertTypeMatchStrategy">OPTIONAL strategy to use to match the incoming type-to-consider with <paramref name="registeredType"/>.  DEFAULT is match when the types are equal.</param>
        public StringSerializerBackedJsonConverter(
            Type registeredType,
            IStringSerializeAndDeserialize backingSerializer,
            CanConvertTypeMatchStrategy canConvertTypeMatchStrategy = CanConvertTypeMatchStrategy.TypeToConsiderEqualsRegisteredType)
        {
            if (registeredType == null)
            {
                throw new ArgumentNullException(nameof(registeredType));
            }

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

            this.RegisteredType              = registeredType;
            this.BackingSerializer           = backingSerializer;
            this.CanConvertTypeMatchStrategy = canConvertTypeMatchStrategy;
        }
Example #11
0
        /// <summary>
        /// Builds a <see cref="TypeToRegisterForBson"/> for a type using the most sensible settings,
        /// with a specified <see cref="IStringSerializeAndDeserialize"/> to use everywhere the type appears.
        /// </summary>
        /// <param name="type">The type to register.</param>
        /// <param name="stringSerializer">The string serializer to use for <paramref name="type"/>.</param>
        /// <returns>
        /// The type to register for BSON serialization.
        /// </returns>
        public static TypeToRegisterForBson ToTypeToRegisterForBsonUsingStringSerializer(
            this Type type,
            IStringSerializeAndDeserialize stringSerializer)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

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

            var serializer = StringSerializerBackedBsonSerializer.Build(type, stringSerializer);

            IBsonSerializer BsonSerializerBuilderFunc() => serializer;

            var bsonSerializerBuilder = new BsonSerializerBuilder(BsonSerializerBuilderFunc, BsonSerializerOutputKind.String);

            var result = new TypeToRegisterForBson(type, MemberTypesToInclude.None, RelatedTypesToInclude.Default, bsonSerializerBuilder, null);

            return(result);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="StringSerializerBackedBsonSerializer{T}"/> class.
 /// </summary>
 /// <param name="backingSerializer">The backing serializer.</param>
 public StringSerializerBackedBsonSerializer(
     IStringSerializeAndDeserialize backingSerializer)
 {
     this.backingSerializer = backingSerializer;
 }
Example #13
0
        /// <summary>
        /// Makes a restful call using supplied information.
        /// </summary>
        /// <typeparam name="TResult">Return type to convert response to (if you provide VoidResultType then null will be returned - basically a void call).</typeparam>
        /// <param name="uri">Uri to make the request against.</param>
        /// <param name="httpVerb">HTTP verb to use.</param>
        /// <param name="body">Optional body object to send (use null if not needed).</param>
        /// <param name="cookieJar">Optional cookie to use (use null if not needed).</param>
        /// <param name="headerJar">Optional headers to use (use null if not needed).</param>
        /// <param name="saveResponseHeadersAction">Optional action to use to save response headers (use null if not needed).</param>
        /// <param name="contentType">Content type to use for request.</param>
        /// <param name="acceptType">Content type to use for response.</param>
        /// <param name="timeout">Timeout to use.</param>
        /// <param name="serializer">Serializer to use.</param>
        /// <returns>Converted response to the specified type.</returns>
        /// <exception cref="ArgumentException">
        /// Must have return of string when accepting text type.
        /// or
        /// ContentType: " + contentType + " not supported at this time. - contentType
        /// or
        /// AcceptType: " + contentType + " not supported at this time. - acceptType
        /// or
        /// AcceptType: " + acceptType + " not supported at this time. - acceptType.
        /// </exception>
        public static TResult Call <TResult>(
            Uri uri,
            string httpVerb,
            object body,
            CookieJar cookieJar,
            HeaderJar headerJar,
            Action <KeyValuePair <string, string>[]> saveResponseHeadersAction,
            ContentType contentType,
            ContentType acceptType,
            TimeSpan timeout,
            IStringSerializeAndDeserialize serializer)
            where TResult : class
        {
            new { uri }.AsArg().Must().NotBeNull();
            new { httpVerb }.AsArg().Must().NotBeNullNorWhiteSpace();
            new { serializer }.AsArg().Must().NotBeNull();

            if (acceptType == ContentType.TextPlain && typeof(TResult) != typeof(string))
            {
                throw new ArgumentException("Must have return of string when accepting text type.");
            }

            if (contentType != ContentType.ApplicationJson)
            {
                throw new ArgumentException("ContentType: " + contentType + " not supported at this time.", nameof(contentType));
            }

            if (acceptType != ContentType.ApplicationJson && acceptType != ContentType.TextPlain)
            {
                throw new ArgumentException("AcceptType: " + contentType + " not supported at this time.", nameof(acceptType));
            }

            if (timeout == default(TimeSpan))
            {
                timeout = TimeSpan.FromSeconds(100);
            }

            var cookieContainer = new CookieContainer();

            foreach (var cookie in cookieJar.Cookies)
            {
                cookieContainer.Add(cookie);
            }

            // ReSharper disable once AccessToStaticMemberViaDerivedType - want to call this method...
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

            request.CookieContainer = cookieContainer;
            request.ContentType     = contentType.ToStringValue();
            request.Accept          = acceptType.ToStringValue();
            request.Method          = httpVerb;
            request.Timeout         = (int)timeout.TotalMilliseconds;

            LoadRequestHeaders(request, headerJar);

            string bodyAsString = null;

            if (contentType == ContentType.ApplicationJson && body != null)
            {
                bodyAsString = serializer.SerializeToString(body);
            }

            if (httpVerb != HttpVerb.Get.ToString().ToUpperInvariant() && !string.IsNullOrWhiteSpace(bodyAsString))
            {
                request.ContentLength = bodyAsString.Length;
                using (var requestStream = request.GetRequestStream())
                {
                    using (var requestWriter = new StreamWriter(requestStream, Encoding.ASCII))
                    {
                        requestWriter.Write(bodyAsString);
                        requestWriter.Close();
                    }
                }
            }

            string contents = null;
            WebHeaderCollection responseHeadersRaw;

            using (var resp = request.GetResponse())
            {
                responseHeadersRaw = resp.Headers;

                var responseStream = resp.GetResponseStream();
                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream))
                    {
                        contents = reader.ReadToEnd();
                    }
                }
            }

            TResult ret = default(TResult);

            if (typeof(TResult) == typeof(VoidResultType))
            {
                return(ret); // this will just be null and should only be used when you don't want a return
            }
            else if (acceptType == ContentType.ApplicationJson)
            {
                ret = serializer.Deserialize <TResult>(contents);
            }
            else if (acceptType == ContentType.TextPlain)
            {
                ret = contents as TResult;
            }
            else
            {
                throw new ArgumentException("AcceptType: " + acceptType + " not supported at this time.", nameof(acceptType));
            }

            var responseHeaders = responseHeadersRaw == null
                ? new KeyValuePair <string, string> [0]
                : responseHeadersRaw.ToKeyValuePairArray();

            saveResponseHeadersAction?.Invoke(responseHeaders);

            return(ret);
        }
Example #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StringSerializerBackedJsonConverter{T}"/> class.
 /// </summary>
 /// <param name="backingSerializer">The backing serializer.</param>
 /// <param name="canConvertTypeMatchStrategy">OPTIONAL strategy to use to match the incoming type-to-consider with <typeparamref name="T"/>.  DEFAULT is match when the types are equal.</param>
 public StringSerializerBackedJsonConverter(
     IStringSerializeAndDeserialize backingSerializer,
     CanConvertTypeMatchStrategy canConvertTypeMatchStrategy = CanConvertTypeMatchStrategy.TypeToConsiderEqualsRegisteredType)
     : base(typeof(T), backingSerializer, canConvertTypeMatchStrategy)
 {
 }
 /// <summary>
 /// Update the serializer for the call.
 /// </summary>
 /// <param name="uri">Uri (extension method variable) to use for chain.</param>
 /// <param name="serializer">Serializer to use.</param>
 /// <returns>Updated fluent grammar chain.</returns>
 public static ICallOnUriAll WithSerializer(this Uri uri, IStringSerializeAndDeserialize serializer)
 {
     return(new ImplementationForICallOnUriAll(uri).WithSerializer(serializer));
 }