public TicketPresentation PurchaseTicket(string eventId, string reservationId) { TicketPresentation presentation = new TicketPresentation(); PurchaseTicketRequest request = new PurchaseTicketRequest(); request.ReservationId = reservationId; request.EventId = eventId; request.CorrelationId = reservationId; PurchaseTicketResponse response = _ticketService.PurchaseTicket(request); if (response.Success) { presentation.Description = string.Format("{0} ticket(s) purchased for {1}. <br/>" + "" + "<small>Your e-ticket id is {2}</small>" , response.NoOfTickets , response.EventName , response.TicketId); presentation.EventId = response.EventId; presentation.TicketId = response.TicketId; presentation.WasAbleToPurchaseTicket = true; } else { presentation.WasAbleToPurchaseTicket = false; presentation.Description = response.Message; } return presentation; }
public TicketPresentation PurchaseReservedTicket(string EventId, string ReservationId) { TicketPresentation ticket = new TicketPresentation(); PurchaseTicketResponse response = new PurchaseTicketResponse(); PurchaseTicketRequest request = new PurchaseTicketRequest(); request.ReservationId = ReservationId; request.EventId = EventId; request.CorrelationId = ReservationId; // In this instance we can use the ReservationId response = _ticketService.PurchaseTicket(request); if (response.Success) { ticket.Description = String.Format("{0} ticket(s) purchased for {1}.<br/><small>Your e-ticket id is {2}.</small>", response.CountOfTickets, response.EventName, response.TicketId); ticket.EventId = response.EventId; ticket.TicketId = response.TicketId; ticket.WasAbleToPurchaseTicket = true; } else { ticket.WasAbleToPurchaseTicket = false; ticket.Description = response.Message; } return(ticket); }
public void Run() { // 95% chance that ticket purchase is approved Random gen = new Random(); bool purchaseApproved = gen.Next(100) <= (100 - failRate); // process each message PurchaseTicketRequest ticketRequestMessage = JsonConvert.DeserializeObject <PurchaseTicketRequest>(payloadMessage); try { string methodName = ticketRequestMessage.MethodName; //string iotHubName = Environment.GetEnvironmentVariable("IotHubName"); string deviceId = ticketRequestMessage.DeviceId; //string responseUrl = $"https://{iotHubName}.azure-devices.net/twins/{deviceId}/methods?api-version=2018-06-30"; string transactionId = ticketRequestMessage.TransactionId; var payload = new PurchaseTicketPayload() { TransactionId = transactionId, IsApproved = purchaseApproved, DeviceId = ticketRequestMessage.DeviceId, DeviceType = ticketRequestMessage.DeviceType, MessageType = ticketRequestMessage.MessageType, }; log.LogInformation($"Response Method: {methodName}"); InvokeMethod(methodName, payload).GetAwaiter().GetResult(); } catch (Exception ex) { log.LogError(ex.Message); } }
public void TestKioskPurchaseTicket() { FakeDeviceClient fakeDeviceClient = new FakeDeviceClient(); FakeEventScheduler fakeScheduler = new FakeEventScheduler(); TestContext.WriteLine(string.Empty); TestContext.WriteLine(">> Testing the purchase ticket simulated event.."); KioskDevice device = new KioskDevice(deviceconfig, fakeDeviceClient, fakeScheduler); // execute a purchase ticket event and check the result, it should always be false Assert.IsFalse(fakeScheduler.EventList[0].EventDelegate()); // that delegate should have sent one message to the cloud Assert.AreEqual(fakeDeviceClient.sendMessageLog.Count, 1); // check the message sent to make sure its correct // create a sample request for comparison PurchaseTicketRequest expectedRequest = new PurchaseTicketRequest() { DeviceId = deviceconfig.DeviceId, DeviceType = deviceconfig.DeviceType, TransactionId = "fakeId", CreateTime = System.DateTime.UtcNow, Price = 1, MethodName = "ReceivePurchaseTicketResponse" }; // get request message into an object so we can compare it PurchaseTicketRequest actualRequest = JsonConvert.DeserializeObject <PurchaseTicketRequest>(fakeDeviceClient.sendMessageLog[0]); // compare properties to make sure they're valid. Assert.AreEqual(actualRequest.DeviceId, expectedRequest.DeviceId); Assert.AreEqual(actualRequest.DeviceType, expectedRequest.DeviceType); Assert.AreEqual(actualRequest.MessageType, expectedRequest.MessageType); // skipping the TransactionID and CreationTime Assert.IsTrue(actualRequest.Price > 2); Assert.IsTrue(actualRequest.Price < 100); Assert.AreEqual(actualRequest.MethodName, expectedRequest.MethodName); // /// test the CloudToEvent PurchaseResponse call we expect back // TestContext.WriteLine(string.Empty); TestContext.WriteLine(">> Testing the ticket approval direct method.."); // test the direct method itself PurchaseTicketPayload approvePurchaseMethodkRequest = new PurchaseTicketPayload() { IsApproved = true, DeviceId = expectedRequest.DeviceId, DeviceType = expectedRequest.DeviceType, MessageType = expectedRequest.MessageType, }; string requestString = JsonConvert.SerializeObject(approvePurchaseMethodkRequest); // execute the method MethodRequest methodRequest = new MethodRequest(expectedRequest.MethodName, Encoding.UTF8.GetBytes(requestString)); MethodResponse methodresult = fakeDeviceClient.directMethods[0](methodRequest, null).Result; // check results Assert.AreEqual(methodresult.Status, 200); // got back an ok }
/// <summary> /// 购票 /// </summary> /// <param name="PurchaseTicketRequest">购票请求</param> /// <returns></returns> public PurchaseTicketResponse PurchaseTicket(PurchaseTicketRequest PurchaseTicketRequest) { PurchaseTicketResponse response = new PurchaseTicketResponse(); try { // Check for a duplicate transaction using the Idempotent Pattern, // the Domain Logic could cope but we can't be sure. //判断该请求在字典仓储中是否唯一 //1 即判断 if (_reservationResponse.IsAUniqueRequest(PurchaseTicketRequest.CorrelationId)) { TicketPurchase ticket; //找到指定的事件 Event my_event = _eventRepository.FindBy(new Guid(PurchaseTicketRequest.EventId)); //判断该票是否已经预定 if (my_event.CanPurchaseTicketWith(new Guid(PurchaseTicketRequest.ReservationId))) { //根据购票id购票 ticket = my_event.PurchaseTicketWith(new Guid(PurchaseTicketRequest.ReservationId)); //保存事件 _eventRepository.Save(my_event); response = ticket.ConvertToPurchaseTicketResponse(); response.Success = true; } else { response.Message = my_event.DetermineWhyATicketCannotbePurchasedWith(new Guid(PurchaseTicketRequest.ReservationId)); response.Success = false; } _reservationResponse.LogResponse(PurchaseTicketRequest.CorrelationId, response); } else { // Retrieve last response response = _reservationResponse.RetrievePreviousResponseFor(PurchaseTicketRequest.CorrelationId); } } catch (Exception ex) { // Shield Exceptions response.Message = ErrorLog.GenerateErrorRefMessageAndLog(ex); response.Success = false; } return(response); }
public void PurchaseTicketTest() { // sample payload to test PurchaseTicketRequest sampleRequest = new PurchaseTicketRequest() { DeviceId = "rjTest", DeviceType = DeviceType.TicketKiosk, TransactionId = "c3d8b13c - 3e8f - 4e57 - a7d5 - ae8adaa8c2b2", CreateTime = System.DateTime.UtcNow, Price = 54, MethodName = "ReceivePurchaseTicketResponse" }; string sampleRequestString = JsonConvert.SerializeObject(sampleRequest); // expected response PurchaseTicketPayload expectedResponse = new PurchaseTicketPayload() { DeviceId = sampleRequest.DeviceId, TransactionId = sampleRequest.TransactionId, DeviceType = sampleRequest.DeviceType, MessageType = MessageType.cmdPurchaseTicket, IsApproved = true }; string expectedResponseString = JsonConvert.SerializeObject(expectedResponse); FakeInvokeDeviceMethod serviceClient = new FakeInvokeDeviceMethod(); PurchaseTicketAction action = new PurchaseTicketAction(serviceClient, 0, sampleRequestString, logger); action.Run(); // Assert that serviceClient.invocations count is 1 Assert.That(Equals(serviceClient.invocations.Count, 1)); // Assert that the device id from the invocation is as expected Assert.That(string.Equals(serviceClient.invocations[0].device, "rjTest")); // Assert that the method name details from the invocation is as expected StringAssert.AreEqualIgnoringCase(sampleRequest.MethodName, serviceClient.invocations[0].method.MethodName); // get response to object PurchaseTicketPayload actualResponse = JsonConvert.DeserializeObject <PurchaseTicketPayload>(serviceClient.invocations[0].method.GetPayloadAsJson()); // check the expected against the actuals Assert.AreEqual(expectedResponse.DeviceId, actualResponse.DeviceId, "Device IDs do not match"); Assert.AreEqual(expectedResponse.DeviceType, actualResponse.DeviceType, "Device Types do not match"); Assert.AreEqual(expectedResponse.TransactionId, actualResponse.TransactionId, "Transaction IDs do not match"); Assert.AreEqual(expectedResponse.MessageType, actualResponse.MessageType, "Message Types do not match"); Assert.IsTrue(actualResponse.IsApproved, "Expected Ticket to be approved, but it was rejected"); }
public PurchaseTicketResponse PurchaseTicket(PurchaseTicketRequest purchaseTicketRequest) { PurchaseTicketResponse response = new PurchaseTicketResponse(); try { // Check for a duplicate transaction using the Idempotent pattern; // the Domain Logic could cope but you can’t be sure. if (_reservationResponse.IsAUniqueRequest(purchaseTicketRequest.CorrelationId)) { TicketPurchase ticket; Event Event = _eventRepository.FindBy(new Guid(purchaseTicketRequest.EventId)); if (Event.CanPurchaseTicketWith(new Guid(purchaseTicketRequest.ReservationId))) { ticket = Event.PurchaseTicketWith(new Guid(purchaseTicketRequest.ReservationId)); _eventRepository.Save(Event); response = ticket.ConvertToPurchaseTicketResponse(); response.Success = true; } else { response.Message = Event.DetermineWhyATicketCannotbePurchasedWith( new Guid(purchaseTicketRequest.ReservationId)); response.Success = false; } _reservationResponse.LogResponse(purchaseTicketRequest.CorrelationId, response); } else { response = _reservationResponse.RetrievePreviousResponseFor( purchaseTicketRequest.CorrelationId); } } catch (Exception ex) { // Shield exceptions response.Message = ErrorLog.GenerateErrorRefMessageAndLog(ex); response.Success = false; } return(response); }
public static void Run( [ EventHubTrigger("purchaseticketeventhub", Connection = "receiverConnectionString") ] EventData[] eventHubMessages, ILogger log) { // process messages foreach (EventData message in eventHubMessages) { string messagePayload = Encoding.UTF8.GetString(message.Body.Array); // process each message PurchaseTicketRequest ticketRequestMessage = JsonConvert.DeserializeObject <PurchaseTicketRequest>(messagePayload); try { string methodName = ticketRequestMessage.MethodName; string deviceId = ticketRequestMessage.DeviceId; string transactionId = ticketRequestMessage.TransactionId; var payload = new PurchaseTicketPayload() { TransactionId = transactionId, IsApproved = true, DeviceId = ticketRequestMessage.DeviceId, DeviceType = ticketRequestMessage.DeviceType, MessageType = ticketRequestMessage.MessageType, }; log.LogInformation($"Response Method: {methodName}"); var connectionString = Environment.GetEnvironmentVariable("IotHubConnectionString"); serviceClient = ServiceClient.CreateFromConnectionString(connectionString); InvokeMethod(methodName, payload).GetAwaiter().GetResult(); } catch (Exception ex) { log.LogError(ex.Message); } } }
private static async void SendPurchaseTicketMessageToCloudAsync() { var random = new Random(); PurchaseTicketRequest purchaseTicketRequest = new PurchaseTicketRequest() { DeviceId = "rjTest", DeviceType = "Kiosk", MessageType = "Purchase", TransactionId = Guid.NewGuid().ToString(), CreateTime = System.DateTime.UtcNow, Price = random.Next(2, 100), MethodName = "ReceivePurchaseTicketResponse" }; var messageString = JsonConvert.SerializeObject(purchaseTicketRequest); var eventJsonBytes = Encoding.UTF8.GetBytes(messageString); var message = new Microsoft.Azure.Devices.Client.Message(eventJsonBytes) { ContentEncoding = "utf-8", ContentType = "application/json" }; // Add a custom application property to the message. // An IoT hub can filter on these properties without access to the message body. var messageProperties = message.Properties; messageProperties.Add("deviceId", "rjTest"); // Send the telemetry message //await _deviceClient.SendMessageAsync(messageString); //DeviceClient client = DeviceClient.CreateFromConnectionString(_connectionString, TransportType.Mqtt); //client.SetMethodHandlerAsync("ReceivePurchaseTicketResponse", ReceivePurchaseTicketResponse, null).Wait(); await _deviceClient.SendMessageAsync(messageString); //await client.SendEventAsync(message); Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); Console.WriteLine(); }
private bool SendPurchaseTicketMessageToCloud() { var random = new Random(); PurchaseTicketRequest purchaseTicketRequest = new PurchaseTicketRequest() { DeviceId = this.deviceId, DeviceType = this.deviceType, TransactionId = Guid.NewGuid().ToString(), CreateTime = System.DateTime.UtcNow, Price = random.Next(2, 100), MethodName = "ReceivePurchaseTicketResponse" // must match callback method }; var messageString = JsonConvert.SerializeObject(purchaseTicketRequest); SendMessageToCloud(messageString); Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); Console.WriteLine(); return(false); // don't restart timer }
public PurchaseTicketResponse PurchaseTicket(PurchaseTicketRequest request) { PurchaseTicketResponse response = new PurchaseTicketResponse(); try { if (_messageResponse.IsUniqueRequest(request.CorrelationId)) { TicketPurchase ticketPurchase; Event eventEntity = _eventRepository.FindBy(new Guid(request.ReservationId)); if (eventEntity.CanPurchaseTicketWith(new Guid(request.ReservationId))) { ticketPurchase = eventEntity.PurchaseTicketWith(new Guid(request.ReservationId)); _eventRepository.Save(eventEntity); response = ticketPurchase.ConvertToPurchaseTicketResponse(); response.Success = true; } else { response.Message = eventEntity.DetermineWhyATicketCannotbePurchasedWith(new Guid(request.ReservationId)); response.Success = false; } _messageResponse.LogResponse(request.CorrelationId, response); } else { response = _messageResponse.RetrievePreviousResponseFor(request.CorrelationId); } } catch (Exception ex) { response.Success = false; response.Message = ErrorLog.GenerateErrorRefMessageAndLog(ex); } return(response); }
public PurchaseTicketResponse PurchaseTicket(PurchaseTicketRequest purchaseTicketRequest) { return(base.Channel.PurchaseTicket(purchaseTicketRequest)); }