static async Task AsyncMain() { Console.Title = "Samples.Serialization.ExternalJson"; #region config var endpointConfiguration = new EndpointConfiguration("Samples.Serialization.ExternalJson"); var settings = new JsonSerializerSettings { Formatting = Formatting.Indented }; endpointConfiguration.UseSerialization<NewtonsoftSerializer>() .Settings(settings); // register the mutator so the the message on the wire is written endpointConfiguration.RegisterComponents(components => { components.ConfigureComponent<MessageBodyWriter>(DependencyLifecycle.InstancePerCall); }); #endregion endpointConfiguration.UsePersistence<InMemoryPersistence>(); endpointConfiguration.EnableInstallers(); endpointConfiguration.SendFailedMessagesTo("error"); var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); try { #region message var message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List<OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; await endpointInstance.SendLocal(message) .ConfigureAwait(false); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } finally { await endpointInstance.Stop() .ConfigureAwait(false); } }
static async Task AsyncMain() { #region config EndpointConfiguration endpointConfiguration = new EndpointConfiguration(); endpointConfiguration.EndpointName("Samples.Serialization.ExternalBson"); SerializationExtentions<NewtonsoftSerializer> serialization = endpointConfiguration.UseSerialization<NewtonsoftSerializer>(); serialization.ReaderCreator(stream => new BsonReader(stream)); serialization.WriterCreator(stream => new BsonWriter(stream)); // register the mutator so the the message on the wire is written endpointConfiguration.RegisterComponents(components => { components.ConfigureComponent<MessageBodyWriter>(DependencyLifecycle.InstancePerCall); }); #endregion endpointConfiguration.SendFailedMessagesTo("error"); endpointConfiguration.UsePersistence<InMemoryPersistence>(); endpointConfiguration.EnableInstallers(); IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration); try { #region message CreateOrder message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List<OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; await endpoint.SendLocal(message); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } finally { await endpoint.Stop(); } }
public void ConstructorCommand_AggregateId_is_used_to_specify_the_new_instances_Id() { var id = Any.Guid(); var createOrder = new CreateOrder(Any.Paragraph(2)) { AggregateId = id }; var order = new Order(createOrder); order.Id.Should().Be(id); }
static async Task AsyncMain() { #region config BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.EndpointName("Samples.Serialization.Xml"); // this is optional since Xml is the default serializer busConfiguration.UseSerialization<XmlSerializer>(); // register the mutator so the the message on the wire is written busConfiguration.RegisterComponents(components => { components.ConfigureComponent<MessageBodyWriter>(DependencyLifecycle.InstancePerCall); }); #endregion busConfiguration.UsePersistence<InMemoryPersistence>(); busConfiguration.EnableInstallers(); busConfiguration.SendFailedMessagesTo("error"); IEndpointInstance endpoint = await Endpoint.Start(busConfiguration); try { IBusSession busSession = endpoint.CreateBusSession(); #region message CreateOrder message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List<OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; await busSession.SendLocal(message); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } finally { await endpoint.Stop(); } }
static void Main() { Console.Title = "Samples.Serialization.Jil"; #region config BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.EndpointName("Samples.Serialization.Jil"); busConfiguration.UseSerialization<JilSerializer>() .Options( new Options( prettyPrint: true, excludeNulls: true, includeInherited: true)); // register the mutator so the the message on the wire is written busConfiguration.RegisterComponents(components => { components.ConfigureComponent<MessageBodyWriter>(DependencyLifecycle.InstancePerCall); }); #endregion busConfiguration.UsePersistence<InMemoryPersistence>(); busConfiguration.EnableInstallers(); using (IBus bus = Bus.Create(busConfiguration).Start()) { #region message CreateOrder message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List<OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; bus.SendLocal(message); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } }
static void Main() { Console.Title = "Samples.Serialization.ExternalJson"; #region config BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.EndpointName("Samples.Serialization.ExternalJson"); JsonSerializerSettings settings = new JsonSerializerSettings { Formatting = Formatting.Indented }; busConfiguration.UseSerialization<NewtonsoftSerializer>() .Settings(settings); // register the mutator so the the message on the wire is written busConfiguration.RegisterComponents(components => { components.ConfigureComponent<MessageBodyWriter>(DependencyLifecycle.InstancePerCall); }); #endregion busConfiguration.UsePersistence<InMemoryPersistence>(); busConfiguration.EnableInstallers(); using (IBus bus = Bus.Create(busConfiguration).Start()) { #region message CreateOrder message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List<OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; bus.SendLocal(message); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } }
public Order Post(CreateOrder request) { var newOrder = request.TranslateTo<Order>(); newOrder.Status = "New"; DbConnExecTransaction((con) => { con.Insert(newOrder); newOrder.Id = (int) con.GetLastInsertId(); }); RedisExec((redisCon) => redisCon.PublishMessage("NewOrder", newOrder.ToJson())); return newOrder; }
static void Main() { Console.Title = "Samples.Serialization.Xml"; #region config //this is optional since Xml is the default serializer Configure.Serialization.Xml(); var configure = Configure.With(); configure.Log4Net(); configure.DefineEndpointName("Samples.Serialization.Xml"); configure.DefaultBuilder(); // register the mutator so the the message on the wire is written configure.Configurer .ConfigureComponent<MessageBodyWriter>(DependencyLifecycle.InstancePerCall); #endregion configure.InMemorySagaPersister(); configure.UseInMemoryTimeoutPersister(); configure.InMemorySubscriptionStorage(); configure.UseTransport<Msmq>(); using (var startableBus = configure.UnicastBus().CreateBus()) { var bus = startableBus.Start(() => configure.ForInstallationOn<Windows>().Install()); #region message var message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List<OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; bus.SendLocal(message); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } }
static async Task AsyncMain() { Console.Title = "Samples.Serialization.Wire"; #region config EndpointConfiguration endpointConfiguration = new EndpointConfiguration("Samples.Serialization.Wire"); endpointConfiguration.UseSerialization<WireSerializer>(); #endregion endpointConfiguration.UsePersistence<InMemoryPersistence>(); endpointConfiguration.EnableInstallers(); endpointConfiguration.SendFailedMessagesTo("error"); IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration); try { #region message CreateOrder message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List<OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; await endpoint.SendLocal(message); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } finally { await endpoint.Stop(); } }
static async Task AsyncMain() { #region config BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.EndpointName("Samples.Serialization.Json"); busConfiguration.UseSerialization<JsonSerializer>(); // register the mutator so the the message on the wire is written busConfiguration.RegisterComponents(components => { components.ConfigureComponent<MessageBodyWriter>(DependencyLifecycle.InstancePerCall); }); #endregion busConfiguration.UsePersistence<InMemoryPersistence>(); busConfiguration.EnableInstallers(); busConfiguration.SendFailedMessagesTo("error"); using (IBus bus = await Bus.Create(busConfiguration).StartAsync()) { #region message CreateOrder message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List<OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; await bus.SendLocalAsync(message); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } }
static void Main() { Console.Title = "Samples.Serialization.Binary"; #region config Configure.Serialization.Binary(); var configure = Configure.With(); configure.Log4Net(); configure.DefineEndpointName("Samples.Serialization.Binary"); #endregion configure.DefaultBuilder(); configure.InMemorySagaPersister(); configure.UseInMemoryTimeoutPersister(); configure.InMemorySubscriptionStorage(); configure.UseTransport<Msmq>(); using (var startableBus = configure.UnicastBus().CreateBus()) { var bus = startableBus.Start(() => configure.ForInstallationOn<Windows>().Install()); #region message var message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List<OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; bus.SendLocal(message); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } }
static void Main() { Console.Title = "Samples.Serialization.Binary"; #region config BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.EndpointName("Samples.Serialization.Binary"); busConfiguration.UseSerialization<BinarySerializer>(); #endregion busConfiguration.UsePersistence<InMemoryPersistence>(); busConfiguration.EnableInstallers(); using (IBus bus = Bus.Create(busConfiguration).Start()) { #region message CreateOrder message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List<OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; bus.SendLocal(message); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } }
public override async Task When_a_clock_is_set_on_a_command_then_it_takes_precedence_over_GetClockName() { // arrange var clockName = Any.CamelCaseName(); var create = new CreateOrder(Any.FullName()) { AggregateId = Any.Guid() }; var clock = new CommandScheduler.Clock { Name = clockName, UtcNow = DateTimeOffset.Parse("2016-03-01 02:00:00 AM") }; using (var commandScheduler = new CommandSchedulerDbContext()) { commandScheduler.Clocks.Add(clock); commandScheduler.SaveChanges(); } var scheduledCommand = new ScheduledCommand<Order>( aggregateId: create.AggregateId, command: create, dueTime: DateTimeOffset.Parse("2016-03-20 09:00:00 AM")) { Clock = clock }; // act var configuration = Configuration.Current; await configuration.CommandScheduler<Order>().Schedule(scheduledCommand); await configuration.SchedulerClockTrigger() .AdvanceClock(clockName, by: 30.Days()); //assert var target = await configuration.Repository<Order>().GetLatest(create.AggregateId); target.Should().NotBeNull(); }
public async Task <IActionResult> Index( [FromServices] IOptionsMonitor <StripeSettings> optionsMonitor, [FromServices] CreateOrder createOrder, [FromServices] GetCart getCart) { StripeConfiguration.ApiKey = optionsMonitor.CurrentValue.SecretKey; var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); try { var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], optionsMonitor.CurrentValue.SigningSecret); _logger.LogInformation("received stripe event {0} {1}", Environment.NewLine, json); if (stripeEvent.Type == Events.PaymentIntentCreated) { var paymentMethod = stripeEvent.Data.Object as PaymentIntent; } else if (stripeEvent.Type == Events.ChargeSucceeded) { var paymentMethod = stripeEvent.Data.Object as Charge; } else if (stripeEvent.Type == Events.PaymentMethodAttached) { var paymentMethod = stripeEvent.Data.Object as PaymentMethod; } else if (stripeEvent.Type == Events.PaymentIntentSucceeded) { var paymentIntent = stripeEvent.Data.Object as PaymentIntent; } else if (stripeEvent.Type == Events.CustomerCreated) { var paymentMethod = stripeEvent.Data.Object as Customer; } else if (stripeEvent.Type == Events.CheckoutSessionCompleted) { var checkoutSession = stripeEvent.Data.Object as Session; var order = new Domain.Models.Order { StripeReference = checkoutSession.Id, CartId = await getCart.Id(checkoutSession.Metadata["user_id"]), }; await createOrder.Do(order); _logger.LogInformation("created order {0},{1}: {2}", order.Id, Environment.NewLine, JsonConvert.SerializeObject(order)); } else { return(BadRequest()); } return(Ok()); } catch (StripeException e) { return(BadRequest(e.Message)); } }
public async Task <IActionResult> OnPost(string stripeEmail, string stripeToken, [FromServices] GetOrderCart getOrder, [FromServices] CreateOrder createOrder, [FromServices] ISessionManager sessionManager) { var customers = new CustomerService(); var charges = new ChargeService(); var cartOrder = getOrder.Exec(); var customer = customers.Create(new CustomerCreateOptions { Email = stripeEmail, Source = stripeToken }); var charge = charges.Create(new ChargeCreateOptions { Amount = cartOrder.GetTotalCharge(), Description = "Shop Purchase", Currency = "usd", Customer = customer.Id }); var sessionId = HttpContext.Session.Id; await createOrder.ExecAsync(new CreateOrderDto { SessionId = sessionId, StripeRef = charge.Id, FirstName = cartOrder.CustomerInformation.FirstName, LastName = cartOrder.CustomerInformation.LastName, Email = cartOrder.CustomerInformation.Email, PhoneNumber = cartOrder.CustomerInformation.PhoneNumber, Address = cartOrder.CustomerInformation.Address, City = cartOrder.CustomerInformation.City, PostCode = cartOrder.CustomerInformation.PostCode, Stocks = cartOrder.Products.Select(x => new StockViewModel { StockId = x.StockId, Quantity = x.Quantity }).ToList() }); sessionManager.ClearCart(); return(RedirectToPage("/Index")); }
static void Main(string[] args) { log4net.Config.XmlConfigurator.ConfigureAndWatch( new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config"))); Console.WriteLine("请输入微信授权码:"); string code = Console.ReadLine(); Console.WriteLine("正在支付。。。。"); CreateOrder createParam = new CreateOrder { auth_code = code.Trim(), //device_info = "test_device_id", device_info = "hlgxczs", partner_id = partner_id, nonce_str = Guid.NewGuid().ToString().Replace("-", ""), total_fee = "1", time_expire = "5", no_rebate_money = "0", spbill_create_ip = "127.0.0.1", operation_id = "0" }; var createResponeXml = CommonSDK.CommonSDK.CreateOrder(createParam, key, ltCreateOrderUrl); Log.InfoFormat("{0}", createResponeXml); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(".......................下单返回......................"); Console.WriteLine(string.Format("下单返回{0}", createResponeXml)); Console.WriteLine(".......................执行查询......................"); WxPayData responseData = new WxPayData(); responseData.FromXml(createResponeXml, key); object shop_id = string.Empty; //窝窝门店ID object supplier_id = string.Empty; //窝窝商户ID object order_id = string.Empty; //窝窝流水号 shop_id = responseData.GetValue("shop_id") ?? ""; supplier_id = responseData.GetValue("supplier_id") ?? ""; order_id = responseData.GetValue("order_id") ?? ""; QueryOrder queryParam = new QueryOrder { nonce_str = Guid.NewGuid().ToString().Replace("-", ""), partner_id = partner_id, shop_id = shop_id.ToString(), supplier_id = supplier_id.ToString(), order_id = order_id.ToString() }; var queryResponeXml = CommonSDK.CommonSDK.QueryOrder(queryParam, key, ltQueryOrderUrl); Log.InfoFormat("查询返回{0}", queryResponeXml); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(".......................查询返回......................"); Console.WriteLine(string.Format("{0}", queryResponeXml)); Console.ReadKey(); }
private void startButton_Click(object sender, EventArgs e) { CreateOrder createOrder = new CreateOrder(); WireEventHandlers(createOrder); string message; string caption; MessageBoxButtons buttons = MessageBoxButtons.OK; DialogResult result; if (TorButton.Checked) { Program.sLoc = "TOR"; Program.torbackupPath = System.Configuration.ConfigurationManager.AppSettings["tor_backup_path"]; Program.iLoc = Program.iLoc ^ 1; } else if (TorandMtlButton.Checked) { Program.sLoc = "TORMTL"; Program.torbackupPath = System.Configuration.ConfigurationManager.AppSettings["tor_backup_path"]; Program.iLoc = Program.iLoc ^ 1; Program.iLoc = Program.iLoc ^ 2; } else if (MtlButton.Checked) { Program.sLoc = "MTL"; Program.torbackupPath = System.Configuration.ConfigurationManager.AppSettings["tor_backup_path"]; Program.iLoc = Program.iLoc ^ 2; } else if (VanButton.Checked) { Program.sLoc = "VAN"; Program.vanbackupPath = System.Configuration.ConfigurationManager.AppSettings["van_backup_path"]; Program.iLoc = Program.iLoc ^ 4; } else if (CalButton.Checked) { Program.sLoc = "CAL"; Program.vanbackupPath = System.Configuration.ConfigurationManager.AppSettings["van_backup_path"]; Program.iLoc = Program.iLoc ^ 8; } else if (VanandCalButton.Checked) { Program.sLoc = "VANCAL"; Program.vanbackupPath = System.Configuration.ConfigurationManager.AppSettings["van_backup_path"]; Program.iLoc = Program.iLoc ^ 4; Program.iLoc = Program.iLoc ^ 8; } if (printToPrinter.Checked) { Program.output = "printer"; } else { Program.output = "preview"; } if (emailSalesRep.Checked) { Program.emailSalesRep = true; } else { Program.emailSalesRep = false; } if (createOrder.PerformPDAImport()) { message = "Import Finished Successfully."; } else { message = "Import had errors!"; } if (TorButton.Checked) { Utilities.CopyFile(Program.torbackupPath, Program.txtOutputFile, System.Configuration.ConfigurationManager.AppSettings["tor_error_path"], System.Configuration.ConfigurationManager.AppSettings["tor_email_bad_data"], System.Configuration.ConfigurationManager.AppSettings["tor_email_bad_data_cc"]); } else if (TorandMtlButton.Checked) { Utilities.CopyFile(Program.torbackupPath, Program.txtOutputFile, System.Configuration.ConfigurationManager.AppSettings["tor_error_path"], System.Configuration.ConfigurationManager.AppSettings["tor_email_bad_data"], System.Configuration.ConfigurationManager.AppSettings["tor_email_bad_data_cc"]); } else if (MtlButton.Checked) { Utilities.CopyFile(Program.torbackupPath, Program.txtOutputFile, System.Configuration.ConfigurationManager.AppSettings["tor_error_path"], System.Configuration.ConfigurationManager.AppSettings["tor_email_bad_data"], System.Configuration.ConfigurationManager.AppSettings["tor_email_bad_data_cc"]); } else if (VanButton.Checked) { Utilities.CopyFile(Program.vanbackupPath, Program.txtOutputFile, System.Configuration.ConfigurationManager.AppSettings["van_error_path"], System.Configuration.ConfigurationManager.AppSettings["van_email_bad_data"], System.Configuration.ConfigurationManager.AppSettings["van_email_bad_data_cc"]); } else if (CalButton.Checked) { Utilities.CopyFile(Program.vanbackupPath, Program.txtOutputFile, System.Configuration.ConfigurationManager.AppSettings["van_error_path"], System.Configuration.ConfigurationManager.AppSettings["van_email_bad_data"], System.Configuration.ConfigurationManager.AppSettings["van_email_bad_data_cc"]); } else if (VanandCalButton.Checked) { Utilities.CopyFile(Program.vanbackupPath, Program.txtOutputFile, System.Configuration.ConfigurationManager.AppSettings["van_error_path"], System.Configuration.ConfigurationManager.AppSettings["van_email_bad_data"], System.Configuration.ConfigurationManager.AppSettings["van_email_bad_data_cc"]); } caption = "Status of Import"; result = MessageBox.Show(message, caption, buttons); this.Close(); }
public void TestEventRequest() { var createOrder = new CreateOrder { user_id = "test_dotnet_booking_with_all_fields", order_id = "oid", amount = 1000000000000L, currency_code = "USD", session_id = "gigtleqddo84l8cm15qe4il", user_email = "*****@*****.**", bookings = new ObservableCollection <Booking>() { new Booking() { booking_type = "$flight", title = "SFO - LAS, 2 Adults", start_time = 2038412903, end_time = 2038412903, price = 49900000, currency_code = "USD", quantity = 1, venue_id = "venue-123", event_id = "event-123", room_type = "deluxe", category = "pop", guests = new ObservableCollection <Guest>() { new Guest() { name = "John Doe", birth_date = "1985-01-19", loyalty_program = "skymiles", loyalty_program_id = "PSOV34DF", phone = "1-415-555-6040", email = "*****@*****.**" }, new Guest() { name = "John Doe" } }, segments = new ObservableCollection <Segment>() { new Segment() { departure_address = new Address { name = "Bill Jones", phone = "1-415-555-6040", address_1 = "2100 Main Street", address_2 = "Apt 3B", city = "New London", region = "New Hampshire", country = "US", zipcode = "03257" }, arrival_address = new Address { name = "Bill Jones", phone = "1-415-555-6040", address_1 = "2100 Main Street", address_2 = "Apt 3B", city = "New London", region = "New Hampshire", country = "US", zipcode = "03257" }, start_time = 203841290300L, end_time = 2038412903, vessel_number = "LH454", fare_class = "Premium Economy", departure_airport_code = "SFO", arrival_airport_code = "LAS" } }, location = new Address { name = "Bill Jones", phone = "1-415-555-6040", address_1 = "2100 Main Street", address_2 = "Apt 3B", city = "New London", region = "New Hampshire", country = "US", zipcode = "03257" }, tags = new ObservableCollection <string>() { "tag-123", "tag-321" } } }, billing_address = new Address { name = "gary", city = "san francisco" }, app = new App { app_name = "my app", app_version = "1.0", client_language = "en-US" }, ordered_from = new OrderedFrom { store_id = "123", store_address = new Address { name = "Bill Jones", phone = "1-415-555-6040", address_1 = "2100 Main Street", address_2 = "Apt 3B", city = "New London", region = "New Hampshire", country = "US", zipcode = "03257" } }, site_country = "US", site_domain = "sift.com", keyless_user_id = "keylessId", brand_name = "sift" }; // Augment with custom fields createOrder.AddField("foo", "bar"); Assert.Equal("{\"$type\":\"$create_order\",\"$user_id\":\"test_dotnet_booking_with_all_fields\"," + "\"$session_id\":\"gigtleqddo84l8cm15qe4il\",\"$order_id\":\"oid\",\"$user_email\":\"[email protected]\"," + "\"$amount\":1000000000000,\"$currency_code\":\"USD\",\"$billing_address\":{\"$name\":\"gary\",\"$city\":\"san francisco\"}," + "\"$bookings\":[{\"$booking_type\":\"$flight\",\"$title\":\"SFO - LAS, 2 Adults\",\"$start_time\":2038412903," + "\"$end_time\":2038412903,\"$price\":49900000,\"$currency_code\":\"USD\",\"$quantity\":1,\"$guests\":[{\"$name\":\"John Doe\"," + "\"$email\":\"[email protected]\",\"$phone\":\"1-415-555-6040\",\"$loyalty_program\":\"skymiles\",\"$loyalty_program_id\":\"PSOV34DF\"," + "\"$birth_date\":\"1985-01-19\"},{\"$name\":\"John Doe\"}],\"$segments\":[{\"$start_time\":203841290300,\"$end_time\":2038412903," + "\"$vessel_number\":\"LH454\",\"$departure_airport_code\":\"SFO\",\"$arrival_airport_code\":\"LAS\",\"$fare_class\":\"Premium Economy\"," + "\"$departure_address\":{\"$name\":\"Bill Jones\",\"$address_1\":\"2100 Main Street\",\"$address_2\":\"Apt 3B\",\"$city\":\"New London\"," + "\"$region\":\"New Hampshire\",\"$country\":\"US\",\"$zipcode\":\"03257\",\"$phone\":\"1-415-555-6040\"}," + "\"$arrival_address\":{\"$name\":\"Bill Jones\",\"$address_1\":\"2100 Main Street\",\"$address_2\":\"Apt 3B\",\"$city\":\"New London\"," + "\"$region\":\"New Hampshire\",\"$country\":\"US\",\"$zipcode\":\"03257\",\"$phone\":\"1-415-555-6040\"}}],\"$room_type\":\"deluxe\"," + "\"$event_id\":\"event-123\",\"$venue_id\":\"venue-123\",\"$location\":{\"$name\":\"Bill Jones\",\"$address_1\":\"2100 Main Street\"," + "\"$address_2\":\"Apt 3B\",\"$city\":\"New London\",\"$region\":\"New Hampshire\",\"$country\":\"US\",\"$zipcode\":\"03257\"," + "\"$phone\":\"1-415-555-6040\"},\"$category\":\"pop\",\"$tags\":[\"tag-123\",\"tag-321\"]}],\"$app\":{\"$app_name\":\"my app\"," + "\"$app_version\":\"1.0\",\"$client_language\":\"en-US\"},\"$brand_name\":\"sift\",\"$site_country\":\"US\",\"$site_domain\":\"sift.com\"," + "\"$ordered_from\":{\"$store_id\":\"123\",\"$store_address\":{\"$name\":\"Bill Jones\",\"$address_1\":\"2100 Main Street\"," + "\"$address_2\":\"Apt 3B\",\"$city\":\"New London\",\"$region\":\"New Hampshire\",\"$country\":\"US\",\"$zipcode\":\"03257\"," + "\"$phone\":\"1-415-555-6040\"}},\"$keyless_user_id\":\"keylessId\",\"foo\":\"bar\"}", createOrder.ToJson()); EventRequest eventRequest = new EventRequest { Event = createOrder }; Assert.Equal("https://api.sift.com/v205/events", eventRequest.Request.RequestUri.ToString()); eventRequest = new EventRequest { Event = createOrder, AbuseTypes = { "legacy", "payment_abuse" }, ReturnScore = true, ReturnRouteInfo = true }; Assert.Equal("https://api.sift.com/v205/events?abuse_types=legacy,payment_abuse&return_score=true&return_route_info=true", Uri.UnescapeDataString(eventRequest.Request.RequestUri.ToString())); }
public void Post([FromBody] CreateOrder value) { _orderServices.handle(value); }
/* * FUNCTION: btnCreateOrder_Click(object sender, RoutedEventArgs e) * DESCRIPTION: Open view to create order * PARAMETERS: object sender - The object that is responsible for firing the event * RoutedEventArgs e - The arguments to be manipulated due to the event * RETURNS: NONE * DEV: */ private void btnCreateOrder_Click(object sender, RoutedEventArgs e) { CreateOrder createOrder = new CreateOrder(); createOrder.ShowDialog(); }
public void Post([FromBody] CreateOrder value) { _handler.HandleCommand(value); }
/// <summary> /// Submit a new or existing order to Thirdwatch for review. This API should contain order item info, the payment info, and user identity info. /// </summary> /// <exception cref="ai.thirdwatch.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">An order to submit for review. Only `_userID` is required field. But this should contain order info.</param> /// <returns>Task of ApiResponse (EventResponse)</returns> public async System.Threading.Tasks.Task <ApiResponse <EventResponse> > CreateOrderAsyncWithHttpInfo(CreateOrder body) { // verify the required parameter 'body' is set if (body == null) { throw new ApiException(400, "Missing required parameter 'body' when calling CreateOrderApi->CreateOrder"); } var localVarPath = "/v1/createOrder"; var localVarPathParams = new Dictionary <String, String>(); var localVarQueryParams = new List <KeyValuePair <String, String> >(); var localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary <String, String>(); var localVarFileParams = new Dictionary <String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) { localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); } if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("X-THIRDWATCH-API-KEY"))) { localVarHeaderParams["X-THIRDWATCH-API-KEY"] = Configuration.GetApiKeyWithPrefix("X-THIRDWATCH-API-KEY"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse)await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int)localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("CreateOrder", localVarResponse); if (exception != null) { throw exception; } } return(new ApiResponse <EventResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (EventResponse)Configuration.ApiClient.Deserialize(localVarResponse, typeof(EventResponse)))); }
[TestFixtureSetUp] public void Context() { _order = CreateOrder.Of(new Product(10)).In(StateOf.CA); }
/// <summary> /// Submit a new or existing order to Thirdwatch for review. This API should contain order item info, the payment info, and user identity info. /// </summary> /// <exception cref="ai.thirdwatch.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">An order to submit for review. Only `_userID` is required field. But this should contain order info.</param> /// <returns>Task of EventResponse</returns> public async System.Threading.Tasks.Task <EventResponse> CreateOrderAsync(CreateOrder body) { ApiResponse <EventResponse> localVarResponse = await CreateOrderAsyncWithHttpInfo(body); return(localVarResponse.Data); }
/// <summary> /// Submit a new or existing order to Thirdwatch for review. This API should contain order item info, the payment info, and user identity info. /// </summary> /// <exception cref="ai.thirdwatch.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">An order to submit for review. Only `_userID` is required field. But this should contain order info.</param> /// <returns>EventResponse</returns> public EventResponse CreateOrder(CreateOrder body) { ApiResponse <EventResponse> localVarResponse = CreateOrderWithHttpInfo(body); return(localVarResponse.Data); }
public IActionResult Post([FromBody] CreateOrder newOrder) { var result = orderService.CreateOrder(newOrder).Result; return(Ok(result)); }
static async Task Main() { Console.Title = "Samples.Serialization.ExternalJson"; #region config var endpointConfiguration = new EndpointConfiguration("Samples.Serialization.ExternalJson"); var settings = new JsonSerializerSettings { Formatting = Formatting.Indented }; var serialization = endpointConfiguration.UseSerialization <NewtonsoftSerializer>(); serialization.Settings(settings); #endregion #region registermutator endpointConfiguration.RegisterComponents( registration: components => { components.ConfigureComponent <MessageBodyWriter>(DependencyLifecycle.InstancePerCall); }); #endregion endpointConfiguration.UsePersistence <LearningPersistence>(); endpointConfiguration.UseTransport <LearningTransport>(); var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); #region message var message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List <OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; await endpointInstance.SendLocal(message) .ConfigureAwait(false); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); await endpointInstance.Stop() .ConfigureAwait(false); }
public async Task CreateOrder([FromBody] CreateOrder command) { await CashRegister.Handle(command); }
/// <summary> /// 在线预约,成功返回订单号 /// </summary> /// <param name="request"></param> /// <returns></returns> public string execute(string request) { //1211|1张三|21381234567|3莘凌路211号(小锦江酒店)|421:00|5asdfas1231asd|6IMEI|7MD5串|8lat|9lng|10remark|11youhui|12youhuijine string result = "0"; string[] req = request.Split('|'); var sign = EncodingUtil.GetMd5(req[2] + "aidaijia", "utf-8"); if (sign.ToLower() == req[7].ToLower()) { //判断T_ClentInfo是否有此手机号相关信息 //如果用户不存在,创建一个新用户 CustomerInfoEntity cinfo = new D_CustomerInfoDal().GetClientInfoByPhone(req[2].Trim()); T_ParterEntity parter = new T_PartyDal().GetParterModelBySign(req[5].ToLower()); if (parter != null) { #region 用户不存在则创建 if (cinfo == null) { int clentnum = new D_CustomerInfoDal().SelectSeqClent(); if (clentnum != 0) { string num = string.Empty; for (int i = 0; i < 8 - clentnum.ToString().Length; i++) { num += @"0"; } num = "U" + num + clentnum; CustomerInfoEntity customerEn = new CustomerInfoEntity() { AccountType = 2, Amount = 0, BusinessmanId = 0, Cellphone = req[2].Trim(), ParentPhone = req[2].Trim(), CustomerId = num, CustomerName = req[1].Trim(), CustomerType = 1, Email = string.Empty, HomeAddress = string.Empty, IsNewCustomer = true, LastAppointmentTime = null, LastCalledAddress = string.Empty, RecommendCode = new D_CustomerInfoDal().GenerateCustomerRecommendCode( new D_CustomerInfoDal().SelectSeqClent()), RegisterFrom = 5, //第三方API RegisterVersion = "" }; bool isture = new D_CustomerInfoDal().AddCustomerInfo(customerEn); if (!isture) { //return "0"; throw new Exception("添加新用户失败。"); } cinfo = customerEn; } else { //return "0"; throw new Exception("获取客户种子数失败。"); } } #endregion #region 优惠码操作 string couponCode = ""; if (!WebUtility.ConfigHelper.CloseSign.ToLower().Contains(req[5].ToLower())) { if (req.Length == 13 && parter.url != null) { ThirdPartyCoupon cc = new ThirdPartyCoupon(); if (!cc.check(req[11], req[12], parter.url)) { throw new Exception("优惠码无效"); } couponCode = cc.addCoupon(parter.Id.ToString(), req[11], req[12], cinfo); } log.log("1211IF:【" + request + "】CLOSESIGN【" + WebUtility.ConfigHelper.CloseSign.ToLower() + "】req[5]【" + req[5].ToLower() + "】", System.Web.HttpContext.Current.Server.MapPath("Log/log.txt")); } else { log.log("1211ELSE:【" + request + "】CLOSESIGN【" + WebUtility.ConfigHelper.CloseSign.ToLower() + "】req[5]【" + req[5].ToLower() + "】", System.Web.HttpContext.Current.Server.MapPath("Log/log.txt")); } #endregion #region 调用web service 处理创建预约订单 CreateOrderServiceRequestEntity createOrderEntity = new CreateOrderServiceRequestEntity(); createOrderEntity.Ucode = string.Empty; createOrderEntity.Parterid = parter.Id; createOrderEntity.RecommendCode = "[" + couponCode; createOrderEntity.BusinessType = 1; // 酒后代驾 createOrderEntity.OrderFrom = 5; // 合作商 createOrderEntity.AppointTime = string.Empty; DateTime appointTime; if (DateTime.TryParse(req[4].Trim(), out appointTime)) { createOrderEntity.AppointTime = appointTime.ToString("yyyy-MM-dd HH:mm"); } createOrderEntity.Address = req[3].Trim(); createOrderEntity.FromCellPhone = cinfo.Cellphone; createOrderEntity.CellPhone = cinfo.Cellphone; string latStr = req[8].Trim(); string lngStr = req[9].Trim(); if (parter.Id == 11)//判断是博泰,对坐标进行转换 { ChangeCoords.ChangeCoordinate(ref latStr, ref lngStr, 3, 5); } double lat; double lng; if (double.TryParse(latStr, out lat) && double.TryParse(lngStr, out lng)) { CoordinateHelper.BaiduToScott(ref lng, ref lat); createOrderEntity.Lat = lat; createOrderEntity.Lng = lng; } createOrderEntity.geoType = 1; createOrderEntity.AllUserCount = 1; createOrderEntity.Remark = req[10].Trim(); createOrderEntity.Status = 0; // result = InvokeCreateOrderService(createOrderEntity); string url = string.Format("http://{0}/api/createOrder", ConfigHelper.APIServer); result = new CreateOrder().InvokeCreateOrderService(url ,createOrderEntity); #endregion } else { throw new Exception("商户标识错误。"); } } else { throw new Exception("签名错误。"); } return result; }
public Order(CreateOrder create) : base(create) { }
public void TestCreateOrderEventWithMerchantProfileField() { var createOrder = new CreateOrder { user_id = "test_dotnet_merchant_profile_field", session_id = "gigtleqddo84l8cm15qe4il", order_id = "12345", payment_methods = new ObservableCollection <PaymentMethod>() { new PaymentMethod { payment_type = "$sepa_instant_credit", shortened_iban_first6 = "FR7630", shortened_iban_last4 = "1234", sepa_direct_debit_mandate = true } }, merchant_profile = new MerchantProfile { merchant_id = "123", merchant_category_code = "9876", merchant_name = "ABC Merchant", merchant_address = new Address { name = "Bill Jones", phone = "1-415-555-6040", address_1 = "2100 Main Street", address_2 = "Apt 3B", city = "New London", region = "New Hampshire", country = "US", zipcode = "03257" } } }; // Augment with custom fields createOrder.AddField("foo", "bar"); Assert.Equal("{\"$type\":\"$create_order\",\"$user_id\":\"test_dotnet_merchant_profile_field\",\"$session_id\":\"gigtleqddo84l8cm15qe4il\"," + "\"$order_id\":\"12345\",\"$payment_methods\":[{\"$payment_type\":\"$sepa_instant_credit\",\"$shortened_iban_first6\":\"FR7630\"," + "\"$shortened_iban_last4\":\"1234\",\"$sepa_direct_debit_mandate\":true}],\"$merchant_profile\":{\"$merchant_id\":\"123\"," + "\"$merchant_category_code\":\"9876\",\"$merchant_name\":\"ABC Merchant\",\"$merchant_address\":{\"$name\":\"Bill Jones\"," + "\"$address_1\":\"2100 Main Street\",\"$address_2\":\"Apt 3B\",\"$city\":\"New London\",\"$region\":\"New Hampshire\"," + "\"$country\":\"US\",\"$zipcode\":\"03257\",\"$phone\":\"1-415-555-6040\"}},\"foo\":\"bar\"}", createOrder.ToJson()); EventRequest eventRequest = new EventRequest { Event = createOrder }; Assert.Equal("https://api.sift.com/v205/events", eventRequest.Request.RequestUri.ToString()); eventRequest = new EventRequest { Event = createOrder, AbuseTypes = { "legacy", "payment_abuse" }, ReturnScore = true }; Assert.Equal("https://api.sift.com/v205/events?abuse_types=legacy,payment_abuse&return_score=true", Uri.UnescapeDataString(eventRequest.Request.RequestUri.ToString())); }
public override async Task When_a_clock_is_set_on_a_command_then_it_takes_precedence_over_default_clock() { // arrange var clockName = Any.CamelCaseName(); var create = new CreateOrder(Any.FullName()) { AggregateId = Any.Guid() }; var clock = new CommandScheduler.Clock { Name = clockName, UtcNow = DateTimeOffset.Parse("2016-03-01 02:00:00 AM") }; using (var commandScheduler = CommandSchedulerDbContext()) { commandScheduler.Clocks.Add(clock); commandScheduler.SaveChanges(); } // act await Schedule( create, dueTime: DateTimeOffset.Parse("2016-03-20 09:00:00 AM"), clock: clock); await AdvanceClock(clockName: clockName, by: 30.Days()); //assert var target = await Get<Order>(create.AggregateId); target.Should().NotBeNull(); }
public async Task <IActionResult> OnPostAsync( [FromServices] ApplicationDbContext ctx, [FromServices] UserManager <ApplicationUser> userManager, [FromServices] SignInManager <ApplicationUser> signInManager, [FromServices] OneOffPayment payment, [FromServices] SetCartAddress setCartAddress, [FromServices] CreateOrder createOrder) { if (!Input.RequestPayment) { ModelState.ClearValidationState("Input.PayerName"); ModelState.ClearValidationState("Input.PayerEmail"); ModelState.MarkFieldValid("Input.PayerName"); ModelState.MarkFieldValid("Input.PayerEmail"); } var user = new ApplicationUser { FirstName = Input.FirstName, LastName = Input.LastName, UserName = Input.Email, Email = Input.Email }; foreach (var item in userManager.PasswordValidators) { var password = await item.ValidateAsync(userManager, user, Input.Password); if (!password.Succeeded) { foreach (var error in password.Errors) { ModelState.AddModelError("Input.Password", string.Format("[{0}] - {1}", error.Code, error.Description)); } } } if (!ModelState.IsValid) { return(Page()); } var address = new Address { Address1 = Input.Address1, Address2 = Input.Address2, City = Input.City, PostCode = Input.PostCode, }; user.Addresses.Add(address); var result = await userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { await userManager.AddClaimAsync(user, new Claim("type", "superuser")); await signInManager.SignInAsync(user, false); await new CreateAccount(ctx, _emailSender) .Do(new CreateAccount.Request { UserId = user.Id, Input = new CreateAccount.BusinessRegisterViewModel { CompanyName = Input.CompanyName, RegistrationNumber = "", CompanyVAT = "", TermAccount = false, Address1 = Input.Address1, Address2 = Input.Address2, City = Input.City, PostCode = Input.PostCode, } }); await setCartAddress.Do(new SetCartAddress.Request { UserMark = GetCartUserMark(), AddressId = address.Id }); if (Input.RequestPayment) { var PaymentReference = Guid.NewGuid().ToString(); var order = await createOrder.Do(new CreateOrder.Request { UserMark = (user.Id, GetSessionId()), PayementReference = PaymentReference, });
public void when_creating_an_order_successfully() { var pickupDate = DateTime.Now; var order = new CreateOrder { AccountId = _accountId, PickupDate = pickupDate, PickupAddress = new Address { RingCode = "3131", Latitude = 45.515065, Longitude = -73.558064, FullAddress = "1234 rue Saint-Hubert", Apartment = "3939" }, DropOffAddress = new Address { Latitude = 45.50643, Longitude = -73.554052, FullAddress = "Velvet auberge st gabriel" }, ClientLanguageCode = "fr", UserLatitude = 46.50643, UserLongitude = -74.554052, UserAgent = "TestUserAgent", ClientVersion = "1.0.0", UserNote = "une note", BookingFees = 5m, Market = "MTL", CompanyKey = "Kramerica", CompanyName = "Kramerica Industries", EstimatedFare = 50.5, IsChargeAccountPaymentWithCardOnFile = true, IsPrepaid = true, OriginatingIpAddress = "192.168.12.30", KountSessionId = "1i3u13n123" }; order.Settings = new BookingSettings { ChargeTypeId = 99, VehicleTypeId = 88, ProviderId = 11, Phone = "5145551212", Passengers = 6, NumberOfTaxi = 1, Name = "Joe Smith", AccountNumber = "account", CustomerNumber = "customer", PayBack = "123" }; _sut.When(order); var orderCreated = _sut.ThenHasSingle <OrderCreated>(); Assert.AreEqual(_accountId, orderCreated.AccountId); Assert.AreEqual(pickupDate, orderCreated.PickupDate); Assert.AreEqual("3939", orderCreated.PickupAddress.Apartment); Assert.AreEqual("1234 rue Saint-Hubert", orderCreated.PickupAddress.FullAddress); Assert.AreEqual("3131", orderCreated.PickupAddress.RingCode); Assert.AreEqual(45.515065, orderCreated.PickupAddress.Latitude); Assert.AreEqual(-73.558064, orderCreated.PickupAddress.Longitude); Assert.AreEqual("Velvet auberge st gabriel", orderCreated.DropOffAddress.FullAddress); Assert.AreEqual(45.50643, orderCreated.DropOffAddress.Latitude); Assert.AreEqual(-73.554052, orderCreated.DropOffAddress.Longitude); Assert.AreEqual(99, orderCreated.Settings.ChargeTypeId); Assert.AreEqual(88, orderCreated.Settings.VehicleTypeId); Assert.AreEqual(11, orderCreated.Settings.ProviderId); Assert.AreEqual("5145551212", orderCreated.Settings.Phone); Assert.AreEqual(6, orderCreated.Settings.Passengers); Assert.AreEqual(1, orderCreated.Settings.NumberOfTaxi); Assert.AreEqual("Joe Smith", orderCreated.Settings.Name); Assert.AreEqual("account", orderCreated.Settings.AccountNumber); Assert.AreEqual("customer", orderCreated.Settings.CustomerNumber); Assert.AreEqual("123", orderCreated.Settings.PayBack); Assert.AreEqual("fr", orderCreated.ClientLanguageCode); Assert.AreEqual(46.50643, orderCreated.UserLatitude); Assert.AreEqual(-74.554052, orderCreated.UserLongitude); Assert.AreEqual("TestUserAgent", orderCreated.UserAgent); Assert.AreEqual("1.0.0", orderCreated.ClientVersion); Assert.AreEqual("une note", orderCreated.UserNote); Assert.AreEqual(5, orderCreated.BookingFees); Assert.AreEqual("MTL", orderCreated.Market); Assert.AreEqual("Kramerica", orderCreated.CompanyKey); Assert.AreEqual("Kramerica Industries", orderCreated.CompanyName); Assert.AreEqual(50.5, orderCreated.EstimatedFare); Assert.AreEqual(true, orderCreated.IsChargeAccountPaymentWithCardOnFile); Assert.AreEqual(true, orderCreated.IsPrepaid); Assert.AreEqual("192.168.12.30", orderCreated.OriginatingIpAddress); Assert.AreEqual("1i3u13n123", orderCreated.KountSessionId); }
private void WireEventHandlers(CreateOrder createOrder) { MyHandler1 handler = new MyHandler1(OnHandler1); createOrder.Event1 += handler; }
/// <summary> /// 立即预约,成功返回订单号 /// </summary> /// <param name="request"></param> /// <returns></returns> public string execute(string request) { //1217|1姓名|2客户手机号|3地址|4司机工号|5lat|6lng|7from|8sign|9IMEI|10MD5串|11remark|12youhui string result = "0"; string[] req = request.Split('|'); var sign = EncodingUtil.GetMd5(req[2] + "aidaijia", "utf-8"); if (sign.ToLower() == req[10].ToLower()) { ThirdPartyCoupon cc = new ThirdPartyCoupon(); //判断T_ClentInfo是否有此手机号相关信息 //如果用户不存在,创建一个新用户 CustomerInfoEntity cinfo = new D_CustomerInfoDal().GetClientInfoByPhone(req[2].Trim()); T_ParterEntity parter = new T_PartyDal().GetParterModelBySign(req[8].ToLower()); string couponCode = ""; if (parter != null) { #region 调用冯超接口检查是否新用户 if (InvokeStateService(req[2].Trim()).Equals(1)) { if (parter.url != null) { cc.isCoupon(parter.url); if (!cc.check(req[12], req[13], parter.url)) { throw new Exception("优惠码无效"); } couponCode = req[11]; } } #endregion #region 优惠码操作 //if (req.Length == 14 && parter.url != null) //{ // if (!cc.check(req[12], req[13], parter.url)) // { // throw new Exception("优惠码无效"); // } // //couponCode = cc.addCoupon(parter.Id.ToString(), req[12], req[13], cinfo); //} #endregion #region 调用web service 处理创建指定司机派单信息 DriverInfoEntity driverInfo = new D_DriverInfoDal().GetDriverInfoByUcode(req[4].Trim()); if (driverInfo == null) { throw new Exception("指定司机不存在!"); } if (driverInfo.Online == 0) { throw new Exception("该司机已经下线,不能接受您指派的任务!"); } else if (driverInfo.OnService == 1 || driverInfo.OnDOService == 1) { throw new Exception("该司机已经在服务中了,不能接受您指派的任务!"); } else { CreateOrderServiceRequestEntity createOrderEntity = new CreateOrderServiceRequestEntity(); createOrderEntity.Ucode = req[4].Trim(); createOrderEntity.RecommendCode = couponCode; createOrderEntity.Parterid = parter.Id; createOrderEntity.BusinessType = 1; // 酒后代驾 createOrderEntity.OrderFrom = 5; // 合作商 createOrderEntity.AppointTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"); createOrderEntity.Address = req[3].Trim(); createOrderEntity.FromCellPhone = req[2].Trim(); createOrderEntity.CellPhone = req[2].Trim(); string latStr = req[5].Trim(); string lngStr = req[6].Trim(); if (parter.Id == 11)//判断是博泰,对坐标进行转换 { ChangeCoords.ChangeCoordinate(ref latStr, ref lngStr, 3, 5); } double lat; if (double.TryParse(latStr, out lat)) { createOrderEntity.Lat = lat; } double lng; if (double.TryParse(lngStr, out lng)) { createOrderEntity.Lng = lng; } createOrderEntity.AllUserCount = 1; createOrderEntity.Remark = req[11].Trim(); createOrderEntity.Status = 0; string url = string.Format("http://{0}/api/createOrder", ConfigHelper.APIServer); result = new CreateOrder().InvokeCreateOrderService(url, createOrderEntity); } #endregion } else { throw new Exception("商户标识错误。"); } } else { throw new Exception("签名错误。"); } return result; }
public async Task <IActionResult> Post(CreateOrder command) { await Dispatcher.SendAsync(command); return(CreatedAtAction(nameof(Get), new { Id = command.Id }, command.Id)); }
public Task <IEnumerable <Order> > Handle(CreateOrder request, CancellationToken cancellationToken) { this.iorderRepository.CreateOrder(request._order); return(this.iorderRepository.AllOrder()); }
public async Task <IActionResult> Post(CreateOrder command) => await SendAsync(command.BindId(c => c.Id).Bind(c => c.CustomerId, UserId), resourceId : command.Id, resource : "orders");
static async Task Main() { //required to prevent possible occurrence of .NET Core issue https://github.com/dotnet/coreclr/issues/12668 Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); Console.Title = "Samples.Serialization.Jil"; #region config var endpointConfiguration = new EndpointConfiguration("Samples.Serialization.Jil"); endpointConfiguration.UseSerialization <JilSerializer>() .Options( new Options( prettyPrint: true, excludeNulls: true, includeInherited: true)); // register the mutator so the the message on the wire is written endpointConfiguration.RegisterComponents(components => { components.ConfigureComponent <MessageBodyWriter>(DependencyLifecycle.InstancePerCall); }); #endregion endpointConfiguration.UsePersistence <LearningPersistence>(); endpointConfiguration.UseTransport <LearningTransport>(); var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); #region message var message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List <OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; await endpointInstance.SendLocal(message) .ConfigureAwait(false); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); await endpointInstance.Stop() .ConfigureAwait(false); }
[TestFixtureSetUp] public void Context() { _order = CreateOrder.Of(new Product(10)).Apply(CreatePromotion.WithDiscountOf(.5m)).In(StateOf.FL); }
public CreateOrder CreateOrder() { HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"]; HttpRequestBase request = context.Request; string jsonText = request["data"]; CreateOrder createOrder = new CreateOrder(); GoodOrderView goodOrderView = JsonConvert.DeserializeObject <GoodOrderView>(jsonText); string payway = request["payway"]; //string jifen = request["jifen"]; string liuyan = request["liuyan"]; int? userID = null; Authentication authentication = new Authentication(request); if (string.IsNullOrEmpty(authentication.state)) { userID = authentication.userID; } bool baoyou = false; OrderDetailsModel orderDetailsModel = new OrderDetailsModel(); Order order = new Order(); using (Entity entity = new Entity()) { foreach (var goodCartView in goodOrderView.GoodCartViewList) { int goodChildID = goodCartView.goodChildID; int num = goodCartView.num; var goodChild = entity.GoodChild.Include("Good").Where(o => o.GoodChildID == goodChildID && o.State == 1).FirstOrDefault(); if (goodChild == null) { createOrder.error = "商品不存在或者已经下架"; return(createOrder); } if (goodChild.Repertory == 0) { createOrder.error = "商品库存不够"; return(createOrder); } if ((goodChild.Good.State & 32) > 0) { baoyou = true; } order.Num += num; orderDetailsModel.OrderDetailModelList.Add(new OrderDetailModel() { GoodID = goodChild.Good.GoodID, Title = goodChild.Good.Title, SubTitle = goodChild.Good.SubTitle, RealPrice = goodChild.Good.RealPrice, GoodChildID = goodChild.GoodChildID, Specification = goodChild.Specification, AddPrice = goodChild.AddPrice, Image = goodChild.Image, num = num }); if (string.IsNullOrEmpty(order.Image)) { order.Image = goodChild.Image; } if (order.GoodID == 0) { order.GoodID = goodChild.Good.GoodID; } if (string.IsNullOrEmpty(order.Title)) { order.Title = goodChild.Good.Title; } if (userID != null) { var t = entity.GoodCart.Where(o => o.UserID == userID && o.GoodChildID == goodChildID).FirstOrDefault(); if (t != null) { entity.GoodCart.Remove(t); } } } order.OrderID = DateTime.Now.ToString("yyMMddhhmmssfff") + new Random().Next(100, 1000).ToString(); order.UserID = userID; order.State = 1; order.Detail = JsonConvert.SerializeObject(orderDetailsModel); order.Remark1 = liuyan; order.CreateTime = DateTime.Now; order.UpdateTime = DateTime.Now; order.LogisticsAddress = request["dizhi"]; order.LogisticsTel = request["Tel"]; order.LogisticsPerson = request["shouhuoren"]; order.OrderExtend = new OrderExtend(); order.OrderExtend.TotalPrice = orderDetailsModel.OrderDetailModelList.Sum(o => (o.RealPrice + o.AddPrice) * o.num); order.OrderExtend.DiscountPrice = 0; order.OrderExtend.LogisticsPrice = 0; order.OrderExtend.PaymentPrice = 0; order.OrderExtend.ThirdPartyPayment = payway; WholeFieldActivity wholeFieldActivity = entity.WholeFieldActivity.Where(o => o.Type == 0).FirstOrDefault(); if (wholeFieldActivity != null) { if (order.OrderExtend.TotalPrice >= wholeFieldActivity.FillPrice) { if (wholeFieldActivity.DiscountPrice != null) { order.OrderExtend.DiscountPrice = wholeFieldActivity.DiscountPrice.Value; } } } order.OrderExtend.PaymentPrice = order.OrderExtend.TotalPrice - order.OrderExtend.DiscountPrice; if (!baoyou) { order.OrderExtend.LogisticsPrice = Convert.ToInt32(ConfigurationManager.AppSettings["LogisticsPrice"]); wholeFieldActivity = entity.WholeFieldActivity.Where(o => o.Type == 1).FirstOrDefault(); if (wholeFieldActivity != null) { if (order.OrderExtend.PaymentPrice >= wholeFieldActivity.FillPrice) { order.OrderExtend.LogisticsPrice = 0; } } } order.OrderExtend.PaymentPrice = order.OrderExtend.TotalPrice - order.OrderExtend.DiscountPrice + order.OrderExtend.LogisticsPrice; //if (jifen == "true" && !string.IsNullOrEmpty(authentication.state)) //{ // var user = entity.User.Find(authentication.userID); // order.OrderExtend.UseIntegral = user.UserExtend.Integral; // order.OrderExtend.PaymentPrice -= (order.OrderExtend.UseIntegral / 100); //} //order.OrderExtend.GainIntegral = Convert.ToInt32(order.OrderExtend.TotalPrice - order.OrderExtend.DiscountPrice + order.OrderExtend.LogisticsPrice); OrderLog orderLog = new OrderLog(); orderLog.State = order.State; orderLog.CreateTime = DateTime.Now; orderLog.UserId = order.UserID; orderLog.Mark = "用户下单"; order.OrderLog.Add(orderLog); entity.Order.Add(order); entity.SaveChanges(); } string subject = "分享"; string body = ""; foreach (var v in orderDetailsModel.OrderDetailModelList) { body += v.Title + " "; } body = body.Trim(); createOrder.orderid = order.OrderID; createOrder.subject = subject; createOrder.body = body; createOrder.fee = order.OrderExtend.PaymentPrice.ToString("#0.00"); return(createOrder); }
public ActionResult Create([Bind(Prefix = "Item")] CreateOrder model) { #region 检验输入的会员是否正确 if (!string.IsNullOrWhiteSpace(Request.Form["txtSearch"])) { string searchtext = Request.Form["txtSearch"]; if (searchtext.IndexOf("-->") > 0) { var text = Request.Form["txtSearch"].Split("-->".ToArray()); var account = AccountService.GetByName(text[text.Length - 1]); var user = MenbershipService.QueryUsers <AccountUser>(new UserRequest() { DisplayNameWith = text[0] }); if (account == null && user.Count() < 1) { model.AddMsg("系统没有找到会员信息,请重新输入!"); model.Read(); model.Ready(); return(View(new EcardModelItem <CreateOrder>(model, model))); } else { if (account == null) { if (user.Count() > 1) { model.AddMsg("根据" + text[0] + "查到不止一个会员,系统无法确定订单所属会员。"); model.Read(); model.Ready(); return(View(new EcardModelItem <CreateOrder>(model, model))); } else { model.AccountId = AccountService.QueryByOwnerId(user.First()).First().AccountId; } } else { model.AccountId = account.AccountId; } } } else { var account = AccountService.GetByName(searchtext); var user = MenbershipService.QueryUsers <AccountUser>(new UserRequest() { DisplayNameWith = searchtext }); if (account == null && user.Count() < 1) { model.AddMsg("系统没有找到会员信息,请重新输入!"); model.Read(); model.Ready(); return(View(new EcardModelItem <CreateOrder>(model, model))); } else { if (account == null) { if (user.Count() > 1) { model.AddMsg("根据" + searchtext + "查到不止一个会员,系统无法确定订单所属会员。"); model.Read(); model.Ready(); return(View(new EcardModelItem <CreateOrder>(model, model))); } else { model.AccountId = AccountService.QueryByOwnerId(user.First()).First().AccountId; } } else { model.AccountId = account.AccountId; } } } } else { model.AddMsg("系统没有找到会员信息,请重新输入!"); model.Read(); model.Ready(); return(View(new EcardModelItem <CreateOrder>(model, model))); } #endregion var ss = model.Detial.Count; int num = 0; List <OrderDetial1> detials = new List <OrderDetial1>(); for (int i = 0; i < ss; i++) { OrderDetial1 detial = new OrderDetial1(); if (Request.Form["Item.Detial[" + i.ToString() + "].Checked"].ToLower().IndexOf("true") > -1) { num++; detial.GoodId = int.Parse(Request.Form["Item.Detial[" + i.ToString() + "].Id"]); detial.Amount = int.Parse(Request.Form["Item.Detial[" + i.ToString() + "].Amount"]); detial.price = decimal.Parse(Request.Form["Item.Detial[" + i.ToString() + "].Price"]); if ((detial.price * detial.Amount) <= 0) { model.AddMsg("没有正确的输入数量或单价"); model.Read(); model.Ready(); return(View(new EcardModelItem <CreateOrder>(model, model))); } detials.Add(detial); } } if (num > 0) { model.Detials = detials; IMessageProvider msg = null; if (ModelState.IsValid) { this.ModelState.Clear(); msg = model.Create(); model = _unityContainer.Resolve <CreateOrder>(); } model.Read(); model.Ready(); return(View(new EcardModelItem <CreateOrder>(model, msg))); } else { // new Exception("没有选择商品"); model.AddMsg("没有选择商品"); model.Read(); model.Ready(); return(View(new EcardModelItem <CreateOrder>(model, model))); } }
public async Task <ActionResult> Post(CreateOrder command) { await _commandDispatcher.SendAsync(command); return(Created($"orders/{command.OrderId}", null)); }
public async Task <ActionResult> Post(CreateOrder command) { await _commandDispatcher.SendAsync(command); return(CreatedAtAction(nameof(Get), new { orderId = command.OrderId }, new object())); }
public string execute(string request) { //1218|1张三|21381234567|3莘凌路211号(小锦江酒店)|421:00|5asdfas1231asd|6IMEI|7MD5串|8lat|9lng|10remark|11youhui|12youhuijine string result = "0"; string[] req = request.Split('|'); var sign = EncodingUtil.GetMd5(req[2] + "aidaijia", "utf-8"); if (sign.ToLower() == req[7].ToLower()) { ThirdPartyCoupon cc = new ThirdPartyCoupon(); //判断T_ClentInfo是否有此手机号相关信息 //如果用户不存在,创建一个新用户 CustomerInfoEntity cinfo = new D_CustomerInfoDal().GetClientInfoByPhone(req[2].Trim()); T_ParterEntity parter = new T_PartyDal().GetParterModelBySign(req[5].ToLower()); if (parter != null) { string couponCode = ""; #region 调用冯超接口检查是否新用户 if (InvokeStateService(req[2].Trim()).Equals(1)) { if (parter.url != null) { cc.isCoupon(parter.url); if (!cc.check(req[12], req[13], parter.url)) { throw new Exception("优惠码无效"); } couponCode = req[11]; } } #endregion #region 优惠码操作 if (req.Length == 13 && parter.url != null) { if (!cc.check(req[11], req[12], parter.url)) { throw new Exception("优惠码无效"); } couponCode = cc.addCoupon(parter.Id.ToString(), req[11], req[12], cinfo); } #endregion #region 调用web service 处理创建预约订单 CreateOrderServiceRequestEntity createOrderEntity = new CreateOrderServiceRequestEntity(); createOrderEntity.Ucode = string.Empty; createOrderEntity.Parterid = parter.Id; createOrderEntity.BusinessType = 1; // 酒后代驾 createOrderEntity.OrderFrom = 5; // 合作商 createOrderEntity.AppointTime = string.Empty; createOrderEntity.RecommendCode = couponCode; DateTime appointTime; if (DateTime.TryParse(req[4].Trim(), out appointTime)) { createOrderEntity.AppointTime = appointTime.ToString("yyyy-MM-dd HH:mm"); } createOrderEntity.Address = req[3].Trim(); createOrderEntity.FromCellPhone = cinfo.Cellphone; createOrderEntity.CellPhone = cinfo.Cellphone; string latStr = req[8].Trim(); string lngStr = req[9].Trim(); if (parter.Id == 11)//判断是博泰,对坐标进行转换 { ChangeCoords.ChangeCoordinate(ref latStr, ref lngStr, 3, 5); } double lat; if (double.TryParse(latStr, out lat)) { createOrderEntity.Lat = lat; } double lng; if (double.TryParse(lngStr, out lng)) { createOrderEntity.Lng = lng; } createOrderEntity.AllUserCount = 1; createOrderEntity.Remark = req[10].Trim(); createOrderEntity.Status = 0; // result = InvokeCreateOrderService(createOrderEntity); string url = string.Format("http://{0}/api/createOrder", ConfigHelper.APIServer); result = new CreateOrder().InvokeCreateOrderService(url, createOrderEntity); #endregion } else { throw new Exception("商户标识错误。"); } } else { throw new Exception("签名错误。"); } return result; }
static async Task AsyncMain() { Console.Title = "Samples.Serialization.Jil"; #region config EndpointConfiguration endpointConfiguration = new EndpointConfiguration("Samples.Serialization.Jil"); endpointConfiguration.UseSerialization<JilSerializer>() .Options( new Options( prettyPrint: true, excludeNulls: true, includeInherited: true)); // register the mutator so the the message on the wire is written endpointConfiguration.RegisterComponents(components => { components.ConfigureComponent<MessageBodyWriter>(DependencyLifecycle.InstancePerCall); }); #endregion endpointConfiguration.UsePersistence<InMemoryPersistence>(); endpointConfiguration.EnableInstallers(); endpointConfiguration.SendFailedMessagesTo("error"); IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration); try { #region message CreateOrder message = new CreateOrder { OrderId = 9, Date = DateTime.Now, CustomerId = 12, OrderItems = new List<OrderItem> { new OrderItem { ItemId = 6, Quantity = 2 }, new OrderItem { ItemId = 5, Quantity = 4 }, } }; await endpoint.SendLocal(message); #endregion Console.WriteLine("Order Sent"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } finally { await endpoint.Stop(); } }
public CashierHomePage() { InitializeComponent(); order = elementHost1.Child as CreateOrder; total_order_number = 0; }