internal static void SetupScope(dynamic Scope, System.Net.Sockets.TcpClient client, Settings Settings, HttpRequestHeader req = null)
        {
            System.Diagnostics.Contracts.Contract.Requires(Settings != null);

            if (client != null && client.Connected && client.Client != null)
            {
                //System.Net.Sockets.TransmitFileOptions.UseSystemThread
                //client.Client.SendFile(,,, System.Net.Sockets.TransmitFileOptions.UseKernelApc)
                Scope.Client = client;
                try { Scope.Stream = client?.GetStream(); }
                catch (Exception exp) {
                    ErrorLogger.WithTrace(Settings, string.Format("[Fatel][Backend error => SetupScope()] : exception-message : {0}.\nstacktrace : {1}\n", exp.Message, exp.StackTrace), typeof(PythonRunner));
                }
                finally
                {
                    Scope.Stream = new System.Net.Sockets.NetworkStream(client.Client); //new System.IO.MemoryStream(new byte[2048], true);
                }
                Scope.SendAsync = new Action <byte[]>(async(bytes) =>
                {
                    try
                    {
                        if (!Scope.Stream.CanWrite)
                        {
                            return;
                        }
                        await Scope.Stream.WriteAsync(bytes);
                        await Scope.Stream?.FlushAsync();

                        if ((bool)Scope.AutoClose)
                        {
                            client.Close();
                        }
                    }
                    catch (Exception exp)
                    {
                        ErrorLogger.WithTrace(Settings, string.Format("[Fatel][Backend error => SendAsync()] : exception-message : {0}.\nstacktrace : {1}\n", exp.Message, exp.StackTrace), typeof(IronPythonObject));
                    }
                });
                Scope.SendTextAsync = new Action <string>(async(text) =>
                {
                    try
                    {
                        if (!Scope.Stream.CanWrite)
                        {
                            return;
                        }
                        await Scope.Stream.WriteAsync(System.Text.Encoding.UTF8.GetBytes(text));
                        await Scope.Stream?.FlushAsync();

                        if ((bool)Scope.AutoClose)
                        {
                            client.Close();
                        }
                    }
                    catch (Exception exp)
                    {
                        ErrorLogger.WithTrace(Settings, string.Format("[Fatel][Backend error => SendTextAsync()] : exception-message : {0}.\nstacktrace : {1}\n", exp.Message, exp.StackTrace), typeof(IronPythonObject));
                    }
                });
                Scope.SendFile = new Action <string, bool>((file, isBigFile) => { client.Client.SendFile(file, null, null, isBigFile ? System.Net.Sockets.TransmitFileOptions.UseSystemThread : System.Net.Sockets.TransmitFileOptions.UseDefaultWorkerThread); });
                Scope.SendText = new Action <string>((text) =>
                {
                    try
                    {
                        if (!Scope.Stream.CanWrite)
                        {
                            return;
                        }
                        Scope.Stream.Write(System.Text.Encoding.UTF8.GetBytes(text));
                        Scope.Stream.Flush();

                        if ((bool)Scope.AutoClose)
                        {
                            client.Close();
                        }
                    }
                    catch (Exception exp)
                    {
                        ErrorLogger.WithTrace(Settings, string.Format("[Fatel][Backend error => SendText()] : exception-message : {0}.\nstacktrace : {1}\n", exp.Message, exp.StackTrace), typeof(IronPythonObject));
                    }
                });
                Scope.Send = new Action <byte[]>(bytes =>
                {
                    try
                    {
                        Scope.Stream.Write(bytes);
                        Scope.Stream.Flush();

                        if ((bool)Scope.AutoClose)
                        {
                            client.Close();
                        }
                    }
                    catch (Exception exp)
                    {
                        ErrorLogger.WithTrace(Settings, string.Format("[Fatel][Backend error => Send()] : exception-message : {0}.\nstacktrace : {1}\n", exp.Message, exp.StackTrace), typeof(IronPythonObject));
                    }
                });
                Scope.ReadAsync = new Action <byte[], int, int>
                                      (async(buffer, offest, length) => await Scope.Stream?.ReadAsync(buffer, offest, length));
                Scope.Read = new Action <byte[], int, int>(
                    (buffer, offest, length) => Scope.Stream?.Read(buffer, offest, length));
                Scope.Close             = new Action(() => client?.Close());
                Scope.IsClientConnected = new Func <bool>(() => client.IsConnected());
                //string address = client.Client.RemoteEndPoint.ToString();
                //Scope.Address = address;
                //Scope.AddressParts = address.Split(':');
            }

            Scope.AutoClose     = false;
            Scope.ReadFileBytes = new Func <string, byte[]>(f => {
                try
                {
                    return(System.IO.File.ReadAllBytes(f));
                }
                catch (Exception exp)
                {
                    ErrorLogger.WithTrace(Settings, string.Format("[Fatel][Backend error => ReadFileBytes()] : exception-message : {0}.\nstacktrace : {1}\n", exp.Message, exp.StackTrace), typeof(IronPythonObject));
                    return(new byte[] { 0 });
                }
            });
            Scope.ReadFileBytesAction = new Action <string, Action <byte[]> >((f, work) => {
                try
                {
                    using System.IO.FileStream stream = new System.IO.FileStream(f, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                    byte[] buffer = new byte[2048];
                    int read      = 0;
                    while ((read = stream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        work?.Invoke(buffer[..read]);
Exemple #2
0
        private static byte[] RunNativeRequestProcessorApp(HttpRequestHeader requestHeader, Settings settings)
        {
            using (System.Diagnostics.Process process = new System.Diagnostics.Process())
            {
                StringBuilder output = new StringBuilder();
                StringBuilder error  = new StringBuilder();

                string serializedString = GenerateSerializedInput(requestHeader);


                process.StartInfo.FileName               = CPYTHON_PATH;
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.Arguments              = $"\"{requestHeader.AbsoluteFilePath}\" \"{serializedString}\"";
                process.StartInfo.RedirectStandardOutput = process.StartInfo.RedirectStandardError = true;
                // Decision made in 31/2/2021 to wrap all input streams
                //                            to pass arguments
                process.StartInfo.RedirectStandardInput = true;

                process.OutputDataReceived += (s, e) =>
                {
                    output.Append(e.Data);
                };
                process.ErrorDataReceived += (s, e) =>
                {
                    error.Append(e.Data);
                };
                process.Start();
                process.StandardInput.WriteLine(serializedString);
                process.StandardInput.Flush();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();



                //process.WaitForExit();
                process.Close();

                //RedirectErrors
                string result = "";
                if (error.Length != 0)
                {
                    if ((bool)settings.Current.RedirectErrors)
                    {
                        result = error.ToString();
                    }
                    else
                    {
                        result = ERR_MESSAGE;
                    }

                    ErrorLogger.WithTrace(settings, string.Format("[Warning][Server error => ProcessPython3Script()] : exception : {0}\n", error.ToString()), typeof(HttpRespondHeader));
                }
                else
                {
                    result = output.ToString();
                }

                byte[] bytes = Encoding.UTF8.GetBytes(result);


                return(bytes);
            }
        }