Exemple #1
0
        /// <summary>
        ///     Set ourselves up as a consumer of the specific service identified by the <paramref name="svcMsg" /> passed.  Also
        ///     configures the payment card information that will
        ///     be used for purchase.
        /// </summary>
        /// <param name="service">The WPWithin service endpoint.</param>
        /// <param name="svcMsg">A description of the service (device) offered that we want to connect to.</param>
        private void ConnectToDevice(WPWithinService service, ServiceMessage svcMsg)
        {
            HceCard card = new HceCard("Bilbo", "Baggins", "Card", "5555555555554444", 11, 2018, "113");

            service.InitConsumer("http://", svcMsg.Hostname, svcMsg.PortNumber ?? 80, svcMsg.UrlPrefix, svcMsg.ServerId,
                                 card);
        }
        private void EndServiceDelivery(WPWithinService service, int serviceId, ServiceDeliveryToken token,
                                        int unitsReceived)
        {
            _output.WriteLine("Calling endServiceDelivery()");

            service.EndServiceDelivery(serviceId, token, unitsReceived);
        }
        private PaymentResponse PurchaseService(WPWithinService service, int serviceId, TotalPriceResponse pReq)
        {
            PaymentResponse pResp = service.MakePayment(pReq);

            if (pResp != null)
            {
                _output.WriteLine("Payment response: ");
                _output.WriteLine("Client UUID: {0}", pResp.ClientUuid);
                _output.WriteLine("Client ServiceId: {0}", pResp.ServerId);
                _output.WriteLine("Total paid: {0}", pResp.TotalPaid);
                _output.WriteLine("ServiceDeliveryToken.issued: {0}", pResp.ServiceDeliveryToken.Issued);
                _output.WriteLine("ServiceDeliveryToken.expiry: {0}", pResp.ServiceDeliveryToken.Expiry);
                _output.WriteLine("ServiceDeliveryToken.key: {0}", pResp.ServiceDeliveryToken.Key);
                _output.WriteLine("ServiceDeliveryToken.signature: [{0}]", ToReadableString(pResp.ServiceDeliveryToken.Signature));
                _output.WriteLine("ServiceDeliveryToken.refundOnExpiry: {0}", pResp.ServiceDeliveryToken.RefundOnExpiry);

                BeginServiceDelivery(service, serviceId, pResp.ServiceDeliveryToken, 1);
            }
            else
            {
                _error.WriteLine("Result of MakePayment call is null");
            }

            return(pResp);
        }
Exemple #4
0
 public void StartAndStop()
 {
     using (WPWithinService service = new WPWithinService("localhost", 9091, 9092))
     {
         Log.InfoFormat("Successfully created service {0}", service);
     }
 }
        private List <ServiceMessage> DiscoverDevices(WPWithinService service)
        {
            List <ServiceMessage> devices = service.DeviceDiscovery(25000).ToList();

            if (devices.Any())
            {
                _output.WriteLine("{0} services found:\n", devices.Count);

                foreach (ServiceMessage svcMsg in devices)
                {
                    _output.WriteLine("Device Description: {0}", svcMsg.DeviceDescription);
                    _output.WriteLine("Hostname: {0}", svcMsg.Hostname);
                    _output.WriteLine("Port: {0}", svcMsg.PortNumber);
                    _output.WriteLine("URL Prefix: {0}", svcMsg.UrlPrefix);
                    _output.WriteLine("ServerId: {0}", svcMsg.ServerId);
                    _output.WriteLine("--------");
                }
            }
            else
            {
                _error.WriteLine("No services found.");
            }

            return(devices);
        }
Exemple #6
0
 /// <summary>
 ///     As a consumer, this notifies the producer that service delivery should now begin.  To emulate receiving the
 ///     service, we wait for 10 seconds, the notify
 ///     the producer that all the units have been received successfully.
 /// </summary>
 /// <param name="service">The service endpoint that will communicate with the consumer.</param>
 /// <param name="serviceId">The unique identity of the service that is delivering something.</param>
 /// <param name="token">A security token that can be used to verify the authenticity of the producer.</param>
 /// <param name="unitsToSupply">The number of units that will be supplied by the service.</param>
 private void ManageServiceDelivery(WPWithinService service, int serviceId, ServiceDeliveryToken token,
                                    int unitsToSupply)
 {
     _output.WriteLine("Calling beginServiceDelivery()");
     service.BeginServiceDelivery(serviceId, token, unitsToSupply);
     _output.WriteLine("Sleeping 10 seconds..");
     Thread.Sleep(10000);
     _output.WriteLine("Calling endServiceDelivery()");
     service.EndServiceDelivery(serviceId, token, unitsToSupply);
 }
        private CommandResult FindProducers(string[] arg)
        {
            RpcAgentConfiguration consumerConfig = new RpcAgentConfiguration
            {
                LogLevel    = "panic,fatal,error,warn,info,debug",
                LogFile     = new FileInfo("WPWithinConsumer.log"),
                ServicePort = 9096,
            };
            RpcAgentManager consumerAgent = new RpcAgentManager(consumerConfig);

            consumerAgent.StartThriftRpcAgentProcess();
            try
            {
                WPWithinService service = new WPWithinService(consumerConfig);
                service.SetupDevice("Scanner", $".NET Sample Producer scanner running on ${Dns.GetHostName()}");
                List <ServiceMessage> devices = service.DeviceDiscovery(10000).ToList();

                _output.WriteLine("Found total of {0} devices", devices.Count);
                for (int deviceIndex = 0; deviceIndex < devices.Count; deviceIndex++)
                {
                    ServiceMessage device = devices[deviceIndex];
                    _output.WriteLine(
                        $"Device {deviceIndex}) {device.ServerId} running on {device.Hostname}:{device.PortNumber}");
                    _output.WriteLine($"\tDescription: {device.DeviceDescription}, URL Prefix: {device.UrlPrefix}");
                    service.InitConsumer("http://", device.Hostname, device.PortNumber ?? 80, device.UrlPrefix,
                                         device.ServerId,
                                         new HceCard("Bilbo", "Baggins", "Card", "5555555555554444", 11, 2018, "113"));
                    try
                    {
                        List <ServiceDetails> services = service.RequestServices().ToList();
                        _output.WriteLine("\t{0} services found on device {1}", services.Count, deviceIndex);
                        for (int serviceIndex = 0; serviceIndex < services.Count; serviceIndex++)
                        {
                            ServiceDetails svc = services[serviceIndex];
                            _output.WriteLine($"\t\tService {serviceIndex}) {svc.ServiceId}: {svc.ServiceDescription}");
                            List <Price> prices = service.GetServicePrices(svc.ServiceId).ToList();
                            foreach (Price price in prices)
                            {
                                _output.WriteLine("\t\t\tPrice: {0}", price);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _error.WriteLine(ex);
                    }
                }
            }
            finally
            {
                consumerAgent.StopThriftRpcAgentProcess();
            }
            return(CommandResult.Success);
        }
        private List <ServiceDetails> GetAvailableServices(WPWithinService service)
        {
            List <ServiceDetails> services = service.RequestServices().ToList();

            _output.WriteLine("{0} services found", services.Count);
            foreach (ServiceDetails svc in services)
            {
                _output.WriteLine(svc);
            }
            return(services);
        }
 private CommandResult StartRpcClient(string[] arg)
 {
     if (_rpcManager != null)
     {
         _error.WriteLine("Thrift RPC Agent already active.  Stop it before trying to start a new one");
         return(CommandResult.NonCriticalError);
     }
     _rpcManager = new RpcAgentManager(new RpcAgentConfiguration());
     _rpcManager.StartThriftRpcAgentProcess();
     _service = new WPWithinService(_defaultAgentConfig);
     return(CommandResult.Success);
 }
Exemple #10
0
        /// <summary>
        ///     This is the entry point for the consumer, that will purchase and consume a single unit of the first price, of the
        ///     first service of the first device found.
        /// </summary>
        /// <param name="service">The WPWithin service endpoint.</param>
        /// <returns>Indication of the success of the operation.</returns>
        public CommandResult MakePurchase(WPWithinService service)
        {
            service.SetupDevice("my-device", "an example consumer device");

            ServiceMessage firstDevice = DiscoverDevices(service)?.FirstOrDefault();

            if (firstDevice == null)
            {
                _error.WriteLine("No devices discovered.  Is a producer running on your network?");
                return(CommandResult.NonCriticalError);
            }
            else
            {
                _output.WriteLine("Discovered device: {0}", firstDevice);
            }

            // Configure our WPWithinService as a consumer, using a dummy payment card.
            ConnectToDevice(service, firstDevice);

            // Get the first service offered by the device.
            ServiceDetails firstService = GetAvailableServices(service)?.FirstOrDefault();

            if (firstService == null)
            {
                _error.WriteLine("Couldn't find any services offered by {0}", firstDevice);
                return(CommandResult.NonCriticalError);
            }
            else
            {
                _output.WriteLine("Found first service {0}", firstService);
            }

            // Get the first first offered by the first service on the first device.
            Price firstPrice = GetServicePrices(service, firstService.ServiceId)?.FirstOrDefault();

            if (firstPrice == null)
            {
                return(CommandResult.NonCriticalError);
            }

            TotalPriceResponse priceResponse = GetServicePriceQuote(service, firstService.ServiceId, 1,
                                                                    firstPrice.Id);

            if (priceResponse == null)
            {
                return(CommandResult.CriticalError);
            }

            PurchaseService(service, firstService.ServiceId, priceResponse);

            return(CommandResult.Success);
        }
        private List <Price> GetServicePrices(WPWithinService service, int serviceId)
        {
            List <Price> prices = service.GetServicePrices(serviceId).ToList();

            _output.WriteLine("{0} prices found for service id {1}", prices.Count, serviceId);

            foreach (Price price in prices)
            {
                _output.WriteLine(
                    $"Price:\n\tId: {price.Id}\n\tDescription: {price.Description}\n\tUnitId: {price.UnitId}\n\tUnitDescription: {price.UnitDescription}\n\tUnit Price Amount: {price.PricePerUnit.Amount}\n\tUnit Price Currency: {price.PricePerUnit.CurrencyCode}");
            }
            return(prices);
        }
 private CommandResult StopRpcClient(string[] arg)
 {
     if (_rpcManager == null)
     {
         _error.WriteLine("Thift RPC Agent not active.  Start it before trying to stop it.");
         return(CommandResult.NonCriticalError);
     }
     _service.Dispose();
     _service = null;
     _rpcManager.StopThriftRpcAgentProcess();
     _rpcManager = null;
     return(CommandResult.Success);
 }
        private void connectToDevice(WPWithinService service, ServiceMessage svcMsg)
        {
            HceCard card = new HceCard
            {
                FirstName  = "Bilbo",
                LastName   = "Baggins",
                CardNumber = "5555555555554444",
                ExpMonth   = 11,
                ExpYear    = 2018,
                Type       = "Card",
                Cvc        = "113",
            };

            service.InitConsumer("http://", svcMsg.Hostname, svcMsg.PortNumber.Value, svcMsg.UrlPrefix, svcMsg.ServerId,
                                 card);
        }
Exemple #14
0
        private CommandResult ConsumePurchase(string[] arg)
        {
            RpcAgentConfiguration consumerConfig = new RpcAgentConfiguration
            {
                LogLevel = "panic,fatal,error,warn,info,debug",
                LogFile = new FileInfo("WPWithinConsumer.log"),
                ServicePort = 9096,
            };
            RpcAgentManager consumerAgent = new RpcAgentManager(consumerConfig);
            consumerAgent.StartThriftRpcAgentProcess();

            WPWithinService service = new WPWithinService(consumerConfig);
            SimpleConsumer consumer = new SimpleConsumer(_output, _error);
            consumer.MakePurchase(service);

            consumerAgent.StopThriftRpcAgentProcess();
            return CommandResult.Success;
        }
        private TotalPriceResponse GetServicePriceQuote(WPWithinService service, int serviceId, int numberOfUnits,
                                                        int priceId)
        {
            TotalPriceResponse tpr = service.SelectService(serviceId, numberOfUnits, priceId);

            if (tpr != null)
            {
                _output.WriteLine("Received price quote:");
                _output.WriteLine("Merchant client key: {0}", tpr.MerchantClientKey);
                _output.WriteLine("Payment reference id: {0}", tpr.PaymentReferenceId);
                _output.WriteLine("Units to supply: {0}", tpr.UnitsToSupply);
                _output.WriteLine("Total price: {0}", tpr.TotalPrice);
            }
            else
            {
                _output.WriteLine("No Total Price Response received");
            }
            return(tpr);
        }
        public CommandResult MakePurchase(WPWithinService service)
        {
            service.SetupDevice("my-device", "an example consumer device");

            ServiceMessage firstDevice = DiscoverDevices(service)?.FirstOrDefault();

            if (firstDevice == null)
            {
                return(CommandResult.NonCriticalError);
            }

            connectToDevice(service, firstDevice);

            ServiceDetails firstService = GetAvailableServices(service)?.FirstOrDefault();

            if (firstService == null)
            {
                return(CommandResult.NonCriticalError);
            }

            Price firstPrice = GetServicePrices(service, firstService.ServiceId.Value)?.FirstOrDefault();

            if (firstPrice == null)
            {
                return(CommandResult.NonCriticalError);
            }

            TotalPriceResponse priceResponse = GetServicePriceQuote(service, firstService.ServiceId.Value, 1,
                                                                    firstPrice.Id.Value);

            if (priceResponse == null)
            {
                return(CommandResult.CriticalError);
            }

            PurchaseService(service, firstService.ServiceId.Value, priceResponse);

            return(CommandResult.Success);
        }
        public void StartAndStop()
        {
            RpcAgentConfiguration cfg = new RpcAgentConfiguration
            {
                CallbackPort = 9092,
                ServicePort  = 9091,
                ServiceHost  = "localhost"
            };
            RpcAgentManager mgr = new RpcAgentManager(cfg);

            mgr.StartThriftRpcAgentProcess();
            try
            {
                using (WPWithinService service = new WPWithinService(cfg))
                {
                    Log.InfoFormat("Successfully connected {0} to Thrift RPC Agent on {1}", service, cfg);
                }
            }
            finally
            {
                mgr.StopThriftRpcAgentProcess();
            }
        }
        public void SendSimpleMessage()
        {
            WPWithinService thriftClient = new WPWithinService(new RpcAgentConfiguration());

            thriftClient.SetupDevice("DotNet RPC client", "This is coming from C# via Thrift RPC.");
            Log.Info("Initialising Producer");
            thriftClient.InitProducer("cl_key", "srv_key");
            thriftClient.StartServiceBroadcast(2000);
            IEnumerable <ServiceMessage> svcMsgs = thriftClient.DeviceDiscovery(2000);

            if (svcMsgs != null)
            {
                foreach (ServiceMessage svcMsg in svcMsgs)
                {
                    Log.InfoFormat("{0} - {1} - {2} - {3}", svcMsg.DeviceDescription, svcMsg.Hostname, svcMsg.PortNumber,
                                   svcMsg.ServerId);
                }
            }
            else
            {
                Log.Info("Broadcast ok, but no services found");
            }
            Log.Info("All done, closing transport");
        }
Exemple #19
0
 public void CreateClient()
 {
     ThriftClient = new WPWithinService(RpcAgentServiceHost, RpcAgentServicePort);
 }
        public void SimpleCallbackTest()
        {
            using (WPWithinService service = new WPWithinService("localhost", 9091, 9092))
            {
                service.SetupDevice(this.GetType().Name, "Unit test from .NET wrapper");
                bool beginEventReceived = false;
                bool endEventReceived   = false;

                service.OnBeginServiceDelivery += (id, token, supply) =>
                {
                    Log.InfoFormat("BeginServiceDelivery event received: id={0}, token={1}, supply={2}", id, token,
                                   supply);
                    beginEventReceived = true;
                };
                service.OnEndServiceDelivery += (id, token, received) =>
                {
                    Log.InfoFormat("BeginServiceDelivery event received: id={0}, token={1}, supply={2}", id, token,
                                   received);
                    endEventReceived = true;
                };

                Log.Info("Initialising Producer");
                service.InitProducer("cl_key", "srv_key");
                service.StartServiceBroadcast(2000);
                List <ServiceMessage> svcMsgs = service.DeviceDiscovery(2000).ToList();

                // Invoke a service and pay for it so the start and stop events are fired.
                Assert.IsNotNull(svcMsgs, "Discovered no services (null)");
                Assert.IsTrue(svcMsgs.Count > 0, "Discovered no services (empty)");

                ServiceMessage serviceDescription = svcMsgs[0];

                if (svcMsgs != null)
                {
                    foreach (ServiceMessage svcMsg in svcMsgs)
                    {
                        Log.InfoFormat("{0} - {1} - {2} - {3}", svcMsg.DeviceDescription, svcMsg.Hostname, svcMsg.PortNumber,
                                       svcMsg.ServerId);
                    }
                }
                else
                {
                    Assert.Fail("Unable to find service to invoke");
                }

                // Wait 5 seconds for the events to be triggered (could probably do this more elegantly, another day...)
                // If not triggered, then test fails.
                for (int i = 0; i < 100; i++)
                {
                    Thread.Sleep(50);
                    if (beginEventReceived && endEventReceived)
                    {
                        break;
                    }
                }
                if (!beginEventReceived || !endEventReceived)
                {
                    Assert.Fail("BeginEvent received {0}; EndEvent received {1}", beginEventReceived, endEventReceived);
                }
            }
        }
 /// <summary>
 /// Initialises a new instance.
 /// </summary>
 /// <param name="output">Where output will be written to.</param>
 /// <param name="error">Where errors will be written to (currently unused).</param>
 /// <param name="service">An initialised service instance.</param>
 public SimpleProducer(TextWriter output, TextWriter error, WPWithinService service)
 {
     _output  = output;
     _error   = error;
     _service = service;
 }