public void Deserialize() { var formatter = new JsonEventFormatter(_typeResolver); var obj = new StoredEvent<JObject>( eventName: "bob", eventVersion: new Version(3, 0) /* different on purpose */, eventIdentifier: new Guid("402639D5-4106-4AE7-B210-45780C7A08F3"), eventSourceId: new Guid("697BAB3C-E122-4C70-85B0-76750BC2D878"), eventSequence: 1, eventTimeStamp: new DateTime(2001, 4, 12, 12, 52, 21, 425, DateTimeKind.Utc), data: new JObject( new JProperty("Name", "Alice"), new JProperty("Value", 10), new JProperty("Day", new DateTime(2000, 01, 01)) ) ); var rawResult = formatter.Deserialize(obj); rawResult.Should().BeOfType<AnEvent>(); var result = (AnEvent) rawResult; result.EventIdentifier.Should().Be(obj.EventIdentifier); result.EventSourceId.Should().Be(obj.EventSourceId); result.EventSequence.Should().Be(obj.EventSequence); result.EventTimeStamp.Should().Be(obj.EventTimeStamp); result.EventVersion.Should().Be(new Version(2, 0)); result.Name.Should().Be("Alice"); result.Value.Should().Be(10); result.Day.Should().Be(new DateTime(2000, 01, 01)); }
public void Serialize() { Assert.Ignore("Throwing an error about not finding NUnit.dll - not sure why..."); var formatter = new JsonEventFormatter(_typeResolver); var theEvent = new AnEvent( eventIdentifier: new Guid("402639D5-4106-4AE7-B210-45780C7A08F3"), eventSourceId: new Guid("697BAB3C-E122-4C70-85B0-76750BC2D878"), eventSequence: 1, eventTimeStamp: new DateTime(2001, 4, 12, 12, 52, 21, 425, DateTimeKind.Utc)) { Day = new DateTime(2000, 01, 01), Name = "Alice", Value = 10, }; var result = formatter.Serialize(theEvent); result.EventName.Should().Be("bob"); result.EventIdentifier.Should().Be(theEvent.EventIdentifier); result.EventSourceId.Should().Be(theEvent.EventSourceId); result.EventSequence.Should().Be(theEvent.EventSequence); result.EventTimeStamp.Should().Be(theEvent.EventTimeStamp); result.EventVersion.Should().Be(theEvent.EventVersion); result.Data.Should().NotBeNull(); result.Data.Count.Should().Be(3); result.Data.Value<string>("Name").Should().Be(theEvent.Name); result.Data.Value<int>("Value").Should().Be(theEvent.Value); result.Data.Value<DateTime>("Day").Should().Be(theEvent.Day); }
public void Deserialize() { var formatter = new JsonEventFormatter(_typeResolver); var obj = new JObject( new JProperty("Name", "Alice"), new JProperty("Value", 10), new JProperty("Day", new DateTime(2000, 01, 01)) ); var rawResult = formatter.Deserialize(obj, "bob"); rawResult.Should().BeOfType<AnEvent>(); var result = (AnEvent) rawResult; result.Name.Should().Be("Alice"); result.Value.Should().Be(10); result.Day.Should().Be(new DateTime(2000, 01, 01)); }
public void Serialize() { var formatter = new JsonEventFormatter(_typeResolver); var theEvent = new AnEvent { Day = new DateTime(2000, 01, 01), Name = "Alice", Value = 10, }; string eventName; var result = formatter.Serialize(theEvent, out eventName); eventName.Should().Be("bob"); result.Should().NotBeNull(); result.Count.Should().Be(3); result.Value<string>("Name").Should().Be(theEvent.Name); result.Value<int>("Value").Should().Be(theEvent.Value); result.Value<DateTime>("Day").Should().Be(theEvent.Day); }
public NoDBEventStore(string path) { _path = path; _formatter = new JsonEventFormatter(new SimpleEventTypeResolver()); }
public void Deserialize_obj_null() { var formatter = new JsonEventFormatter(_typeResolver); var ex = Assert.Throws<ArgumentNullException>(() => formatter.Deserialize(null)); ex.ParamName.Should().Be("obj"); }
public void Ctor() { var formatter = new JsonEventFormatter(_typeResolver); }
//[Produces("application/json", "application/problem+json")] public async Task <IActionResult> PlaceOrder([FromBody] OrderCreateDto orderCreate) { // dependency tracking var telemetryClient = _telemetryClientFactory.Create(); _logger.LogInformation("API - Order controller - PlaceOrders"); ConcertUser entityConcertUser; try { entityConcertUser = Mapper.Map <ConcertUser>(orderCreate); _ordersRepository.PlaceOrderAsync(entityConcertUser); await _ordersRepository.SaveChangesAsync(); } catch (Exception ex) { _logger.LogError(ex.Message); if (ex.InnerException.Message.Contains("PK_")) { return(BadRequest(new ProblemDetailsError(StatusCodes.Status400BadRequest, "Duplicate order."))); } throw; } _logger.LogInformation($"Retrieving new order"); var orderDb = await _ordersRepository.GetOrderAsync(entityConcertUser.Token); var orderDto = Mapper.Map <OrderDto>(orderDb); // dependency tracking var current = Activity.Current; var requestActivity = new Activity("command://order.pay"); var requestOperation = telemetryClient.StartOperation <RequestTelemetry>(requestActivity); try { // drop message in the queue _logger.LogInformation($"Drop message in the queue"); var sbConnectionString = String.Empty; try { sbConnectionString = _vaultService.GetSecret("cn-servicebus").Result; } catch (Exception ex) { // TODO local debug with docker // MSI + docker not working in debug mode? _logger.LogError(ex.Message); } if (String.IsNullOrEmpty(sbConnectionString)) { sbConnectionString = _configuration.GetConnectionString(name: "ServiceBus"); } var pub = new Publisher("q-payment-in", sbConnectionString); var cloudEvent = new CloudEvent("command://order.pay", new Uri("app://ticketing.api")) { Id = Guid.NewGuid().ToString(), DataContentType = new ContentType(MediaTypeNames.Application.Json), Data = JsonConvert.SerializeObject(new PaymentContext() { Attendee = orderDto.Attendee, OrderId = orderDto.OrderId.ToString(), Token = orderDto.Token, }) }; var dictionary = new Dictionary <string, string>(); dictionary.Add("ShortDescription", "cloud event publishing [command://order.pay]"); dictionary.Add("EntityType", LoggingContext.EntityType.Order.ToString()); dictionary.Add("EventId", LoggingContext.EventId.Processing.ToString()); dictionary.Add("Status", LoggingContext.Status.Pending.ToString()); dictionary.Add("CorrelationId", Activity.Current.Id); dictionary.Add("Checkpoint", LoggingContext.CheckPoint.Publisher.ToString()); dictionary.Add("Description", "N/A"); telemetryClient.TrackEvent("command://order.pay", dictionary); _logger.LogInformation(new EventId((int)LoggingContext.EventId.Processing), string.Format("({0})", string.Join(",", dictionary.Values))); _logger.LogInformation("COMMAND - Sending message to the bus."); var jsonFormatter = new JsonEventFormatter(); var messageBody = jsonFormatter.EncodeStructuredEvent(cloudEvent, out var contentType); await pub.SendMessagesAsync(Encoding.UTF8.GetString(messageBody)); } catch (Exception ex) { // dependency tracking telemetryClient.TrackException(ex); throw; } finally { // dependency tracking telemetryClient.StopOperation(requestOperation); } _logger.LogInformation($"Returning order token '{entityConcertUser.Token}'"); return(CreatedAtRoute("Orders_GetOrderDetails", new { token = entityConcertUser.Token }, orderDto)); }
public async Task <(string, string)> ReadCloudStorageData(HttpContext context) { _logger.LogInformation("Reading cloud storage data"); string bucket = null, name = null; CloudEvent cloudEvent; CloudEventFormatter formatter; var ceType = context.Request.Headers["ce-type"]; switch (ceType) { case LogEntryData.WrittenCloudEventType: //"protoPayload" : {"resourceName":"projects/_/buckets/events-atamel-images-input/objects/atamel.jpg}"; formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(LogEntryData)); cloudEvent = await context.Request.ToCloudEventAsync(formatter); _logger.LogInformation($"Received CloudEvent\n{cloudEvent.GetLog()}"); var logEntryData = (LogEntryData)cloudEvent.Data; var tokens = logEntryData.ProtoPayload.ResourceName.Split('/'); bucket = tokens[3]; name = tokens[5]; break; case StorageObjectData.FinalizedCloudEventType: formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(StorageObjectData)); cloudEvent = await context.Request.ToCloudEventAsync(formatter); _logger.LogInformation($"Received CloudEvent\n{cloudEvent.GetLog()}"); var storageObjectData = (StorageObjectData)cloudEvent.Data; bucket = storageObjectData.Bucket; name = storageObjectData.Name; break; case MessagePublishedData.MessagePublishedCloudEventType: // {"message": { // "data": "eyJidWNrZXQiOiJldmVudHMtYXRhbWVsLWltYWdlcy1pbnB1dCIsIm5hbWUiOiJiZWFjaC5qcGcifQ==", // },"subscription": "projects/events-atamel/subscriptions/cre-europe-west1-trigger-resizer-sub-000"} formatter = CloudEventFormatterAttribute.CreateFormatter(typeof(MessagePublishedData)); cloudEvent = await context.Request.ToCloudEventAsync(formatter); _logger.LogInformation($"Received CloudEvent\n{cloudEvent.GetLog()}"); var messagePublishedData = (MessagePublishedData)cloudEvent.Data; var pubSubMessage = messagePublishedData.Message; _logger.LogInformation($"Type: {ceType} data: {pubSubMessage.Data.ToBase64()}"); var decoded = pubSubMessage.Data.ToStringUtf8(); _logger.LogInformation($"decoded: {decoded}"); var parsed = JValue.Parse(decoded); bucket = (string)parsed["bucket"]; name = (string)parsed["name"]; break; default: // Data: // {"bucket":"knative-atamel-images-input","name":"beach.jpg"} formatter = new JsonEventFormatter(); cloudEvent = await context.Request.ToCloudEventAsync(formatter); _logger.LogInformation($"Received CloudEvent\n{cloudEvent.GetLog()}"); dynamic data = cloudEvent.Data; bucket = data.bucket; name = data.name; break; } _logger.LogInformation($"Extracted bucket: {bucket} and name: {name}"); return(bucket, name); }
public static async Task Run( [ServiceBusTrigger("q-notifications", Connection = "SB-Queue-In-AppSettings")] string notificationMsg, ILogger log, ExecutionContext context) { log.LogInformation("Incoming message from queue q-notifications"); // TODO: This should be done with a DURABLE function // or implement compensation var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); var sbConnectionString = config["Values:SB-Queue-In-AppSettings"]; var jsonFormatter = new JsonEventFormatter(); var inboundEvent = jsonFormatter.DecodeStructuredEvent(Encoding.UTF8.GetBytes(notificationMsg)); log.LogInformation($" message type : { inboundEvent.Type}"); var notification = JsonConvert.DeserializeObject <ObjectStatus>((string)inboundEvent.Data); dynamic jPatch = new JObject(); jPatch.op = "replace"; jPatch.path = "/status"; jPatch.value = notification.Status; var patchArray = new JArray(jPatch); log.LogInformation($" Status to be changed for the object {notification.Id} value: { notification.Status}"); var text = new AsciiArt(notification.Status); log.LogInformation(text.ToString()); var httpContent = new StringContent(patchArray.ToString(), Encoding.UTF8, "application/json-patch+json"); var url = string.Format(config["Values:ApiUpdateOrderUrl"], notification.Id); //TODO add authentication //_httpClient.DefaultRequestHeaders.Authorization =new AuthenticationHeaderValue("Bearer", "to be added"); log.LogInformation(" Call the web api ..."); var response = await Policy .HandleResult <HttpResponseMessage>(message => !message.IsSuccessStatusCode) .WaitAndRetryAsync(new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(5) }, (result, timeSpan, retryCount, ctx) => { log.LogWarning($"Request failed with {result.Result.StatusCode}. Waiting {timeSpan} before next retry. Attempt #{retryCount}"); }) .ExecuteAsync(() => _httpClient.PatchAsync(url, httpContent)); if (!response.IsSuccessStatusCode) { var pub = new Publisher("q-errors", sbConnectionString); var result = pub.SendMessagesAsync(notificationMsg); } return; }