Example #1
0
        void Connection_PacketReceived(RConnection sender, Packet packet)
        {
            Console.WriteLine("<< {0} {1}", packet.Tick, packet);

            var servername = (sender.Servername != null && sender.Servername.Count() > 0) ? sender.Servername : string.Concat(sender.HostName, ":", sender.Port);

            if (!packet.Message.Contains("OK"))
            {
                var msg = new Message(packet.Message);

                var m = new Event
                {
                    isResponse = packet.IsResponse,
                    Message    = new Message(packet.Message),
                    Origin     = (Int32)packet.Origin,
                    SequenceId = (Int64)packet.SequenceId,
                    ServerName = servername,
                    Tick       = packet.Tick
                };

                skynet.Invoke("SendEvent", Serialize(m)).ContinueWith(task =>
                {
                    if (task.IsFaulted)
                    {
                        Console.WriteLine(">>> {0} {1} {2}", DateTime.Now, "Unable to call remote method send: ", task.Exception.GetBaseException());
                    }
                    else
                    {
                        // Do something here later if everything is successful
                        //Console.WriteLine(task.IsCompleted);
                    }
                });
            }
        }
        /// <summary>
        /// Executes the program
        /// </summary>
        /// <param name="args">The arguments.</param>
        public static void Main( string[] args )
        {
            using ( var s = new RConnection( new System.Net.IPAddress( new byte[] { 127 , 0 , 0 , 1 } ) ) )
            {
                // Generate some example data
                var x = Enumerable.Range( 1 , 20 ).ToArray();
                var y = ( from a in x select ( 0.5 * a * a ) + 2 ).ToArray();

                // Build an R data frame
                var d = Sexp.MakeDataFrame();
                d[ "x" ] = Sexp.Make( x );
                d[ "y" ] = Sexp.Make( y );
                s[ "d" ] = d;

                // Run a linear regression, obtain the summary, and print the result
                s.VoidEval( "linearModelSummary = summary(lm(y ~ x, d))" );
                var coefs = s[ "linearModelSummary$coefficients" ];
                var rSquared = s[ "linearModelSummary$r.squared" ].AsDouble;
                Console.WriteLine( "y = {0} x + {1}. R^2 = {2,4:F}%" , coefs[ 1 , 0 ] , coefs[ 0 , 0 ] , rSquared * 100 );

                // Now let's do some linear algebra
                var matA = new double[ , ] { { 14 , 9 , 3 } , { 2 , 11 , 15 } , { 0 , 12 , 17 } , { 5 , 2 , 3 } };
                var matB = new double[ , ] { { 12 , 25 } , { 9 , 10 } , { 8 , 5 } };
                s[ "a" ] = Sexp.Make( matA );
                s[ "b" ] = Sexp.Make( matB );
                Console.WriteLine( s[ "a %*% b" ].ToString() );
            }
            Console.WriteLine( "Done" );
        }
Example #3
0
        private void ReConnect(RConnection sender, int tries = 5, int wait = 10000)
        {
            var numberOfTime = 0;

            while (!sender.Client.Connected)
            {
                try
                {
                    Console.WriteLine("{0} {1}", DateTime.Now, "[INFO] Trying reconnect to game server");
                    Initialize();
                }
                catch (SocketException s)
                {
                    Console.WriteLine("{0} {1}", DateTime.Now, "[WARNING] Unable to connect, will try to reconnect in 10seconds");
                    Thread.Sleep(wait);

                    if (numberOfTime == tries)
                    {
                        Console.WriteLine("{0} {1}", DateTime.Now, "[WARNING] Reached the maximum number of tries, will no longer try to reconnect");

                        // TODO: Add more logic for sending this information to the hub and inform master
                        break;
                    }
                    else
                    {
                        numberOfTime++;
                        continue;
                    }
                }
            }
        }
Example #4
0
        /// <summary>
        /// Executes the program
        /// </summary>
        /// <param name="args">The arguments.</param>
        public static void Main(string[] args)
        {
            using (var s = new RConnection(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 })))
            {
                // Generate some example data
                var x = Enumerable.Range(1, 20).ToArray();
                var y = (from a in x select(0.5 * a * a) + 2).ToArray();

                // Build an R data frame
                var d = Sexp.MakeDataFrame();
                d["x"] = Sexp.Make(x);
                d["y"] = Sexp.Make(y);
                s["d"] = d;

                // Run a linear regression, obtain the summary, and print the result
                s.VoidEval("linearModelSummary = summary(lm(y ~ x, d))");
                var coefs    = s["linearModelSummary$coefficients"];
                var rSquared = s["linearModelSummary$r.squared"].AsDouble;
                Console.WriteLine("y = {0} x + {1}. R^2 = {2,4:F}%", coefs[1, 0], coefs[0, 0], rSquared * 100);

                // Now let's do some linear algebra
                var matA = new double[, ] {
                    { 14, 9, 3 }, { 2, 11, 15 }, { 0, 12, 17 }, { 5, 2, 3 }
                };
                var matB = new double[, ] {
                    { 12, 25 }, { 9, 10 }, { 8, 5 }
                };
                s["a"] = Sexp.Make(matA);
                s["b"] = Sexp.Make(matB);
                Console.WriteLine(s["a %*% b"].ToString());
            }
            Console.WriteLine("Done");
        }
Example #5
0
        void Connection_Error(RConnection sender, Exception e)
        {
            Console.WriteLine("{0} {1}", DateTime.Now, "[ERROR] An error occured!");
            Console.WriteLine("Exception: {0}", e.Message);

            ReConnect(sender);
        }
Example #6
0
 void Connection_PacketSent(RConnection sender, Packet packet)
 {
     if (!packet.Message.Contains("OK"))
     {
         Console.WriteLine(">> {0} {1}", packet.Tick, packet);
     }
 }
        private void ReConnectToRserve()
        {
            while (RserveToken != null && !RserveToken.IsCancellationRequested)
            {
                try
                {
                    if (Connection == null)
                    {
                        string userLogString = "empty user";
                        if (Parameter.Credentials != null)
                        {
                            userLogString = Parameter.User;
                        }

                        RConnection con = null;
                        if (Parameter.UseIpAddress)
                        {
                            con = RConnection.Connect(Parameter.IpAddress, Parameter.Port, Parameter.Credentials);
                            logger.Info($"Connected to RServe {Parameter.IpAddress}:{Parameter.Port} with user ({userLogString})");
                        }
                        else
                        {
                            con = RConnection.Connect(Parameter.Hostname, Parameter.Port, Parameter.Credentials);
                            logger.Info($"Connected to RServe {Parameter.Hostname}:{Parameter.Port} with user ({userLogString})");
                        }
                        Thread.Sleep(150);

                        //Load Workspace
                        if (!String.IsNullOrWhiteSpace(Parameter.InitScript))
                        {
                            logger.Debug("Sending InitScript to Rserve...");
                            con.Eval(Parameter.InitScript);
                            logger.Debug("...InitScript done");
                        }
                        Connection = con;
                    }

                    if (!Connection.IsConnected())
                    {
                        Connection = null;
                    }
                }
                catch (SocketException ex)
                {
                    logger.Error($"Reconnect to Rserve failed (Socket error): {ex.Message}");
                    Connection = null;
                }
                catch (Exception ex)
                {
                    logger.Error($"Reconnect to Rserve failed: {ex.Message}");
                    Connection = null;
                }
                finally
                {
                    Thread.Sleep(5000);
                }
            }
        }
        public static bool IsConnected(this RConnection rconnection)
        {
            if (fi_socket == null)
            {
                fi_socket = typeof(RConnection).GetField("_socket", BindingFlags.NonPublic | BindingFlags.Instance);
            }

            return((fi_socket.GetValue(rconnection) as Socket)?.Connected ?? false);
        }
Example #9
0
 private void close()
 {
     if (this.client != null && this.connection != null && !this.client.IsClosed())
     {
         this.client.Execute(c => c.closeConnection(this.connection));
         this.client     = null;
         this.connection = null;
     }
 }
Example #10
0
 /// <summary>
 /// Reads a specified file using an RConnection
 /// </summary>
 private static byte[] ReadFile(RConnection connection, string fileName)
 {
     using (var ist = connection.ReadFile(fileName))
     {
         var checkstream = new System.IO.MemoryStream();
         ist.CopyTo(checkstream);
         var checkbytes = checkstream.ToArray();
         return(checkbytes);
     }
 }
Example #11
0
        public RConnection AddConnection(RNode src, RNode dst, bool isOneWay, bool isOnlyFoot)
        {
            RConnection C = new RConnection(__MaxArcID, src, dst, isOneWay, isOnlyFoot);

            src.Connections.Add(C);
            Connections.Add(__MaxArcID, C);
            RConnections.Add(__MaxArcID, C);
            ++(__MaxArcID);
            return(C);
        }
Example #12
0
        public RedisConnection(string ipPort, bool debugMode = false)
        {
            var address = ipPort.GetIPPort();

            _cnn            = new RConnection(102400, address.Item1, address.Item2);
            _cnn.OnActived += _cnn_OnActived;
            _cnn.OnMessage += _cnn_OnMessage;
            _redisCoder     = new RedisCoder();
            _debugMode      = debugMode;
        }
 /// <summary>
 /// Reads a specified file using an RConnection
 /// </summary>
 private static byte[] ReadFile( RConnection connection , string fileName )
 {
     using ( var ist = connection.ReadFile( fileName ) )
     {
         var checkstream = new System.IO.MemoryStream();
         ist.CopyTo( checkstream );
         var checkbytes = checkstream.ToArray();
         return checkbytes;
     }
 }
 /// <summary>
 /// Create a file with random data and transfer a file to R
 /// </summary>
 /// <param name="fileName">The name of the file</param>
 /// <param name="connection">The RConnection</param>
 /// <param name="length">The length of the file to be transferred.</param>
 private static byte[] CreateAndTransferFile( RConnection connection , string fileName , int length )
 {
     var data = new byte[ length ];
     var rnd = new Random( 2302 );
     rnd.NextBytes( data );
     using ( var os = new System.IO.MemoryStream( data ) )
     {
         connection.WriteFile( fileName , os );
     }
     return data;
 }
Example #15
0
        /// <summary>
        /// Create a file with random data and transfer a file to R
        /// </summary>
        /// <param name="fileName">The name of the file</param>
        /// <param name="connection">The RConnection</param>
        /// <param name="length">The length of the file to be transferred.</param>
        private static byte[] CreateAndTransferFile(RConnection connection, string fileName, int length)
        {
            var data = new byte[length];
            var rnd  = new Random(2302);

            rnd.NextBytes(data);
            using (var os = new System.IO.MemoryStream(data))
            {
                connection.WriteFile(fileName, os);
            }
            return(data);
        }
        private static void Run(RConnection c)
        {
            string filePath = "C:/Users/DarkBlue/Google Drive/onlinedatalab/source/dummy data.csv";
            string scriptPath = @"C:\OnlineDataLab\Scripts\input.R";
            REngine.RunScript(c, scriptPath);
            Sexp r = c.TryEval(string.Format("processInput(\"{0}\")", filePath));
            Console.WriteLine(r.AsDictionary);
            //var x = c.Eval("R.version.string");
            //Console.WriteLine(x.AsString);

            //Task.Factory.StartNew(() =>
            //{
            //    //using (var s1 = RConnection.Connect(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 })))
            //    //{
            //    string filePath = "C:/Users/DarkBlue/Google Drive/onlinedatalab/source/dummy data.csv";
            //    string scriptPath = @"C:\OnlineDataLab\Scripts\input.R";
            //    c.TryVoidEval(File.ReadAllText(scriptPath));
            //    c.TryVoidEval("processInput <- function(inputFilePath){ uploaddata < -read.csv(inputFilePath);outputdata < -toJSON(uploaddata[1:20,]);allchoices < -names(uploaddata);return (list(\"uploaddata\" = uploaddata, \"outputdata\" = outputdata, \"allchoices\" = allchoices));}");
            //    //c.VoidEval(string.Format("uploaddata <- read.csv(\"{0}\")", filePath));
            //    var data = c.Eval("test()");
            //    Console.WriteLine(data.AsList);
            //    //s1.Shutdown();
            //    //}
            //}).Wait();

            //using (var s = RConnection.Connect(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 })))
            //{
            //    // Generate some example data
            //    var x = Enumerable.Range(1, 20).ToArray();
            //    var y = (from a in x select (0.5 * a * a) + 2).ToArray();

            //    // Build an R data frame
            //    var d = Sexp.MakeDataFrame();
            //    d["x"] = Sexp.Make(x);
            //    d["y"] = Sexp.Make(y);
            //    s["d"] = d;

            //    // Run a linear regression, obtain the summary, and print the result
            //    s.VoidEval("linearModelSummary = summary(lm(y ~ x, d))");
            //    var coefs = s["linearModelSummary$coefficients"];
            //    var rSquared = s["linearModelSummary$r.squared"].AsDouble;
            //    Console.WriteLine("y = {0} x + {1}. R^2 = {2,4:F}%", coefs[1, 0], coefs[0, 0], rSquared * 100);

            //    // Now let's do some linear algebra
            //    var matA = new double[,] { { 14, 9, 3 }, { 2, 11, 15 }, { 0, 12, 17 }, { 5, 2, 3 } };
            //    var matB = new double[,] { { 12, 25 }, { 9, 10 }, { 8, 5 } };
            //    s["a"] = Sexp.Make(matA);
            //    s["b"] = Sexp.Make(matB);
            //    Console.WriteLine(s["a %*% b"].ToString());
            //}
        }
Example #17
0
        /// <summary>
        /// Executes the program
        /// </summary>
        /// <param name="args">The arguments.</param>
        public static void Main(string[] args)
        {
            using (var s = new RConnection(new System.Net.IPAddress(new byte[] { 192, 168, 37, 10 }), port: 6311, user: "******", password: "******"))
            {
                // Generate some example data
                var x = Enumerable.Range(1, 20).ToArray();
                var y = (from a in x select(0.5 * a * a) + 2).ToArray();

                // Build an R data frame
                var d = Sexp.MakeDataFrame();
                d["x"] = Sexp.Make(x);
                d["y"] = Sexp.Make(y);
                s["d"] = d;

                // Run a linear regression, obtain the summary, and print the result
                var linearModelSummary = s["summary(lm(y ~ x, d))"];
                Console.WriteLine(linearModelSummary.Count);
                var coefs    = linearModelSummary["coefficients"];
                var rSquared = ( double )linearModelSummary["r.squared"];
                Console.WriteLine("y = {0} x + {1}. R^2 = {2,4:F}%", coefs[1, 0], coefs[0, 0], rSquared * 100);

                // Make a chart and transfer it to the local machine
                s.VoidEval("library(ggplot2)");
                s.VoidEval("pdf(\"outfile.pdf\")");
                s.VoidEval("print(qplot(x,y, data=d))");
                s.VoidEval("dev.off()");

                using (var f = File.Create("Data Plot.pdf"))
                {
                    s.ReadFile("outfile.pdf").CopyTo(f);
                }

                s.RemoveFile("outfile.pdf");

                // Now let's do some linear algebra
                var matA = new double[, ] {
                    { 14, 9, 3 }, { 2, 11, 15 }, { 0, 12, 17 }, { 5, 2, 3 }
                };
                var matB = new double[, ] {
                    { 12, 25 }, { 9, 10 }, { 8, 5 }
                };
                s["a"] = Sexp.Make(matA);
                s["b"] = Sexp.Make(matB);
                Console.WriteLine(s["a %*% b"].ToString());
            }

            Console.WriteLine("Done");
        }
Example #18
0
        private void Initialize(CreateInstance instance = null)
        {
            Connection        = new RConnection();
            this.InstanceName = string.Concat(this.Host, ":", this.Port);

            Connection.HostName          = this.Host;
            Connection.Port              = (ushort)this.Port;
            Connection.PlaintextPassword = this.Password;

            Connection.Connected      += Connection_Connected;
            Connection.Error          += Connection_Error;
            Connection.Disconnected   += Connection_Disconnected;
            Connection.PacketReceived += Connection_PacketReceived;
            Connection.PacketSent     += Connection_PacketSent;

            RunClient();
        }
Example #19
0
        /// <summary>
        /// Executes the program
        /// </summary>
        /// <param name="args">The arguments.</param>
        public static void Main( string[] args )
        {
            using ( var s = new RConnection( new System.Net.IPAddress( new byte[] { 192 , 168 , 37 , 10 } ) , port: 6311 , user: "******" , password: "******" ) )
            {
                // Generate some example data
                var x = Enumerable.Range( 1 , 20 ).ToArray();
                var y = ( from a in x select ( 0.5 * a * a ) + 2 ).ToArray();

                // Build an R data frame
                var d = Sexp.MakeDataFrame();
                d[ "x" ] = Sexp.Make( x );
                d[ "y" ] = Sexp.Make( y );
                s[ "d" ] = d;

                // Run a linear regression, obtain the summary, and print the result
                var linearModelSummary = s[ "summary(lm(y ~ x, d))" ];
                Console.WriteLine( linearModelSummary.Count );
                var coefs = linearModelSummary[ "coefficients" ];
                var rSquared = ( double )linearModelSummary[ "r.squared" ];
                Console.WriteLine( "y = {0} x + {1}. R^2 = {2,4:F}%" , coefs[ 1 , 0 ] , coefs[ 0 , 0 ] , rSquared * 100 );

                // Make a chart and transfer it to the local machine
                s.VoidEval( "library(ggplot2)" );
                s.VoidEval( "pdf(\"outfile.pdf\")" );
                s.VoidEval( "print(qplot(x,y, data=d))" );
                s.VoidEval( "dev.off()" );

                using ( var f = File.Create( "Data Plot.pdf" ) )
                {
                    s.ReadFile( "outfile.pdf" ).CopyTo( f );
                }

                s.RemoveFile( "outfile.pdf" );

                // Now let's do some linear algebra
                var matA = new double[ , ] { { 14 , 9 , 3 } , { 2 , 11 , 15 } , { 0 , 12 , 17 } , { 5 , 2 , 3 } };
                var matB = new double[ , ] { { 12 , 25 } , { 9 , 10 } , { 8 , 5 } };
                s[ "a" ] = Sexp.Make( matA );
                s[ "b" ] = Sexp.Make( matB );
                Console.WriteLine( s[ "a %*% b" ].ToString() );
            }

            Console.WriteLine( "Done" );
        }
Example #20
0
        private void CheckConnectivity()
        {
            List <RNode> Nodes = MatchingSolution.Where(x => x != null).ToList();
            List <Tuple <RNode, RNode> > Cuts = new List <Tuple <RNode, RNode> >();

            RNode u = null, v = null; RConnection C = null;

            for (int i = 0; i < Nodes.Count - 1; ++i)
            {
                u = Nodes[i]; v = Nodes[i + 1];
                C = RoadNetwork.AreConnected(u, v);
                if (C == null)
                {
                    Cuts.Add(new Tuple <RNode, RNode>(u, v));
                }
            }
            //
            foreach (Tuple <RNode, RNode> T in Cuts)
            {
                u = T.Item1; v = T.Item2;

                Node Source = RoadNetwork.ResolvePoint(u.Point, 0.1f).First();
                Node Target = RoadNetwork.ResolvePoint(v.Point, 0.1f).First();

                Router router = new Router(Source, Target, string.Empty, 0, TravelMode.Car, ObjFunction.Distance);
                router.Start();

                List <RNode> route = new List <RNode>();
                foreach (Connection conn in router.Solution)
                {
                    route.Add((RNode)conn.GetDestination());
                }
                route.RemoveAll(x => x == u || x == v);
                RNode prev = u, next = null;
                for (int i = 0; i < route.Count; ++i)
                {
                    next = route[i];
                    MatchingSolution.AddAfter(MatchingSolution.Find(prev), next);
                    prev = next;
                }
            }
        }
Example #21
0
        /// <summary>
        /// Creates a self-hosted Rserve.
        /// </summary>
        /// <param name="showWindow">If true then the Rserve window will be visible.  Useful for debugging.  Default is false.</param>
        /// <param name="maxInputBufferSizeInKb">The maximal allowable size of the input buffer in kilobytes.  That is, the maximal size of data transported from the client to the server.</param>
        public Rservice(bool showWindow = false, int maxInputBufferSizeInKb = 0)
        {
            // ReSharper disable AssignNullToNotNullAttribute
#if RTERM_PROCESS
            var    codeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
            var    is64BitOperatingSystem = Environment.Is64BitOperatingSystem;
            string assemblyDir            = new Uri(Path.GetDirectoryName(codeBase)).AbsolutePath;
            // ReSharper restore AssignNullToNotNullAttribute
            string rExeFilePath = Path.Combine(assemblyDir, "R-2.15.3", "bin", is64BitOperatingSystem ? "x64" : "i386", "Rterm.exe");

            // the only way to set maxinbuf is via configuration file
            // generate a config file and reference it as part of the args parameter to Rserve() below
            string args = "";
            if (maxInputBufferSizeInKb > 0)
            {
                string configFile = Path.GetTempFileName();
                // plaintext warning only shows when using a config file.  setting plaintext enable to eliminate the warning
                File.WriteAllText(configFile, "maxinbuf " + maxInputBufferSizeInKb + "\r\n" + "plaintext enable");
                args = string.Format(", args = '--RS-conf {0}' ", configFile.Replace(@"\", "/"));
            }

            // launch RTerm and tell it load Rserve.
            // Keep RTerm open, otherwise the child process will be killed.
            // We will use CmdShutdown to stop the server
            // ReSharper disable UseObjectOrCollectionInitializer
            _rtermProcess = new Process();
            _rtermProcess.StartInfo.FileName        = rExeFilePath;
            _rtermProcess.StartInfo.Arguments       = string.Format("--no-site-file --no-init-file --no-save -e \"library( Rserve ); Rserve( port = {0} , wait = TRUE {1});\"", Port, args);
            _rtermProcess.StartInfo.UseShellExecute = false;
            _rtermProcess.StartInfo.CreateNoWindow  = !showWindow;
            _rtermProcess.Start();
            Thread.Sleep(3000);
            // ReSharper restore UseObjectOrCollectionInitializer
#endif
            string hostname = "localhost";

            // create a connection to the server
            // ReSharper disable RedundantArgumentDefaultValue
            RConnection = RConnection.Connect(port: Port, hostname: hostname);
            // ReSharper restore RedundantArgumentDefaultValue
        }
Example #22
0
        private static Boolean SendMessage(Server server, String message)
        {
            var con = new RConnection();

            con.HostName          = server.Host;
            con.Port              = (ushort)server.Port;
            con.PlaintextPassword = server.Password;

            con.Connect();

            while (!con.Client.Connected)
            {
                System.Threading.Thread.Sleep(200);
            }
            con.Login();
            con.Command("admin.say", message, "all");
            System.Threading.Thread.Sleep(200);
            con.Shutdown();

            return(true);
        }
Example #23
0
        /// <summary>
        /// Creates a self-hosted Rserve.
        /// </summary>
        /// <param name="showWindow">If true then the Rserve window will be visible.  Useful for debugging.  Default is false.</param>
        /// <param name="maxInputBufferSizeInKb">The maximal allowable size of the input buffer in kilobytes.  That is, the maximal size of data transported from the client to the server.</param>
        public Rservice(bool showWindow = false, int maxInputBufferSizeInKb = 0)
        {
            // ReSharper disable AssignNullToNotNullAttribute
            string assemblyDir = new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath;
            // ReSharper restore AssignNullToNotNullAttribute
            string rExeFilePath = Path.Combine(assemblyDir, "R-2.15.3", "bin", "x64", "Rterm.exe");

            // the only way to set maxinbuf is via configuration file
            // generate a config file and reference it as part of the args parameter to Rserve() below
            string args = "";

            if (maxInputBufferSizeInKb > 0)
            {
                string configFile = Path.GetTempFileName();
                // plaintext warning only shows when using a config file.  setting plaintext enable to eliminate the warning
                File.WriteAllText(configFile, "maxinbuf " + maxInputBufferSizeInKb + "\r\n" + "plaintext enable");
                args = string.Format(", args = '--RS-conf {0}' ", configFile.Replace(@"\", "/"));
            }

            // launch RTerm and tell it load Rserve, tell it wait until RServe has completed.  We want RTerm to stay open because
            // our only strategy for finding/killing RServe is to search RTerm's child processes.  If wait = FALSE then RTerm completes
            // but RServe does not die
            // ReSharper disable UseObjectOrCollectionInitializer
            _rtermProcess = new Process();
            _rtermProcess.StartInfo.FileName        = rExeFilePath;
            _rtermProcess.StartInfo.Arguments       = string.Format("-e \"library( Rserve ); Rserve( port = {0} , wait = TRUE {1});\"", Port, args);
            _rtermProcess.StartInfo.UseShellExecute = false;
            _rtermProcess.StartInfo.CreateNoWindow  = !showWindow;
            _rtermProcess.Start();
            Thread.Sleep(3000);
            // ReSharper restore UseObjectOrCollectionInitializer

            // create a connection to the server
            // ReSharper disable RedundantArgumentDefaultValue
            RConnection = new RConnection(port: Port);
            // ReSharper restore RedundantArgumentDefaultValue
        }
Example #24
0
        private bool _disposed; // to detect redundant calls

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Creates a self-hosted Rserve.
        /// </summary>
        /// <param name="showWindow">If true then the Rserve window will be visible.  Useful for debugging.  Default is false.</param>
        /// <param name="maxInputBufferSizeInKb">The maximal allowable size of the input buffer in kilobytes.  That is, the maximal size of data transported from the client to the server.</param>
        public Rservice( bool showWindow = false , int maxInputBufferSizeInKb = 0 )
        {
            // ReSharper disable AssignNullToNotNullAttribute
            string assemblyDir = new Uri( Path.GetDirectoryName( Assembly.GetExecutingAssembly().CodeBase ) ).AbsolutePath;
            // ReSharper restore AssignNullToNotNullAttribute
            string rExeFilePath = Path.Combine( assemblyDir , "R-2.15.3" , "bin" , "x64" , "Rterm.exe" );

            // the only way to set maxinbuf is via configuration file
            // generate a config file and reference it as part of the args parameter to Rserve() below
            string args = "";
            if ( maxInputBufferSizeInKb > 0 )
            {
                string configFile = Path.GetTempFileName();
                // plaintext warning only shows when using a config file.  setting plaintext enable to eliminate the warning
                File.WriteAllText( configFile , "maxinbuf " + maxInputBufferSizeInKb + "\r\n" + "plaintext enable" );
                args = string.Format( ", args = '--RS-conf {0}' " , configFile.Replace( @"\" , "/" ) );
            }

            // launch RTerm and tell it load Rserve, tell it wait until RServe has completed.  We want RTerm to stay open because
            // our only strategy for finding/killing RServe is to search RTerm's child processes.  If wait = FALSE then RTerm completes
            // but RServe does not die
            // ReSharper disable UseObjectOrCollectionInitializer
            _rtermProcess = new Process();
            _rtermProcess.StartInfo.FileName = rExeFilePath;
            _rtermProcess.StartInfo.Arguments = string.Format( "-e \"library( Rserve ); Rserve( port = {0} , wait = TRUE {1});\"" , Port , args );
            _rtermProcess.StartInfo.UseShellExecute = false;
            _rtermProcess.StartInfo.CreateNoWindow = !showWindow;
            _rtermProcess.Start();
            Thread.Sleep( 3000 );
            // ReSharper restore UseObjectOrCollectionInitializer

            // create a connection to the server
            // ReSharper disable RedundantArgumentDefaultValue
            RConnection = new RConnection( port: Port );
            // ReSharper restore RedundantArgumentDefaultValue
        }
 public static void RunScript(RConnection c, string scriptPath)
 {
     try
     {
         string script = File.ReadAllText(scriptPath);
         script = script.Replace("\r\n", "\r");
         c.TryVoidEval(script);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
Example #26
0
 void Connection_Connected(RConnection sender)
 {
     Console.WriteLine("{0} {1}", DateTime.Now, "Node is now connected to game server");
     sender.Login();
     sender.EnableEvents();
 }
 public RServeClient(string servername)
 {
     _rconnection = RConnection.Connect(servername);
 }
Example #28
0
 internal DBConnection(AbstractJDBCClient client, RConnection connection)
 {
     this.client     = client;
     this.connection = connection;
 }
Example #29
0
        void Connection_Disconnected(RConnection sender)
        {
            Console.WriteLine("{0} {1}", DateTime.Now, "[INFO] Node has been disconnected from game server");

            ReConnect(sender, 100);
        }
        /// Try to get a real error message and stack trace; if that fails rethrow the original exception.
        private static void GetAndThrowRealError(RConnection conn, RserveException ex)
        {
            // Try to get the error message
            String msg;
            try
            {
                msg = conn.Eval("geterrmessage()").AsString;
            }
            catch
            {
                throw ex;
            }

            if (String.IsNullOrWhiteSpace(msg))
                throw ex;

            // Try to get the stack trace
            // It's possible that geterrmessage() succeeds and traceback() fails.
            // If so just use the error message
            try
            {
                var tracebacks = conn.Eval("traceback()").AsStrings;
                var traceback = String.Join("\r\n", tracebacks);
            #if DEBUG
                msg = msg + traceback;
            #endif
            }
            catch
            {
            }

            // Throw with a helpful message
            throw new RserveException(msg);
        }