예제 #1
0
        /// <summary>
        /// If the encoder encodes a given object.
        /// </summary>
        /// <param name="Object">Object to encode.</param>
        /// <param name="Grade">How well the encoder encodes the object.</param>
        /// <param name="AcceptedContentTypes">Optional array of accepted content types. If array is empty, all content types are accepted.</param>
        /// <returns>If the encoder can encode the given object.</returns>
        public bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
        {
            if (InternetContent.IsAccepted(JsonContentTypes, AcceptedContentTypes))
            {
                if (Object is IEnumerable <KeyValuePair <string, object> > )
                {
                    Grade = Grade.Ok;
                    return(true);
                }
                else if (Object == null ||
                         Object is IEnumerable ||
                         Object is string ||
                         Object is bool ||
                         Object is decimal ||
                         Object is double ||
                         Object is float ||
                         Object is int ||
                         Object is long ||
                         Object is short ||
                         Object is byte ||
                         Object is uint ||
                         Object is ulong ||
                         Object is ushort ||
                         Object is sbyte ||
                         Object is char)
                {
                    Grade = Grade.Barely;
                    return(true);
                }
            }

            Grade = Grade.NotAtAll;
            return(false);
        }
예제 #2
0
        public void LWM2M_TLV_Test_07_Decode_BootstrapInfo()
        {
            byte[] Tlv = new byte[]
            {
                0xc8, 0x00, 0x1e, 0x63, 0x6f, 0x61, 0x70, 0x3a,
                0x2f, 0x2f, 0x6c, 0x65, 0x73, 0x68, 0x61, 0x6e,
                0x2e, 0x65, 0x63, 0x6c, 0x69, 0x70, 0x73, 0x65,
                0x2e, 0x6f, 0x72, 0x67, 0x3a, 0x35, 0x36, 0x38,
                0x33, 0xc1, 0x01, 0x01, 0xc1, 0x02, 0x03, 0xc0,
                0x03, 0xc0, 0x04, 0xc0, 0x05, 0xc1, 0x06, 0x03,
                0xc0, 0x07, 0xc0, 0x08, 0xc0, 0x09, 0xc1, 0x0a,
                0x6f, 0xc1, 0x0b, 0x01, 0xc1, 0x0c, 0x00
            };

            object Decoded = InternetContent.Decode(TlvDecoder.ContentType, Tlv, null);

            Assert.IsNotNull(Decoded);

            TlvRecord[] Records = Decoded as TlvRecord[];
            Assert.IsNotNull(Records);

            foreach (TlvRecord Record in Records)
            {
                Console.Out.WriteLine(Record.ToString());
            }
        }
예제 #3
0
        /// <summary>
        /// Encodes an object.
        /// </summary>
        /// <param name="Object">Object to encode.</param>
        /// <param name="Encoding">Desired encoding of text. Can be null if no desired encoding is speified.</param>
        /// <param name="ContentType">Content Type of encoding. Includes information about any text encodings used.</param>
        /// <returns>Encoded object.</returns>
        /// <param name="AcceptedContentTypes">Optional array of accepted content types. If array is empty, all content types are accepted.</param>
        /// <exception cref="ArgumentException">If the object cannot be encoded.</exception>
        public byte[] Encode(object Object, Encoding Encoding, out string ContentType, params string[] AcceptedContentTypes)
        {
            SKData Data;
            bool   Dispose = false;

            byte[] Bin;

            if (!(Object is SKImage Image))
            {
                if (Object is SKBitmap Bitmap)
                {
                    Image   = SKImage.FromBitmap(Bitmap);
                    Dispose = true;
                }
                else
                {
                    throw new ArgumentException("Object not an image derived from SkiaSharp.SKImage or SkiaSharp.SKBitmap.", nameof(Object));
                }
            }

            if (InternetContent.IsAccepted("image/png", AcceptedContentTypes))
            {
                Data        = Image.Encode(SKEncodedImageFormat.Png, 100);
                ContentType = "image/png";
            }
            else if (InternetContent.IsAccepted("image/bmp", AcceptedContentTypes))
            {
                Data        = Image.Encode(SKEncodedImageFormat.Bmp, 100);
                ContentType = "image/bmp";
            }
            else if (InternetContent.IsAccepted("image/jpeg", AcceptedContentTypes))
            {
                Data        = Image.Encode(SKEncodedImageFormat.Jpeg, 90);
                ContentType = "image/jpeg";
            }
            else if (InternetContent.IsAccepted("image/gif", AcceptedContentTypes))
            {
                Data        = Image.Encode(SKEncodedImageFormat.Gif, 100);
                ContentType = "image/gif";
            }
            else if (InternetContent.IsAccepted("image/x-icon", AcceptedContentTypes))
            {
                Data        = Image.Encode(SKEncodedImageFormat.Ico, 100);
                ContentType = "image/x-icon";
            }
            else
            {
                throw new ArgumentException("Unable to encode object, or content type not accepted.", nameof(Object));
            }

            Bin = Data.ToArray();
            Data.Dispose();

            if (Dispose)
            {
                Image.Dispose();
            }

            return(Bin);
        }
예제 #4
0
        /// <summary>
        /// Performs the actual conversion.
        /// </summary>
        /// <param name="FromContentType">Content type of the content to convert from.</param>
        /// <param name="From">Stream pointing to binary representation of content.</param>
        /// <param name="FromFileName">If the content is coming from a file, this parameter contains the name of that file.
        /// Otherwise, the parameter is the empty string.</param>
        /// <param name="LocalResourceName">Local resource name of file, if accessed from a web server.</param>
        /// <param name="URL">URL of resource, if accessed from a web server.</param>
        /// <param name="ToContentType">Content type of the content to convert to.</param>
        /// <param name="To">Stream pointing to where binary representation of content is to be sent.</param>
        /// <param name="Session">Session states.</param>
        /// <returns>If the result is dynamic (true), or only depends on the source (false).</returns>
        public bool Convert(string FromContentType, Stream From, string FromFileName, string LocalResourceName, string URL, string ToContentType,
                            Stream To, Variables Session)
        {
            string Script;

            using (StreamReader rd = new StreamReader(From))
            {
                Script = rd.ReadToEnd();
            }

            Expression Exp = new Expression(Script);

            if (Session is null)
            {
                Session = new Variables();
            }

            object Result = Exp.Evaluate(Session);

            if (!InternetContent.Encodes(Result, out Grade _, out IContentEncoder Encoder, ToContentType))
            {
                throw new NotAcceptableException("Unable to encode objects of type " + Result.GetType().FullName + " to Internet Content Type " + ToContentType);
            }

            byte[] Data = Encoder.Encode(Result, Encoding.UTF8, out string _, ToContentType);
            To.Write(Data, 0, Data.Length);

            return(true);
        }
예제 #5
0
        /// <summary>
        /// Downloads a certificate.
        /// </summary>
        /// <param name="AccountLocation">Account location.</param>
        /// <param name="CertificateLocation">URI of certificate.</param>
        /// <returns>Certificate chain.</returns>
        public async Task <X509Certificate2[]> DownloadCertificate(Uri AccountLocation, Uri CertificateLocation)
        {
            string ContentType           = PemDecoder.ContentType;
            HttpResponseMessage Response = await this.HttpPost(CertificateLocation, AccountLocation, ContentType, null);

            Response.EnsureSuccessStatusCode();

            byte[] Bin = await Response.Content.ReadAsByteArrayAsync();

            if (Response.Headers.TryGetValues("Content-Type", out IEnumerable <string> Values))
            {
                foreach (string s in Values)
                {
                    ContentType = s;
                    break;
                }
            }

            object Decoded = InternetContent.Decode(ContentType, Bin, CertificateLocation);

            if (!(Decoded is X509Certificate2[] Certificates))
            {
                throw new Exception("Unexpected response returned. Content-Type: " + ContentType);
            }

            return(Certificates);
        }
예제 #6
0
        /// <summary>
        /// Gets a resource, using a Uniform Resource Identifier (or Locator).
        /// </summary>
        /// <param name="Uri">URI</param>
        /// <param name="TimeoutMs">Timeout, in milliseconds.</param>
        /// <param name="Headers">Optional headers. Interpreted in accordance with the corresponding URI scheme.</param>
        /// <returns>Decoded object.</returns>
        public async Task <object> GetAsync(Uri Uri, int TimeoutMs, params KeyValuePair <string, string>[] Headers)
        {
            using (HttpClient HttpClient = new HttpClient()
            {
                Timeout = TimeSpan.FromMilliseconds(TimeoutMs)
            })
            {
                using (HttpRequestMessage Request = new HttpRequestMessage()
                {
                    RequestUri = Uri,
                    Method = HttpMethod.Get
                })
                {
                    PrepareHeaders(Request, Headers);

                    HttpResponseMessage Response = await HttpClient.SendAsync(Request);

                    Response.EnsureSuccessStatusCode();

                    byte[] Bin = await Response.Content.ReadAsByteArrayAsync();

                    string ContentType = Response.Content.Headers.ContentType.ToString();
                    object Decoded     = InternetContent.Decode(ContentType, Bin, Uri);

                    return(Decoded);
                }
            }
        }
예제 #7
0
        /// <summary>
        /// Gets a resource, using a Uniform Resource Identifier (or Locator).
        /// </summary>
        /// <param name="Uri">URI</param>
        /// <param name="TimeoutMs">Timeout, in milliseconds. (Default=60000)</param>
        /// <param name="Headers">Optional headers. Interpreted in accordance with the corresponding URI scheme.</param>
        /// <exception cref="InvalidOperationException">No <see cref="HttpxProxy"/> set in the HTTPX <see cref="Types"/> module parameter.</exception>
        /// <exception cref="ArgumentException">If the <paramref name="Uri"/> parameter is invalid.</exception>
        /// <exception cref="ArgumentException">If the object response be decoded.</exception>
        /// <exception cref="ConflictException">If an approved presence subscription with the remote entity does not exist.</exception>
        /// <exception cref="ServiceUnavailableException">If the remote entity is not online.</exception>
        /// <exception cref="TimeoutException">If the request times out.</exception>
        /// <exception cref="OutOfMemoryException">If resource too large to decode.</exception>
        /// <exception cref="IOException">If unable to read from temporary file.</exception>
        /// <returns>Decoded object.</returns>
        public async Task <object> GetAsync(Uri Uri, int TimeoutMs, params KeyValuePair <string, string>[] Headers)
        {
            KeyValuePair <string, TemporaryFile> Rec = await this.GetTempFileAsync(Uri, TimeoutMs, Headers);

            string        ContentType = Rec.Key;
            TemporaryFile File        = Rec.Value;

            try
            {
                if (File is null)
                {
                    return(null);
                }

                File.Position = 0;

                if (File.Length > int.MaxValue)
                {
                    throw new OutOfMemoryException("Resource too large.");
                }

                int    Len = (int)File.Length;
                byte[] Bin = new byte[Len];
                if (await File.ReadAsync(Bin, 0, Len) != Len)
                {
                    throw new IOException("Unable to read from file.");
                }

                return(InternetContent.Decode(ContentType, Bin, Uri));
            }
            finally
            {
                File?.Dispose();
            }
        }
예제 #8
0
        /// <summary>
        /// Encodes an object.
        /// </summary>
        /// <param name="Object">Object to encode.</param>
        /// <param name="Encoding">Desired encoding of text. Can be null if no desired encoding is speified.</param>
        /// <param name="ContentType">Content Type of encoding. Includes information about any text encodings used.</param>
        /// <param name="AcceptedContentTypes">Optional array of accepted content types. If array is empty, all content types are accepted.</param>
        /// <returns>Encoded object.</returns>
        /// <exception cref="ArgumentException">If the object cannot be encoded.</exception>
        public byte[] Encode(object Object, Encoding Encoding, out string ContentType, params string[] AcceptedContentTypes)
        {
            if (InternetContent.IsAccepted(WsContentTypes, out ContentType, AcceptedContentTypes))
            {
                string s = null;

                if (Object is Expression Expression)
                {
                    s = Expression.Script;
                }
                else if (Object is string s2)
                {
                    s = s2;
                }

                if (s != null)
                {
                    if (Encoding is null)
                    {
                        ContentType += "; charset=utf-8";
                        return(Encoding.UTF8.GetBytes(s));
                    }
                    else
                    {
                        ContentType += "; charset=" + Encoding.WebName;
                        return(Encoding.GetBytes(s));
                    }
                }
            }

            throw new ArgumentException("Unable to encode object, or content type not accepted.", nameof(Object));
        }
예제 #9
0
파일: Get.cs 프로젝트: live0717/IoTGateway
        /// <summary>
        /// Evaluates the node, using the variables provided in the <paramref name="Variables"/> collection.
        /// </summary>
        /// <param name="Arguments">Function arguments.</param>
        /// <param name="Variables">Variables collection.</param>
        /// <returns>Result.</returns>
        public override IElement Evaluate(IElement[] Arguments, Variables Variables)
        {
            Uri Url = new Uri(Arguments[0].AssociatedObjectValue?.ToString());
            List <KeyValuePair <string, string> > HeaderList = null;

            if (Arguments.Length > 1)
            {
                object Arg1 = Arguments[1].AssociatedObjectValue;

                if (Arg1 is IDictionary <string, IElement> Headers)
                {
                    HeaderList = new List <KeyValuePair <string, string> >();

                    foreach (KeyValuePair <string, IElement> P in Headers)
                    {
                        HeaderList.Add(new KeyValuePair <string, string>(P.Key, P.Value.AssociatedObjectValue?.ToString()));
                    }
                }
                else if (Arg1 is string Accept)
                {
                    HeaderList = new List <KeyValuePair <string, string> >()
                    {
                        new KeyValuePair <string, string>("Accept", Accept)
                    };
                }
                else
                {
                    throw new ScriptRuntimeException("Invalid second parameter to Get. Should be either an accept string, or an object with protocol-specific headers or options.", this);
                }
            }

            object Result = InternetContent.GetAsync(Url, HeaderList?.ToArray() ?? new KeyValuePair <string, string> [0]).Result;

            return(new ObjectValue(Result));
        }
예제 #10
0
        /// <summary>
        /// Encodes an object.
        /// </summary>
        /// <param name="Object">Object to encode.</param>
        /// <param name="Encoding">Desired encoding of text. Can be null if no desired encoding is speified.</param>
        /// <param name="ContentType">Content Type of encoding. Includes information about any text encodings used.</param>
        /// <param name="AcceptedContentTypes">Optional array of accepted content types. If array is empty, all content types are accepted.</param>
        /// <returns>Encoded object.</returns>
        /// <exception cref="ArgumentException">If the object cannot be encoded.</exception>
        public byte[] Encode(object Object, Encoding Encoding, out string ContentType, params string[] AcceptedContentTypes)
        {
            if (InternetContent.IsAccepted(HtmlContentTypes, out ContentType, AcceptedContentTypes))
            {
                string Html = null;

                if (Object is HtmlDocument HtmlDoc)
                {
                    Html = HtmlDoc.HtmlText;
                }
                else if (Object is string s)
                {
                    Html = s;
                }

                if (Html != null)
                {
                    if (Encoding == null)
                    {
                        ContentType += "; charset=utf-8";
                        return(Encoding.UTF8.GetBytes(Html));
                    }
                    else
                    {
                        ContentType += "; charset=" + Encoding.WebName;
                        return(Encoding.GetBytes(Html));
                    }
                }
            }

            throw new ArgumentException("Unable to encode object, or content type not accepted.", nameof(Object));
        }
예제 #11
0
        /// <summary>
        /// Executes the GET method on the resource.
        /// </summary>
        /// <param name="Request">HTTP Request</param>
        /// <param name="Response">HTTP Response</param>
        /// <exception cref="HttpException">If an error occurred when processing the method.</exception>
        public async Task GET(HttpRequest Request, HttpResponse Response)
        {
            string FullPath = this.GetFullPath(Request);

            if (File.Exists(FullPath))
            {
                DateTime LastModified = File.GetLastWriteTime(FullPath).ToUniversalTime();
                CacheRec Rec;

                Rec = this.CheckCacheHeaders(FullPath, LastModified, Request);

                string ContentType = InternetContent.GetContentType(Path.GetExtension(FullPath));
                Stream f           = CheckAcceptable(Request, Response, ref ContentType, out bool Dynamic, FullPath, Request.Header.Resource);
                Rec.IsDynamic = Dynamic;

                if (Response.ResponseSent)
                {
                    return;
                }

                await SendResponse(f, FullPath, ContentType, Rec.IsDynamic, Rec.ETag, LastModified, Response, Request);
            }
            else
            {
                await this.RaiseFileNotFound(FullPath, Request, Response);
            }
        }
예제 #12
0
        private object Decode(string FileName)
        {
            byte[] Data        = File.ReadAllBytes("Data\\" + FileName + ".bin");
            string ContentType = File.ReadAllText("Data\\" + FileName + ".txt");

            return(InternetContent.Decode(ContentType, Data, null));
        }
예제 #13
0
        /// <summary>
        /// Posts to a resource, using a Uniform Resource Identifier (or Locator).
        /// </summary>
        /// <param name="Uri">URI</param>
        /// <param name="Data">Data to post.</param>
        /// <param name="TimeoutMs">Timeout, in milliseconds. (Default=60000)</param>
        /// <param name="Headers">Optional headers. Interpreted in accordance with the corresponding URI scheme.</param>
        /// <returns>Decoded response.</returns>
        public virtual async Task <object> PostAsync(Uri Uri, object Data, int TimeoutMs, params KeyValuePair <string, string>[] Headers)
        {
            byte[] Bin = InternetContent.Encode(Data, System.Text.Encoding.UTF8, out string ContentType);
            KeyValuePair <byte[], string> Result = await this.PostAsync(Uri, Bin, ContentType, TimeoutMs, Headers);

            return(InternetContent.Decode(Result.Value, Result.Key, Uri));
        }
예제 #14
0
        /// <summary>
        /// If the link provided should be embedded in a multi-media construct automatically.
        /// </summary>
        /// <param name="Url">Inline link.</param>
        public override bool EmbedInlineLink(string Url)
        {
            string Extension   = Path.GetExtension(Url);
            string ContentType = InternetContent.GetContentType(Extension);

            return(ContentType.StartsWith("image/"));
        }
예제 #15
0
        /// <summary>
        /// Downloads a certificate.
        /// </summary>
        /// <param name="CertificateLocation">URI of certificate.</param>
        /// <returns>Certificate chain.</returns>
        public async Task <X509Certificate2[]> DownloadCertificate(Uri CertificateLocation)
        {
            HttpRequestMessage Request     = new HttpRequestMessage(HttpMethod.Get, CertificateLocation);
            string             ContentType = PemDecoder.ContentType;

            Request.Headers.TryAddWithoutValidation("Accept", ContentType);
            HttpResponseMessage Response = await this.httpClient.SendAsync(Request);

            Response.EnsureSuccessStatusCode();

            Stream Stream = await Response.Content.ReadAsStreamAsync();

            byte[] Bin = await Response.Content.ReadAsByteArrayAsync();

            if (Response.Headers.TryGetValues("Content-Type", out IEnumerable <string> Values))
            {
                foreach (string s in Values)
                {
                    ContentType = s;
                    break;
                }
            }

            object Decoded = InternetContent.Decode(ContentType, Bin, CertificateLocation);

            if (!(Decoded is X509Certificate2[] Certificates))
            {
                throw new Exception("Unexpected response returned. Content-Type: " + ContentType);
            }

            return(Certificates);
        }
예제 #16
0
파일: Encode.cs 프로젝트: iamr8/IoTGateway
        /// <summary>
        /// Evaluates the function.
        /// </summary>
        /// <param name="Arguments">Function arguments.</param>
        /// <param name="Variables">Variables collection.</param>
        /// <returns>Function result.</returns>
        public override IElement Evaluate(IElement[] Arguments, Variables Variables)
        {
            string ContentType;

            byte[] Bin;

            if (Arguments.Length > 1)
            {
                if (!(Arguments[1].AssociatedObjectValue is Array A))
                {
                    throw new ScriptRuntimeException("Second parameter to Encode should be an array of acceptable content types.", this);
                }

                int      i, c = A.Length;
                string[] AcceptedTypes = new string[c];

                for (i = 0; i < c; i++)
                {
                    AcceptedTypes[i] = A.GetValue(i)?.ToString();
                }

                Bin = InternetContent.Encode(Arguments[0].AssociatedObjectValue, System.Text.Encoding.UTF8, out ContentType, AcceptedTypes);
            }
            else
            {
                Bin = InternetContent.Encode(Arguments[0].AssociatedObjectValue, System.Text.Encoding.UTF8, out ContentType);
            }

            return(new ObjectVector(new ObjectValue(Bin), new StringValue(ContentType)));
        }
예제 #17
0
        /// <summary>
        /// Decodes data sent in request.
        /// </summary>
        /// <returns>Decoded data.</returns>
        public object DecodeData()
        {
            if (this.dataStream is null)
            {
                return(null);
            }

            long l = this.dataStream.Length;

            if (l > int.MaxValue)
            {
                throw new OutOfMemoryException("Data object too large for in-memory decoding.");
            }

            int Len = (int)l;

            byte[] Data = new byte[Len];
            this.dataStream.Position = 0;
            this.dataStream.Read(Data, 0, Len);

            HttpFieldContentType ContentType = this.header.ContentType;

            if (ContentType is null)
            {
                return(Data);
            }

            return(InternetContent.Decode(ContentType.Type, Data, ContentType.Encoding, ContentType.Fields,
                                          new Uri(this.header.GetURL(false, false))));
        }
예제 #18
0
        /// <summary>
        /// If the encoder encodes a given object.
        /// </summary>
        /// <param name="Object">Object to encode.</param>
        /// <param name="Grade">How well the encoder encodes the object.</param>
        /// <param name="AcceptedContentTypes">Optional array of accepted content types. If array is empty, all content types are accepted.</param>
        /// <returns>If the encoder can encode the given object.</returns>
        public bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
        {
            if (Object is string)
            {
                if (InternetContent.IsAccepted("text/plain", AcceptedContentTypes))
                {
                    Grade = Grade.Ok;
                    return(true);
                }
                else
                {
                    foreach (string s in AcceptedContentTypes)
                    {
                        if (s.StartsWith("text/"))
                        {
                            Grade = Grade.Barely;
                            return(true);
                        }
                    }
                }
            }

            Grade = Grade.NotAtAll;
            return(false);
        }
예제 #19
0
        /// <summary>
        /// Evaluates the function on a scalar argument.
        /// </summary>
        /// <param name="Argument">Function argument.</param>
        /// <param name="Variables">Variables collection.</param>
        /// <returns>Function result.</returns>
        public override IElement EvaluateScalar(string Argument, Variables Variables)
        {
            byte[] Bin         = File.ReadAllBytes(Argument);
            string ContentType = InternetContent.GetContentType(Path.GetExtension(Argument));
            object Decoded     = InternetContent.Decode(ContentType, Bin, new Uri(Argument));

            return(new ObjectValue(Decoded));
        }
예제 #20
0
 /// <summary>
 /// Encodes an object.
 /// </summary>
 /// <param name="Object">Object to encode.</param>
 /// <param name="Encoding">Desired encoding of text. Can be null if no desired encoding is speified.</param>
 /// <param name="ContentType">Content Type of encoding. Includes information about any text encodings used.</param>
 /// <param name="AcceptedContentTypes">Optional array of accepted content types. If array is empty, all content types are accepted.</param>
 /// <returns>Encoded object.</returns>
 /// <exception cref="ArgumentException">If the object cannot be encoded.</exception>
 public byte[] Encode(object Object, Encoding Encoding, out string ContentType, params string[] AcceptedContentTypes)
 {
     if (Object is ReportContent Report &&
         InternetContent.IsAccepted(ContentTypes, AcceptedContentTypes))
     {
         string Boundary = Guid.NewGuid().ToString();
         ContentType = ReportCodec.ContentType + "; boundary=\"" + Boundary + "\"";
         return(FormDataDecoder.Encode(Report.Content, Boundary));
     }
예제 #21
0
        /// <summary>
        /// Returns an object to the client. This method can only be called once per response, and only as the only method that returns a response
        /// to the client.
        /// </summary>
        /// <param name="Object">Object to return. Object will be encoded using Internet Content encoders, as defined in <see cref="Waher.Content"/>.</param>
        public void Return(object Object)
        {
            byte[] Data = InternetContent.Encode(Object, this.encoding, out string ContentType);

            this.ContentType   = ContentType;
            this.ContentLength = Data.Length;

            this.Write(Data);
        }
예제 #22
0
 /// <summary>
 /// Serializes an object to an array of bytes.
 /// </summary>
 /// <param name="Value">Value</param>
 /// <returns>Binary serialization.</returns>
 public static byte[] SerializeToBinary(object Value)
 {
     if (Value is byte[] Bin)
     {
         return(Bin);
     }
     else
     {
         return(InternetContent.Encode(Value, Encoding.UTF8, out string ContentType));
     }
 }
예제 #23
0
        internal async Task <AcmeResponse> POST(Uri URL, Uri KeyID, params KeyValuePair <string, object>[] Payload)
        {
            HttpResponseMessage Response = await this.HttpPost(URL, KeyID, null, Payload);

            byte[] Bin = await Response.Content.ReadAsByteArrayAsync();

            string   CharSet = Response.Content.Headers.ContentType?.CharSet;
            Encoding Encoding;

            if (string.IsNullOrEmpty(CharSet))
            {
                Encoding = Encoding.UTF8;
            }
            else
            {
                Encoding = InternetContent.GetEncoding(CharSet);
            }

            AcmeResponse AcmeResponse = new AcmeResponse()
            {
                Json            = Encoding.GetString(Bin),
                Location        = URL,
                ResponseMessage = Response,
                Payload         = null
            };

            if (Response.Headers.TryGetValues("Location", out IEnumerable <string> Values))
            {
                foreach (string s in Values)
                {
                    AcmeResponse.Location = new Uri(s);
                    break;
                }
            }

            if (string.IsNullOrEmpty(AcmeResponse.Json))
            {
                AcmeResponse.Payload = null;
            }
            else if ((AcmeResponse.Payload = JSON.Parse(AcmeResponse.Json) as IEnumerable <KeyValuePair <string, object> >) is null)
            {
                throw new Exception("Unexpected response returned.");
            }

            if (Response.IsSuccessStatusCode)
            {
                return(AcmeResponse);
            }
            else
            {
                throw CreateException(AcmeResponse.Payload, Response);
            }
        }
예제 #24
0
 /// <summary>
 /// If the encoder encodes a given object.
 /// </summary>
 /// <param name="Object">Object to encode.</param>
 /// <param name="Grade">How well the encoder encodes the object.</param>
 /// <param name="AcceptedContentTypes">Optional array of accepted content types. If array is empty, all content types are accepted.</param>
 /// <returns>If the encoder can encode the given object.</returns>
 public bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
 {
     if ((Object is SKImage || Object is SKBitmap) && InternetContent.IsAccepted(ContentTypes, AcceptedContentTypes))
     {
         Grade = Grade.Ok;
         return(true);
     }
     else
     {
         Grade = Grade.NotAtAll;
         return(false);
     }
 }
예제 #25
0
 /// <summary>
 /// If the encoder encodes a given object.
 /// </summary>
 /// <param name="Object">Object to encode.</param>
 /// <param name="Grade">How well the encoder encodes the object.</param>
 /// <param name="AcceptedContentTypes">Optional array of accepted content types. If array is empty, all content types are accepted.</param>
 /// <returns>If the encoder can encode the given object.</returns>
 public bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
 {
     if (Object is MarkdownDocument && InternetContent.IsAccepted(ContentTypes, AcceptedContentTypes))
     {
         Grade = Grade.Excellent;
         return(true);
     }
     else
     {
         Grade = Grade.NotAtAll;
         return(false);
     }
 }
예제 #26
0
 /// <summary>
 /// If the encoder encodes a given object.
 /// </summary>
 /// <param name="Object">Object to encode.</param>
 /// <param name="Grade">How well the encoder encodes the object.</param>
 /// <param name="AcceptedContentTypes">Optional array of accepted content types. If array is empty, all content types are accepted.</param>
 /// <returns>If the encoder can encode the given object.</returns>
 public bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
 {
     if (Object is JwtToken && InternetContent.IsAccepted(ContentType, AcceptedContentTypes))
     {
         Grade = Grade.Perfect;
         return(true);
     }
     else
     {
         Grade = Grade.NotAtAll;
         return(false);
     }
 }
예제 #27
0
        /// <summary>
        /// If the encoder encodes a given object.
        /// </summary>
        /// <param name="Object">Object to encode.</param>
        /// <param name="Grade">How well the encoder encodes the object.</param>
        /// <param name="AcceptedContentTypes">Optional array of accepted content types. If array is empty, all content types are accepted.</param>
        /// <returns>If the encoder can encode the given object.</returns>
        public bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
        {
            if (Object is HtmlDocument || (Object is string s && s.TrimEnd().EndsWith("</html>", StringComparison.OrdinalIgnoreCase)))
            {
                if (InternetContent.IsAccepted(HtmlContentTypes, AcceptedContentTypes))
                {
                    Grade = Grade.Ok;
                    return(true);
                }
            }

            Grade = Grade.NotAtAll;
            return(false);
        }
예제 #28
0
 /// <summary>
 /// If the encoder encodes a given object.
 /// </summary>
 /// <param name="Object">Object to encode.</param>
 /// <param name="Grade">How well the encoder encodes the object.</param>
 /// <param name="AcceptedContentTypes">Optional array of accepted content types. If array is empty, all content types are accepted.</param>
 /// <returns>If the encoder can encode the given object.</returns>
 public bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
 {
     if (InternetContent.IsAccepted(CsvContentTypes, AcceptedContentTypes) &&
         (Object is string[][] || Object is IMatrix))
     {
         Grade = Grade.Ok;
         return(true);
     }
     else
     {
         Grade = Grade.NotAtAll;
         return(false);
     }
 }
예제 #29
0
        /// <summary>
        /// If the encoder encodes a given object.
        /// </summary>
        /// <param name="Object">Object to encode.</param>
        /// <param name="Grade">How well the encoder encodes the object.</param>
        /// <param name="AcceptedContentTypes">Optional array of accepted content types. If array is empty, all content types are accepted.</param>
        /// <returns>If the encoder can encode the given object.</returns>
        public bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
        {
            if (Object is HtmlDocument)
            {
                if (InternetContent.IsAccepted(HtmlContentTypes, AcceptedContentTypes))
                {
                    Grade = Grade.Ok;
                    return(true);
                }
            }

            Grade = Grade.NotAtAll;
            return(false);
        }
예제 #30
0
        /// <summary>
        /// If the encoder encodes a given object.
        /// </summary>
        /// <param name="Object">Object to encode.</param>
        /// <param name="Grade">How well the encoder encodes the object.</param>
        /// <param name="AcceptedContentTypes">Optional array of accepted content types. If array is empty, all content types are accepted.</param>
        /// <returns>If the encoder can encode the given object.</returns>
        public bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
        {
            if (Object is Expression)
            {
                if (InternetContent.IsAccepted(WsContentTypes, AcceptedContentTypes))
                {
                    Grade = Grade.Excellent;
                    return(true);
                }
            }

            Grade = Grade.NotAtAll;
            return(false);
        }