Example #1
0
        public void RunClient(IPAddress endPoint, int port, int name)//==>TODO#8 Extract into separate class
        {
            var client = new TcpQbservableClient <string>(endPoint, port);

            var query =
                (from value in client.Query()
                 select value);

            //==>TODO#8 move code to separate handlers
            //Handle messages published by this certain agent
            //==>TODO#5 Extract messeges to logger
            using (query.Subscribe(
                       value => {
                var messsege = JsonSerializer.Deserialize <TCPMesssege>(value);

                Logger.PrintReceivedMessage(_agentId, messsege, name);
                SaveAgentPosition(_agentId, messsege.CurrentAgentPosition);  //Handle recieved info published by other agents
            },
                       ex => Console.WriteLine("Error In agent #{1} in client #{2}: {0}", ex.Message, _agentId, name),
                       () => Console.WriteLine("In agent #{0} client #{1} completed", _agentId, name)))
            {
                Console.WriteLine("Agent #{0} client #{1} started.  Waiting for basic service notifications...", _agentId, name);
                Console.ReadKey(intercept: true); //DO NOT REMOVE it. leads to ProtocolNegotiationError
            }
        }
        private void OnControlLoaded()
        {
            var client = new TcpQbservableClient <string>(new IPEndPoint(IPAddress.Loopback, 3205));

            var query = from value in client.Query() select value;

            this.clientDisposable = query.Subscribe(
                value => OnParseMessageAsync(value),
                ex => this.Message = ex.Message,
                () => this.Message = "Completed");
        }
Example #3
0
        static void Main(string[] args)
        {
            var client = new TcpQbservableClient <long>(new IPEndPoint(IPAddress.Loopback, 3205));

            //thie expression tree filtering will happen server side
            //THAT IS AWESOME
            IQbservable <string> query =
                from value in client.Query()
                where value <= 5 || value >= 8
                select string.Format("The incoming value has been doubled to {0}", value * 2);

            using (query.Subscribe(
                       value => Console.WriteLine("Client observed: " + value),
                       ex => Console.WriteLine("Error: {0}", ex.Message),
                       () => Console.WriteLine("Completed")))
            {
                Console.ReadKey();
            }
        }
Example #4
0
        public void Run()
        {
            Console.WriteLine();
            Console.WriteLine("Feed aggregation client starting...");

            var feedAggregatorServiceArgs = new List <FeedServiceArgument>()
            {
                new FeedServiceArgument()
                {
                    IsAtom = false, Url = new Uri("http://rss.cnn.com/rss/cnn_topstories.rss")
                },
                new FeedServiceArgument()
                {
                    IsAtom = false, Url = new Uri("http://blogs.msdn.com/b/rxteam/rss.aspx")
                },
                new FeedServiceArgument()
                {
                    IsAtom = true, Url = new Uri("http://social.msdn.microsoft.com/Forums/en-US/rx/threads?outputAs=atom")
                }
            };

            var client = new TcpQbservableClient <FeedItem>(Program.AdvancedServiceEndPoint, typeof(FeedItem));

            IQbservable <FeedItem> query =
                (from item in client.Query(feedAggregatorServiceArgs)
                 where item.PublishDate >= DateTimeOffset.UtcNow.AddHours(-DateTimeOffset.UtcNow.TimeOfDay.TotalHours)
                 select item)
                .Do(value => Console.WriteLine("{0} pushing value: {1}", Assembly.GetEntryAssembly().EntryPoint.DeclaringType.Namespace, value.Title));

            using (query.Subscribe(
                       value => ConsoleTrace.WriteLine(ConsoleColor.Green, "Feed client observed: ({0}) {1}", value.FeedUrl.Host, value.Title),
                       ex => ConsoleTrace.WriteLine(ConsoleColor.Red, "Feed client error: {0}", ex.Message),
                       () => ConsoleTrace.WriteLine(ConsoleColor.DarkCyan, "Feed client completed")))
            {
                Console.WriteLine();
                Console.WriteLine("Feed client started.  Waiting for advanced service notifications...");
                Console.WriteLine();
                Console.WriteLine("(Press any key to continue)");
                Console.WriteLine();

                Console.ReadKey(intercept: true);
            }
        }
Example #5
0
        public void Run()
        {
            Console.WriteLine();
            Console.WriteLine("Advanced client starting...");
            Console.WriteLine();

            var suffix               = ")";
            var localObj             = new LocalObject();
            var localTransferableObj = new SharedLibrary.TransferableObject(100);

            var client = new TcpQbservableClient <long>(Program.BasicServiceEndPoint, typeof(SharedLibrary.TransferableObject));

            IQbservable <string> query =
                (from value in client.Query()
                 let r = new TransferableObject(42)
                         let numberBase = new { Remote = r.Value, Local = localTransferableObj.Value }
                 from n in Observable.Range(1, 5)
                 let number = (value + 1) * n
                              where number % 2 == 0
                              let result = numberBase.Remote + numberBase.Local + number
                                           let prefix = LocalStaticMethod(localObj.LocalInstanceMethod()) + localObj.LocalInstanceProperty
                                                        let list = (from i in LocalIterator()
                                                                    select i * 2)
                                                                   .Aggregate("", (acc, cur) => acc + cur + ",", acc => acc.Substring(0, acc.Length - 1))
                                                                   select prefix + result + ", [" + list + "]" + suffix)
                .Take(16)
                .Do(value => Console.WriteLine("{0} pushing value: {1}", Assembly.GetEntryAssembly().EntryPoint.DeclaringType.Namespace, value));

            using (query.Subscribe(
                       value => ConsoleTrace.WriteLine(ConsoleColor.Green, "Advanced client observed: {0}", value),
                       ex => ConsoleTrace.WriteLine(ConsoleColor.Red, "Advanced client error: {0}", ex.Message),
                       () => ConsoleTrace.WriteLine(ConsoleColor.DarkCyan, "Advanced client completed")))
            {
                Console.WriteLine();
                Console.WriteLine("Advanced client started.  Waiting for basic service notifications...");
                Console.WriteLine();
                Console.WriteLine("(Press any key to continue)");
                Console.WriteLine();

                Console.ReadKey(intercept: true);
            }
        }
Example #6
0
        public void Run()
        {
            Console.WriteLine();
            Console.WriteLine("Duplex client starting...");

            var trace = new TraceSource("Custom", SourceLevels.All);

            trace.Listeners.Add(new AbbreviatedConsoleTraceListener());

            var suffix          = ")";
            var localObj        = new LocalObject();
            var localObservable = Observable
                                  .Interval(TimeSpan.FromSeconds(2))
                                  .Take(2)
                                  .Do(value => trace.TraceInformation("localObservable: {0}", value));

            var client = new TcpQbservableClient <long>(Program.BasicServiceEndPoint, new DuplexLocalEvaluator());

            IQbservable <string> query =
                (from serviceValue in client.Query()
                 let prefix = LocalStaticMethod(localObj.LocalInstanceMethod()) + localObj.LocalInstanceProperty
                              from clientValue in localObservable
                              .Do(value => Console.WriteLine("{0} received value: {1}", Assembly.GetEntryAssembly().EntryPoint.DeclaringType.Namespace, value))
                              from random in LocalIterator()
                              select prefix + clientValue + "/" + serviceValue + ", R=" + random + suffix)
                .Take(21)
                .Do(value => Console.WriteLine("{0} pushing value: {1}", Assembly.GetEntryAssembly().EntryPoint.DeclaringType.Namespace, value));

            using (query.Subscribe(
                       value => ConsoleTrace.WriteLine(ConsoleColor.Green, "Duplex client observed: {0}", value),
                       ex => ConsoleTrace.WriteLine(ConsoleColor.Red, "Duplex client error: {0}", ex.Message),
                       () => ConsoleTrace.WriteLine(ConsoleColor.DarkCyan, "Duplex client completed")))
            {
                Console.WriteLine();
                Console.WriteLine("Duplex client started.  Waiting for basic service notifications...");
                Console.WriteLine();
                Console.WriteLine("(Press any key to continue)");
                Console.WriteLine();

                Console.ReadKey(intercept: true);
            }
        }
Example #7
0
        public void Run()
        {
            var client = new TcpQbservableClient <ChatServiceHooks>(Program.ChatServiceEndPoint);

            Console.WriteLine();
            Console.Write("Enter your user name> ");

            string userName = Console.ReadLine();

            Console.Write("Enter names to ignore separated by commas> ");

            var userNamesToIgnore = Console.ReadLine().Split(',').Select(name => name.Trim() + ' ');

            var myMessages = new Subject <string>();

            IObservable <string> outgoingMessages = myMessages;

            IQbservable <string> query =
                (from hooks in client.Query(userName)
                 .Do(hooks => outgoingMessages.Subscribe(hooks.IncomingMessages))
                 from message in hooks.OutgoingMessages
                 where !userNamesToIgnore.Any(message.StartsWith)
                 select message);

            using (query.Subscribe(
                       message => ConsoleTrace.WriteLine(ConsoleColor.Green, message),
                       ex => ConsoleTrace.WriteLine(ConsoleColor.Red, "Chat client error: " + ex.Message),
                       () => ConsoleTrace.WriteLine(ConsoleColor.DarkCyan, "Chat client completed")))
            {
                Console.WriteLine();
                Console.WriteLine("Chat client started.  You may begin entering messages...");
                Console.WriteLine();
                Console.WriteLine("(Enter a blank line to stop)");
                Console.WriteLine();

                string message;
                while ((message = Console.ReadLine()).Length > 0)
                {
                    myMessages.OnNext(message);
                }
            }
        }
Example #8
0
        public void Run()
        {
            var client = new TcpQbservableClient <long>(Program.TimerServiceEndPoint);

            IQbservable <int> query =
                (from value in client.Query(TimeSpan.FromSeconds(1))
                 from page in new WebClient().DownloadStringTaskAsync(new Uri("http://blogs.msdn.com/b/rxteam"))
                 select page.Length)
                .Do(result => Console.WriteLine("Where am I?  Result = " + result));

            using (query.Subscribe(
                       value => ConsoleTrace.WriteLine(ConsoleColor.Green, "Timer client observed: " + value),
                       ex => ConsoleTrace.WriteLine(ConsoleColor.Red, "Timer client error: " + ex.Message),
                       () => ConsoleTrace.WriteLine(ConsoleColor.DarkCyan, "Timer client completed")))
            {
                Console.WriteLine();
                Console.WriteLine("Timer client started.  Waiting for timer service notification...");
                Console.WriteLine();
                Console.WriteLine("(Press any key to continue)");
                Console.WriteLine();

                Console.ReadKey(intercept: true);
            }
        }
Example #9
0
        public void Run()
        {
            var client = new TcpQbservableClient <long>(Program.BasicServiceEndPoint);

            var query =
                (from value in client.Query()
                 where value % 2 == 0
                 select value)
                .Do(value => Console.WriteLine("{0} pushing value: {1}", Assembly.GetEntryAssembly().EntryPoint.DeclaringType.Namespace, value));

            using (query.Subscribe(
                       value => ConsoleTrace.WriteLine(ConsoleColor.Green, "Basic client observed: {0}", value),
                       ex => ConsoleTrace.WriteLine(ConsoleColor.Red, "Basic client error: {0}", ex.Message),
                       () => ConsoleTrace.WriteLine(ConsoleColor.DarkCyan, "Basic client completed")))
            {
                Console.WriteLine();
                Console.WriteLine("Basic client started.  Waiting for basic service notifications...");
                Console.WriteLine();
                Console.WriteLine("(Press any key to continue)");
                Console.WriteLine();

                Console.ReadKey(intercept: true);
            }
        }
Example #10
0
        private void Run(IPEndPoint serviceEndPoint)
        {
            var client = new TcpQbservableClient <int>(serviceEndPoint, typeof(MessageBox));

            // This query is allowed in both service scenarios
            IQbservable <string> query1 = client.Query()
                                          .Take(1)
                                          .Select(_ => "I'm allowed to get my permissions...\r\n" + AppDomain.CurrentDomain.PermissionSet.ToString());

            /* The sandboxed service does not prevent Console.WriteLine because that API doesn't demand any permissions.
             * This shows why setting AllowExpressionsUnrestricted to true is a bad idea, unless you trust all clients.
             */
            IQbservable <string> query2 = client.Query()
                                          .Take(1)
                                          .Do(_ => Console.WriteLine("Hello from malicious client!"))
                                          .Select(_ => "Malicious message sent successfully.");

            /* The default expression limiter does not prevent Environment.CurrentDirectory from being read because it's a property.
             * This shows why hosting services in a sandboxed AppDomain is a good idea, unless you trust all clients.
             */
            IQbservable <string> query3 = client.Query()
                                          .Take(1)
                                          .Select(_ => Environment.CurrentDirectory);

            // This query is prevented in both service scenarios
            IQbservable <string> query4 = client.Query()
                                          .Select(_ => MessageBox.Show("Hello from malicious client!").ToString());

            // This query is prevented in both service scenarios
            IQbservable <string> query5 = client.Query()
                                          .Select(_ => Environment.GetEnvironmentVariable("Temp", EnvironmentVariableTarget.Machine));

            // This query is prevented in both service scenarios
            IQbservable <string> query6 = client.Query()
                                          .Select(_ => System.IO.File.Create("c:\\malicious.exe").Length.ToString());

            // This query is prevented in both service scenarios
            IQbservable <string> query7 = client.Query()
                                          .Select(_ => AppDomain.CreateDomain(
                                                      "Malicious Domain",
                                                      null,
                                                      new AppDomainSetup()
            {
                ApplicationBase = "C:\\Windows\\Temp\\"
            },
                                                      new PermissionSet(PermissionState.Unrestricted))
                                                  .FriendlyName);

            // This query is prevented in both service scenarios
            IQbservable <string> query8 = client.Query()
                                          .Select(_ => System.Reflection.Assembly.GetExecutingAssembly().CodeBase);

            // This query is prevented in both service scenarios
            IQbservable <string> query9 = client.Query()
                                          .Do(_ => new PermissionSet(PermissionState.Unrestricted).Assert())
                                          .Select(_ => string.Empty);

            Func <int, IObserver <string> > createObserver = queryNumber => Observer.Create <string>(
                value => ConsoleTrace.WriteLine(ConsoleColor.Green, "Malicious query #{0} observed: {1}", queryNumber, value),
                ex => ConsoleTrace.WriteLine(ConsoleColor.Red, "Malicious query #{0} error: {1}", queryNumber, ex.Message),
                () => ConsoleTrace.WriteLine(ConsoleColor.DarkCyan, "Malicious query #{0} completed", queryNumber));

            using (Observable.OnErrorResumeNext(
                       query1.AsObservable().Do(createObserver(1)),
                       query2.AsObservable().Do(createObserver(2)),
                       query3.AsObservable().Do(createObserver(3)),
                       query4.AsObservable().Do(createObserver(4)),
                       query5.AsObservable().Do(createObserver(5)),
                       query6.AsObservable().Do(createObserver(6)),
                       query7.AsObservable().Do(createObserver(7)),
                       query8.AsObservable().Do(createObserver(8)),
                       query9.AsObservable().Do(createObserver(9)))
                   .Subscribe(_ => { }, ex => { }, () => Console.WriteLine("All queries terminated. Press any key to continue...")))
            {
                Console.WriteLine();
                Console.WriteLine("Malicious client started. Waiting for query terminations...");
                Console.WriteLine();
                Console.WriteLine("(Press any key to cancel)");
                Console.WriteLine();

                Console.ReadKey(intercept: true);
            }

            IQbservable <int> safeQuery =
                from value in client.Query()
                where value > 0
                select value * 10;

            using (safeQuery.Subscribe(
                       value => ConsoleTrace.WriteLine(ConsoleColor.Green, "Safe query observed: " + value),
                       ex => ConsoleTrace.WriteLine(ConsoleColor.Red, "Safe query error: " + ex.Message),
                       () => ConsoleTrace.WriteLine(ConsoleColor.DarkCyan, "Safe query completed")))
            {
                Console.WriteLine();
                Console.WriteLine("Waiting for service notifications...");
                Console.WriteLine();
                Console.WriteLine("(Press any key to continue)");
                Console.WriteLine();

                Console.ReadKey(intercept: true);
            }
        }