Esempio n. 1
0
        static StackObject *WriteAsync_20(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 5);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Threading.CancellationToken @cancellationToken = (System.Threading.CancellationToken) typeof(System.Threading.CancellationToken).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Int32 @count = ptr_of_this_method->Value;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Int32 @offset = ptr_of_this_method->Value;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 4);
            System.Byte[] @buffer = (System.Byte[]) typeof(System.Byte[]).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 5);
            System.IO.MemoryStream instance_of_this_method = (System.IO.MemoryStream) typeof(System.IO.MemoryStream).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.WriteAsync(@buffer, @offset, @count, @cancellationToken);

            object obj_result_of_this_method = result_of_this_method;

            if (obj_result_of_this_method is CrossBindingAdaptorType)
            {
                return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance));
            }
            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Esempio n. 2
0
        static int _m_WriteAsync(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                System.IO.MemoryStream gen_to_be_invoked = (System.IO.MemoryStream)translator.FastGetCSObj(L, 1);



                {
                    byte[] _buffer = LuaAPI.lua_tobytes(L, 2);
                    int    _offset = LuaAPI.xlua_tointeger(L, 3);
                    int    _count  = LuaAPI.xlua_tointeger(L, 4);
                    System.Threading.CancellationToken _cancellationToken; translator.Get(L, 5, out _cancellationToken);

                    System.Threading.Tasks.Task gen_ret = gen_to_be_invoked.WriteAsync(_buffer, _offset, _count, _cancellationToken);
                    translator.Push(L, gen_ret);



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
Esempio n. 3
0
        public async Task <string> UploadBlob(string blobContainer, IFormFile file, string directoryName, bool isThumbnail)
        {
            int    fileNameStartLocation = file.FileName.LastIndexOf("\\") + 1;
            string fileName = file.FileName.Substring(fileNameStartLocation);

            CloudBlobContainer container = _client.GetContainerReference(blobContainer);
            await container.CreateIfNotExistsAsync();

            await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(directoryName + @"\" + fileName);

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

            MagickImage image = new MagickImage(file.OpenReadStream());

            image.AutoOrient();

            if (isThumbnail)
            {
                if (image.Width > image.Height)
                {
                    image.Resize((new MagickGeometry()
                    {
                        Height = 200, Width = 340, FillArea = true
                    }));
                }
                else
                {
                    image.Extent(new MagickGeometry()
                    {
                        Height = 200, Width = 340, FillArea = false, Greater = true, Less = true
                    }, Gravity.Center);
                }


                //image.AdaptiveResize(new MagickGeometry() { Width = 340, Height = 200, FillArea = true });
                image.Crop(340, 200, Gravity.Center);
            }

            await memoryStream.WriteAsync(image.ToByteArray(), 0, image.ToByteArray().Count());

            memoryStream.Position = 0;
            await blockBlob.UploadFromStreamAsync(memoryStream);

            return(blockBlob.Uri.AbsoluteUri);
        }
Esempio n. 4
0
        public async Task <byte[]> UploadAsync(IFileListEntry file, Func <long, long, int, Task> callback = null)
        {
            using (var ms = new System.IO.MemoryStream())
            {
                var    seek = 0; var count = 0;
                byte[] buffer = new byte[1024];
                while (seek < file.Size)
                {
                    count = await file.Data.ReadAsync(buffer, 0, buffer.Length);

                    await ms.WriteAsync(buffer, 0, count);

                    if (callback != null)
                    {
                        await callback(file.Size, seek, count);
                    }
                    seek += count;
                }
                return(ms.ToArray());
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Determines the content for request body and uses the HTTP request
        /// to write the content to the HTTP request body.
        /// </summary>
        /// <param name="requestContent">Content to be written.</param>
        /// <param name="httpRequest">The HTTP request.</param>
        /// <param name="requestContext">The request context.</param>
        private async System.Threading.Tasks.Task WriteContentToRequestBodyAsync(TRequestContent requestContent,
                                                                                 IHttpRequest <TRequestContent> httpRequest,
                                                                                 IRequestContext requestContext)
        {
            IRequest wrappedRequest = requestContext.Request;

            // This code path ends up using a ByteArrayContent for System.Net.HttpClient used by .NET Core.
            // HttpClient can't seem to handle ByteArrayContent with 0 length so in that case use
            // the StreamContent code path.
            if (wrappedRequest.Content != null && wrappedRequest.Content.Length > 0)
            {
                byte[] requestData = wrappedRequest.Content;
                requestContext.Metrics.AddProperty(Metric.RequestSize, requestData.Length);
                await httpRequest.WriteToRequestBodyAsync(requestContent, requestData, requestContext.Request.Headers, requestContext.CancellationToken).ConfigureAwait(false);
            }
            else
            {
                System.IO.Stream originalStream;
                if (wrappedRequest.ContentStream == null)
                {
                    originalStream = new System.IO.MemoryStream();
                    await originalStream.WriteAsync(wrappedRequest.Content, 0, wrappedRequest.Content.Length, requestContext.CancellationToken).ConfigureAwait(false);

                    originalStream.Position = 0;
                }
                else
                {
                    originalStream = wrappedRequest.ContentStream;
                }

                var callback = ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)wrappedRequest.OriginalRequest).StreamUploadProgressCallback;
                if (callback != null)
                {
                    originalStream = httpRequest.SetupProgressListeners(originalStream, requestContext.ClientConfig.ProgressUpdateInterval, this.CallbackSender, callback);
                }
                var inputStream = GetInputStream(requestContext, originalStream, wrappedRequest);
                await httpRequest.WriteToRequestBodyAsync(requestContent, inputStream,
                                                          requestContext.Request.Headers, requestContext).ConfigureAwait(false);
            }
        }
        public async Task <IActionResult> Download(string id)
        {
            var stream = new System.IO.MemoryStream();
            var buf    = new byte[1024];

            for (var i = 0; i < buf.Length; i++)
            {
                buf[i] = (byte)i;
            }

            for (var i = 0; i < 100; i++)
            {
                await stream.WriteAsync(buf);
            }

            stream.Position = 0;

            if (stream == null)
            {
                return(NotFound());                           // returns a NotFoundResult with Status404NotFound response.
            }
            return(File(stream, "application/octet-stream")); // returns a FileStreamResult
        }
Esempio n. 7
0
 async private void WriteMemoryStream(System.IO.MemoryStream stream, byte[] data)
 {
     await stream.WriteAsync(data, 0, data.Length);
 }
Esempio n. 8
0
        private async Task SocketConnect(ParseMessage parseMessage)
        {
            if (_webSocketClient.State != WebSocketState.Open)
            {
                //State_check();
                try
                { await _webSocketClient.ConnectAsync(new Uri(_uri), new CancellationToken()).ConfigureAwait(false); }
                catch (Exception ex)
                {
                    //_logger.Log(LogPriority.Debug, "Connection unaviable");
                }
            }
            if (_webSocketClient.State == WebSocketState.Open)
            {
                //State_check();
                var connected = new SocketEventHandlerArgs
                {
                    chnlName = _chnlName,
                    type     = StreamMessageType.Logon
                };
                await parseMessage(connected);

                while (_webSocketClient.State == WebSocketState.Open && !_source.Token.IsCancellationRequested)
                {
                    using (var stream = new System.IO.MemoryStream(1024))
                    {
                        WebSocketReceiveResult webSocketReceiveResult;
                        do
                        {
                            var receiveBuffer = new ArraySegment <byte>(new byte[1024 * 8]);
                            try
                            {
                                webSocketReceiveResult = await _webSocketClient.ReceiveAsync(receiveBuffer, _source.Token);

                                if (webSocketReceiveResult.CloseStatus != null || webSocketReceiveResult.CloseStatusDescription != null)
                                {
                                    _logger.Log(LogPriority.Debug, $"Server request for closing: CloseStatus - {webSocketReceiveResult.CloseStatus}, Description - {webSocketReceiveResult.CloseStatusDescription}", _name);
                                }
                                if (webSocketReceiveResult.Count == 0)
                                {
                                    _logger.Log(LogPriority.Debug, $"Websocket empty msg", _name);
                                }
                                if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close)
                                {
                                    _logger.Log(LogPriority.Debug, $"Websocket received {webSocketReceiveResult.MessageType}", _name);
                                }
                                if (webSocketReceiveResult.CloseStatus != null)
                                {
                                    _logger.Log(LogPriority.Debug, $"Websocket received {webSocketReceiveResult.CloseStatus} reason:{webSocketReceiveResult.CloseStatusDescription}", _name);
                                }
                            }
                            catch (Exception ex)
                            {
                                await _webSocketClient.CloseAsync(WebSocketCloseStatus.NormalClosure, "", new CancellationToken());

                                //State_check();
                                var disconnected = new SocketEventHandlerArgs
                                {
                                    chnlName = _chnlName,
                                    type     = StreamMessageType.Logout
                                };
                                await parseMessage(disconnected);

                                return;
                            }
                            await stream.WriteAsync(receiveBuffer.Array, receiveBuffer.Offset, receiveBuffer.Count);

                            //State_check();
                        }while (!webSocketReceiveResult.EndOfMessage || Convert.ToChar(stream.GetBuffer()[stream.Length - 1]) != 0);

                        var stream_to_msg = stream.ToArray().Where(b => b != 0).ToArray();
                        var message       = new SocketEventHandlerArgs
                        {
                            msg      = stream_to_msg,
                            chnlName = _chnlName,
                            type     = StreamMessageType.Data
                        };

                        try
                        {
                            await parseMessage(message);
                        }
                        catch (Exception ex)
                        {
                            //State_check();
                            //_internal_error(message, $" Exception: {ex.Message}  stack {ex.StackTrace}");
                            var encode_error = Encoding.ASCII.GetBytes($" Exception: {ex.Message}  stack {ex.StackTrace}");
                            var error        = new SocketEventHandlerArgs
                            {
                                msg      = encode_error,
                                chnlName = _chnlName,
                                type     = StreamMessageType.Error
                            };
                            await parseMessage(error);
                        }
                    }
                }
            }
        }
Esempio n. 9
0
        public static async void RunServer(object server)
        {
            System.Net.Sockets.TcpListener tcp = (System.Net.Sockets.TcpListener)server;
            tcp.Start();
            System.Console.WriteLine("Listening");
            while (true)
            {
                using (System.Net.Sockets.TcpClient socket = await tcp.AcceptTcpClientAsync())
                {
                    System.Console.WriteLine("Client connected");
                    // SslStream stream = new SslStream(socket.GetStream());
                    // NoValidateServerCertificate
                    // https://stackoverflow.com/questions/57399520/set-sni-in-a-client-for-a-streamsocket-or-sslstream
                    // https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml
                    // SslStream stream = new SslStream(socket.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate))
                    // SslStream stream = new SslStream(socket.GetStream(), false, new RemoteCertificateValidationCallback(NoValidateServerCertificate) ,new LocalCertificateSelectionCallback(My))


                    // ((System.Net.IPEndPoint)socket.Client.RemoteEndPoint).Address.ToString();

#if false
                    StreamExtended.DefaultBufferPool bufferPool = new StreamExtended.DefaultBufferPool();

                    StreamExtended.Network.CustomBufferedStream yourClientStream =
                        new StreamExtended.Network.CustomBufferedStream(socket.GetStream(), bufferPool, 4096);

                    StreamExtended.ClientHelloInfo clientSslHelloInfo =
                        await StreamExtended.SslTools.PeekClientHello(yourClientStream, bufferPool);

                    //will be null if no client hello was received (not a SSL connection)
                    if (clientSslHelloInfo != null)
                    {
                        string sniHostName = clientSslHelloInfo.Extensions?.FirstOrDefault(x => x.Key == "server_name").Value?.Data;
                        System.Console.WriteLine(sniHostName);
                    }
                    else
                    {
                        System.Console.WriteLine("ciao");
                    }
#else
                    System.Net.Sockets.NetworkStream yourClientStream = socket.GetStream();
#endif

                    System.Net.Security.SslStream stream = new System.Net.Security.SslStream(yourClientStream, false
                                                                                             , new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate))
                    {
                        ReadTimeout  = IOTimeout,
                        WriteTimeout = IOTimeout
                    };

                    // System.Net.Security.SslStream stream;
                    // .NET 5.0 only stream.TargetHostName

                    // Specifying a delegate instead of directly providing the certificate works
                    System.Net.Security.SslServerAuthenticationOptions sslOptions =
                        new System.Net.Security.SslServerAuthenticationOptions
                    {
                        // ServerCertificate = certificate,
                        ServerCertificateSelectionCallback = (sender, name) => cert,
                        CertificateRevocationCheckMode     = System.Security.Cryptography.X509Certificates.X509RevocationMode.Offline,
                        EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12
                    };
                    stream.AuthenticateAsServer(sslOptions);

                    // new System.Net.Security.SslStream(null, true, null,null, )


                    // https://docs.microsoft.com/en-us/aspnet/core/security/authentication/certauth?view=aspnetcore-5.0
                    // System.Net.Security.ServerCertificateSelectionCallback
                    // System.Net.Security.SslServerAuthenticationOptions
                    System.Console.WriteLine(stream.TargetHostName);
                    // await stream.AuthenticateAsServerAsync(cert);
                    // await stream.AuthenticateAsServerAsync(cert, false, System.Security.Authentication.SslProtocols.Tls13, true);

                    // System.Console.WriteLine(stream.TargetHostName);

                    while (true)
                    {
                        //NetworkStream stream= socket.GetStream();
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        System.IO.MemoryStream    ms = new System.IO.MemoryStream();
                        int len = -1;
                        do
                        {
                            byte[] buff = new byte[1000];
                            len = await stream.ReadAsync(buff, 0, buff.Length);

                            await ms.WriteAsync(buff, 0, len);

                            string line = new string(System.Text.Encoding.UTF8.GetChars(buff, 0, len));
                            if (line.EndsWith("<EOF>"))
                            {
                                break;
                            }
                        } while (len != 0);

                        //string echo=Encoding.UTF8.GetString(buff).Trim('\0');
                        string echo = System.Text.Encoding.UTF8.GetString(ms.ToArray());
                        ms.Close();
                        System.Console.WriteLine(echo);
                        if (echo.Equals("q"))
                        {
                            break;
                        }
                    } // Whend

                    socket.Close();
                } // End Using socket
            }     // Whend
        }         // End Task RunServer