public void ArrayBufferWithOffsetConstructorWorks() {
			var buf = new ArrayBuffer(80);
			var arr = new Uint8Array(buf, 16);
			Assert.IsTrue((object)arr is Uint8Array);
			Assert.IsTrue(arr.Buffer == buf, "buffer");
			Assert.AreEqual(arr.Length, 64, "length");
		}
		public void ArrayBufferAndByteOffsetAndByteLengthConstructorWorks() {
			var b = new Uint8Array(new byte[] { 2, 3, 5, 7, 2, 0 }).Buffer;
			var view = new DataView(b, 1, 3);
			Assert.IsTrue((object)view is DataView, "Should be DataView");
			Assert.AreEqual(view.GetInt8(1), 5, "StartIndex should be correct");
			Assert.Throws(() => view.GetInt8(4), "Length should be correct");
		}
		private byte[] GetArray(ArrayBuffer b) {
			var result = new byte[b.ByteLength];
			var a = new Uint8Array(b);
			for (int i = 0; i < result.Length; i++)
				result[i] = a[i];
			return result;
		}
		public void ConstructorFromUint8ArrayWorks() {
			 var source = new Uint8Array(new byte[] { 3, 8, 4 });
			 var arr = new Uint8ClampedArray(source);
			 Assert.IsTrue(arr != source, "New object");
			 Assert.IsTrue((object)arr is Uint8ClampedArray, "is Uint8ClampedArray");
			 AssertContent(arr, new[] { 3, 8, 4 }, "content");
		}
예제 #5
0
파일: Buffer.cs 프로젝트: sbrown345/quakejs
 public static void BlockCopy(Uint8Array src, int srcOffset, Uint8Array dst, int dstOffset, int count)
 {
     for (var i = 0; i < count; i++)
     {
         dst[i + dstOffset] = src[i + srcOffset];
     }
 }
예제 #6
0
파일: Helper.cs 프로젝트: sbrown345/quakejs
 public static int fread(Uint8Array data, int size, int count, FILE file)
 {
     var reader = new BinaryReader(file.stream);
     Uint8Array buf = reader.ReadBytes(size);
     Buffer.BlockCopy(buf, 0, data, 0, size);
     return count;
 }
예제 #7
0
파일: wad.cs 프로젝트: sbrown345/quakejs
        public static Uint8Array W_GetLumpName(string name)
        {
            lumpinfo_t lump;

            lump = W_GetLumpinfo(name);
            Uint8Array buf = new Uint8Array(lump.size);
            for(int kk = 0; kk < lump.size; kk++)
                buf[kk] = wad_base[lump.filepos + kk];
            return buf;
        }
		private void AssertContent(Uint8Array actual, int[] expected, string message) {
			if (actual.Length != expected.Length) {
				Assert.Fail(message + ": Expected length " + expected.Length + ", actual: " + actual.Length);
				return;
			}
			for (int i = 0; i < expected.Length; i++) {
				if (actual[i] != expected[i]) {
					Assert.Fail(message + ": Position " + i + ": expected " + expected[i] + ", actual: " + actual[i]);
					return;
				}
			}
			Assert.IsTrue(true, message);
		}
		public void TypePropertiesAreCorrect() {
			Assert.AreEqual(typeof(Uint8Array).FullName, "Uint8Array", "FullName");

			var interfaces = typeof(Uint8Array).GetInterfaces();
			Assert.AreEqual(interfaces.Length, 3, "Interface count should be 3");
			Assert.IsTrue(interfaces.Contains(typeof(IEnumerable<byte>)), "Interfaces should contain IEnumerable<byte>");
			Assert.IsTrue(interfaces.Contains(typeof(ICollection<byte>)), "Interfaces should contain ICollection<byte>");
			Assert.IsTrue(interfaces.Contains(typeof(IList<byte>)), "Interfaces should contain IList<byte>");

			object arr = new Uint8Array(0);
			Assert.IsTrue(arr is Uint8Array, "Is Uint8Array");
			Assert.IsTrue(arr is IEnumerable<byte>, "Is IEnumerable<byte>");
			Assert.IsTrue(arr is ICollection<byte>, "Is ICollection<byte>");
			Assert.IsTrue(arr is IList<byte>, "Is IList<byte>");
		}
예제 #10
0
파일: wad.cs 프로젝트: sbrown345/quakejs
        /*
        ====================
        W_LoadWadFile
        ====================
        */
        public static void W_LoadWadFile(string filename)
        {
            lumpinfo_t  lump_p;
            wadinfo_t   header = new wadinfo_t();
            uint        i;
            int         infotableofs;

            int ofs;
            int kk;

            wad_base = common.COM_LoadHunkFile(filename);
            if (wad_base == null)
                sys_linux.Sys_Error("W_LoadWadFile: couldn't load " + filename);

            ofs = 0;
            header.identification = common.parseString(wad_base, ref ofs, 4);
            header.numlumps = common.parseInt(wad_base, ref ofs);
            header.infotableofs = common.parseInt(wad_base, ref ofs);

            if (header.identification != "WAD2")
                sys_linux.Sys_Error("Wad file " + filename + "doesn't have WAD2 id");

            wad_numlumps = header.numlumps;
            infotableofs = header.infotableofs;

            wad_lumps = new lumpinfo_t[wad_numlumps];
            ofs = infotableofs;
            for (kk = 0; kk < wad_numlumps; kk++)
            {
                wad_lumps[kk] = new lumpinfo_t();
                wad_lumps[kk].filepos = common.parseInt(wad_base, ref ofs);
                wad_lumps[kk].disksize = common.parseInt(wad_base, ref ofs);
                wad_lumps[kk].size = common.parseInt(wad_base, ref ofs);
                wad_lumps[kk].type = common.parseChar(wad_base, ref ofs);
                wad_lumps[kk].compression = common.parseChar(wad_base, ref ofs);
                wad_lumps[kk].pad1 = common.parseChar(wad_base, ref ofs);
                wad_lumps[kk].pad2 = common.parseChar(wad_base, ref ofs);
                wad_lumps[kk].name = common.parseString(wad_base, ref ofs, 16);
            }

            for (i = 0; i < wad_numlumps; i++)
            {
                lump_p = wad_lumps[i];
                lump_p.name = W_CleanupName(lump_p.name);
            }
        }
예제 #11
0
파일: r_main.cs 프로젝트: sbrown345/quakejs
        /*
        ================
        R_RenderView

        r_refdef must be set before the first call
        ================
        */
        static void R_RenderView_()
        {
            Uint8Array warpbuffer = new Uint8Array(draw.WARP_WIDTH * draw.WARP_HEIGHT);

            r_warpbuffer = warpbuffer;

            if (r_timegraph.value != 0 || r_speeds.value != 0 || r_dspeeds.value != 0)
                r_time1 = sys_linux.Sys_FloatTime();

            R_SetupFrame ();

            R_MarkLeaves ();	// done here so we know if we're in water

            if (client.cl_entities[0].model == null || client.cl.worldmodel == null)
                sys_linux.Sys_Error ("R_RenderView: NULL worldmodel");

            if (r_dspeeds.value == 0)
            {
                sound.S_ExtraUpdate();	// don't let sound get messed up if going slow
            }

            R_EdgeDrawing (); //draw map

            if (r_dspeeds.value == 0)
            {
                sound.S_ExtraUpdate();	// don't let sound get messed up if going slow
            }

            R_DrawEntitiesOnList (); //draw zombies etc -  models

            R_DrawViewModel (); //draw gun

            R_DrawParticles ();

            if (r_dowarp)
                draw.D_WarpScreen ();

            view.V_SetContentsColor(r_viewleaf.contents);

            if (r_timegraph.value != 0)
                R_TimeGraph();
        }
예제 #12
0
 public static float ToSingle(Uint8Array value, int startIndex)
 {
     throw new ImplementedInJavaScript();
 }
예제 #13
0
 public MemoryStream(Uint8Array data)
     : base(data.Buffer)
 {
 }
예제 #14
0
        /*
        ================
        R_AliasDrawModel
        ================
        */
        static void R_AliasDrawModel(alight_t plighting)
        {
            r_amodels_drawn++;

            // cache align
            pfinalverts = (draw.finalvert_t[])finalverts;
            pauxverts = auxverts;

            paliashdr = (model.aliashdr_t)model.Mod_Extradata (currententity.model);
            pmdl = (model.mdl_t)paliashdr.model;

            R_AliasSetupSkin ();
            R_AliasSetUpTransform (currententity.trivial_accept);
            R_AliasSetupLighting (plighting);
            R_AliasSetupFrame ();

            if (currententity.colormap == null)
                sys_linux.Sys_Error ("R_AliasDrawModel: !currententity.colormap");

            r_affinetridesc.drawtype = (currententity.trivial_accept == 3) &&
                    r_recursiveaffinetriangles;

            if (r_affinetridesc.drawtype)
            {
                draw.D_PolysetUpdateTables ();		// FIXME: precalc...
            }
            else
            {
            }

            acolormap = currententity.colormap;

            if (currententity != client.cl.viewent)
                ziscale = (double)0x8000 * (double)0x10000;
            else
                ziscale = (double)0x8000 * (double)0x10000 * 3.0;

            if (currententity.trivial_accept != 0)
                R_AliasPrepareUnclippedPoints ();
            else
                R_AliasPreparePoints ();
        }
예제 #15
0
 public void GetByteTimeDomainData(Uint8Array array) { }
예제 #16
0
 /// <summary>
 /// Creates a new Uint8Array out of the specified Uint8Array.
 /// </summary>
 /// <param name="typedArray">Uint8Array to use as initial contents to the new array.</param>
 public Uint8Array(Uint8Array typedArray)
 {
 }
예제 #17
0
            public override async Task <int> ReadAsync(byte [] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                if (buffer == null)
                {
                    throw new ArgumentNullException(nameof(buffer));
                }
                if (offset < 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(offset));
                }
                if (count < 0 || buffer.Length - offset < count)
                {
                    throw new ArgumentOutOfRangeException(nameof(count));
                }

                if (_reader == null)
                {
                    // If we've read everything, then _reader and _status will be null
                    if (_status == null)
                    {
                        return(0);
                    }

                    using (var body = _status.Body) {
                        _reader = (JSObject)body.Invoke("getReader");
                    }
                }

                if (_bufferedBytes != null && _position < _bufferedBytes.Length)
                {
                    return(ReadBuffered());
                }

                var t = (Task <object>)_reader.Invoke("read");

                using (var read = (JSObject)await t) {
                    if ((bool)read.GetObjectProperty("done"))
                    {
                        _reader.Dispose();
                        _reader = null;

                        _status.Dispose();
                        _status = null;
                        return(0);
                    }

                    _position = 0;
                    // value for fetch streams is a Uint8Array
                    using (Uint8Array binValue = (Uint8Array)read.GetObjectProperty("value"))
                        _bufferedBytes = binValue.ToArray();
                }

                return(ReadBuffered());

                int ReadBuffered()
                {
                    int n = _bufferedBytes.Length - _position;

                    if (n > count)
                    {
                        n = count;
                    }
                    if (n <= 0)
                    {
                        return(0);
                    }

                    Buffer.BlockCopy(_bufferedBytes, _position, buffer, offset, n);
                    _position += n;

                    return(n);
                }
            }
예제 #18
0
파일: wad.cs 프로젝트: sbrown345/quakejs
        Uint8Array W_GetLumpNum(int num, ref int offset)
        {
            lumpinfo_t lump;

            if (num < 0 || num > wad_numlumps)
                sys_linux.Sys_Error("W_GetLumpNum: bad number: " + num);

            lump = wad_lumps[num];

            var buf = new Uint8Array(lump.size);
            for(int kk = 0; kk < lump.size; kk++)
                buf[kk] = wad_base[lump.filepos + kk];
            return buf;
        }
예제 #19
0
 public static void MarshalByteBuffer(Uint8Array buffer)
 {
     byteBuffer = buffer.ToArray();
 }
예제 #20
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201503/20150323

            // X:\jsc.svn\examples\javascript\Test\TestWebCrypto\TestWebCrypto\Application.cs
            // X:\jsc.svn\examples\javascript\async\Test\TestWebCryptoAsync\TestWebCryptoAsync\Application.cs
            // X:\jsc.svn\examples\javascript\Test\TestWebCryptoEncryption\TestWebCryptoEncryption\Application.cs
            // X:\jsc.svn\examples\javascript\Test\TestWebCryptoKeyExport\TestWebCryptoKeyExport\Application.cs



            new IHTMLButton {
                "generateKey in UI"
            }.AttachToDocument().onclick +=
                async delegate
            {
                new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument();
                var sw             = Stopwatch.StartNew();
                var publicExponent = new Uint8Array(new byte[] { 0x01, 0x00, 0x01 });

                new IHTMLPre {
                    "before generateKey " + new { sw.ElapsedMilliseconds }
                }.AttachToDocument();

                // http://blog.engelke.com/2014/08/23/public-key-cryptography-in-the-browser/


                // The JWA alg “RSA-OAEP” requires this hash function to be SHA-1 (the default
                //> from RFC 3447).

                var algorithm = new
                {
                    name = "RSA-OAEP",
                    //hash = new { name = "SHA-256" },
                    hash = new { name = "SHA-1" },

                    modulusLength = 2048,
                    publicExponent,
                };

                var pgenerateKeyAsync = Native.crypto.subtle.generateKeyAsync(
                    algorithm,
                    extractable: false,
                    keyUsages: new[] { "encrypt", "decrypt" }
                    );


                // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise
                new IHTMLPre {
                    "after generateKey " + new { pgenerateKeyAsync, sw.ElapsedMilliseconds }
                }.AttachToDocument();

                var key = await pgenerateKeyAsync;

                // continue generateKey {{ privateKey = [object CryptoKey], publicKey = [object CryptoKey], ElapsedMilliseconds = 5021 }}
                new IHTMLPre {
                    "continue generateKey "
                    + new {
                        key.privateKey,
                        key.publicKey,
                        key.publicKey.extractable,
                        sw.ElapsedMilliseconds
                    }
                }.AttachToDocument();

                // continue generateKey {{ privateKey = [object CryptoKey], publicKey = [object CryptoKey], extractable = true, ElapsedMilliseconds = 671 }}

                var JSONWebKey = await Native.crypto.subtle.exportJSONWebKeyAsync(key.publicKey);

                // continue exportKey {{ JSONWebKey = [object Object], ElapsedMilliseconds = 835 }}
                // continue exportKey {{ p = null, q = null, qi = null, ElapsedMilliseconds = 3055 }}


                // X:\jsc.svn\examples\javascript\appengine\test\TestAppEngineWebCryptoKeyImport\TestAppEngineWebCryptoKeyImport\Application.cs

                new IHTMLPre {
                    "continue exportKey " +
                    new {
                        JSONWebKey.alg,

                        // exponent
                        JSONWebKey.e,
                        // modolo
                        JSONWebKey.n,


                        //JSONWebKey.ext,
                        //JSONWebKey.kty,

                        sw.ElapsedMilliseconds
                    }
                }.AttachToDocument();

                var Exponent = Convert.FromBase64String(JSONWebKey.e);

                new IHTMLPre {
                    "Exponent " + new { Exponent.Length }
                }.AttachToDocument();

                var Modulus = Convert.FromBase64String(JSONWebKey.n);

                new IHTMLPre {
                    "Modulus " + new { Modulus.Length }
                }.AttachToDocument();

                //Exponent { { Length = 3 } }
                //Modulus { { Length = 256 } }

                // continue exportKey {{ alg = RSA-OAEP-256, e = AQAB, ext = true, kty = RSA, n = 8tGdxZBpFAIQN3Pzc-7NC_vDF26dleCMGDY7egB8Q136YlqfB7tRpYMU9k88MXGDIleUyEPoDT03yopH8B3Cuio61Wzk-6uXTl6WGjK-FvpxiJWMxa6rXdng7cCyzsG5rah3wI8B3ko4NhHO7NrdKoWG4-y1qxWi2JdAv1g8DLKFUqTuu4siLXPEXvHdWcV4booyeVzCsIf-xq2Zrh7hLbhN83_6bCG0KdkQCIYUgqbI2kHOI4acqTKcXE5_W2cqbw0GStQOyoqClNb0k7VIyufiYpKCRv5176NOmTjFeVBVRhnHkRn96n4Fc4EwLL-KBAj9sfJ1dVrQ2pS-IHIe3w, ElapsedMilliseconds = 6027 }}

                // view-source:42599 0:36694ms decryptAsync { err = OperationError:  }
                new IHTMLButton {
                    "ask server to encrypt for client "
                }.AttachToDocument().onclick +=
                    async delegate
                {
                    new IHTMLPre {
                        "before Encrypt"
                    }.AttachToDocument();

                    var xbytes = await this.Encrypt(Exponent, Modulus);

                    // are the bytes correct?

                    var xxbytes = new Uint8Array(xbytes);


                    new IHTMLPre {
                        "before decryptAsync. (doesnt work anymore? 20150323) " + new { xxbytes, xbytes.Length }
                    }.AttachToDocument();

                    // https://code.google.com/p/chromium/issues/detail?id=390475
                    // RSA-OAEP public keys do not support decrypt/unwrapKey.
                    // ?

                    // RSA/ECB/OAEPWithSHA-1AndMGF1Padding
                    // RSA using Optimal Asymmetric Encryption Padding (OAEP), as defined in RFC 3447 [RFC3447]
                    // http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p	RSA/ECB/OAEPWithSHA-1AndMGF1Padding
                    // http://openid.net/specs/draft-jones-json-web-encryption-02.html

                    // why aint it working??
                    // view-source:42612 0:33308ms decryptAsync { err = OperationError:  }
                    // either wait, test imprt next?

                    // Unhandled promise rejection
                    var zbytes = await Native.crypto.subtle.decryptAsync(
                        algorithm,
                        key.privateKey,

                        //key.publicKey,

                        xxbytes
                        );

                    //  OperationError
                    // ?????

                    //19606ms decryptAsync { err = OperationError:  }
                    //2015 - 03 - 23 10:59:39.115 192.168.1.196 /:1 Uncaught(in promise) DOMException

                    new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument();

                    foreach (var item in zbytes)
                    {
                        new IHTMLCode {
                            " 0x" + item.ToString("x2")
                        }.AttachToDocument();
                    }

                    new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument();


                    var zstring = Encoding.UTF8.GetString(zbytes);

                    // which is it?
                    new IHTMLPre {
                        new { zstring }
                    }.AttachToDocument();
                }
                ;
            };
        }
예제 #21
0
 public static void MarshalArrayBuffer(ArrayBuffer buffer)
 {
     using (var bytes = new Uint8Array(buffer))
         byteBuffer = bytes.ToArray();
 }
예제 #22
0
 public RAM(ArrayBuffer heap, int ramoffset)
 {
     this.mem      = heap;
     this.int32mem = new Int32Array(this.mem, ramoffset);
     this.uint8mem = new Uint8Array(this.mem, ramoffset);
 }
예제 #23
0
        private static Uint8Array Uint8ArrayFrom()
        {
            var array = new byte[50];

            return(Uint8Array.From(array));
        }
예제 #24
0
 private static void MarshalByteBuffer(Uint8Array buffer)
 {
     _byteBuffer = buffer.ToArray();
 }
예제 #25
0
        private async Task doFetch(TaskCompletionSource <HttpResponseMessage> tcs, HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try {
                var requestObject = new JSObject();
                requestObject.SetObjectProperty("method", request.Method.Method);

                // See https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials for
                // standard values and meanings
                requestObject.SetObjectProperty("credentials", DefaultCredentials);

                // See https://developer.mozilla.org/en-US/docs/Web/API/Request/cache for
                // standard values and meanings
                requestObject.SetObjectProperty("cache", Cache);

                // See https://developer.mozilla.org/en-US/docs/Web/API/Request/mode for
                // standard values and meanings
                requestObject.SetObjectProperty("mode", Mode);

                // We need to check for body content
                if (request.Content != null)
                {
                    if (request.Content is StringContent)
                    {
                        requestObject.SetObjectProperty("body", await request.Content.ReadAsStringAsync());
                    }
                    else
                    {
                        // 2.1.801 seems to have a problem with the line
                        // using (var uint8Buffer = Uint8Array.From(await request.Content.ReadAsByteArrayAsync ()))
                        // so we split it up into two lines.
                        var byteAsync = await request.Content.ReadAsByteArrayAsync();

                        using (var uint8Buffer = Uint8Array.From(byteAsync))
                        {
                            requestObject.SetObjectProperty("body", uint8Buffer);
                        }
                    }
                }

                // Process headers
                // Cors has it's own restrictions on headers.
                // https://developer.mozilla.org/en-US/docs/Web/API/Headers
                using (var jsHeaders = new HostObject("Headers")) {
                    if (request.Headers != null)
                    {
                        foreach (var header in request.Headers)
                        {
                            foreach (var value in header.Value)
                            {
                                jsHeaders.Invoke("append", header.Key, value);
                            }
                        }
                    }
                    if (request.Content?.Headers != null)
                    {
                        foreach (var header in request.Content.Headers)
                        {
                            foreach (var value in header.Value)
                            {
                                jsHeaders.Invoke("append", header.Key, value);
                            }
                        }
                    }
                    requestObject.SetObjectProperty("headers", jsHeaders);
                }

                JSObject           abortController    = null;
                JSObject           signal             = null;
                WasmHttpReadStream wasmHttpReadStream = null;

                CancellationTokenRegistration abortRegistration = default(CancellationTokenRegistration);
                if (cancellationToken.CanBeCanceled)
                {
                    abortController = new HostObject("AbortController");

                    signal = (JSObject)abortController.GetObjectProperty("signal");
                    requestObject.SetObjectProperty("signal", signal);
                    abortRegistration = cancellationToken.Register((Action)(() => {
                        if (abortController.JSHandle != -1)
                        {
                            abortController.Invoke((string)"abort");
                            abortController?.Dispose();
                        }
                        wasmHttpReadStream?.Dispose();
                    }));
                }

                var args = new Core.Array();
                args.Push(request.RequestUri.ToString());
                args.Push(requestObject);

                requestObject.Dispose();

                var response = fetch.Invoke("apply", window, args) as Task <object>;
                args.Dispose();
                if (response == null)
                {
                    throw new Exception("Internal error marshalling the response Promise from `fetch`.");
                }

                var t = await response;

                var status = new WasmFetchResponse((JSObject)t, abortController, abortRegistration);

                //Console.WriteLine($"bodyUsed: {status.IsBodyUsed}");
                //Console.WriteLine($"ok: {status.IsOK}");
                //Console.WriteLine($"redirected: {status.IsRedirected}");
                //Console.WriteLine($"status: {status.Status}");
                //Console.WriteLine($"statusText: {status.StatusText}");
                //Console.WriteLine($"type: {status.ResponseType}");
                //Console.WriteLine($"url: {status.Url}");

                HttpResponseMessage httpresponse = new HttpResponseMessage((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), status.Status.ToString()));

                httpresponse.Content = StreamingSupported && StreamingEnabled
                                    ? new StreamContent(wasmHttpReadStream = new WasmHttpReadStream(status))
                                    : (HttpContent) new WasmHttpContent(status);

                // Fill the response headers
                // CORS will only allow access to certain headers.
                // If a request is made for a resource on another origin which returns the CORs headers, then the type is cors.
                // cors and basic responses are almost identical except that a cors response restricts the headers you can view to
                // `Cache-Control`, `Content-Language`, `Content-Type`, `Expires`, `Last-Modified`, and `Pragma`.
                // View more information https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types
                //
                // Note: Some of the headers may not even be valid header types in .NET thus we use TryAddWithoutValidation
                using (var respHeaders = (JSObject)status.Headers) {
                    if (respHeaders != null)
                    {
                        using (var entriesIterator = (JSObject)respHeaders.Invoke("entries")) {
                            JSObject nextResult = null;
                            try {
                                nextResult = (JSObject)entriesIterator.Invoke("next");
                                while (!(bool)nextResult.GetObjectProperty("done"))
                                {
                                    using (var resultValue = (WebAssembly.Core.Array)nextResult.GetObjectProperty("value")) {
                                        var name  = (string)resultValue [0];
                                        var value = (string)resultValue [1];
                                        if (!httpresponse.Headers.TryAddWithoutValidation(name, value))
                                        {
                                            if (httpresponse.Content != null)
                                            {
                                                if (!httpresponse.Content.Headers.TryAddWithoutValidation(name, value))
                                                {
                                                    Console.WriteLine($"Warning: Can not add response header for name: {name} value: {value}");
                                                }
                                            }
                                        }
                                    }
                                    nextResult?.Dispose();
                                    nextResult = (JSObject)entriesIterator.Invoke("next");
                                }
                            } finally {
                                nextResult?.Dispose();
                            }
                        }
                    }
                }

                tcs.SetResult(httpresponse);

                signal?.Dispose();
            } catch (Exception exception) {
                tcs.SetException(exception);
            }
        }
예제 #26
0
        /*
        ==============
        CL_SendMove
        ==============
        */
        static void CL_SendMove(usercmd_t cmd)
        {
            int		i;
            int		bits;
            common.sizebuf_t	buf = new common.sizebuf_t();
            Uint8Array data = new Uint8Array(128);

            buf.maxsize = 128;
            buf.cursize = 0;
            buf.data = data;

            cl.cmd = cmd;

            //
            // send the movement message
            //
            common.MSG_WriteByte (buf, net.clc_move);

            common.MSG_WriteFloat(buf, cl.mtime[0]);	// so server can get ping times

            for (i=0 ; i<3 ; i++)
                common.MSG_WriteAngle(buf, cl.viewangles[i]);

            common.MSG_WriteShort(buf, (int)cmd.forwardmove);
            common.MSG_WriteShort(buf, (int)cmd.sidemove);
            common.MSG_WriteShort(buf, (int)cmd.upmove);

            //
            // send button bits
            //
            bits = 0;

            if (( in_attack.state & 3 ) != 0)
                bits |= 1;
            in_attack.state &= ~2;

            if ((in_jump.state & 3) != 0)
                bits |= 2;
            in_jump.state &= ~2;

            common.MSG_WriteByte(buf, bits);

            common.MSG_WriteByte(buf, in_impulse);
            in_impulse = 0;

            //
            // deliver the message
            //
            if (cls.demoplayback)
                return;

            //
            // allways dump the first two message, because it may contain leftover inputs
            // from the last level
            //
            if (++cl.movemessages <= 2)
                return;

            if (net.NET_SendUnreliableMessage (cls.netcon, buf) == -1)
            {
                console.Con_Printf ("CL_SendMove: lost server connection\n");
                CL_Disconnect ();
            }
        }
예제 #27
0
        public static void CoreTypes()
        {
            var arr = new Uint8ClampedArray(50);

            Assert.Equal(50, arr.Length);
            Assert.Equal(TypedArrayTypeCode.Uint8ClampedArray, arr.GetTypedArrayType());

            var arr1 = new Uint8Array(50);

            Assert.Equal(50, arr1.Length);
            Assert.Equal(TypedArrayTypeCode.Uint8Array, arr1.GetTypedArrayType());

            var arr2 = new Uint16Array(50);

            Assert.Equal(50, arr2.Length);
            Assert.Equal(TypedArrayTypeCode.Uint16Array, arr2.GetTypedArrayType());

            var arr3 = new Uint32Array(50);

            Assert.Equal(50, arr3.Length);
            Assert.Equal(TypedArrayTypeCode.Uint32Array, arr3.GetTypedArrayType());

            var arr4 = new Int8Array(50);

            Assert.Equal(50, arr4.Length);
            Assert.Equal(TypedArrayTypeCode.Int8Array, arr4.GetTypedArrayType());

            var arr5 = new Int16Array(50);

            Assert.Equal(50, arr5.Length);
            Assert.Equal(TypedArrayTypeCode.Int16Array, arr5.GetTypedArrayType());

            var arr6 = new Int32Array(50);

            Assert.Equal(50, arr6.Length);
            Assert.Equal(TypedArrayTypeCode.Int32Array, arr6.GetTypedArrayType());

            var arr7 = new Float32Array(50);

            Assert.Equal(50, arr7.Length);
            Assert.Equal(TypedArrayTypeCode.Float32Array, arr7.GetTypedArrayType());

            var arr8 = new Float64Array(50);

            Assert.Equal(50, arr8.Length);
            Assert.Equal(TypedArrayTypeCode.Float64Array, arr8.GetTypedArrayType());

            var sharedArr40 = new SharedArrayBuffer(40);
            var sharedArr50 = new SharedArrayBuffer(50);

            var arr9 = new Uint8ClampedArray(sharedArr50);

            Assert.Equal(50, arr9.Length);

            var arr10 = new Uint8Array(sharedArr50);

            Assert.Equal(50, arr10.Length);

            var arr11 = new Uint16Array(sharedArr50);

            Assert.Equal(25, arr11.Length);

            var arr12 = new Uint32Array(sharedArr40);

            Assert.Equal(10, arr12.Length);

            var arr13 = new Int8Array(sharedArr50);

            Assert.Equal(50, arr13.Length);

            var arr14 = new Int16Array(sharedArr40);

            Assert.Equal(20, arr14.Length);

            var arr15 = new Int32Array(sharedArr40);

            Assert.Equal(10, arr15.Length);

            var arr16 = new Float32Array(sharedArr40);

            Assert.Equal(10, arr16.Length);

            var arr17 = new Float64Array(sharedArr40);

            Assert.Equal(5, arr17.Length);
        }
예제 #28
0
 public void getByteTimeDomainData(Uint8Array array)
 {
 }
예제 #29
0
        public static void TestUseCase()
        {
            var isToStringToTypeNameLogic = !BrowserHelper.IsChrome();

            var v1 = new Float32Array(10);

            Assert.True(v1 != null, "Float32Array created");

            v1[1] = 11;
            v1[5] = 5;
            v1[9] = 99;
            Assert.AreEqual(11, v1[1], "Float32Array indexier works 1");
            Assert.AreEqual(99, v1[9], "Float32Array indexier works 9");

            // Check just a select number of references inside the Prototype inheritance.
            Assert.True(v1.Buffer != null, "Float32Array Buffer");
            Assert.AreEqual(40, v1.ByteLength, "Float32Array ByteLength");
            Assert.AreEqual(0, v1.ByteOffset, "Float32Array ByteOffset");
            Assert.AreEqual(10, v1.Length, "Float32Array Length");

            /*
             * Commented out. Reason: Only Firefox implements them.
             * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array
             * var mA = v1.Join();
             * v1.Reverse();
             * var mB = v1.Slice();
             * var mC = v1.Sort();
             */

            var expectedToStringFloat32Array1 = isToStringToTypeNameLogic ? "[object Float32Array]" : "0,11,0,0,0,5,0,0,0,99";

            Assert.AreEqual(expectedToStringFloat32Array1, v1.ToLocaleString(), "Float32Array ToLocaleString");
            Assert.AreEqual(expectedToStringFloat32Array1, v1.ToString(), "Float32Array ToString");

            // Some browsers do not support SubArray() with no parameters.
            // At least 'begin' must be provided.
            var subArray11 = v1.SubArray(1);
            var expectedToStringFloat32Array2 = isToStringToTypeNameLogic ? "[object Float32Array]" : "11,0,0,0,5,0,0,0,99";

            Assert.True(subArray11 != null, "Float32Array SubArray1");
            Assert.AreEqual(9, subArray11.Length, "Float32Array SubArray1 Length");
            Assert.AreEqual(expectedToStringFloat32Array2, subArray11.ToString(), "Float32Array SubArray1 ToString");
            Assert.AreEqual(4, subArray11.ByteOffset, "Float32Array SubArray1 ByteOffset");

            var subArray12 = subArray11.SubArray(2, 6);
            var expectedToStringFloat32Array3 = isToStringToTypeNameLogic ? "[object Float32Array]" : "0,0,5,0";

            Assert.True(subArray12 != null, "Float32Array SubArray2");
            Assert.AreEqual(4, subArray12.Length, "Float32Array SubArray2 Length");
            Assert.AreEqual(expectedToStringFloat32Array3, subArray12.ToString(), "Float32Array SubArray2 ToString");
            Assert.AreEqual(12, subArray12.ByteOffset, "Float32Array SubArray2 ByteOffset");

            var v2 = new Float64Array(10);

            Assert.True(v2 != null, "Float64Array created");

            v2[1] = 11;
            v2[5] = 5;
            v2[9] = 99;
            Assert.AreEqual(11, v2[1], "Float64Array indexier works 1");
            Assert.AreEqual(99, v2[9], "Float64Array indexier works 9");

            Assert.True(v2.Buffer != null, "Float64Array Buffer");
            Assert.AreEqual(80, v2.ByteLength, "Float64Array ByteLength");
            Assert.AreEqual(0, v2.ByteOffset, "Float64Array ByteOffset");
            Assert.AreEqual(10, v2.Length, "Float64Array Length");

            var expectedToStringFloat64Array1 = isToStringToTypeNameLogic ? "[object Float64Array]" : "0,11,0,0,0,5,0,0,0,99";

            Assert.AreEqual(expectedToStringFloat64Array1, v2.ToLocaleString(), "Float64Array ToLocaleString");
            Assert.AreEqual(expectedToStringFloat64Array1, v2.ToString(), "Float64Array ToString");

            var subArray21 = v2.SubArray(1);
            var expectedToStringFloat64Array2 = isToStringToTypeNameLogic ? "[object Float64Array]" : "11,0,0,0,5,0,0,0,99";

            Assert.True(subArray21 != null, "Float64Array SubArray1");
            Assert.AreEqual(9, subArray21.Length, "Float64Array SubArray1 Length");
            Assert.AreEqual(expectedToStringFloat64Array2, subArray21.ToString(), "Float64Array SubArray1 ToString");
            Assert.AreEqual(8, subArray21.ByteOffset, "Float64Array SubArray1 ByteOffset");

            var subArray22 = subArray21.SubArray(2, 6);
            var expectedToStringFloat64Array3 = isToStringToTypeNameLogic ? "[object Float64Array]" : "0,0,5,0";

            Assert.True(subArray22 != null, "Float64Array SubArray2");
            Assert.AreEqual(4, subArray22.Length, "Float64Array SubArray2 Length");
            Assert.AreEqual(expectedToStringFloat64Array3, subArray22.ToString(), "Float64Array SubArray2 ToString");
            Assert.AreEqual(24, subArray22.ByteOffset, "Float64Array SubArray2 ByteOffset");

            var v3 = new Int16Array(10);

            Assert.True(v3 != null, "Int16Array created");

            v3[1] = 11;
            v3[5] = 5;
            v3[9] = 99;
            Assert.AreEqual(11, v3[1], "Int16Array indexier works 1");
            Assert.AreEqual(99, v3[9], "Int16Array indexier works 9");

            Assert.True(v3.Buffer != null, "Int16Array Buffer");
            Assert.AreEqual(20, v3.ByteLength, "Int16Array ByteLength");
            Assert.AreEqual(0, v3.ByteOffset, "Int16Array ByteOffset");
            Assert.AreEqual(10, v3.Length, "Int16Array Length");

            var expectedToStringInt16Array1 = isToStringToTypeNameLogic ? "[object Int16Array]" : "0,11,0,0,0,5,0,0,0,99";

            Assert.AreEqual(expectedToStringInt16Array1, v3.ToLocaleString(), "Int16Array ToLocaleString");
            Assert.AreEqual(expectedToStringInt16Array1, v3.ToString(), "Int16Array ToString");

            var subArray31 = v3.SubArray(1);
            var expectedToStringInt16Array2 = isToStringToTypeNameLogic ? "[object Int16Array]" : "11,0,0,0,5,0,0,0,99";

            Assert.True(subArray31 != null, "Int16Array SubArray1");
            Assert.AreEqual(9, subArray31.Length, "Int16Array SubArray1 Length");
            Assert.AreEqual(expectedToStringInt16Array2, subArray31.ToString(), "Int16Array SubArray1 ToString");
            Assert.AreEqual(2, subArray31.ByteOffset, "Int16Array SubArray1 ByteOffset");

            var subArray32 = subArray31.SubArray(2, 6);
            var expectedToStringInt16Array3 = isToStringToTypeNameLogic ? "[object Int16Array]" : "0,0,5,0";

            Assert.True(subArray32 != null, "Int16Array SubArray2");
            Assert.AreEqual(4, subArray32.Length, "Int16Array SubArray2 Length");
            Assert.AreEqual(expectedToStringInt16Array3, subArray32.ToString(), "Int16Array SubArray2 ToString");
            Assert.AreEqual(6, subArray32.ByteOffset, "Int16Array SubArray2 ByteOffset");

            var v4 = new Int32Array(10);

            Assert.True(v4 != null, "Int32Array created");

            v4[1] = 11;
            v4[5] = 5;
            v4[9] = 99;
            Assert.AreEqual(11, v4[1], "Int32Array indexier works 1");
            Assert.AreEqual(99, v4[9], "Int32Array indexier works 9");

            Assert.True(v4.Buffer != null, "Int32Array Buffer");
            Assert.AreEqual(40, v4.ByteLength, "Int32Array ByteLength");
            Assert.AreEqual(0, v4.ByteOffset, "Int32Array ByteOffset");
            Assert.AreEqual(10, v4.Length, "Int32Array Length");

            var expectedToStringInt32Array1 = isToStringToTypeNameLogic ? "[object Int32Array]" : "0,11,0,0,0,5,0,0,0,99";

            Assert.AreEqual(expectedToStringInt32Array1, v4.ToLocaleString(), "Int32Array ToLocaleString");
            Assert.AreEqual(expectedToStringInt32Array1, v4.ToString(), "Int32Array ToString");

            var subArray41 = v4.SubArray(1);
            var expectedToStringInt32Array2 = isToStringToTypeNameLogic ? "[object Int32Array]" : "11,0,0,0,5,0,0,0,99";

            Assert.True(subArray41 != null, "Int32Array SubArray1");
            Assert.AreEqual(9, subArray41.Length, "Int32Array SubArray1 Length");
            Assert.AreEqual(expectedToStringInt32Array2, subArray41.ToString(), "Int32Array SubArray1 ToString");
            Assert.AreEqual(4, subArray41.ByteOffset, "Int32Array SubArray1 ByteOffset");

            var subArray42 = subArray41.SubArray(2, 6);
            var expectedToStringInt32Array3 = isToStringToTypeNameLogic ? "[object Int32Array]" : "0,0,5,0";

            Assert.True(subArray42 != null, "Int32Array SubArray2");
            Assert.AreEqual(4, subArray42.Length, "Int32Array SubArray2 Length");
            Assert.AreEqual(expectedToStringInt32Array3, subArray42.ToString(), "Int32Array SubArray2 ToString");
            Assert.AreEqual(12, subArray42.ByteOffset, "Int32Array SubArray2 ByteOffset");

            var v5 = new Int8Array(10);

            Assert.True(v5 != null, "Int8Array created");

            v5[1] = 11;
            v5[5] = 5;
            v5[9] = 99;
            Assert.AreEqual(11, v5[1], "Int8Array indexier works 1");
            Assert.AreEqual(99, v5[9], "Int8Array indexier works 9");

            Assert.True(v5.Buffer != null, "Int8Array Buffer");
            Assert.AreEqual(10, v5.ByteLength, "Int8Array ByteLength");
            Assert.AreEqual(0, v5.ByteOffset, "Int8Array ByteOffset");
            Assert.AreEqual(10, v5.Length, "Int8Array Length");

            var expectedToStringInt8Array1 = isToStringToTypeNameLogic ? "[object Int8Array]" : "0,11,0,0,0,5,0,0,0,99";

            Assert.AreEqual(expectedToStringInt8Array1, v5.ToLocaleString(), "Int8Array ToLocaleString");
            Assert.AreEqual(expectedToStringInt8Array1, v5.ToString(), "Int8Array ToString");

            var subArray51 = v5.SubArray(1);
            var expectedToStringInt8Array2 = isToStringToTypeNameLogic ? "[object Int8Array]" : "11,0,0,0,5,0,0,0,99";

            Assert.True(subArray51 != null, "Int8Array SubArray1");
            Assert.AreEqual(9, subArray51.Length, "Int8Array SubArray1 Length");
            Assert.AreEqual(expectedToStringInt8Array2, subArray51.ToString(), "Int8Array SubArray1 ToString");
            Assert.AreEqual(1, subArray51.ByteOffset, "Int8Array SubArray1 ByteOffset");

            var subArray52 = subArray51.SubArray(2, 6);
            var expectedToStringInt8Array3 = isToStringToTypeNameLogic ? "[object Int8Array]" : "0,0,5,0";

            Assert.True(subArray52 != null, "Int8Array SubArray2");
            Assert.AreEqual(4, subArray52.Length, "Int8Array SubArray2 Length");
            Assert.AreEqual(expectedToStringInt8Array3, subArray52.ToString(), "Int8Array SubArray2 ToString");
            Assert.AreEqual(3, subArray52.ByteOffset, "Int8Array SubArray2 ByteOffset");

            var v6 = new Uint16Array(10);

            Assert.True(v6 != null, "Uint16Array created");

            v6[1] = 11;
            v6[5] = 5;
            v6[9] = 99;
            Assert.AreEqual(11, v6[1], "Uint16Array indexier works 1");
            Assert.AreEqual(99, v6[9], "Uint16Array indexier works 9");

            Assert.True(v6.Buffer != null, "Uint16Array Buffer");
            Assert.AreEqual(20, v6.ByteLength, "Uint16Array ByteLength");
            Assert.AreEqual(0, v6.ByteOffset, "Uint16Array ByteOffset");
            Assert.AreEqual(10, v6.Length, "Uint16Array Length");

            var expectedToStringUint16Array1 = isToStringToTypeNameLogic ? "[object Uint16Array]" : "0,11,0,0,0,5,0,0,0,99";

            Assert.AreEqual(expectedToStringUint16Array1, v6.ToLocaleString(), "Uint16Array ToLocaleString");
            Assert.AreEqual(expectedToStringUint16Array1, v6.ToString(), "Uint16Array ToString");

            var subArray61 = v6.SubArray(1);
            var expectedToStringUint16Array2 = isToStringToTypeNameLogic ? "[object Uint16Array]" : "11,0,0,0,5,0,0,0,99";

            Assert.True(subArray61 != null, "Uint16Array SubArray1");
            Assert.AreEqual(9, subArray61.Length, "Uint16Array SubArray1 Length");
            Assert.AreEqual(expectedToStringUint16Array2, subArray61.ToString(), "Uint16Array SubArray1 ToString");
            Assert.AreEqual(2, subArray61.ByteOffset, "Uint16Array SubArray1 ByteOffset");

            var subArray62 = subArray61.SubArray(2, 6);
            var expectedToStringUint16Array3 = isToStringToTypeNameLogic ? "[object Uint16Array]" : "0,0,5,0";

            Assert.True(subArray62 != null, "Uint16Array SubArray2");
            Assert.AreEqual(4, subArray62.Length, "Uint16Array SubArray2 Length");
            Assert.AreEqual(expectedToStringUint16Array3, subArray62.ToString(), "Uint16Array SubArray2 ToString");
            Assert.AreEqual(6, subArray62.ByteOffset, "Uint16Array SubArray2 ByteOffset");

            var v7 = new Uint32Array(10);

            Assert.True(v7 != null, "Uint32Array created");

            v7[1] = 11;
            v7[5] = 5;
            v7[9] = 99;
            Assert.AreEqual(11, v7[1], "Uint32Array indexier works 1");
            Assert.AreEqual(99, v7[9], "Uint32Array indexier works 9");

            Assert.True(v7.Buffer != null, "Uint32Array Buffer");
            Assert.AreEqual(40, v7.ByteLength, "Uint32Array ByteLength");
            Assert.AreEqual(0, v7.ByteOffset, "Uint32Array ByteOffset");
            Assert.AreEqual(10, v7.Length, "Uint32Array Length");

            var expectedToStringUint32Array1 = isToStringToTypeNameLogic ? "[object Uint32Array]" : "0,11,0,0,0,5,0,0,0,99";

            Assert.AreEqual(expectedToStringUint32Array1, v7.ToLocaleString(), "Uint32Array ToLocaleString");
            Assert.AreEqual(expectedToStringUint32Array1, v7.ToString(), "Uint32Array ToString");

            var subArray71 = v7.SubArray(1);
            var expectedToStringUint32Array2 = isToStringToTypeNameLogic ? "[object Uint32Array]" : "11,0,0,0,5,0,0,0,99";

            Assert.True(subArray71 != null, "Uint32Array SubArray1");
            Assert.AreEqual(9, subArray71.Length, "Uint32Array SubArray1 Length");
            Assert.AreEqual(expectedToStringUint32Array2, subArray71.ToString(), "Uint32Array SubArray1 ToString");
            Assert.AreEqual(4, subArray71.ByteOffset, "Uint32Array SubArray1 ByteOffset");

            var subArray72 = subArray71.SubArray(2, 6);
            var expectedToStringUint32Array3 = isToStringToTypeNameLogic ? "[object Uint32Array]" : "0,0,5,0";

            Assert.True(subArray72 != null, "Uint32Array SubArray2");
            Assert.AreEqual(4, subArray72.Length, "Uint32Array SubArray2 Length");
            Assert.AreEqual(expectedToStringUint32Array3, subArray72.ToString(), "Uint32Array SubArray2 ToString");
            Assert.AreEqual(12, subArray72.ByteOffset, "Uint32Array SubArray2 ByteOffset");

            var v8 = new Uint8Array(10);

            Assert.True(v8 != null, "Uint8Array created");

            v8[1] = 11;
            v8[5] = 5;
            v8[9] = 99;
            Assert.AreEqual(11, v8[1], "Uint8Array indexier works 1");
            Assert.AreEqual(99, v8[9], "Uint8Array indexier works 9");

            Assert.True(v8.Buffer != null, "Uint8Array Buffer");
            Assert.AreEqual(10, v8.ByteLength, "Uint8Array ByteLength");
            Assert.AreEqual(0, v8.ByteOffset, "Uint8Array ByteOffset");
            Assert.AreEqual(10, v8.Length, "Uint8Array Length");

            var expectedToStringUint8Array1 = isToStringToTypeNameLogic ? "[object Uint8Array]" : "0,11,0,0,0,5,0,0,0,99";

            Assert.AreEqual(expectedToStringUint8Array1, v8.ToLocaleString(), "Uint8Array ToLocaleString");
            Assert.AreEqual(expectedToStringUint8Array1, v8.ToString(), "Uint8Array ToString");

            var subArray81 = v8.SubArray(1);
            var expectedToStringUint8Array2 = isToStringToTypeNameLogic ? "[object Uint8Array]" : "11,0,0,0,5,0,0,0,99";

            Assert.True(subArray81 != null, "Uint8Array SubArray1");
            Assert.AreEqual(9, subArray81.Length, "Uint8Array SubArray1 Length");
            Assert.AreEqual(expectedToStringUint8Array2, subArray81.ToString(), "Uint8Array SubArray1 ToString");
            Assert.AreEqual(1, subArray81.ByteOffset, "Uint8Array SubArray1 ByteOffset");

            var subArray82 = subArray81.SubArray(2, 6);
            var expectedToStringUint8Array3 = isToStringToTypeNameLogic ? "[object Uint8Array]" : "0,0,5,0";

            Assert.True(subArray82 != null, "Uint8Array SubArray2");
            Assert.AreEqual(4, subArray82.Length, "Uint8Array SubArray2 Length");
            Assert.AreEqual(expectedToStringUint8Array3, subArray82.ToString(), "Uint8Array SubArray2 ToString");
            Assert.AreEqual(3, subArray82.ByteOffset, "Uint8Array SubArray2 ByteOffset");

            var v9 = new Uint8ClampedArray(10);

            Assert.True(v9 != null, "Uint8ClampedArray created");

            v9[1] = 11;
            v9[5] = 5;
            v9[9] = 99;
            Assert.AreEqual(11, v9[1], "Uint8ClampedArray indexier works 1");
            Assert.AreEqual(99, v9[9], "Uint8ClampedArray indexier works 9");

            Assert.True(v9.Buffer != null, "Uint8ClampedArray Buffer");
            Assert.AreEqual(10, v9.ByteLength, "Uint8ClampedArray ByteLength");
            Assert.AreEqual(0, v9.ByteOffset, "Uint8ClampedArray ByteOffset");
            Assert.AreEqual(10, v9.Length, "Uint8ClampedArray Length");

            var expectedToStringUint8ClampedArray1 = isToStringToTypeNameLogic ? "[object Uint8ClampedArray]" : "0,11,0,0,0,5,0,0,0,99";

            Assert.AreEqual(expectedToStringUint8ClampedArray1, v9.ToLocaleString(), "Uint8ClampedArray ToLocaleString");
            Assert.AreEqual(expectedToStringUint8ClampedArray1, v9.ToString(), "Uint8ClampedArray ToString");

            var subArray91 = v9.SubArray(1);
            var expectedToStringUint8ClampedArray2 = isToStringToTypeNameLogic ? "[object Uint8ClampedArray]" : "11,0,0,0,5,0,0,0,99";

            Assert.True(subArray91 != null, "Uint8ClampedArray SubArray1");
            Assert.AreEqual(9, subArray91.Length, "Uint8ClampedArray SubArray1 Length");
            Assert.AreEqual(expectedToStringUint8ClampedArray2, subArray91.ToString(), "Uint8ClampedArray SubArray1 ToString");
            Assert.AreEqual(1, subArray91.ByteOffset, "Uint8ClampedArray SubArray1 ByteOffset");

            var subArray92 = subArray91.SubArray(2, 6);
            var expectedToStringUint8ClampedArray3 = isToStringToTypeNameLogic ? "[object Uint8ClampedArray]" : "0,0,5,0";

            Assert.True(subArray92 != null, "Uint8ClampedArray SubArray2");
            Assert.AreEqual(4, subArray92.Length, "Uint8ClampedArray SubArray2 Length");
            Assert.AreEqual(expectedToStringUint8ClampedArray3, subArray92.ToString(), "Uint8ClampedArray SubArray2 ToString");
            Assert.AreEqual(3, subArray92.ByteOffset, "Uint8ClampedArray SubArray2 ByteOffset");
        }
예제 #30
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201511/20151103
			// https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201503/20150323

			// X:\jsc.svn\examples\javascript\Test\TestWebCrypto\TestWebCrypto\Application.cs
			// X:\jsc.svn\examples\javascript\async\Test\TestWebCryptoAsync\TestWebCryptoAsync\Application.cs
			// X:\jsc.svn\examples\javascript\Test\TestWebCryptoEncryption\TestWebCryptoEncryption\Application.cs

			#region secure origin
			new IHTMLPre { new { Native.document.location.host } }.AttachToDocument();

            if (Native.document.location.host.TakeUntilOrEmpty(":") != "127.0.0.1")
            {
                new IHTMLAnchor
                {
                    href = "http://127.0.0.1:" + Native.document.location.host.SkipUntilOrEmpty(":"),
                    innerText = "open as secure origin!"
                }.AttachToDocument();

                return;
            }
            #endregion


            // https://developer.chrome.com/extensions/enterprise_platformKeys
            // Only non-extractable RSASSA-PKCS1-V1_5 keys with modulusLength up to 2048 can be generated. Each key can be used for signing data at most once.
            // ?

            // https://src.chromium.org/viewvc/chrome/trunk/src/content/child/webcrypto/jwk.cc?pathrev=257759
            // // RSA private key import is not currently supported
            // ImportRsaPublicKey
            // https://code.google.com/p/chromium/issues/detail?id=373550&q=ImportKey&colspec=ID%20Pri%20M%20Iteration%20ReleaseBlock%20Cr%20Status%20Owner%20Summary%20OS%20Modified
            // http://www.ibiblio.org/hhalpin/homepage/presentations/webcrypto/Overview.html
            // thevulnerability of RSA PKCS#1 v1.5 to variants of Bleichenbacher's attack and unauthenticated block ciphers, to be precise.

            // Update August 30, 2014: The Web Cryptography API has dropped support of the RSAES-PKCS1-v1_5 algorithm that was 
            // used here originally, so this post has been changed to use RSA-OAEP instead. 
            // There’s a new post with more information, including how to update Ubuntu 14.04 so that this algorithm will work in browsers.
            // haha.

            // http://blog.engelke.com/2014/08/29/changes-to-the-web-cryptography-api/
            // Chrome 37 made it to Stable a few days ago, and now supports the Web Cryptography API without needing to set a special flag. YAY!
            // The only public-key encryption and decryption algorithm in the spec now is RSA-OAEP. 
            // http://msdn.microsoft.com/en-us/library/ie/dn302338(v=vs.85).aspx

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201511/20151103
            new IHTMLButton { "generateKey in UI" }.AttachToDocument().onclick +=
                async delegate
            {
                new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument();
                var sw = Stopwatch.StartNew();
                var publicExponent = new Uint8Array(new byte[] { 0x01, 0x00, 0x01 });

                new IHTMLPre { "before generateKey" + new { sw.ElapsedMilliseconds } }.AttachToDocument();

                // http://blog.engelke.com/2014/08/23/public-key-cryptography-in-the-browser/

                var value = Native.crypto.subtle.generateKeyAsync(
                new
                {
                    //name = "RSASSA-PKCS1-v1_5",
                    name = "RSA-OAEP",
                    hash = new { name = "SHA-256" },

                    modulusLength = 2048,
                    publicExponent,
                },
                    false,
            new[] { "encrypt", "decrypt" }
                //new[] { "sign", "verify" }
                );

                // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise
                new IHTMLPre { "after generateKey " + new { value, sw.ElapsedMilliseconds } }.AttachToDocument();

                var key = await value;

                // continue generateKey {{ privateKey = [object CryptoKey], publicKey = [object CryptoKey], ElapsedMilliseconds = 5021 }}
                new IHTMLPre { "continue generateKey " + new { key.privateKey, key.publicKey, sw.ElapsedMilliseconds } }.AttachToDocument();
            };

            #region generateKey in Worker
            new IHTMLButton { "generateKey in Worker" }.AttachToDocument().onclick +=
            async delegate
            {
                new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachToDocument();

                var sw = Stopwatch.StartNew();

                new IHTMLPre { "before generateKey" + new { sw.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId } }.AttachToDocument();

                var __value = Task.Run(
                    async delegate
                {
                    var publicExponent = new Uint8Array(new byte[] { 0x01, 0x00, 0x01 });
                    var sw2 = Stopwatch.StartNew();

                    Console.WriteLine("worker before generateKeyAsync " + new { sw2.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId });

                    var value = Native.crypto.subtle.generateKeyAsync(
                        new
                    {
                        //name = "RSASSA-PKCS1-v1_5",
                        name = "RSA-OAEP",
                        hash = new { name = "SHA-256" },


                        modulusLength = 2048,
                        publicExponent,

                        //  RsaHashedKeyGenParams: hash: Algorithm: Not an object
                    },
                        false,
                        new[] { "encrypt", "decrypt" }
                    //new[] { "sign", "verify" }
                    );
                    Console.WriteLine("worker after generateKeyAsync " + new { sw2.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId });

                    var xkey = await value;
                    Console.WriteLine("worker continue generateKeyAsync " + new { sw2.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId });

                    //                    0:6071ms worker before generateKeyAsync { { ElapsedMilliseconds = 0, ManagedThreadId = 10 } }
                    //0:6072ms worker after generateKeyAsync { { ElapsedMilliseconds = 2, ManagedThreadId = 10 } }
                    //0:6073ms worker Task Run function has returned { value_Task = { IsCompleted = false, Result =  }, value_TaskOfT = { IsCompleted = false, Result =  } }
                    //0:7090ms worker continue generateKeyAsync { { ElapsedMilliseconds = 1020, ManagedThreadId = 10 } }
                    return xkey;

                }
                );

                new IHTMLPre { " after generateKeyAsync " + new { sw.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId } }.AttachToDocument();


                var __key = await __value;

                // continue generateKey {{ key = [object Object], ElapsedMilliseconds = 313 }}
                new IHTMLPre { "continue generateKey " + new { __key.privateKey, __key.publicKey, sw.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId } }.AttachToDocument();
            };
            #endregion


        }
예제 #31
0
        /// <summary>
        /// Send data on <see cref="T:WebAssembly.Net.WebSockets.ClientWebSocket"/> as an asynchronous operation.
        /// </summary>
        /// <returns>The async.</returns>
        /// <param name="buffer">Buffer.</param>
        /// <param name="messageType">Message type.</param>
        /// <param name="endOfMessage">If set to <c>true</c> end of message.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public override async Task SendAsync(ArraySegment <byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
        {
            ThrowIfNotConnected();

            if (messageType != WebSocketMessageType.Binary &&
                messageType != WebSocketMessageType.Text)
            {
                throw new ArgumentException($"Invalid message type: '{messageType}' specified in method 'SendAsync'.  Valid types are 'Binary' and 'Text'",
                                            nameof(messageType));
            }

            if (!endOfMessage)
            {
                writeBuffer = writeBuffer ?? new MemoryStream();

                writeBuffer.Write(buffer.Array, buffer.Offset, buffer.Count);
                return;
            }
            else if (writeBuffer != null)
            {
                writeBuffer.Write(buffer.Array, buffer.Offset, buffer.Count);

                if (!writeBuffer.TryGetBuffer(out buffer))
                {
                    throw new WebSocketException(WebSocketError.NativeError);
                }
            }

            var tcsSend = new TaskCompletionSource <bool>();
            // Wrap the cancellationToken in a using so that it can be disposed of whether
            // we successfully send or not.
            // Otherwise any timeout/cancellation would apply to the full session.
            var writtenBuffer = writeBuffer;

            writeBuffer = null;

            using (cancellationToken.Register(() => tcsSend.TrySetCanceled()))
            {
                try
                {
                    if (messageType == WebSocketMessageType.Binary)
                    {
                        using (var uint8Buffer = Uint8Array.From(buffer))
                        {
                            innerWebSocket.Invoke("send", uint8Buffer);
                            await Task.Delay(1);

                            while ((int)innerWebSocket.GetObjectProperty("bufferedAmount") != 0)
                            {
                                ThrowIfNotConnected();
                                await Task.WhenAny(tcsSend.Task, Task.Delay(200));
                            }
                            tcsSend.SetResult(true);
                        }
                    }
                    else if (messageType == WebSocketMessageType.Text)
                    {
                        var strBuffer = Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count);
                        innerWebSocket.Invoke("send", strBuffer);
                        await Task.Delay(1);

                        while ((int)innerWebSocket.GetObjectProperty("bufferedAmount") != 0)
                        {
                            ThrowIfNotConnected();
                            await Task.WhenAny(tcsSend.Task, Task.Delay(200));
                        }
                        tcsSend.SetResult(true);
                    }
                }
                catch (Exception excb)
                {
                    tcsSend.TrySetException(new WebSocketException(WebSocketError.NativeError, excb));
                }
                finally
                {
                    writtenBuffer?.Dispose();
                }
                await tcsSend.Task;
            }
        }
예제 #32
0
파일: r_sky.cs 프로젝트: sbrown345/quakejs
        int r_skydirect; // not used?

        #endregion Fields

        #region Methods

        //  of newsky on the left of each scan, 128 bytes
        //  of topsky on the right, because the low-level
        //  drawers need 256-byte scan widths
        /*
        =============
        R_InitSky

        A sky texture is 256*128, with the right side being a masked overlay
        ==============
        */
        public static void R_InitSky(model.texture_t mt)
        {
            int     i, j;
            int     src;

            src = (int)mt.offsets[0];

            for (i = 0; i < 128; i++)
            {
                for (j = 0; j < 128; j++)
                {
                    newsky[(i * 256) + j + 128] = mt.pixels[src+i * 256 + j + 128];
                }
            }

            for (i = 0; i < 128; i++)
            {
                for (j = 0; j < 131; j++)
                {
                    if (mt.pixels[src + i * 256 + (j & 0x7F)] != 0)
                    {
                        bottomsky[(i * 131) + j] = mt.pixels[src + i * 256 + (j & 0x7F)];
                        bottommask[(i * 131) + j] = 0;
                    }
                    else
                    {
                        bottomsky[(i * 131) + j] = 0;
                        bottommask[(i * 131) + j] = 0xff;
                    }
                }
            }

            r_skysource = newsky;
        }
예제 #33
0
        public void LengthWorks()
        {
            var arr = new Uint8Array(13);

            Assert.AreEqual(13, arr.Length, "Length");
        }
예제 #34
0
 /// <summary>
 /// Creates a new Uint8Array out of the specified Uint8Array.
 /// </summary>
 /// <param name="typedArray">Uint8Array to use as initial contents to the new array.</param>
 public Uint8Array(Uint8Array typedArray)
 {
 }
예제 #35
0
        private async Task doFetch(TaskCompletionSource <HttpResponseMessage> tcs, HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try {
                var requestObject = new JSObject();
                requestObject.SetObjectProperty("method", request.Method.Method);

                // See https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials for
                // standard values and meanings
                requestObject.SetObjectProperty("credentials", DefaultCredentials);

                // See https://developer.mozilla.org/en-US/docs/Web/API/Request/cache for
                // standard values and meanings
                requestObject.SetObjectProperty("cache", Cache);

                // See https://developer.mozilla.org/en-US/docs/Web/API/Request/mode for
                // standard values and meanings
                requestObject.SetObjectProperty("mode", Mode);

                // We need to check for body content
                if (request.Content != null)
                {
                    if (request.Content is StringContent)
                    {
                        requestObject.SetObjectProperty("body", await request.Content.ReadAsStringAsync());
                    }
                    else
                    {
                        using (var uint8Buffer = Uint8Array.From(await request.Content.ReadAsByteArrayAsync()))
                        {
                            requestObject.SetObjectProperty("body", uint8Buffer);
                        }
                    }
                }

                // Process headers
                // Cors has it's own restrictions on headers.
                // https://developer.mozilla.org/en-US/docs/Web/API/Headers
                using (var jsHeaders = new HostObject("Headers")) {
                    if (request.Headers != null)
                    {
                        foreach (var header in request.Headers)
                        {
                            foreach (var value in header.Value)
                            {
                                jsHeaders.Invoke("append", header.Key, value);
                            }
                        }
                    }
                    if (request.Content?.Headers != null)
                    {
                        foreach (var header in request.Content.Headers)
                        {
                            foreach (var value in header.Value)
                            {
                                jsHeaders.Invoke("append", header.Key, value);
                            }
                        }
                    }
                    requestObject.SetObjectProperty("headers", jsHeaders);
                }

                JSObject           abortController    = null;
                JSObject           signal             = null;
                WasmHttpReadStream wasmHttpReadStream = null;

                CancellationTokenRegistration abortRegistration = default(CancellationTokenRegistration);
                if (cancellationToken.CanBeCanceled)
                {
                    abortController = new HostObject("AbortController");

                    signal = (JSObject)abortController.GetObjectProperty("signal");
                    requestObject.SetObjectProperty("signal", signal);
                    abortRegistration = cancellationToken.Register((Action)(() => {
                        if (abortController.JSHandle != -1)
                        {
                            abortController.Invoke((string)"abort");
                            abortController?.Dispose();
                        }
                        wasmHttpReadStream?.Dispose();
                    }));
                }

                var args = new Core.Array();
                args.Push(request.RequestUri.ToString());
                args.Push(requestObject);

                requestObject.Dispose();

                var response = (Task <object>)fetch.Invoke("apply", window, args);
                args.Dispose();

                var t = await response;

                var status = new WasmFetchResponse((JSObject)t, abortController, abortRegistration);

                //Console.WriteLine($"bodyUsed: {status.IsBodyUsed}");
                //Console.WriteLine($"ok: {status.IsOK}");
                //Console.WriteLine($"redirected: {status.IsRedirected}");
                //Console.WriteLine($"status: {status.Status}");
                //Console.WriteLine($"statusText: {status.StatusText}");
                //Console.WriteLine($"type: {status.ResponseType}");
                //Console.WriteLine($"url: {status.Url}");

                HttpResponseMessage httpresponse = new HttpResponseMessage((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), status.Status.ToString()));

                httpresponse.Content = StreamingSupported && StreamingEnabled
                                    ? new StreamContent(wasmHttpReadStream = new WasmHttpReadStream(status))
                                    : (HttpContent) new WasmHttpContent(status);

                // Fill the response headers
                // CORS will only allow access to certain headers.
                // If a request is made for a resource on another origin which returns the CORs headers, then the type is cors.
                // cors and basic responses are almost identical except that a cors response restricts the headers you can view to
                // `Cache-Control`, `Content-Language`, `Content-Type`, `Expires`, `Last-Modified`, and `Pragma`.
                // View more information https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types
                //
                // Note: Some of the headers may not even be valid header types in .NET thus we use TryAddWithoutValidation
                using (var respHeaders = status.Headers) {
                    // Here we invoke the forEach on the headers object
                    // Note: the Action takes 3 objects and not two.  The other seems to be the Header object.
                    var foreachAction = new Action <object, object, object> ((value, name, other) => {
                        if (!httpresponse.Headers.TryAddWithoutValidation((string)name, (string)value))
                        {
                            if (httpresponse.Content != null)
                            {
                                if (!httpresponse.Content.Headers.TryAddWithoutValidation((string)name, (string)value))
                                {
                                    Console.WriteLine($"Warning: Can not add response header for name: {name} value: {value}");
                                }
                            }
                        }
                        ((JSObject)other).Dispose();
                    });

                    try {
                        respHeaders.Invoke("forEach", foreachAction);
                    } finally {
                        // Do not remove the following line of code.  The httpresponse is used in the lambda above when parsing the Headers.
                        // if a local is captured (used) by a lambda it becomes heap memory as we translate them into fields on an object.
                        // The foreachAction is allocated when marshalled to JavaScript.  Since we do not know when JS is finished with the
                        // Action we need to tell the Runtime to de-allocate the object and remove the instance from JS as well.
                        WebAssembly.Runtime.FreeObject(foreachAction);
                    }
                }

                tcs.SetResult(httpresponse);

                signal?.Dispose();
            } catch (Exception exception) {
                tcs.SetException(exception);
            }
        }
예제 #36
0
        /*
        ================
        D_PolysetUpdateTables
        ================
        */
        public static void D_PolysetUpdateTables()
        {
            int		i;
            int     s;

            if (render.r_affinetridesc.skinwidth != skinwidth ||
                render.r_affinetridesc.pskin != skinstart)
            {
                skinwidth = render.r_affinetridesc.skinwidth;
                skinstart = render.r_affinetridesc.pskin;
                s = 0;
                for (i=0 ; i<MAX_LBM_HEIGHT ; i++, s+=skinwidth)
                    skintable[i] = s;
            }
        }
예제 #37
0
파일: vid.cs 프로젝트: sbrown345/quakejs
 /*
 ================
 VID_SetPalette
 ================
 */
 public static void VID_SetPalette(Uint8Array palette)
 {
     if (palette != vid_current_palette)
     {
         Buffer.BlockCopy(palette, 0, vid_current_palette, 0, 768);
         /*if (surface != null)
             surface.UpdatePalette();*/
     }
 }
예제 #38
0
 public static short ToInt16(Uint8Array value, int startIndex)
 {
     throw new ImplementedInJavaScript();
 }
예제 #39
0
파일: vid.cs 프로젝트: sbrown345/quakejs
        /*
        ================
        VID_SetMode
        ================
        */
        static int VID_SetMode(int modenum, Uint8Array palette)
        {
            int		stat;

            if ((modenum >= numvidmodes) || (modenum < 0))
            {
                cvar_t.Cvar_SetValue("vid_mode", (double)vid_modenum);

                nomodecheck = true;
                console.Con_Printf ("No such video mode: " + modenum);
                nomodecheck = false;

                modenum = 0;	// mode hasn't been set yet, so initialize to base
                                //  mode since they gave us an invalid initial mode
                return 0;
            }

            // initialize the new mode
            screen.vid.width = Page.gwidth;
            screen.vid.height = Page.gheight;
            screen.vid.aspect = ((double)screen.vid.height / (double)screen.vid.width) * (320.0 / 240.0);
            screen.vid.rowbytes = screen.vid.width;
            screen.vid.numpages = 1;
            screen.vid.colormap = host.host_colormap;
            screen.vid.fullbright = 256 - BitConverter.ToInt32(screen.vid.colormap, 2048*4);

            draw.D_InitCaches(656400);

            screen.vid.maxwarpwidth = draw.WARP_WIDTH;
            screen.vid.maxwarpheight = draw.WARP_HEIGHT;

            VID_SetPalette(palette);

            screen.vid.buffer = new Uint8Array(screen.vid.width * screen.vid.height);
            //surface = new BitmapData(vid_current_palette, screen.vid.buffer, (int)screen.vid.width, (int)screen.vid.height);
            surface = new WriteableBitmap((int)screen.vid.width, (int)screen.vid.height);
            Page.thePage.image.Source = surface;
            /*Page.thePage.image2.Source = surface;
            Page.thePage.image3.Source = surface;
            Page.thePage.image4.Source = surface;*/

            screen.vid.conbuffer = screen.vid.buffer;
            screen.vid.conrowbytes = (int)screen.vid.rowbytes;
            screen.vid.conwidth = screen.vid.width;
            screen.vid.conheight = screen.vid.height;

            vid_modenum = modenum;
            cvar_t.Cvar_SetValue ("vid_mode", (double)vid_modenum);

            screen.vid.recalc_refdef = true;

            return 1;
        }
예제 #40
0
 public static uint ToUInt32(Uint8Array value, int startIndex)
 {
     throw new ImplementedInJavaScript();
 }
예제 #41
0
        public void ByteLengthPropertyWorks()
        {
            var arr = new Uint8Array(23);

            Assert.AreEqual(23, arr.ByteLength, "Should be correct");
        }
예제 #42
0
파일: vid.cs 프로젝트: sbrown345/quakejs
 /*
 ================
 VID_ShiftPalette
 ================
 */
 public static void VID_ShiftPalette(Uint8Array palette)
 {
     VID_SetPalette (palette);
 }
예제 #43
0
 public void append(Uint8Array data)
 {
 }
예제 #44
0
파일: vid.cs 프로젝트: sbrown345/quakejs
        /*
        ================
        VID_Init
        ================
        */
        public static void VID_Init(Uint8Array palette)
        {
            cvar_t.Cvar_RegisterVariable(vid_mode);

            vid_testingmode = 0;

            vid_modenum = (int)vid_mode.value;

            VID_SetMode (vid_modenum, palette);

            vid_realmode = vid_modenum;

            draw.d_pzbuffer = new short[screen.vid.width * screen.vid.height];
        }
예제 #45
0
        public static void CoreTypes()
        {
            var arr1 = new Uint8Array(50);

            Assert.Equal(50, arr1.Length);
        }
예제 #46
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefault  page)
        {
            #region AtFile
            Action<File> AtFile =
                f =>
                {
                    var n = new MyFile();
                    // databind here?
                    n.name.innerText = f.name;
                    n.type.innerText = f.type;
                    n.lastModifiedDate.innerText = "" + f.lastModifiedDate;

                    #region hex
                    new FileReader().With(
                        reader =>
                        {
                            reader.onload = IFunction.Of(
                                delegate
                                {
                                    var x = (ArrayBuffer)reader.result;

                                    var u8 = new Uint8Array(x, 0, 8);

                                    var pre = new IHTMLPre().AttachTo(n.Container);

                                    pre.style.border = "1px solid gray";

                                    for (uint i = 0; i < u8.length; i++)
                                    {
                                        pre.innerText += u8[i].ToString("x2") + " ";

                                    }
                                }
                            );

                            // Read in the image file as a data URL.
                            reader.readAsArrayBuffer(f);
                        }
                     );
                    #endregion

                    #region AsDataURL
                    Action<Action<string>> AsDataURL =
                        h =>
                        {
                            var reader = new FileReader();

                            reader.onload = IFunction.Of(
                                delegate
                                {
                                    var base64 = (string)reader.result;

                                    h(base64);

                                }
                            );
                            
                            // Read in the image file as a data URL.
                            reader.readAsDataURL(f);

                        };
                    #endregion


                    #region image
                    if (f.type.StartsWith("image/"))
                    {
                        AsDataURL(
                            base64 =>
                                new IHTMLImage
                                {
                                    src = base64,

                                }.AttachTo(n.Container)
                        );
                    }
                    #endregion


                    #region audio
                    if (f.type.StartsWith("audio/"))
                    {
                        AsDataURL(
                           base64 =>
                               new IHTMLAudio
                               {
                                   src = base64,
                                   controls = true,
                               }.AttachTo(n.Container)
                       );
                    }
                    #endregion

                    #region video
                    //if (f.type.StartsWith("video/"))
                    //{
                    //    AsDataURL(
                    //       base64 =>
                    //           new IHTMLVideo
                    //           {
                    //               src = base64,
                    //               controls = true,

                    //           }.AttachTo(n.Container)
                    //   );
                    //}
                    #endregion

                    n.Container.AttachTo(page.list);
                };
            #endregion


            #region onchange
            page.files.onchange +=
                e =>
                {
                    FileList x = page.files.files;
                    page.list.Clear();
                    page.list.Add("files: " + x.length);
                    for (uint i = 0; i < x.length; i++)
                    {
                        File f = x[i];

                        AtFile(f);
                    }

                };
            #endregion

            page.drop_zone.ondragleave +=
                delegate
                {
                    page.drop_zone.style.borderColor = JSColor.Gray;
                    page.drop_zone.style.backgroundColor = JSColor.None;
                };

            #region dragover
            page.drop_zone.ondragover +=
                    evt =>
                    {
                        page.drop_zone.style.borderColor = JSColor.Red;
                        page.drop_zone.style.backgroundColor = JSColor.FromRGB(0xff, 0xaf, 0xaf);

                        evt.StopPropagation();
                        evt.PreventDefault();
                        evt.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy.
                    };

            page.drop_zone.ondrop +=
                  evt =>
                  {
                      page.drop_zone.style.borderColor = JSColor.Green;
                      page.drop_zone.style.backgroundColor = JSColor.FromRGB(0xaf, 0xff, 0xaf);


                      evt.StopPropagation();
                      evt.PreventDefault();

                      FileList x = evt.dataTransfer.files; // FileList object.

                      page.list.Clear();
                      page.list.Add("files: " + x.length);
                      for (uint i = 0; i < x.length; i++)
                      {
                          File f = x[i];

                          AtFile(f);
                      }
                  };
            #endregion


        }
 public static T Deserialize <T>(Uint8Array data) => MsgPack5Decoder.Default.Decode <T>(data);
예제 #48
0
 public void GetByteFrequencyData(Uint8Array array) { }
예제 #49
0
 public void getByteFrequencyData(Uint8Array array)
 {
 }
예제 #50
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {

            // Uncaught TypeError: Failed to execute 'digest' on 'SubtleCrypto': No function was found that matched the signature provided.

            // {{ err = NotSupportedError: Only secure origins are allowed. http://goo.gl/lq4gCo }}

            // X:\jsc.svn\examples\javascript\Test\TestWebCrypto\TestWebCrypto\Application.cs
            // X:\jsc.svn\examples\javascript\async\Test\TestWebCryptoAsync\TestWebCryptoAsync\Application.cs
            // X:\jsc.svn\examples\javascript\Test\TestWebCryptoEncryption\TestWebCryptoEncryption\Application.cs
            // X:\jsc.svn\examples\javascript\Test\TestWebCryptoKeyExport\TestWebCryptoKeyExport\Application.cs
            // X:\jsc.svn\examples\javascript\Test\TestWebCryptoKeyImport\TestWebCryptoKeyImport\Application.cs

            #region secure origin
            new IHTMLPre { new { Native.document.location.host } }.AttachToDocument();

            if (Native.document.location.host.TakeUntilOrEmpty(":") != "127.0.0.1")
            {
                // https://code.google.com/p/chromium/issues/detail?id=412681

                new IHTMLAnchor
                {
                    href = "http://127.0.0.1:" + Native.document.location.host.SkipUntilOrEmpty(":"),
                    innerText = "open as secure origin!"
                }.AttachToDocument();

                return;
            }
            #endregion


            new IHTMLButton { "digest" }.AttachToDocument().onclick +=
                delegate
            {
                // shall we change jsc to do byte arrays in Uint8Array ?
                var data = new Uint8Array(7, 8);


                var p = Native.crypto.subtle.digest(
                     new { name = "SHA-1" },
                     //new byte[] { 7, 8 }
                     data
                 );

                p.then(
                    onSuccess: x =>
                    {
                        // {{ x = [object ArrayBuffer] }}

                        new IHTMLPre { new { x } }.AttachToDocument();
                    },
                    onError: err =>
                {
                    new IHTMLPre { new { err } }.AttachToDocument();
                }
            );
            };


            new IHTMLButton { "digestAsync" }.AttachToDocument().onclick +=

                async delegate
            {
                var sw = Stopwatch.StartNew();

                // shall we change jsc to do byte arrays in Uint8Array ?
                var data = new Uint8Array(7, 8);

                var a = new { name = "SHA-1" };
                //var a = new { name = "SHA-512" };
                var x = await Native.crypto.subtle.digestAsync(a, data);

                // {{ Length = 20 }}
                // {{ a = {{ name = SHA-512 }}, Length = 64 }}
                //{{ a = {{ name = SHA-512 }}, Length = 64, ElapsedMilliseconds = 3164 }}
                //{{ a = {{ name = SHA-512 }}, Length = 64, ElapsedMilliseconds = 3 }}
                //{{ a = {{ name = SHA-512 }}, Length = 64, ElapsedMilliseconds = 1 }}

                new IHTMLPre { new { a, x.Length, sw.ElapsedMilliseconds } }.AttachToDocument();
            };



        }
예제 #51
0
 public BinaryReader(Uint8Array arraybuf)
 {
     data = arraybuf;
 }