Пример #1
0
        public static void Main(string[] args)
        {
            int          subMqttComponent = 2;
            BrokerClient client           = new BrokerClient(subMqttComponent);

            Thread t = new Thread(CreateWebHostBuilder(args).Build().Run);

            t.Start();

            Thread t2 = new Thread(LaunchMqttServer);

            t2.Start();

            Thread t3 = new Thread(LaunchCalculEngine);

            t3.Start();

            //Thread.Sleep(4000);

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();

            /*
             *
             * client.sendBrokerMessage("device/telemetry", "Nique tout");*/
        }
Пример #2
0
        /// <summary>获取代理客户端</summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected BrokerClient GetBroker(String name)
        {
            if (_Brokers.TryGetValue(name, out var client))
            {
                return(client);
            }

            var bk = Brokers?.FirstOrDefault(e => name == null || e.Name == name);

            if (bk == null)
            {
                return(null);
            }

            // 实例化客户端
            client = new BrokerClient(bk.Addresses)
            {
                Id     = ClientId,
                Name   = bk.Name,
                Config = this,
                Log    = Log,
            };

            // 尝试添加
            var client2 = _Brokers.GetOrAdd(name, client);

            if (client2 != client)
            {
                return(client2);
            }

            client.Start();

            return(client);
        }
Пример #3
0
        public Order?DecideOrder(PositionDelta delta)
        {
            OptionQuote quote = delta.Quote ?? MarketDataClient.GetOptionQuote(delta.Symbol);

            // TODO: Remove after testing
            //Log.Warning("Not getting real quote");
            //OptionQuote quote = new OptionQuote(delta.Symbol, delta.Price * (float).99, delta.Price * (float)1.01, delta.Price, delta.Price * (float)1.06, (float)1.0);

            if (quote.Time < DateTime.Now.AddSeconds(-15))
            {
                Log.Information("Getting new quote. Old quote- {@Quote}", quote);
                quote = MarketDataClient.GetOptionQuote(delta.Symbol);
            }
            Log.Information("{DeltaType} delta {@Delta}- current mark price {Mark}. Symbol {Symbol}", delta.DeltaType, delta, quote.Mark.ToString("0.00"), delta.Symbol);

            Position?currentPos = BrokerClient.GetPosition(delta.Symbol);

            if (delta.DeltaType == DeltaType.SELL)
            {
                return(DecideSell(delta, currentPos));
            }
            else if (delta.DeltaType == DeltaType.ADD ||
                     delta.DeltaType == DeltaType.NEW)
            {
                return(DecideBuy(delta, currentPos, quote));
            }
            else
            {
                Log.Error("Unrecognized deltaType: {type}", delta.DeltaType);
                return(null);
            }
        }
Пример #4
0
        private int DecideBuyQuantity(float price, PositionDelta delta, Position?currentPos, float currentAskPrice)
        {
            IEnumerable <Order> existingBuyOrders = BrokerClient.GetOpenOrdersForSymbol(delta.Symbol)
                                                    .Where(order => order.Instruction == InstructionType.BUY_TO_OPEN);

            if (existingBuyOrders.Count() >= _config.MaxNumOpenBuyOrdersForSymbol)
            {
                Log.Warning("Many buy orders encountered: {@BuyOrders}- skipping this order.", existingBuyOrders.ToList());
                return(0);
            }
            float openBuyAlloc = AggregateBuyOrders(existingBuyOrders, currentAskPrice);

            float currentPosTotalAlloc = openBuyAlloc + (currentPos != null
                ? currentPos.LongQuantity * currentPos.AveragePrice * 100
                : 0);

            int buyQuantity;

            if (delta.DeltaType == DeltaType.NEW ||
                delta.DeltaType == DeltaType.ADD && currentPosTotalAlloc == 0)
            {
                float deltaMarketValue = delta.Price * delta.Quantity * 100;
                float percentOfMaxSize = deltaMarketValue / _config.LivePortfolioPositionMaxSize;
                if (percentOfMaxSize > 1)
                {
                    Log.Warning("New position in live portfolio exceeds expected max size. Delta {@Delta}", delta);
                    percentOfMaxSize = 1;
                }
                buyQuantity = (int)Math.Floor((percentOfMaxSize * _config.MyPositionMaxSize) / (price * 100));
            }
            else if (delta.DeltaType == DeltaType.ADD && currentPosTotalAlloc > 0)
            {
                float addAlloc = currentPosTotalAlloc * delta.Percent;
                buyQuantity = (int)Math.Floor(addAlloc / (price * 100));
            }
            else
            {
                Log.Warning("Invalid delta type supplied to DecideBuyQuantity function. Delta {@Delta}", delta);
                return(0);
            }

            float addedAlloc = buyQuantity * price * 100;
            float remainingFundsForTrading = BrokerClient.GetAvailableFundsForTrading() - addedAlloc;
            float newTotalAllocThisPos     = currentPosTotalAlloc + addedAlloc;

            if (newTotalAllocThisPos > _config.MyPositionMaxSize)
            {
                Log.Information("Buying " + buyQuantity + " {Symbol} would exceed maximum allocation of " + _config.MyPositionMaxSize.ToString("0.00"), delta.Symbol);
                return(0);
            }
            else if (remainingFundsForTrading < _config.MinAvailableFundsForTrading)
            {
                Log.Information("Buying " + buyQuantity + " {Symbol} would put available funds below " + _config.MinAvailableFundsForTrading.ToString("0.00"), delta.Symbol);
                return(0);
            }
            else
            {
                return(buyQuantity);
            }
        }
Пример #5
0
        /// <summary>
        /// Try to begin receive messages
        /// </summary>
        /// <param name="ccs">indicating the channel and the client</param>
        /// <returns>if the operation completed synchronously</returns>
        protected override bool TryToBeginReceive(ChannelClientState ccs)
        {
            IDuplexSessionChannel channel = (IDuplexSessionChannel)ccs.Channel;
            BrokerClient          client  = ccs.Client;
            IAsyncResult          ar      = null;

            try
            {
                ar = channel.BeginReceive(this.receiveRequest, ccs);
            }
            catch (Exception e)
            {
                BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[DuplexFrontEnd] Exception throwed while begin receive messages: {0}", e);

                // Channel must be in falted state
                lock (channel)
                {
                    if (channel.State == CommunicationState.Faulted)
                    {
                        BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[DuplexFrontEnd] About the channel.");
                        this.FrontendDisconnect(channel, client);

                        // About the falted channel
                        channel.Abort();
                    }
                }

                return(false);
            }

            return(ar.CompletedSynchronously && channel.State == CommunicationState.Opened);
        }
Пример #6
0
        public static void Main(string[] args)
        {
            Console.WriteLine("UDP Producer test");

            if (args.Length == 0)
            {
                System.Console.WriteLine(CommandLineArguments.Usage());
                return;
            }

            log4net.Config.BasicConfigurator.Configure();

            CommandLineArguments cliArgs = new CommandLineArguments();
            Parser parser = new Parser(System.Environment.CommandLine, cliArgs);

            parser.Parse();

            int    numberOfMessages = 10;
            string message          = "Hello, how are you?";

            while ((numberOfMessages--) != 0)
            {
                System.Console.WriteLine("Publishing UDP message");
                NetBrokerMessage brokerMessage = new NetBrokerMessage(System.Text.Encoding.UTF8.GetBytes(message));
                BrokerClient.PublishMessageOverUdp(brokerMessage, cliArgs.DestinationName, new HostInfo(cliArgs.Hostname, cliArgs.PortNumber), BrokerClient.DefaultMessageSerializer);
                System.Threading.Thread.Sleep(500);
            }
        }
Пример #7
0
        public static void Main(string[] args)
        {
            Console.WriteLine("New Blog Consumer");

            BrokerClient brokerClient = new BrokerClient(new HostInfo("broker.bk.sapo.pt", 3323));

            Subscription subscription = new Subscription("test@/sapo/blogs/activity/post", NetAction.DestinationType.VIRTUAL_QUEUE);

            subscription.OnMessage += delegate(NetNotification notification)
            {
                if (((++count) % 100) == 0)
                {
                    Console.WriteLine("{0} - New message received. Count: {1}", DateTime.Now.ToLongTimeString(), count);
                }
                brokerClient.Acknowledge(notification.Destination, notification.Message.MessageId);
            };

            brokerClient.Subscribe(subscription);

            Console.WriteLine("Write X to unsbscribe and exit");
            while (!System.Console.Read().Equals('X'))
            {
                ;
            }
            Console.WriteLine();
            Console.WriteLine("Unsubscribe...");

            // Note Subscription instance could other than the one used for subscription as long as it was equivelent (same destination type and subscription pattern). Since the application is ending and therefor the socket will be closed agent's will discard the previous subscription.
            brokerClient.Unsubscribe(subscription);

            Console.WriteLine("Good bye");
        }
Пример #8
0
        /// <summary>
        /// Asks VS to open specified URL in the help window browser
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        Task IRCallbacks.WebBrowser(string url)
        {
            var newUrl   = BrokerClient.HandleUrl(url, CancellationToken.None);
            var callback = _callback;

            return(callback != null?callback.ShowHelp(newUrl) : Task.CompletedTask);
        }
        public string PostDevice([FromBody] dynamic data)
        {
            string id = Guid.NewGuid().ToString();
            string name;

            if (data.name.ToString().Length == 0)
            {
                name = data.deviceType.ToString() + " - " + id;
            }
            else
            {
                name = data.name.ToString();
            }

            var finalData = new
            {
                action   = "registerDevice",
                source   = "",
                callback = "",
                payload  = new
                {
                    deviceId   = id,
                    deviceName = name,
                    deviceType = data.deviceType.ToString()
                }
            };
            string jsonDataSet   = JsonConvert.SerializeObject(finalData);
            string returnDataSet = JsonConvert.SerializeObject(finalData.payload);

            BrokerClient.sendMqttMessage(jsonDataSet, "Data-Controller");

            return(returnDataSet);
        }
Пример #10
0
        public void StopReceiving_NoErrors_ResultIsNotFailure_SubscribersCleared()
        {
            var mocks      = CreateMocks();
            var mockLogger = new Mock <Log>();

            var client = new BrokerClient(
                () => mocks.Item1.Object,
                _mockOpenAsync.Object,
                _mockExeNonQueryAsync.Object,
                mockLogger.Object);

            var mockObserver1 = CreateMockObserver();

            mockObserver1.Setup(f => f.OnCompleted()).Throws <InvalidOperationException>();
            var mockObserver2 = CreateMockObserver();

            client.Subscribe(mockObserver1.Object);
            client.Subscribe(mockObserver2.Object);

            Expect(client.ReceiveMessages(QueueName).StopReceiving().Failed, True);
            Expect(client.Subscribers.Count, EqualTo(0));

            mockObserver1.Verify(o => o.OnCompleted(), Times.Once());
            mockObserver2.Verify(o => o.OnCompleted(), Times.Once());
            mockLogger.Verify(f => f(It.IsRegex("Receiver stopped"), It.IsAny <string>(), It.IsAny <TraceEventType>()), Times.Once());
        }
Пример #11
0
    public void WhenTheDocumentIsSentToWebServiceTheRenderDocumentService()
    {
        brokerClient = new BrokerClient();
        var documentXml = context.Get <string>("DocumentXML");                                                // get the document from the context dictionary

        context["RenderDocumentResponse"] = brokerClient.RenderDocument(FileUtils.Base64Encode(documentXml)); // set in the dictionary the json response of the service
    }
Пример #12
0
        public CalculationEngine()
        {
            _target = Guid.NewGuid().ToString();
            string topic = "calculation";

            BrokerClient.addNewListener(this, topic);
        }
Пример #13
0
        public void ReceiveMessages_SBEndDialogMessageReceived_EndDialogCalled()
        {
            var mockObserver   = CreateMockObserver();
            var mocks          = CreateMocks(ServiceBrokerEndDialogMessageType);
            var mockConnection = mocks.Item1;
            var mockCommand    = mocks.Item3;
            var mockParams     = mocks.Item4;

            mockConnection.Setup(c => c.Dispose()).Callback(fun(() =>
            {
                var count = 0;

                return(new Action(() =>
                {
                    if (++count == 2)
                    {
                        _wait.Set();
                    }
                }));
            })());

            var client = new BrokerClient(() => mocks.Item1.Object, _mockOpenAsync.Object, _mockExeNonQueryAsync.Object);

            client.Subscribe(mockObserver.Object);
            var running = client.ReceiveMessages(QueueName);

            _wait.WaitOne();
            running.StopReceiving();

            ExpectEndDialog(mocks);
            ExpectAllDisposed(mocks);
        }
Пример #14
0
        public void ReceiveMessages_ExeQueryFirstParamIsDBNull_ObserverOnNextNotCalled()
        {
            var mocks           = CreateMocks();
            var mockConnection  = mocks.Item1;
            var mockTransaction = mocks.Item2;
            var mockCommand     = mocks.Item3;
            var mockParams      = mocks.Item4;
            var mockObserver    = CreateMockObserver();
            var client          = new BrokerClient(() => mockConnection.Object, _mockOpenAsync.Object, _mockExeNonQueryAsync.Object);

            mockConnection.Setup(c => c.Dispose()).Callback(() => _wait.Set());
            mockParams.Setup(p => p[It.IsAny <int>()])
            .Callback(() => new SqlParameter("", DBNull.Value));

            client.Subscribe(mockObserver.Object);
            var running = client.ReceiveMessages(QueueName);

            _wait.WaitOne();
            running.StopReceiving();

            mockObserver.Verify(o => o.OnNext(It.Is <BrokerMessage>(msg => msg == BrokerMessage.Empty)), Times.Never());

            ExpectReceiveMessage(mocks);
            ExpectAllDisposed(mocks);
        }
Пример #15
0
        static void Main(string[] args)
        {
            BrokerClient client = null;
            try
            {
                client = new BrokerClient();
                Console.WriteLine("Username : "******"0" + i;
                    v.value = "a" + i;
                    client.StorePair(k, v, myid);
                    Console.WriteLine(i);
                }
                Console.WriteLine("done store");

                for (int i = 0; i < 10; i++)
                {
                    IKey k = new Key();
                    k.key = "0" + i;
                    IValue v = (IValue)client.ReadPair(k);
                    Console.WriteLine(v.value);
                }
                Console.WriteLine("done read");

                object[] aux = (object[])client.GetAllPairs(myid);

                for (int i = 0; i < aux.Length; ++i)
                {
                    KeyValuePair<object, object>[] a = (KeyValuePair<object, object>[])aux[i];

                    foreach (KeyValuePair<object, object> pair in a)
                    {
                        Console.WriteLine("Key - {0} , Value - {1}", ((IKey)pair.Key).key, ((IValue)pair.Value).value);
                    }
                }

                client.Close();
            }
            catch (TimeoutException)
            {
                Console.WriteLine("Service operation time out");
                client.Abort();
            }
            catch (FaultException exception)
            {

                Console.WriteLine(exception.Message);
                client.Abort();
            }
            catch (CommunicationException)
            {
                Console.WriteLine("communication problem");
                client.Abort();
            }
        }
Пример #16
0
        static void Main(string[] args)
        {
            BrokerClient client = null;

            try
            {
                client = new BrokerClient();
                Console.WriteLine("Username : "******"0" + i;
                    v.value = "a" + i;
                    client.StorePair(k, v, myid);
                    Console.WriteLine(i);
                }
                Console.WriteLine("done store");

                for (int i = 0; i < 10; i++)
                {
                    IKey k = new Key();
                    k.key = "0" + i;
                    IValue v = (IValue)client.ReadPair(k);
                    Console.WriteLine(v.value);
                }
                Console.WriteLine("done read");

                object[] aux = (object[])client.GetAllPairs(myid);

                for (int i = 0; i < aux.Length; ++i)
                {
                    KeyValuePair <object, object>[] a = (KeyValuePair <object, object>[])aux[i];

                    foreach (KeyValuePair <object, object> pair in a)
                    {
                        Console.WriteLine("Key - {0} , Value - {1}", ((IKey)pair.Key).key, ((IValue)pair.Value).value);
                    }
                }

                client.Close();
            }
            catch (TimeoutException)
            {
                Console.WriteLine("Service operation time out");
                client.Abort();
            }
            catch (FaultException exception)
            {
                Console.WriteLine(exception.Message);
                client.Abort();
            }
            catch (CommunicationException)
            {
                Console.WriteLine("communication problem");
                client.Abort();
            }
        }
Пример #17
0
        static void Main(string[] args)
        {
            BrokerClient prx = new BrokerClient();
            Pair p = new Pair();

            IContextManager ctxManager = prx.InnerChannel.GetProperty<IContextManager>();
            IDictionary<string, string> context = ctxManager.GetContext();

            context["clientName"] = "Client1";
            ctxManager.SetContext(context);

            for (int i = 0; i < 50; ++i)
            {
                p.Key = "" + i;
                p.Value = "My val " + i;

                try
                {
                    prx.StorePair(p);
                }
                catch (FaultException e)
                {
                    Console.WriteLine(e.Reason);
                }
            }

            Console.WriteLine("Keys Added. Press any key to exit.");
            Console.ReadLine();
        }
Пример #18
0
        public static void Main(string[] args)
        {
            Console.WriteLine("MultipleProducers test");

            if (args.Length == 0)
            {
                System.Console.WriteLine(CommandLineArguments.Usage());
                return;
            }

            log4net.Config.BasicConfigurator.Configure();

            CommandLineArguments cliArgs = new CommandLineArguments();
            Parser parser = new Parser(System.Environment.CommandLine, cliArgs);

            parser.Parse();

            BrokerClient brokerClient     = new BrokerClient(new HostInfo(cliArgs.Hostname, cliArgs.PortNumber));
            int          numberOfMessages = 500000;

            Thread[] threads = new System.Threading.Thread[NR_THREADS];

            for (int i = 0; i != threads.Length; ++i)
            {
                threads[i] = new Thread(
                    new ThreadStart(() =>
                {
                    int msgs     = numberOfMessages;
                    int threadId = i;

                    while ((--msgs) != 0)
                    {
                        int msgId      = Interlocked.Increment(ref message_id);
                        string message = String.Format("{0} - Thread id: {1}", msgId, threadId);
                        NetBrokerMessage brokerMessage = new NetBrokerMessage(System.Text.Encoding.UTF8.GetBytes(message));

                        System.Console.WriteLine(message);
                        if (cliArgs.DestinationType == NetAction.DestinationType.TOPIC)
                        {
                            brokerClient.Publish(brokerMessage, cliArgs.DestinationName);
                        }
                        else
                        {
                            brokerClient.Enqueue(brokerMessage, cliArgs.DestinationName);
                        }
                    }
                }
                                    )
                    );

                threads[i].Start();
            }

            Console.WriteLine("Write X to unsbscribe and exit");
            while (!System.Console.Read().Equals('X'))
            {
                ;
            }
        }
 public NotificationHandler(BrokerClient client, NetAction.DestinationType actionType, int expectedMessages)
 {
     this.client           = client;
     this.actionType       = actionType;
     this.expectedMessages = expectedMessages;
     this.Notifications    = new List <NetNotification>();
     this.ManualResetEvent = new ManualResetEvent(false);
 }
Пример #20
0
        private void retrieveResp()
        {
            #region Init
            result[] results = new result[10];
            for (int i = 0; i < 10; i++)
            {
                results[i] = new result();
            }
            #endregion

            SessionAttachInfo attachInfo = new SessionAttachInfo(Config.headNode, Convert.ToInt32(this.Range["D20", missing].Value2));

            using (DurableSession session = DurableSession.AttachSession(attachInfo))
            {
                using (BrokerClient <IService1> client = new BrokerClient <IService1>(session))
                {
                    foreach (BrokerResponse <PriceAsianOptionsResponse> response in client.GetResponses <PriceAsianOptionsResponse>())
                    {
                        cellContext idx   = response.GetUserData <cellContext>();
                        double      price = response.Result.PriceAsianOptionsResult;
                        Interlocked.Increment(ref results[idx.iteration].count);

                        this.Range[idx.range, missing].Value2 = price;

                        results[idx.iteration].min = Math.Min(results[idx.iteration].min, price);
                        results[idx.iteration].max = Math.Max(results[idx.iteration].max, price);

                        results[idx.iteration].sumPrice       += price;
                        results[idx.iteration].sumSquarePrice += price * price;

                        results[idx.iteration].stdDev = Math.Sqrt(results[idx.iteration].sumSquarePrice - results[idx.iteration].sumPrice * results[idx.iteration].sumPrice / results[idx.iteration].count) / ((results[idx.iteration].count == 1) ? 1 : results[idx.iteration].count - 1);
                        results[idx.iteration].stdErr = results[idx.iteration].stdDev / Math.Sqrt(results[idx.iteration].count);

                        if (results[idx.iteration].count == 100)
                        {
                            int i = idx.iteration;
                            this.Range[string.Format("{0}14", cols[i]), missing].Value2 = results[i].sumPrice / results[i].count;
                            this.Range[string.Format("{0}15", cols[i]), missing].Value2 = results[i].min;
                            this.Range[string.Format("{0}16", cols[i]), missing].Value2 = results[i].max;
                            this.Range[string.Format("{0}17", cols[i]), missing].Value2 = results[i].stdDev;
                            this.Range[string.Format("{0}18", cols[i]), missing].Value2 = results[i].stdErr;
                        }
                    }
                }
                session.Close();
            }

            #region Summarize
            for (int i = 0; i < 10; i++)
            {
                this.Range[string.Format("{0}14", cols[i]), missing].Value2 = results[i].sumPrice / results[i].count;
                this.Range[string.Format("{0}15", cols[i]), missing].Value2 = results[i].min;
                this.Range[string.Format("{0}16", cols[i]), missing].Value2 = results[i].max;
                this.Range[string.Format("{0}17", cols[i]), missing].Value2 = results[i].stdDev;
                this.Range[string.Format("{0}18", cols[i]), missing].Value2 = results[i].stdErr;
            }
            #endregion
        }
Пример #21
0
        static void Main(string[] args)
        {
            //change the headnode name here
            const string     headnode    = "[headnode]";
            const string     serviceName = "EchoService";
            const int        numRequests = 12;
            SessionStartInfo info        = new SessionStartInfo(headnode, serviceName);

            //session in the session pool should be a shared session
            info.ShareSession   = true;
            info.UseSessionPool = true;
            Console.Write("Creating a session using session pool for EchoService...");

            using (DurableSession session = DurableSession.CreateSession(info))
            {
                Console.WriteLine("done session id = {0}", session.Id);
                NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);

                //to make sure the client id is unique among the sessions
                string clientId = Guid.NewGuid().ToString();

                using (BrokerClient <IService1> client = new BrokerClient <IService1>(clientId, session, binding))
                {
                    Console.Write("Sending {0} requests...", numRequests);
                    for (int i = 0; i < numRequests; i++)
                    {
                        EchoRequest request = new EchoRequest("hello world!");
                        client.SendRequest <EchoRequest>(request, i);
                    }

                    client.EndRequests();
                    Console.WriteLine("done");

                    Console.WriteLine("Retrieving responses...");
                    foreach (var response in client.GetResponses <EchoResponse>())
                    {
                        try
                        {
                            string reply = response.Result.EchoResult;
                            Console.WriteLine("\tReceived response for request {0}: {1}", response.GetUserData <int>(), reply);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error occured while processing {0}-th request: {1}", response.GetUserData <int>(), ex.Message);
                        }
                    }

                    Console.WriteLine("Done retrieving {0} responses", numRequests);
                }

                //should not purge the session if the session is expected to stay in the session pool
                //the shared session is kept in the session pool
                session.Close(false);
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Пример #22
0
        private static void Worker(int sessionId)
        {
            DurableSession session     = DurableSession.AttachSession(new SessionAttachInfo(headnode, sessionId));
            int            numRequests = 32;
            NetTcpBinding  binding     = new NetTcpBinding(SecurityMode.Transport);
            string         guid        = Guid.NewGuid().ToString();

            // Create a BrokerClient proxy
            // This proxy is able to map One-Way, Duplex message exchange patterns
            // with the Request / Reply Services.  As such, the client program can send the
            // requests, exit and re-attach to the session to retrieve responses (see the
            // FireNRecollect project for details

            using (BrokerClient <IService1> client = new BrokerClient <IService1>(guid, session, binding))
            {
                Console.Write("Sending {0} requests...", numRequests);
                for (int i = 0; i < numRequests; i++)
                {
                    // EchoRequest are created as you add Service Reference
                    // EchoService to the project
                    EchoRequest request = new EchoRequest("hello world!");
                    client.SendRequest <EchoRequest>(request, i);
                }

                // Flush the message.  After this call, the runtime system
                // starts processing the request messages.  If this call is not called,
                // the system will not process the requests.  The client.GetResponses() will return
                // with an empty collection
                client.EndRequests();
                client.Close();
                Console.WriteLine("done");
            }

            using (BrokerClient <IService1> client = new BrokerClient <IService1>(guid, session, binding))
            {
                Console.WriteLine("Retrieving responses...");

                // GetResponses from the runtime system
                // EchoResponse class is created as you add Service Reference "EchoService"
                // to the project

                foreach (var response in client.GetResponses <EchoResponse>())
                {
                    try
                    {
                        string reply = response.Result.EchoResult;
                        Console.WriteLine("\tReceived response for request {0}: {1}", response.GetUserData <int>(), reply);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error occured while processing {0}-th request: {1}", response.GetUserData <int>(), ex.Message);
                    }
                }

                Console.WriteLine("Done retrieving {0} responses", numRequests);
            }
        }
        public async Task WhenGetBrokerStatsIsCalled_AggregatesBrokerStatsFromMultiplePartitions()
        {
            var brokerClient = new BrokerClient(new MockBrokerServiceLocatorMultiPartition());
            var queueStats   = await brokerClient.GetBrokerStatsAsync();

            Assert.IsTrue(queueStats.Count == 2);
            Assert.IsTrue(queueStats.ContainsKey("MessageOneQueue") && queueStats["MessageOneQueue"].Count == 1 && queueStats["MessageOneQueue"].First().TotalDelivered == 34);
            Assert.IsTrue(queueStats.ContainsKey("MessageTwoQueue") && queueStats["MessageTwoQueue"].Count == 1 && queueStats["MessageTwoQueue"].First().TotalReceived == 500);
        }
        public static void Main(string[] args)
        {
            Console.WriteLine("ConsumerWithAutoAck test");

            if (args.Length == 0)
            {
                System.Console.WriteLine(CommandLineArguments.Usage());
                return;
            }

            CommandLineArguments cliArgs = new CommandLineArguments();
            Parser parser = new Parser(System.Environment.CommandLine, cliArgs);

            parser.Parse();

            BrokerClient brokerClient = new BrokerClient(new HostInfo(cliArgs.Hostname, cliArgs.PortNumber));

            Subscription subscription = new Subscription(cliArgs.DestinationName, cliArgs.DestinationType);

            if (cliArgs.DestinationType != NetAction.DestinationType.TOPIC)
            {
                // Set AutoAcknowledge
                subscription.AutoAcknowledge = true;
            }

            int i = 0;

            subscription.OnMessage += delegate(NetNotification notification)
            {
                System.Console.WriteLine("Message received: {0}, Total: {1}",
                                         System.Text.Encoding.UTF8.GetString(notification.Message.Payload), (++i).ToString());

                /*
                 *  AutoAcknowledge is enable, so, there is no need to excplicit acknowledge message
                 *
                 * if (notification.DestinationType != NetAction.DestinationType.TOPIC)
                 * {
                 *  brokerClient.Acknowledge(notification);
                 * }
                 */
            };

            brokerClient.Subscribe(subscription);

            Console.WriteLine("Write X to unsbscribe and exit");
            while (!System.Console.Read().Equals('X'))
            {
                ;
            }
            Console.WriteLine();
            Console.WriteLine("Unsubscribe...");

            // Note Subscription instance could other than the one used for subscription as long as it was equivelent (same destination type and subscription pattern). Since the application is ending and therefor the socket will be closed agent's will discard the previous subscription.
            brokerClient.Unsubscribe(subscription);

            Console.WriteLine("Good bye");
        }
Пример #25
0
        public string VerificaCredenziali(string username, string password, string role)
        {
            string       addr   = null;
            BrokerClient client = new BrokerClient();

            addr = client.GestisciLogin(username, password, role);
            client.Close();
            return(addr);
        }
Пример #26
0
        /// <summary>
        /// Gets the client
        /// If the broker client is null, a broker client is created by the client id and returned
        /// If the broker client is not null, the client id must match the broker client's id if this is not a singleton frontend, otherwise an exception would be throwed
        /// </summary>
        /// <param name="clientId">indicating the client id</param>
        /// <returns>the broker client</returns>
        private BrokerClient GetClient(string clientId)
        {
            // Bug 3062: For http client, the connection is always the same thus we should allow different client id in the same channel
            if (this.isSingleton)
            {
                BrokerClient client = this.clientManager.GetClient(clientId, GetUserName());
                client.SingletonInstanceConnected();
                return(client);
            }
            else
            {
                if (this.client == null)
                {
                    lock (this.lockToCreateClient)
                    {
                        if (this.client == null)
                        {
                            //get domainUsername.
                            string domainUsername;
                            if (SoaCommonConfig.WithoutSessionLayer)
                            {
                                string domain   = Environment.UserDomainName;
                                string username = Environment.UserName;
                                if (domain != System.Net.Dns.GetHostName())
                                {
                                    domainUsername = Path.Combine(domain, username);
                                }
                                else
                                {
                                    domainUsername = username;
                                }
                            }
                            else
                            {
                                domainUsername = GetUserName();
                            }
                            this.client = this.clientManager.GetClient(clientId, domainUsername);
                            this.client.FrontendConnected(this, this);
                            return(this.client);
                        }
                    }
                }

                if (String.Compare(this.client.ClientId, clientId, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    return(this.client);
                }
                else
                {
                    ThrowHelper.ThrowSessionFault(SOAFaultCode.Broker_ClientIdNotMatch, SR.ClientIdNotMatch);
                    Debug.Fail("[ServiceJobMonitor] This line could not be reached.");
                    return(null);
                }
            }
        }
Пример #27
0
 private static void LoopPublish()
 {
     while (true)
     {
         SensorInfo value = SensorFaker.Generate();
         CurrValue = JsonConvert.SerializeObject(value, Formatting.Indented);
         BrokerClient.Publish("home/device/data", Encoding.Default.GetBytes(CurrValue));
         Console.WriteLine($"Published: {CurrValue}");
         Thread.Sleep(1000);
     }
 }
        public async Task WhenGetBrokerStatsIsCalledAgain_StatsAreAddedToTheList()
        {
            var brokerClient = new BrokerClient(new MockBrokerServiceLocatorMultiPartition());
            await brokerClient.GetBrokerStatsAsync();

            var queueStats = await brokerClient.GetBrokerStatsAsync();

            Assert.IsTrue(queueStats.Count == 2);
            Assert.IsTrue(queueStats.ContainsKey("MessageOneQueue") && queueStats["MessageOneQueue"].Count == 2 && queueStats["MessageOneQueue"].Last().TotalDelivered == 39);
            Assert.IsTrue(queueStats.ContainsKey("MessageTwoQueue") && queueStats["MessageTwoQueue"].Count == 2 && queueStats["MessageTwoQueue"].Last().TotalReceived == 510);
        }
        public async Task WhenUnsubscribeByQueueName_UnsubscribeIsCalledWithTheRightReferenceWrapper()
        {
            var brokerService = new MockBrokerServicePartitionOne();
            var brokerClient  = new BrokerClient(new MockBrokerServiceLocatorMultiPartition(new List <IBrokerService> {
                brokerService
            }));
            await brokerClient.UnsubscribeByQueueNameAsync("MessageOneQueue");

            Assert.IsTrue(brokerService.UnsubscribeMessageTypeName == "MessageOneQueue");
            Assert.IsInstanceOfType(brokerService.UnsubscribeReference, typeof(ServiceReferenceWrapper));
        }
Пример #30
0
        /// <summary>
        /// Asks VS to open specified URL in the help window browser
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        async Task IRCallbacks.WebBrowser(string url, CancellationToken cancellationToken)
        {
            var callback = _callback;

            if (callback != null)
            {
                var newUrl = await BrokerClient.HandleUrlAsync(url, cancellationToken);

                await callback.ShowHelpAsync(newUrl, cancellationToken);
            }
        }
Пример #31
0
        /// <summary>
        /// Start a new session using for testing multiple sessions and maxunit parameters
        /// </summary>
        public Session StartNewSession(SessionStartInfo sessionStartInfo, int max)
        {
            Session session = Session.CreateSession(sessionStartInfo);
            var     epr     = new EndpointAddress(string.Format(NetTcpEndpointPattern, Server, session.Id));

            Info("EPR: {0}", epr);
            Info("Begin to send requests");

            string guid = Guid.NewGuid().ToString();

            try
            {
                Info("Client {0}: Begin to send requests.", guid);
                using (BrokerClient <IEchoSvc> client = new BrokerClient <IEchoSvc>(guid, session))
                {
                    for (int j = 0; j < NumberOfCalls; j++)
                    {
                        client.SendRequest <EchoRequest>(new EchoRequest(j.ToString()), j + ":" + guid);
                    }

                    Info("Client {0}: Begin to call EndOfMessage.", guid);
                    client.EndRequests();
                    Info("Client {0}: Begin to get responses.", guid);
                    int count = 0;

                    foreach (BrokerResponse <EchoResponse> response in client.GetResponses <EchoResponse>())
                    {
                        count++;
                        Info(response.Result.EchoResult);
                        string[] rtn = response.Result.EchoResult.Split(new[] { ':' });
                        Assert(
                            rtn[rtn.Length - 1] == response.GetUserData <string>().Split(new[] { ':' })[0] && response.GetUserData <string>().Split(new[] { ':' })[1] == guid,
                            "Result is corrupt: expected:computername:{0}, actual:{1}",
                            response.GetUserData <string>().Split(new[] { ':' })[0],
                            response.Result.EchoResult);
                    }

                    if (count == NumberOfCalls)
                    {
                        Info("Client {0}: Total {1} calls returned.", guid, count);
                    }
                    else
                    {
                        Error("Client {0}: Total {1} calls returned, but losing {2} results.", guid, count, NumberOfCalls - count);
                    }
                }
            }
            catch (Exception e)
            {
                Error("Unexpected exception of Client {0}", e.ToString());
                throw;
            }
            return(session);
        }
Пример #32
0
        internal static void Initialize()
        {
            Broker broker = new Broker();

            broker.service.Start();

            BrokerClient.Initialize <BrokerClient>();
            Console.WriteLine("Press any key to stop the service");
            Console.ReadKey();

            broker.service.Stop();
        }
Пример #33
0
        public SocketClient(string host, int port, BrokerClient bkClient)
        {
            _isDisposed = false;
            _isWaitingMessage = false;
            _host = host;
            _port = port;
            _bkClient = bkClient;

            // Create the socket instance
            _clientSocket = new Socket(
                AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _clientSocket.Connect(_host, _port);
        }
Пример #34
0
        static void Main(string[] args)
        {
            if (args.Length >= 1)
            {
                name = args[0];
            }

            if (args.Length >= 2)
            {
                headnode = args[1];
            }

            if (args.Length >= 3)
            {
                messageCount = int.Parse(args[2]);
            }

            Console.WriteLine("Creating session...");

            using (Session session = Session.CreateSession(new SessionStartInfo(headnode, "HelloWorld")))
            {
                using (BrokerClient<IHelloWorld> brokerClient = new BrokerClient<IHelloWorld>(session))
                {
                    brokerClient.SetResponseHandler<SayHelloResponse>(ResponseHandler);

                    Console.WriteLine("Sending requests...");

                    for (int i = 0; i < messageCount; i++)
                    {
                        brokerClient.SendRequest(new SayHelloRequest(name));
                    }

                    Console.WriteLine("Committing requests...");

                    brokerClient.EndRequests();

                    Console.WriteLine("Waiting for responses...");
                    Console.ReadLine();
                }
            }
        }
Пример #35
0
        private void RefreshClusterBrokers(string clusterName)
        {
            var remotingClient = GetAvailableNameServerRemotingClient();
            var requestData = _binarySerializer.Serialize(new GetClusterBrokersRequest { ClusterName = clusterName });
            var remotingRequest = new RemotingRequest((int)NameServerRequestCode.GetClusterBrokers, requestData);
            var remotingResponse = remotingClient.InvokeSync(remotingRequest, 30000);

            if (remotingResponse.Code == ResponseCode.Success)
            {
                var brokerInfoList = _binarySerializer.Deserialize<IEnumerable<BrokerInfo>>(remotingResponse.Body);
                var brokerClientList = new List<BrokerClient>();
                foreach (var brokerInfo in brokerInfoList)
                {
                    var client = new SocketRemotingClient(brokerInfo.AdminAddress.ToEndPoint(), Settings.SocketSetting).Start();
                    var brokerClient = new BrokerClient { BrokerInfo = brokerInfo, RemotingClient = client };
                    brokerClientList.Add(brokerClient);
                }
                IList<BrokerClient> removedList;
                if (_clusterBrokerDict.TryRemove(clusterName, out removedList))
                {
                    foreach (var brokerClient in removedList)
                    {
                        brokerClient.RemotingClient.Shutdown();
                    }
                }
                _clusterBrokerDict.TryAdd(clusterName, brokerClientList);
            }
            else
            {
                throw new Exception(string.Format("GetClusterBrokers failed, errorMessage: {0}", Encoding.UTF8.GetString(remotingResponse.Body)));
            }
        }
Пример #36
0
        static void Main(string[] args)
        {
            m_broker = new BrokerClient();

            //This need to be define before open the channel
            SetClientName();

            RunMenu();
        }
Пример #37
0
        static void Main(string[] args)
        {
            //change the headnode name here
            const string headnode = "localhost";
            const string serviceName = "JavaEchoSvc1";
            const int numRequests = 12;
            SessionStartInfo info = new SessionStartInfo(headnode, serviceName);

            Console.Write("Creating a session for EchoService...");

            // Create a durable session
            // Request and response messages in a durable session are persisted so that
            // in event of failure, no requests nor responses will be lost.  Another authorized
            // client can attached to a session with the same session Id and retrieve responses
            using (DurableSession session = DurableSession.CreateSession(info))
            {
                Console.WriteLine("done session id = {0}", session.Id);
                NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);

                // Create a BrokerClient proxy
                // This proxy is able to map One-Way, Duplex message exchange patterns
                // with the Request / Reply Services.  As such, the client program can send the
                // requests, exit and re-attach to the session to retrieve responses (see the
                // FireNRecollect project for details
                using (BrokerClient<IEchoSvc> client = new BrokerClient<IEchoSvc>(session, binding))
                {
                    Console.Write("Sending {0} requests...", numRequests);
                    for (int i = 0; i < numRequests; i++)
                    {
                        // EchoRequest are created as you add Service Reference
                        // EchoService to the project
                        EchoRequest request = new EchoRequest("hello world!");
                        client.SendRequest<EchoRequest>(request, i);
                    }

                    // Flush the message.  After this call, the runtime system
                    // starts processing the request messages.  If this call is not called,
                    // the system will not process the requests.  The client.GetResponses() will return
                    // with an empty collection
                    client.EndRequests();
                    Console.WriteLine("done");

                    Console.WriteLine("Retrieving responses...");

                    // GetResponses from the runtime system
                    // EchoResponse class is created as you add Service Reference "EchoService"
                    // to the project
                    foreach (var response in client.GetResponses<EchoResponse>())
                    {
                        try
                        {
                            string reply = response.Result.EchoResult;
                            Console.WriteLine("\tReceived response for request {0}: {1}", response.GetUserData<int>(), reply);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error occured while processing {0}-th request: {1}", response.GetUserData<int>(), ex.Message);
                        }
                    }

                    Console.WriteLine("Done retrieving {0} responses", numRequests);
                }

                //explict close the session to free the resource
                session.Close();
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Пример #38
0
Файл: Kvs.cs Проект: Baptista/SD
 static Kvs()
 {
     _client = new BrokerClient();
     _client.Register("net.tcp://localhost:1234/Kvs");
 }
Пример #39
0
        public static void SendRequests(Session session, List<BrokerClient<ISoamSvc>> clientList)
        {
            ThreadStart runnalbe = new ThreadStart(() =>
            {

                // Create a BrokerClient proxy
                // This proxy is able to map One-Way, Duplex message exchange patterns
                // with the Request / Reply Services.  As such, the client program can send the
                // requests, exit and re-attach to the session to retrieve responses (see the
                // FireNRecollect project for details
                String clientId = Guid.NewGuid().ToString();
                BrokerClient<ISoamSvc> client = new BrokerClient<ISoamSvc>(clientId, session);
                clientList.Add(client);

                for (int i = 0; i < numBatchRequests; i++)
                {
                    // SoamInvokeRequest are created as you add Service Reference
                    // SoamInvokeService to the project
                    MyInput input = new MyInput();
                    SoamInvokeRequest request = new SoamInvokeRequest();
                    request.SetSoamInputObject(input);
                    client.SendRequest<SoamInvokeRequest>(request, i);
                    //Console.WriteLine("\tSent request {0}: {1}", i, input);
                }

                // Flush the message.  After this call, the runtime system
                // starts processing the request messages.  If this call is not called,
                // the system will not process the requests.  The client.GetResponses() will return
                // with an empty collection
                client.EndRequests();
            });

            Thread[] threads = new Thread[numBatchs];
            for (int i = 0; i < numBatchs; i++)
            {
                threads[i] = new Thread(runnalbe);
                threads[i].Start();
            }

            for (int i = 0; i < numBatchs; i++)
            {
                try
                {
                    threads[i].Join();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
        }