Example #1
0
        static void Main(string[] args)
        {
            var client = new QbservableTcpClient<long>(new IPEndPoint(IPAddress.Parse("10.6.40.209"), 3205));

            using (client.Query().Subscribe(
                value => Console.WriteLine("Client observed: " + value),
                ex => Console.WriteLine("Error: {0}", ex.Message),
                () => Console.WriteLine("Completed")))
            {
                Console.ReadLine();
            }
        }
Example #2
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 QbservableTcpClient <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 stop)");
                Console.WriteLine();

                Console.ReadKey(intercept: true);
            }
        }
Example #3
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 QbservableTcpClient <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 stop)");
                Console.WriteLine();

                Console.ReadKey(intercept: true);
            }
        }
Example #4
0
        public void Run()
        {
            var client = new QbservableTcpClient <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 #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 QbservableTcpClient <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 stop)");
                Console.WriteLine();

                Console.ReadKey(intercept: true);
            }
        }
Example #6
0
        public void Connect()
        {
            var client = new QbservableTcpClient<ChatServiceHooks>(serviceEndPoint);

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

            string userName = Console.ReadLine();

            var myMessages = new Subject<string>();

            IObservable<string> outgoingMessages = myMessages;

            IObservable<string> query =
                (from hooks in client.Query(userName)
                     .Do(hooks => outgoingMessages.Subscribe(hooks.IncomingMessages))
                 from message in hooks.OutgoingMessages
                 select message);

            using (query.Subscribe(
                message => ConsoleTrace.WriteLine(ConsoleColor.Blue, 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 #7
0
        public void Run()
        {
            var client = new QbservableTcpClient <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 stop)");
                Console.WriteLine();

                Console.ReadKey(intercept: true);
            }
        }
Example #8
0
        public void Run()
        {
            var client = new QbservableTcpClient <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 stop)");
                Console.WriteLine();

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

            /* 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> query1 = 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> query2 = client.Query()
                                          .Take(1)
                                          .Select(_ => Environment.CurrentDirectory);

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

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

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

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

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

            // This query is prevented in both service scenarios
            IQbservable <string> query8 = 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 (query1.Subscribe(createObserver(1)))
                using (query2.Subscribe(createObserver(2)))
                    using (query3.Subscribe(createObserver(3)))
                        using (query4.Subscribe(createObserver(4)))
                            using (query5.Subscribe(createObserver(5)))
                                using (query6.Subscribe(createObserver(6)))
                                    using (query7.Subscribe(createObserver(7)))
                                        using (query8.Subscribe(createObserver(8)))
                                        {
                                            Console.WriteLine();
                                            Console.WriteLine("Malicious client started.  Waiting for service errors...");
                                            Console.WriteLine();
                                            Console.WriteLine("(Press any key to continue)");
                                            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);
            }
        }
        private IObservable <Either <T, Exception> > ObserveOneUnsafe <T>(string agentId, string propertyName, bool ignoreAgentState = false, bool ignoreUnreachable = false, TimeSpan?timeout = null)
        {
            if (string.IsNullOrEmpty(agentId))
            {
                throw new ArgumentNullException("agentId");
            }
            if (string.IsNullOrEmpty(propertyName))
            {
                throw new ArgumentNullException("propertyName");
            }

            var observable = Observable.Defer(
                () =>
            {
                AgentInformation agentInfo;
                if (!TryGetAgentInformation(agentId, out agentInfo))
                {
                    throw new InvalidOperationException(string.Format("Agent '{0}' cannot be found.", agentId));
                }

                if (agentInfo.IsRecycled)
                {
                    throw new InvalidOperationException(string.Format("Agent '{0}' has been recycled.", agentId));
                }
                else if (!ignoreUnreachable && !agentInfo.IsReachable)
                {
                    throw new InvalidOperationException(string.Format("Agent '{0}' has been disconnected.", agentId));
                }

                if (agentInfo.IsLocal)
                {
                    var local      = (LocalAgentInformation)agentInfo;
                    var dataSource = (IObservable <T>)local.Agent.GetType().GetProperty(propertyName).GetValue(local.Agent);

                    // if agent becomes invalid, manually create an error to invoke Retry wrapper added at the end of this method
                    return
                    (local.Agent.StateDataSource
                     .Select(
                         state =>
                    {
                        if (state == AgentState.Disposed)
                        {
                            return Notification.CreateOnError <T>(new InvalidOperationException(string.Format("Agent '{0}' has been disposed.", local.AgentId)));
                        }
                        else if (!ignoreAgentState && state != AgentState.Activated)
                        {
                            return Notification.CreateOnError <T>(new InvalidOperationException(string.Format("Agent '{0}' is not active.", local.AgentId)));
                        }
                        else
                        {
                            return Notification.CreateOnNext(default(T));
                        }
                    })
                     .Dematerialize()
                     .IgnoreElements()
                     .Merge(dataSource));
                }
                else
                {
                    var remote      = (RemoteAgentInformation)agentInfo;
                    var peerAgentId = GetAgentId(remote.PeerNode, PeerCommunicationAgent.Configuration.Name);

                    var datasource =
                        Observable.FromAsync(() => TryExecuteOnOneUnsafe <IPeerCommunicationAgent, int>(peerAgentId, a => a.EnsureObservableListening(remote.AgentId, propertyName), ignoreAgentState: false, ignoreUnreachable: ignoreUnreachable))
                        .SelectMany(
                            portResult =>
                    {
                        if (!portResult.IsSuccessful)
                        {
                            throw portResult.Exception ?? (portResult.IsCanceled ? (Exception) new OperationCanceledException() : new InvalidOperationException(string.Format("An unknown error occurred while getting the Rx port via agent '{0}'.", portResult.AgentId)));
                        }
                        else
                        {
                            var knownTypes = new List <Type>();
                            knownTypes.Add(typeof(T));
                            if (typeof(T).IsGenericType)
                            {
                                knownTypes.AddRange(typeof(T).GenericTypeArguments);
                            }

                            var client = new QbservableTcpClient <T>(new IPEndPoint(remote.PeerNode.Host, portResult.Result), knownTypes.ToArray());
                            return(client.Query());
                        }
                    });

                    return
                    (this.AgentDataSource
                     .Where(info => string.Equals(info.AgentId, agentId, StringComparison.InvariantCulture))
                     .Select(
                         info =>
                    {
                        // agent deconnection is already managed by QbservableTcpClient
                        if (info.LastKnownState == AgentState.Disposed)
                        {
                            return Notification.CreateOnError <T>(new InvalidOperationException(string.Format("Agent '{0}' has been disposed.", info.AgentId)));
                        }
                        else if (!ignoreAgentState && info.LastKnownState != AgentState.Activated)
                        {
                            return Notification.CreateOnError <T>(new InvalidOperationException(string.Format("Agent '{0}' is not active.", info.AgentId)));
                        }
                        else
                        {
                            return Notification.CreateOnNext(default(T));
                        }
                    })
                     .Dematerialize()
                     .IgnoreElements()
                     .Merge(datasource));
                }
            });

            // if an error occurs, try to reconnect after retryCount * MinOperationRetryDelay, up to MaxOperationRetryDelay
            return(observable
                   .Retry(
                       int.MaxValue,
                       (ex, retryCount) =>
            {
                Log.Trace().Message("Could not connect to the observable related to property '{0}'.", propertyName).Exception(ex).WithAgent(agentId).Write();

                if (timeout != null)
                {
                    return timeout.Value;
                }
                else
                {
                    return TimeSpan.FromMilliseconds(Math.Min(retryCount * this.MinOperationRetryDelay.TotalMilliseconds, this.MaxOperationRetryDelay.TotalMilliseconds));
                }
            })
                   .TakeWhile(_ => this.State == ServiceState.Started));
        }