Ejemplo n.º 1
0
        public async Task <IHttpActionResult> GetServiceHealth(string servicename)
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(TheSettingService, TheLoggerService);

            handler.Start(LOG_TAG, "GetServiceHealth", GetServiceProperties());

            try
            {
                ServiceLocationService locator = new ServiceLocationService();
                UriBuilderService      builder = new UriBuilderService(Constants.ContosoEventsApplicationInstance, servicename);
                return(Ok(await _fabricClient.HealthManager.GetServiceHealthAsync(builder.ToUri())));
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return(BadRequest(ex.Message));
            }
            finally
            {
                handler.Stop(error);
            }
        }
        public async Task <IHttpActionResult> GetEventStatsById(string id)
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(TheSettingService, TheLoggerService);

            handler.Start(LOG_TAG, "GetEventStatsById", GetServiceProperties());

            try
            {
                IActorLocationService locator    = ServiceFactory.GetInstance().GetActorLocationService();
                IEventActor           eventActor = locator.Create <IEventActor>(new ActorId(id), Constants.ContosoEventsApplicationName);
                return(Ok(await eventActor.GetStats()));
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return(BadRequest(ex.Message));
            }
            finally
            {
                handler.Stop(error);
            }
        }
Ejemplo n.º 3
0
        public async Task <List <TicketOrderStats> > GetOrderStats()
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(_settingService, _loggerService);

            handler.Start(LOG_TAG, "GetOrderStats", null);

            try
            {
                if (this._docDbClient == null)
                {
                    return(new List <TicketOrderStats>());
                }

                FeedOptions queryOptions = new FeedOptions {
                    MaxItemCount = -1
                };

                IQueryable <TicketOrder> ordersQuery = this._docDbClient.CreateDocumentQuery <TicketOrder>(
                    UriFactory.CreateDocumentCollectionUri(_databaseName, _ordersCollectionName), queryOptions).
                                                       Where(o => o.FulfillDate != null);

                var orders = ordersQuery.ToList();
                return(orders.GroupBy(o => new { ID = o.Tag }).Select(g => new TicketOrderStats {
                    Tag = g.Key.ID, Count = g.Count(), SumSeconds = g.Sum(x => ((DateTime)x.FulfillDate - x.OrderDate).TotalSeconds), AverageSeconds = g.Average(x => ((DateTime)x.FulfillDate - x.OrderDate).TotalSeconds)
                }).ToList());
            }
            catch (Exception ex)
            {
                error = ex.Message;
                throw new Exception(error);
            }
            finally
            {
                handler.Stop(error);
            }
        }
Ejemplo n.º 4
0
        public async Task <IHttpActionResult> DeleteAllLogMessges()
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(TheSettingService, TheLoggerService);

            handler.Start(LOG_TAG, "DeleteAllLogMessges", GetServiceProperties());

            try
            {
                IDataStoreService dataService = ServiceFactory.GetInstance().GetDataStoreService(TheSettingService, TheLoggerService);
                await dataService.DeleteAllLogMessages();

                return(Ok("Done"));
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return(BadRequest(ex.Message));
            }
            finally
            {
                handler.Stop(error);
            }
        }
Ejemplo n.º 5
0
        public async Task <TicketEventStats> GetStats()
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(SettingService, LoggerService);

            handler.Start(LOG_TAG, "GetStats", GetActorProperties());
            var stats = new TicketEventStats();

            try
            {
                var state = await this.StateManager.GetStateAsync <EventActorState>(ActorStatePropertyName);

                stats = new TicketEventStats()
                {
                    Tickets          = state.Tickets,
                    RequestedTickets = state.RequestedTickets,
                    FailedTickets    = state.FailedTickets,
                    CancelledTickets = state.CancelledTickets,
                    Orders           = state.Orders.Count
                };
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            finally
            {
                handler.Stop(error);
                if (!string.IsNullOrEmpty(error))
                {
                    this.HealthReporterService.SendReportForService(HealthState.Error, GetHealthErrorMessage("GetStats", error));
                }
            }

            return(stats);
        }
        public async Task <IHttpActionResult> GetEvents()
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(TheSettingService, TheLoggerService);

            handler.Start(LOG_TAG, "GetEvents", GetServiceProperties());

            try
            {
                IDataStoreService dataService = ServiceFactory.GetInstance().GetDataStoreService(TheSettingService, TheLoggerService);
                var itemsList = await dataService.GetEvents();

                return(Ok(itemsList.OrderBy(p => p.EndDate).ToList()));
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return(BadRequest(ex.Message));
            }
            finally
            {
                handler.Stop(error);
            }
        }
Ejemplo n.º 7
0
        public async Task ProcessOrder(TicketOrder order)
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(SettingService, LoggerService);

            handler.Start(LOG_TAG, "ProcessOrder", GetActorProperties());

            try
            {
                if (order == null)
                {
                    handler.Info("Process order is null");
                    return;
                }

                var state = await this.StateManager.GetStateAsync <TicketOrder>(ActorStatePropertyName);

                state = order;

                // Validate the order
                bool isValid = true;
                try
                {
                    TicketOrder.Validate(state);
                }
                catch (Exception e)
                {
                    state.Note = e.Message;
                    isValid    = false;
                }

                if (isValid)
                {
                    // Validate the event
                    TicketEvent tEvent = await this.DataStoreService.GetEventById(order.EventId);

                    if (tEvent == null)
                    {
                        state.FulfillDate = null;
                        state.IsFulfilled = false;
                        state.Note        = "The Event ID is not valid!";
                        //TODO: Exercise 6 - Task 1
                        //state.Status = OrderStatuses.Invalid;
                    }
                    else
                    {
                        state.PricePerTicket = tEvent.PricePerTicket;
                        state.Currency       = tEvent.Currency;
                        state.Price          = state.Tickets * state.PricePerTicket;

                        // Locate the event actor
                        IEventActor eventActor  = this.ActorLocationService.Create <IEventActor>(new ActorId(order.EventId), Constants.ContosoEventsApplicationName);
                        bool        isAvailable = await eventActor.ReserveTickets(order);

                        if (isAvailable || !SettingService.IsTicketAvailabilityCheck())
                        {
                            // Charge credit card
                            string confirmationNumber = await this.PaymentProcessorService.Authorize(order);

                            if (!string.IsNullOrEmpty(confirmationNumber))
                            {
                                state.PaymentProcessorConfirmation = confirmationNumber;
                                state.FulfillDate = DateTime.Now;
                                state.IsFulfilled = true;
                                //TODO: Exercise 6 - Task 1
                                //state.Status = OrderStatuses.Fufilled;
                            }
                            else
                            {
                                state.FulfillDate = null;
                                state.IsFulfilled = false;
                                state.Note        = "Credit card failed to authorize!";
                                await eventActor.FailTickets(order);

                                //TODO: Exercise 6 - Task 1
                                //state.Status = OrderStatuses.CreditCardDenied;
                            }
                        }
                        else
                        {
                            state.FulfillDate = null;
                            state.IsFulfilled = false;
                            state.Note        = "Event Tickets are exhausted!";
                            //TODO: Exercise 6 - Task 1
                            //state.Status = OrderStatuses.TicketsExhausted;
                        }
                    }
                }
                else
                {
                    state.FulfillDate = null;
                    state.IsFulfilled = false;
                    //TODO: Exercise 6 - Task 1
                    //state.Status = OrderStatuses.Invalid;
                }

                // Make sure the state is saved
                await SetEntityStateAsync(state);

                // Externalize the state
                await this.ExternalizationService.Externalize(state);

                // Notify the user
                await this.NotificationService.Notify(state);
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            finally
            {
                handler.Stop(error);
                if (!string.IsNullOrEmpty(error))
                {
                    this.HealthReporterService.SendReportForService(HealthState.Error, GetHealthErrorMessage("ProcessOrder", error));
                }
            }
        }
Ejemplo n.º 8
0
        public async Task <IHttpActionResult> UpdateServiceHealthState(UpdateHealthRequest request)
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(TheSettingService, TheLoggerService);

            handler.Start(LOG_TAG, "UpdateServiceHealthState", GetServiceProperties());

            try
            {
                UpdateHealthRequest.Validate(request);

                int ticketOrderServices           = 0;
                int ticketOrderActors             = 0;
                int eventActors                   = 0;
                ServiceLocationService locator    = new ServiceLocationService();
                UriBuilderService      builder    = new UriBuilderService(Constants.ContosoEventsApplicationInstance, Constants.ContosoEventsTicketOrderServiceName);
                ServicePartitionList   partitions = await _fabricClient.QueryManager.GetPartitionListAsync(builder.ToUri());

                foreach (Partition p in partitions)
                {
                    long minKey = (p.PartitionInformation as Int64RangePartitionInformation).LowKey;
                    ITicketOrderService dispenderService = locator.Create <ITicketOrderService>(builder.ToUri());
                    await dispenderService.UpdateHealthState(GetHealthStateFromString(request.State), request.Message);

                    ticketOrderServices++;
                }

                ActorLocationService actorLocator         = new ActorLocationService();
                UriBuilderService    orderActorBuilder    = new UriBuilderService(Constants.ContosoEventsApplicationInstance, Constants.ContosoEventsTicketOrderActorName);
                ServicePartitionList orderActorPartitions = await _fabricClient.QueryManager.GetPartitionListAsync(orderActorBuilder.ToUri());

                foreach (Partition p in orderActorPartitions)
                {
                    string            minKey = (p.PartitionInformation as Int64RangePartitionInformation).Id.ToString();
                    ITicketOrderActor actor  = actorLocator.Create <ITicketOrderActor>(new ActorId(minKey), Constants.ContosoEventsApplicationName);
                    await actor.UpdateHealthState(GetHealthStateFromString(request.State), request.Message);

                    ticketOrderActors++;
                    // May require contiunuation
                }

                IDataStoreService  dataService = ServiceFactory.GetInstance().GetDataStoreService(TheSettingService, TheLoggerService);
                List <TicketEvent> events      = await dataService.GetEvents();

                UriBuilderService eventActorBuilder = new UriBuilderService(Constants.ContosoEventsApplicationInstance, Constants.ContosoEventsEventActorName);
                foreach (var tEvent in events)
                {
                    IEventActor actor = actorLocator.Create <IEventActor>(new ActorId(tEvent.Id), Constants.ContosoEventsApplicationName);
                    await actor.UpdateHealthState(GetHealthStateFromString(request.State), request.Message);

                    eventActors++;
                    // May require contiunuation
                }

                return(Ok("Done: " + ticketOrderServices + "|" + ticketOrderActors + "|" + eventActors));
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return(BadRequest(ex.Message));
            }
            finally
            {
                handler.Stop(error);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// This method is called whenever an actor is activated.
        /// An actor is activated the first time any of its methods are invoked.
        /// </summary>
        protected override async Task OnActivateAsync()
        {
            this.ActorLocationService = ServiceFactory.GetActorLocationService();
            this.SettingService       = ServiceFactory.GetSettingService();
            this.OltpConnectorService = ServiceFactory.GetOltpConnectorService(this.SettingService);

            var error   = "";
            var message = "";
            var handler = HandlersFactory.GetProfilerHandler(SettingService);

            handler.Start(LOG_TAG, "OnActivateAsync", GetActorProperties());

            try
            {
                EntityActorState state = await GetEntityStateAsync();

                if (state == null)
                {
                    // This is the first time this actor has ever been activated.
                    state = new EntityActorState();

                    // Set the actor's initial state values.
                    state.Purchases     = 0;
                    state.Cancellations = 0;
                    state.SoldItems     = 0;
                    state.Revenue       = 0;
                    state.Tax           = 0;
                    state.Shipping      = 0;

                    // Use the actor ID (which packs the enity type and business key) to load the state entity
                    List <string> actorIdParts = this.Id.GetStringId().Split('|').Select(s => s).ToList();
                    if (actorIdParts == null || actorIdParts.Count != 2)
                    {
                        message = string.Format("Actor ID {0} state could not be determined!!!!", this.Id.GetStringId());
                        handler.Info(message);
                        state.Entity = new Entity(EntityTypes.SalesOffice, -1);
                    }
                    else
                    {
                        state.Entity = new Entity();

                        try
                        {
                            EntityTypes type        = (EntityTypes)Int32.Parse(actorIdParts.ToArray()[0]);
                            int         businessKey = Int32.Parse(actorIdParts.ToArray()[1]);
                            var         entity      = await OltpConnectorService.GetEntity(type, businessKey);

                            if (entity != null)
                            {
                                state.Entity = await OltpConnectorService.GetEntity(type, businessKey);
                            }
                        }
                        catch (Exception)
                        {
                            message = string.Format("Actor ID {0} state could not be parsed to determine actor entity!!!!", this.Id.GetStringId());
                            handler.Info(message);
                        }
                    }

                    // Make sure the state is saved
                    await SetEntityStateAsync(state);
                }

                state = await this.StateManager.GetStateAsync <EntityActorState>(ActorStatePropertyName);

                message = string.Format("Actor {0} activated", this.Id.GetStringId());
                handler.Info(message);
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            finally
            {
                handler.Stop(error);
            }
        }
Ejemplo n.º 10
0
        // IRemindable Interface Implementation
        public async Task ReceiveReminderAsync(string reminderName, byte[] context, TimeSpan dueTime, TimeSpan period)
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(SettingService);

            handler.Start(LOG_TAG, "ReceiveReminderAsync", GetActorProperties());

            try
            {
                handler.Info("Reminder " + reminderName);
                var state = await this.StateManager.GetStateAsync <EntityActorState>(ActorStatePropertyName);

                EntityTransaction transaction = (EntityTransaction)ByteArrayToObject(context);
                if (transaction == null)
                {
                    handler.Info("Transaction is null");
                }

                switch (reminderName)
                {
                case ReprocessReminder:
                {
                    // Unregister the reminder so the actor will be garbage collected
                    IActorReminder reminder = this.GetReminder(ReprocessReminder);
                    await this.UnregisterReminderAsync(reminder);

                    // Process this transaction
                    if (transaction.TransactionType == TransactionTypes.Purchase)
                    {
                        state.Purchases++;
                        state.SoldItems += transaction.SoldItems;
                        state.Revenue   += transaction.Revenue;
                        state.Tax       += transaction.Tax;
                        state.Shipping  += transaction.Shipping;
                    }
                    else if (transaction.TransactionType == TransactionTypes.Cancellation)
                    {
                        state.Cancellations++;
                        state.SoldItems -= transaction.SoldItems;
                        state.Revenue   -= transaction.Revenue;
                        state.Tax       -= transaction.Tax;
                        state.Shipping  -= transaction.Shipping;
                    }

                    // Make sure the state is saved
                    await SetEntityStateAsync(state);

                    // Publish an event that we are done processing
                    // Right now it is useless
                    // It is an excercise to see how events work
                    var ev = GetEvent <IEntityActorEvents>();
                    ev.MeasuresRecalculated(await GetEntity(), state.Purchases, state.Cancellations, state.SoldItems, state.Revenue, state.Tax, state.Shipping);

                    // If available, process the parent
                    var parent = await GetParent();

                    if (parent != null)
                    {
                        handler.Info("Parent actor type " + parent.Type);
                        IEntityActor parentActor = ActorLocationService.Create <IEntityActor>(parent.GetPartitionKey(), ApplicationName);
                        await parentActor.Process(transaction);
                    }

                    return;
                }

                default:
                {
                    // We should never arrive here normally. The system won't call reminders that don't exist.
                    // But for our own sake in case we add a new reminder somewhere and forget to handle it, this will remind us.
                    handler.Info("Unknown reminder: " + reminderName);
                    return;
                }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }
            finally
            {
                handler.Stop(error);
            }
        }
        // ITicketDispenserService Interface Implementation
        public async Task <string> EnqueueOrder(TicketOrder order)
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(SettingService, LoggerService);

            handler.Start(LOG_TAG, "EnqueueOrder", GetServiceProperties());
            string orderId   = Guid.NewGuid().ToString();
            bool   blProceed = true;

            try
            {
                // Do some sanity checking
                TicketOrder.Validate(order);

                // Quick check to see if tickets are available
                if (SettingService.IsTicketAvailabilityCheck())
                {
                    IEventActor eventActor = this.ActorLocationService.Create <IEventActor>(new ActorId(order.EventId), Constants.ContosoEventsApplicationName);
                    if (!await eventActor.CheckTickets(order))
                    {
                        handler.Info("Processing order - Event Id: " + order.EventId + " - Order Id: " + orderId + " - tickets: " + order.Tickets + " - Tickets are exhausted!");
                        // Do not throw an exception because we will get a health issue
                        // throw new Exception("Tickets are exhausted!");
                        // Need to alert the admin only as tickets are exhausted

                        // Prevent proceeding with the order
                        blProceed = false;
                        // Reset the order id to indicate to the Web API client that the order did not go through
                        orderId = "";
                    }
                }

                if (blProceed)
                {
                    order.Id = orderId;
                    handler.Info("Processing order - Event Id: " + order.EventId + " - Order Id: " + orderId + " - tickets: " + order.Tickets);

                    //TODO: Task 2.1 - Get (or create) a reliable queue called "OrderQueue" in this partition.
                    //var requests = await this.StateManager./*...complete this...*/<IReliableQueue<TicketOrder>>(OrderQueueName);
                    var requests = await this.StateManager.GetOrAddAsync <IReliableQueue <TicketOrder> >(OrderQueueName);

                    //TODO: Task 2.2 - Create a new transaction scope
                    //using (var tx = this.StateManager./*...complete this...*/)
                    //{
                    // TODO: Task 2.3 - Enqueue the order to the reliable queue within the transaction
                    //await requests.EnqueueAsync(/*...complete this...*/, /*...complete this...*/);

                    // TODO: Task 2.4 - Commit the transaction if enqueue was successful
                    //await tx./*...complete this...*/();
                    //}

                    using (var tx = this.StateManager.CreateTransaction())
                    {
                        await requests.EnqueueAsync(tx, order);

                        await tx.CommitAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                throw ex;
            }
            finally
            {
                handler.Stop(error);
                if (!string.IsNullOrEmpty(error))
                {
                    this.HealthReporterService.SendReportForService(HealthState.Error, GetHealthErrorMessage("EnqueueOrder", error));
                }
            }

            return(orderId);
        }
Ejemplo n.º 12
0
        private async Task Initialize()
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(_settingService, _loggerService);

            handler.Start(LOG_TAG, "Initialize", null);

            try
            {
                _events = new List <TicketEvent>();

                var event1 = new TicketEvent()
                {
                    Id                       = "EVENT1-ID-00001",
                    Name                     = "Seattle Rock and Rollers",
                    Summary                  = "Seattle Rock and Rollers Summary",
                    Description              = "Seattle Rock and Rollers Description",
                    ImageUrl                 = "http://www.loremimages.com/gen.php?size=300x200&bg=0000&fg=fff&format=png",
                    Latitude                 = 0,
                    Longitude                = 0,
                    StartDate                = DateTime.Now.AddDays(-60),
                    EndDate                  = DateTime.Now.AddDays(60),
                    TotalTickets             = 100000,
                    PricePerTicket           = 25,
                    Currency                 = "USD",
                    PaymentProcessorUrl      = "",
                    PaymentProcessorAccount  = "",
                    PaymentProcessorPassword = "",
                    SuccessEmailTemplate     = @"
                    <h1> Ticket Purchase Notification </h1>
                    Dear @Model.UserName, 
                    <p>
                    Congratulations! Your have @Model.Tickets tickets guranateed to Seattle Rock and Rollers.
                    </p>
                    ",
                    FailedEmailTemplate      = @"
                    <h1> Ticket Purchase Failure Notification </h1>
                    Dear @Model.UserName, 
                    <p>
                    Sorry! Your @Model.Tickets tickets could not be purchased to Seattle Rock and Rollers.
                    </p>
                    ",
                    SuccessSmsTemplate       = @"
                    <h1> Ticket Purchase Notification </h1>
                    Dear @Model.UserName, 
                    <p>
                    Congratulations! Your have @Model.Tickets tickets guranateed to Seattle Rock and Rollers.
                    </p>
                    ",
                    FailedSmsTemplate        = @"
                    <h1> Ticket Purchase Failure Notification </h1>
                    Dear @Model.UserName, 
                    <p>
                    Sorry! Your @Model.Tickets tickets could not be purchased to Seattle Rock and Rollers.
                    </p>
                    "
                };

                _events.Add(event1);

                if (string.IsNullOrEmpty(_endpointUri) ||
                    string.IsNullOrEmpty(_primaryKey)
                    )
                {
                    return; // Exit gracefully
                }

                // Seed events
                _docDbClient = new DocumentClient(new Uri(_endpointUri), _primaryKey);

                try
                {
                    await this._docDbClient.ReadDocumentAsync(UriFactory.CreateDocumentUri(_databaseName, _eventsCollectionName, event1.Id));
                }
                catch (DocumentClientException de)
                {
                    if (de.StatusCode == HttpStatusCode.NotFound)
                    {
                        await this._docDbClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(_databaseName, _eventsCollectionName), event1);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                throw new Exception(error);
            }
            finally
            {
                handler.Stop(error);
            }
        }
Ejemplo n.º 13
0
        public async Task <TicketEventStats> GetEventStats(string eventId)
        {
            var error   = string.Empty;
            var handler = HandlersFactory.GetProfilerHandler(settingService, logger);

            handler.Start(LOG_TAG, "GetEventStats", null);

            try
            {
                var ticketEvent = await GetEventById(eventId);

                if (ticketEvent == null)
                {
                    return(new TicketEventStats());
                }

                using (CosmosClient cosmosClient = new CosmosClient(endpointUri, primaryKey))
                {
                    var databaseResponse = await cosmosClient.Databases.CreateDatabaseIfNotExistsAsync(databaseName);

                    var containerResponse = await databaseResponse.Database.Containers.CreateContainerIfNotExistsAsync(ordersContainerName, "/EventId");

                    var query           = $"SELECT * FROM Orders o WHERE o.EventId = '{eventId}'";
                    var queryDefinition = new CosmosSqlQueryDefinition(query);
                    var iterator        = containerResponse.Container.Items.CreateItemQuery <TicketOrder>(queryDefinition, maxConcurrency: 1);

                    var ticketOrders = new List <TicketOrder>();

                    while (iterator.HasMoreResults)
                    {
                        var queryResponse = await iterator.FetchNextSetAsync();

                        foreach (var item in queryResponse)
                        {
                            ticketOrders.Add(item);
                        }
                    }

                    var requestedCount = ticketOrders.Sum(o => o.Tickets);
                    var failedCount    = ticketOrders.Where(o => o.IsFulfilled == false && o.IsCancelled == false).Sum(o => o.Tickets);
                    var canxCount      = ticketOrders.Where(o => o.IsFulfilled == false && o.IsCancelled == true).Sum(o => o.Tickets);

                    return(new TicketEventStats()
                    {
                        Tickets = ticketEvent.TotalTickets,
                        RequestedTickets = requestedCount,
                        FailedTickets = failedCount,
                        CancelledTickets = canxCount,
                        Orders = ticketOrders.Count
                    });
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                throw new Exception(error);
            }
            finally
            {
                handler.Stop(error);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// This is the main entry point for your service replica.
        /// This method executes when this replica of your service becomes primary and has write status.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service replica.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            // Gets (or creates) a replicated dictionary called "myDictionary" in this partition.
            var requests = await this.StateManager.GetOrAddAsync <IReliableQueue <EntityTransaction> >(ProcessQueueName);

            try
            {
                // This partition's replica continues processing until the replica is terminated.
                while (!cancellationToken.IsCancellationRequested)
                {
                    using (var tx = this.StateManager.CreateTransaction())
                    {
                        var result = await requests.TryDequeueAsync(tx, TxTimeout, cancellationToken);

                        if (result.HasValue)
                        {
                            var error   = "";
                            var handler = HandlersFactory.GetProfilerHandler(SettingService);
                            handler.Start(LOG_TAG, "AcquiredQueueItem", GetServiceProperties());

                            try
                            {
                                EntityTransaction transaction = result.Value;
                                handler.Info("Acquired item business key: " + transaction.BusinessKey + " - entity type: " + transaction.EntityType);

                                IActorLocationService locator     = ServiceFactory.GetActorLocationService();
                                IEntityActor          entityActor = locator.Create <IEntityActor>(new Entity(transaction.EntityType, transaction.BusinessKey).GetPartitionKey(), Constants.ApplicationName);
                                await entityActor.SubscribeAsync <IEntityActorEvents>(this);

                                await entityActor.Process(transaction);
                            }
                            catch (Exception ex)
                            {
                                error = ex.Message;
                            }
                            finally
                            {
                                handler.Stop(error);
                            }
                        }

                        // This commits the dequeue operations.
                        // If the request to add the stock to the inventory service throws, this commit will not execute
                        // and the items will remain on the queue, so we can be sure that we didn't dequeue items
                        // that didn't get saved successfully in the inventory service.
                        // However there is a very small chance that the stock was added to the inventory service successfully,
                        // but service execution stopped before reaching this commit (machine crash, for example).
                        await tx.CommitAsync();
                    }

                    // Pause for 2 second before continue processing.
                    await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken);
                }
            }
            catch (Exception ex)
            {
            }

            // Pause for 1 second before continue processing.
            await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
        }
        public async Task Notify(TicketOrder order)
        {
            var error   = "";
            var handler = HandlersFactory.GetProfilerHandler(_settingService, _loggerService);

            handler.Start(LOG_TAG, "Notify", null);

            try
            {
                if (order == null)
                {
                    throw new Exception("No Order");
                }

                if (string.IsNullOrEmpty(order.Email))
                {
                    throw new Exception("No Email in order!");
                }

                TicketEvent ev = await _dataStoreService.GetEventById(order.EventId);

                if (ev == null)
                {
                    throw new Exception("No associated Event");
                }

                var templateBody = "";
                if (order.IsCancelled)
                {
                    templateBody = ev.FailedEmailTemplate;
                }
                else if (order.IsFulfilled)
                {
                    templateBody = ev.SuccessEmailTemplate;
                }
                else if (!order.IsFulfilled)
                {
                    templateBody = ev.FailedEmailTemplate;
                }

                if (string.IsNullOrEmpty(templateBody))
                {
                    throw new Exception("No Template available");
                }

                if (
                    string.IsNullOrEmpty(_settingService.GetEmailServerUrl()) ||
                    string.IsNullOrEmpty(_settingService.GetEmailServerUserName()) ||
                    string.IsNullOrEmpty(_settingService.GetEmailServerPassword())
                    )
                {
                    return; // Exit gracefully
                }

                // Produce the body by binding the template and the model
                string body = Engine.Razor.RunCompile(templateBody, "templateCahe", order.GetType(), order);

                SmtpClient client = new SmtpClient(_settingService.GetEmailServerUrl(), _settingService.GetEmailServerPort());
                client.EnableSsl   = true;
                client.Credentials = new System.Net.NetworkCredential(_settingService.GetEmailServerUserName(), _settingService.GetEmailServerPassword());

                MailMessage message = new MailMessage();
                message.From = new MailAddress("*****@*****.**", "*****@*****.**", System.Text.Encoding.UTF8);
                message.To.Add(order.Email);
                message.Body            = body;
                message.BodyEncoding    = System.Text.Encoding.UTF8;
                message.IsBodyHtml      = true;
                message.Subject         = "ContosoEvents [" + ev.Name + "] Order " + (order.IsFulfilled ? "Confirmation" : "Failure");
                message.SubjectEncoding = System.Text.Encoding.UTF8;
                client.Send(message);
            }
            catch (Exception ex)
            {
                error = ex.Message;
                // Ignore expeptions as the account crdentials can be wrong and we don't want to cause health issues
                //throw new Exception(error);
            }
            finally
            {
                handler.Stop(error);
            }
        }