Ejemplo n.º 1
0
        public static void Main(string[] commandArgs)
        {
            try
            {
                var record = new Record();
                record.Add(new Property("title", "My Title"));
                record.Add(new Property("header", "My Header"));

                var link = new Link();
                link.Add(new Property("title", "My Title"));
                link.Add(new Property("href", "My #ref"));
                link.Add(new Property("header", "My Header"));
                link.Add(new Class("header"));
                link.Add(new Rel("header"));
                record.Add(link);

                var file = new ResourceRef();
                file.Add(new Property("title", "My Title"));
                file.Add(new Property("href", "My #ref"));
                file.Add(new Property("header", "My Header"));
                file.Add(new Class("header"));
                file.Add(new Rel("header"));
                record.Add(file);

                record.Add(new Property("__meta", Value.CreateObject(new
                {
                    Tables = new
                    {
                        Headers = new VName[] {
                            "Id",
                            "Name"
                        }
                    }
                })));


                var p1 = record.GetProperty <VArray>("__meta.tables.headers");
                record.SetProperty("__meta.tables.headers.id", new[] { 10 });
                var p2 = record.GetProperty <VArray>("__meta.tables.headers.id");

                var serializer = new MediaSerializer(MimeType.JsonSiren);
                var step1      = serializer.Serialize(record);

                var target = serializer.Deserialize(step1);
                var step2  = serializer.Serialize(record);


                Debug.WriteLine(Json.Beautify(step1));
                Debug.WriteLine(Json.Beautify(step2));
            }
            catch (Exception ex)
            {
                ex.Trace();
            }
        }
Ejemplo n.º 2
0
        private static async Task WriteEntityAsync(IResponse res, IEntity entity, HttpStatusCode status = HttpStatusCode.OK)
        {
            var req         = res.Context.Request;
            var accept      = req.Headers[HeaderNames.Accept] ?? MimeTypeNames.JsonSiren;
            var contentType = MediaSerializer.ParseMediaType(accept);

            var hasSelf = (
                from link in entity.OfType <Link>()
                from rel in link.OfType <Rel>()
                where rel.Name == Rel.Self.Name
                select link
                ).Any();

            if (!hasSelf)
            {
                var link = new Link();
                link.Href = req.RequestUri;
                link.Add(Rel.Self);
                entity.Add(link);
            }

            res.Status = status;
            res.Headers[HeaderNames.ContentType] = $"{contentType}; charset=UTF-8";

            var serializer = new MediaSerializer(contentType);

            serializer.Serialize(entity, res.Body);

            await Task.Yield();
        }
Ejemplo n.º 3
0
        public async Task Invoke(HttpContext httpContext, IServiceProvider injector)
        {
            var path = httpContext.Request.Path.Value;

            var renderer = registry.FindPaperRenderer(path);

            if (renderer == null)
            {
                await next(httpContext);

                return;
            }

            var req = httpContext.Request;
            var res = httpContext.Response;

            var ret    = RenderEntity(httpContext, injector, renderer);
            var entity = ret.Data ?? HttpEntity.CreateFromRet(req.GetRequestUri(), ret);

            var contentType = HttpNegotiation.SelectContentType(req);
            var encoding    = HttpNegotiation.SelectEncoding(req);

            var serializer = new MediaSerializer(contentType);
            var data       = serializer.Serialize(entity);

            res.StatusCode  = ret.Status;
            res.ContentType = $"{contentType}; charset={encoding.HeaderName}";

            await res.WriteAsync(data, encoding);
        }
Ejemplo n.º 4
0
        private async Task SerializeAsync(object source, string type, string charset, Stream target)
        {
            if (source is Entity entity)
            {
                var serializer = new MediaSerializer(type);
                serializer.Serialize(entity, target, charset);
                return;
            }

            if (source is byte[] bytes)
            {
                await target.WriteAsync(bytes, 0, bytes.Length);

                return;
            }

            if (source is string body)
            {
                using (var writer = new StreamWriter(target))
                {
                    await writer.WriteAsync(body);

                    await writer.FlushAsync();
                }
                return;
            }

            throw new MediaException("Formato de dados não suportado: " + source.GetType().FullName);
        }
Ejemplo n.º 5
0
        public static string ToJson(this Payload payload, bool indent = true)
        {
            var entity     = payload.ToEntity();
            var serializer = new MediaSerializer(MediaSerializer.Json);
            var json       = serializer.Serialize(entity);

            return(indent ? Json.Beautify(json) : json);
        }
Ejemplo n.º 6
0
        async Task GetPaper(string paper)
        {
            var descriptor = paperCatalog.FindPaperDescriptor(defaultCatalog, paper);

            if (descriptor == null)
            {
                var ret = Ret.Fail(HttpStatusCode.NotFound, $"O objeto não existe: {defaultCatalog}/{paper}");
                await Res.SendEntityStatusAsync(ret);

                return;
            }

            object output;

            var instance = objectFactory.CreateObject(descriptor.PaperType);

            if (instance._HasMethod("Render"))
            {
                output = objectFactory.Call(instance, "Render", null);
            }
            else
            {
                throw new HttpException($"Não há um algoritmo de renderização conhecido para objeto do tipo ${descriptor.PaperType.FullName}.");
            }

            if (output is Stream stream)
            {
                await stream.CopyToAsync(Res.Body);

                await Res.Body.FlushAsync();
            }
            else if (output is StreamReader reader)
            {
                var encoding = Encoding.UTF8;
                var writer   = new StreamWriter(Res.Body, encoding);
                await reader.CopyToAsync(writer);

                await writer.FlushAsync();

                await Res.Body.FlushAsync();
            }
            else if (output is Entity entity)
            {
                var encoding   = Encoding.UTF8;
                var mimeType   = "json";
                var serializer = new MediaSerializer(mimeType);
                serializer.Serialize(entity, Res.Body, encoding);
                await Res.Body.FlushAsync();
            }
            else
            {
                throw new HttpException($"Não há suporte para renderização de dados do tipo {output.GetType().FullName}");
            }
        }
Ejemplo n.º 7
0
        private async Task WriteAsync(Request req, Response res, HttpStatusCode status, string message, Exception ex)
        {
            try
            {
                if (message == null)
                {
                    message = ex?.Message ?? status.ToString().ChangeCase(TextCase.ProperCase);
                }

                var validMimeTypes = new[] {
                    MediaSerializer.JsonSiren,
                    MediaSerializer.Json,
                    MediaSerializer.XmlSiren,
                    MediaSerializer.Xml
                };

                var accept     = new AcceptHeader(req.Headers, req.QueryArgs);
                var encoding   = accept.BestEncoding;
                var mimeType   = accept.SelectBestMatch(accept.MimeTypes, validMimeTypes) ?? MediaSerializer.Json;
                var renderType = mimeType.Contains("json") ? MediaSerializer.JsonSiren : MediaSerializer.XmlSiren;

                var serializer = new MediaSerializer(renderType);
                using (var memory = new MemoryStream())
                {
                    var entity = (ex != null)
            ? HttpEntity.Create(req.RequestUri, status, message, ex)
            : HttpEntity.Create(req.RequestUri, status, message);

                    serializer.Serialize(entity, memory, encoding);

                    memory.Position = 0;

                    res.Status = status;
                    res.Headers[HeaderNames.ContentType] = $"{mimeType}; charset={encoding.WebName}";

                    await memory.CopyToAsync(res.Body);
                }
            }
            catch (Exception exx)
            {
                res.Status = status;
                res.Headers[HeaderNames.ContentType] = $"text/plain; charset=UTF-8";

                var ln          = Environment.NewLine;
                var description = status.ToString().ChangeCase(TextCase.ProperCase);

                var writer = new StreamWriter(res.Body, Encoding.UTF8, bufferSize: 8 * 1024, leaveOpen: true);
                await writer.WriteAsync(
                    $"{(int)status} - {description}{ln}{message}{ln}Fault:{ln}{exx.GetStackTrace()}{ln}Caused by:{ln}{ex.GetStackTrace()}"
                    );
            }
        }
Ejemplo n.º 8
0
        private async Task SendStatusAsync(HttpContext httpContext, Ret ret)
        {
            var req = httpContext.Request;
            var res = httpContext.Response;

            var entity =
                (ret.Value as Entity)
                ?? HttpEntity.CreateFromRet(req.GetRequestUri(), ret);

            var contentType = HttpNegotiation.SelectContentType(req);
            var encoding    = HttpNegotiation.SelectEncoding(req);

            var serializer = new MediaSerializer(contentType);
            var data       = serializer.Serialize(entity);

            res.StatusCode  = ret.Status;
            res.ContentType = $"{contentType}; charset={encoding.HeaderName}";

            await res.WriteAsync(data, encoding);
        }
Ejemplo n.º 9
0
        public async Task Invoke(HttpContext httpContext, IServiceProvider serviceProvider)
        {
            Entity entity = null;
            int    status;

            try
            {
                var target = RenderTarget(httpContext);
                if (target?.Value is Uri uri)
                {
                    // Redirecionando para outra URI
                    httpContext.Response.StatusCode = (int)HttpStatusCode.Found;
                    httpContext.Response.Headers[HeaderNames.Location] = uri.ToString();
                    return;
                }

                entity = target?.Value as Entity;
                if (entity == null)
                {
                    var requestUri = httpContext.Request.GetDisplayUrl();
                    entity = HttpEntity.Create(requestUri, HttpStatusCode.NotFound);
                }

                status = (int)HttpStatusCode.OK;
            }
            catch (Exception ex)
            {
                ex.Trace();
                entity = HttpEntity.Create(httpContext.Request.GetDisplayUrl(), ex);
                status = (int)HttpStatusCode.InternalServerError;
            }

            try
            {
                var mediaType = httpContext.Request.ContentType?.Contains("xml") == true
          ? "application/xml"
          : "application/json";

                var serializer = new MediaSerializer();
                var content    = serializer.Serialize(entity, mediaType);

                httpContext.Response.StatusCode  = (int)status;
                httpContext.Response.ContentType = $"{mediaType}; charset=UTF-8";

                await httpContext.Response.WriteAsync(content);
            }
            catch (Exception ex)
            {
                ex.Trace();

                status = (int)HttpStatusCode.InternalServerError;

                var statusDecription =
                    HttpStatusCode.InternalServerError
                    .ToString()
                    .ChangeCase(TextCase.ProperCase);

                httpContext.Response.StatusCode  = status;
                httpContext.Response.ContentType = $"text/plain; charset=UTF-8";

                var nl      = Environment.NewLine;
                var cause   = string.Join(nl, ex.GetCauseMessages().Select(x => $"  • {x}"));
                var message = $"Fault {nl}  {status} - {statusDecription} {nl}Cause {nl}{cause}";

                await httpContext.Response.WriteAsync(message);
            }
        }
Ejemplo n.º 10
0
        public void WriteData(IEntity data)
        {
            var serializer = new MediaSerializer(contentType);

            serializer.Serialize((Entity)data, content, encoding);
        }
Ejemplo n.º 11
0
        public void WriteData(IEntity result)
        {
            var serializer = new MediaSerializer(contentType);

            serializer.Serialize((Entity)result, content);
        }