/// <summary>
        ///     Creates a new instance of the <see cref="ProtoBufContent" /> class that will contain the
        ///     <see cref="value" />  serialized as ProtoBuf.
        /// </summary>
        /// <param name="type">The type of the value to serialize.</param>
        /// <param name="value">The value to serialize.</param>
        /// <param name="typeModel">Options to control the behavior during serialization.</param>
        /// <param name="mediaType">The media type to use for the content.</param>
        /// <returns>A <see cref="ProtoBufContent" /> instance.</returns>
        public static ProtoBufContent Create(Type type,
                                             object?value, TypeModel?typeModel = null, MediaTypeHeaderValue?mediaType = null)
        {
            var formatter = new ProtoBufMediaTypeFormatter(typeModel);

            return(new ProtoBufContent(type, value, formatter, mediaType));
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     Reads the HTTP content and returns the value that results from deserializing the content as ProtoBuf in an
        ///     asynchronous operation.
        /// </summary>
        /// <typeparam name="T">The target type to deserialize to.</typeparam>
        /// <param name="content">The content to read from.</param>
        /// <param name="typeModel">Options to control the behavior during deserialization.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of
        ///     cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public static async Task <T> ReadFromProtoBufAsync <T>(this HttpContent content,
                                                               TypeModel?typeModel = null, CancellationToken cancellationToken = default)
        {
            Guard.NotNull(content, nameof(content));

            var result = await ReadFromProtoBufAsync(content, typeof(T), typeModel, cancellationToken).ConfigureAwait(false);

            return((T)result !);
        }
        private static async Task <T> GetFromProtoBufAsyncCore <T>(Task <HttpResponseMessage> taskResponse,
                                                                   TypeModel?typeModel, CancellationToken cancellationToken)
        {
            using var response = await taskResponse.ConfigureAwait(false);

            response.EnsureSuccessStatusCode();
            return(await response.Content.ReadFromProtoBufAsync <T>(typeModel, cancellationToken)
                   .ConfigureAwait(false));
        }
        /// <summary>
        ///     Sends a GET request to the specified Uri and returns the value that results from deserializing the response body as
        ///     ProtoBuf in an asynchronous operation.
        /// </summary>
        /// <param name="client">The client used to make the request.</param>
        /// <param name="requestUri">The Uri the request is sent to.</param>
        /// <param name="type">The type of the object to deserialize to and return.</param>
        /// <param name="typeModel">Options for running the serialization.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of
        ///     cancellation.
        /// </param>
        /// <returns>A task object representing the asynchronous operation.</returns>
        public static Task <object?> GetFromProtoBufAsync(this HttpClient client, Uri requestUri, Type type,
                                                          TypeModel?typeModel = null, CancellationToken cancellationToken = default)
        {
            Guard.NotNull(client, nameof(client));

            var requestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri);

            requestMessage.Headers.Accept.Add(ProtoBufDefaults.MediaTypeHeader);

            var taskResponse = client.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead,
                                                cancellationToken);

            return(GetFromProtoBufAsyncCore(taskResponse, type, typeModel, cancellationToken));
        }
Ejemplo n.º 5
0
        /// <summary>
        ///     Reads the HTTP content and returns the value that results from deserializing the content as ProtoBuf in an
        ///     asynchronous operation.
        /// </summary>
        /// <param name="content">The content to read from.</param>
        /// <param name="type">The type of the object to deserialize to and return.</param>
        /// <param name="typeModel">Options to control the behavior during deserialization.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of
        ///     cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public static async Task <object?> ReadFromProtoBufAsync(this HttpContent content, Type type,
                                                                 TypeModel?typeModel = null, CancellationToken cancellationToken = default)
        {
            Guard.NotNull(type, nameof(type));
            Guard.NotNull(content, nameof(content));

            if (content is ObjectContent objectContent)
            {
                return(objectContent.Value);
            }

            var formatter = new ProtoBufMediaTypeFormatter(typeModel);

            using var readStream = await content.ReadAsStreamAsync().ConfigureAwait(false);

            return(await formatter.ReadFromStreamAsync(type, readStream, content, null, cancellationToken)
                   .ConfigureAwait(false));
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="ProtoBufMediaTypeFormatter" /> class.
 /// </summary>
 /// <param name="model">Options for running serialization.</param>
 public ProtoBufMediaTypeFormatter(TypeModel?model = null)
 {
     TypeModel = model ?? ProtoBufDefaults.TypeModel;
     SupportedMediaTypes.Add(ProtoBufDefaults.MediaTypeHeaders.ApplicationProtoBuf);
     SupportedMediaTypes.Add(ProtoBufDefaults.MediaTypeHeaders.ApplicationXProtoBuf);
 }
Ejemplo n.º 7
0
    private IList <TypeModel> GetTypes(PublishedItemType itemType, IContentTypeComposition[] contentTypes)
    {
        var typeModels  = new List <TypeModel>();
        var uniqueTypes = new HashSet <string>();

        // get the types and the properties
        foreach (IContentTypeComposition contentType in contentTypes)
        {
            var typeModel = new TypeModel
            {
                Id          = contentType.Id,
                Alias       = contentType.Alias,
                ClrName     = GetClrName(_shortStringHelper, contentType.Name, contentType.Alias),
                ParentId    = contentType.ParentId,
                Name        = contentType.Name,
                Description = contentType.Description,
            };

            // of course this should never happen, but when it happens, better detect it
            // else we end up with weird nullrefs everywhere
            if (uniqueTypes.Contains(typeModel.ClrName))
            {
                throw new PanicException($"Panic: duplicate type ClrName \"{typeModel.ClrName}\".");
            }

            uniqueTypes.Add(typeModel.ClrName);

            IPublishedContentType publishedContentType = _publishedContentTypeFactory.CreateContentType(contentType);
            switch (itemType)
            {
            case PublishedItemType.Content:
                typeModel.ItemType = publishedContentType.ItemType == PublishedItemType.Element
                        ? TypeModel.ItemTypes.Element
                        : TypeModel.ItemTypes.Content;
                break;

            case PublishedItemType.Media:
                typeModel.ItemType = publishedContentType.ItemType == PublishedItemType.Element
                        ? TypeModel.ItemTypes.Element
                        : TypeModel.ItemTypes.Media;
                break;

            case PublishedItemType.Member:
                typeModel.ItemType = publishedContentType.ItemType == PublishedItemType.Element
                        ? TypeModel.ItemTypes.Element
                        : TypeModel.ItemTypes.Member;
                break;

            default:
                throw new InvalidOperationException(string.Format(
                                                        "Unsupported PublishedItemType \"{0}\".",
                                                        itemType));
            }

            typeModels.Add(typeModel);

            foreach (IPropertyType propertyType in contentType.PropertyTypes)
            {
                var propertyModel = new PropertyModel
                {
                    Alias       = propertyType.Alias,
                    ClrName     = GetClrName(_shortStringHelper, propertyType.Name, propertyType.Alias),
                    Name        = propertyType.Name,
                    Description = propertyType.Description,
                };

                IPublishedPropertyType?publishedPropertyType =
                    publishedContentType.GetPropertyType(propertyType.Alias);
                if (publishedPropertyType == null)
                {
                    throw new PanicException(
                              $"Panic: could not get published property type {contentType.Alias}.{propertyType.Alias}.");
                }

                propertyModel.ModelClrType = publishedPropertyType.ModelClrType;

                typeModel.Properties.Add(propertyModel);
            }
        }

        // wire the base types
        foreach (TypeModel typeModel in typeModels.Where(x => x.ParentId > 0))
        {
            typeModel.BaseType = typeModels.SingleOrDefault(x => x.Id == typeModel.ParentId);

            // Umbraco 7.4 introduces content types containers, so even though ParentId > 0, the parent might
            // not be a content type - here we assume that BaseType being null while ParentId > 0 means that
            // the parent is a container (and we don't check).
            typeModel.IsParent = typeModel.BaseType != null;
        }

        // discover mixins
        foreach (IContentTypeComposition contentType in contentTypes)
        {
            TypeModel?typeModel = typeModels.SingleOrDefault(x => x.Id == contentType.Id);
            if (typeModel == null)
            {
                throw new PanicException("Panic: no type model matching content type.");
            }

            IEnumerable <IContentTypeComposition> compositionTypes;
            if (contentType is IMediaType contentTypeAsMedia)
            {
                compositionTypes = contentTypeAsMedia.ContentTypeComposition;
            }
            else if (contentType is IContentType contentTypeAsContent)
            {
                compositionTypes = contentTypeAsContent.ContentTypeComposition;
            }
            else if (contentType is IMemberType contentTypeAsMember)
            {
                compositionTypes = contentTypeAsMember.ContentTypeComposition;
            }
            else
            {
                throw new PanicException(string.Format(
                                             "Panic: unsupported type \"{0}\".",
                                             contentType.GetType().FullName));
            }

            foreach (IContentTypeComposition compositionType in compositionTypes)
            {
                TypeModel?compositionModel = typeModels.SingleOrDefault(x => x.Id == compositionType.Id);
                if (compositionModel == null)
                {
                    throw new PanicException("Panic: composition type does not exist.");
                }

                if (compositionType.Id == contentType.ParentId)
                {
                    continue;
                }

                // add to mixins
                typeModel.MixinTypes.Add(compositionModel);

                // mark as mixin - as well as parents
                compositionModel.IsMixin = true;
                while ((compositionModel = compositionModel.BaseType) != null)
                {
                    compositionModel.IsMixin = true;
                }
            }
        }

        return(typeModels);
    }
Ejemplo n.º 8
0
        /// <summary>
        ///     Send a PUT request to the specified Uri containing the <paramref name="value" /> serialized as ProtoBuf in the
        ///     request body.
        /// </summary>
        /// <typeparam name="TValue">The type of the value to serialize.</typeparam>
        /// <param name="client">The client used to make the request.</param>
        /// <param name="requestUri">The Uri the request is sent to.</param>
        /// <param name="value">The value to serialize.</param>
        /// <param name="typeModel">Options for running the serialization.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of
        ///     cancellation.
        /// </param>
        /// <returns>A task object representing the asynchronous operation.</returns>
        public static Task <HttpResponseMessage> PutAsProtoBufAsync <TValue>(this HttpClient client, Uri requestUri,
                                                                             TValue value, TypeModel?typeModel = null, CancellationToken cancellationToken = default)
        {
            Guard.NotNull(client, nameof(client));

            var content = ProtoBufContent.Create(value, typeModel);

            return(client.PutAsync(requestUri, content, cancellationToken));
        }
 /// <summary>
 ///     Creates a new instance of the <see cref="ProtoBufContent" /> class that will contain the
 ///     <see cref="value" />  serialized as ProtoBuf.
 /// </summary>
 /// <typeparam name="T">The type of the value to serialize.</typeparam>
 /// <param name="value">The value to serialize.</param>
 /// <param name="typeModel">Options to control the behavior during serialization.</param>
 /// <param name="mediaType">The media type to use for the content.</param>
 /// <returns>A <see cref="ProtoBufContent" /> instance.</returns>
 public static ProtoBufContent Create <T>(T value,
                                          TypeModel?typeModel = null, MediaTypeHeaderValue?mediaType = null)
 {
     return(Create(typeof(T), value, typeModel, mediaType));
 }