示例#1
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string email   = txtEmail.Text.Trim();
            string subject = txtSubject.Text.Trim();

            if (email.Length > 0 && subject.Length > 0)
            {
                ContactUsInfoDto contactUsInfo = new ContactUsInfoDto();
                contactUsInfo.Email      = email;
                contactUsInfo.Subject    = subject;
                contactUsInfo.Name       = txtName.Text.Trim();
                contactUsInfo.Phone      = txtPhone.Text.Trim();
                contactUsInfo.Address    = txtAddress.Text.Trim();
                contactUsInfo.Message    = txtMessage.Text.Trim();
                contactUsInfo.IssuedTime = DateTime.Now;

                try
                {
                    NotificationProcessor.SendContactUs(contactUsInfo);
                    lbResultMsg.Text = Localize("Shop.ContactUsPage.lbResultMsg", "Thank you for contacting us! Your message has been sent to our support team.");
                    ClearForm();
                }
                catch (Exception ex)
                {
                    ProcException(ex, "Sending email failed. ");
                }
            }
        }
示例#2
0
        public async Task <IEnumerable <GetUserNotificationsQueryResult> > GetActiveUserNotifications()
        {
            var userNotifications = NotificationProcessor.GetNotifications();

            var notHiddenNotifications =
                QueryProcessor.Execute(new GetUserNotificationsQuery(GetUserNotificationsType.Visible));

            if (userNotifications.Any())
            {
                await Task.Run(
                    () => CommandProcessor.Execute(new AddUserNotificationCommand(userNotifications))
                    ).ConfigureAwait(true);
            }

            return
                (userNotifications
                 .Select(notification => new GetUserNotificationsQueryResult
            {
                Key = notification.Key,
                Text = notification.Text,
                Title = notification.Title,
                CreatedAt = notification.CreatedAt,
                Type = Enum.GetName(typeof(UserNotificationType), notification.Type)
            })
                 .Union(notHiddenNotifications)
                 .OrderBy(x => x.CreatedAt));
        }
示例#3
0
 private void SaveQuote()
 {
     using (IUnitOfWork uow = UnitOfWorkFactory.Instance.Start(DataStoreResolver.CRMDataStoreKey))
     {
         QuoteFacade facade = new QuoteFacade(uow);
         FacadeUpdateResult <QuoteData> result = facade.SaveNewQuote(CurrentInstance);
         if (result.IsSuccessful)
         {
             // Load saved Quote
             CurrentInstance.QuoteId  = result.Result.Id;
             CurrentInstance.StatusId = result.Result.StatusId;
             ucSavedQuote.LoadData(CurrentInstance);
             // Send notification
             try
             {
                 NotificationProcessor.SendQuoteCreation(CurrentInstance);
             }
             catch (Exception ex)
             {
                 ProcException(ex, "Quote creation successful. But sending email failed. ");
             }
         }
         else
         {
             ProcUpdateResult(result.ValidationResult, result.Exception);
         }
     }
 }
        public void Run(DatabaseContext context, Logging log, string settings)
        {
            NotificationProcessor proc = new NotificationProcessor(context, JsonConvert.DeserializeObject <NotificationProcessorSettings>(settings), log);
            int Processed = proc.ProcessQueue();

            if (Processed > 0)
            {
                log.LogMessage(string.Format("NotificationProcessor: Processed {0} notifications\r\n", Processed.ToString()));
            }
        }
示例#5
0
        //test


        public void Run(string settings)
        {
            NotificationProcessor proc = new NotificationProcessor(_repository, JsonConvert.DeserializeObject <NotificationProcessorSettings>(settings));
            int Processed = proc.ProcessQueue();

            if (Processed > 0)
            {
                Logging.LogMessage(string.Format("NotificationProcessor: Processed {0} notifications\r\n", Processed.ToString()));
            }
        }
示例#6
0
        private void BuildSyncManager()
        {
            try
            {
                // Synchronizer
                var impressionsCountSender = new ImpressionsCountSender(_impressionsSdkApiClient, _impressionsCounter, _tasksManager);
                var backOff      = new BackOff(backOffBase: 10, attempt: 0, maxAllowed: 60);
                var synchronizer = new Synchronizer(_splitFetcher, _selfRefreshingSegmentFetcher, _impressionsLog, _eventsLog, impressionsCountSender, _wrapperAdapter, _statusManager, _telemetrySyncTask, _tasksManager, _splitCache, backOff, _config.OnDemandFetchMaxRetries, _config.OnDemandFetchRetryDelayMs, _segmentCache);

                // Workers
                var splitsWorker   = new SplitsWorker(_splitCache, synchronizer, _tasksManager);
                var segmentsWorker = new SegmentsWorker(synchronizer, _tasksManager);

                // NotificationProcessor
                var notificationProcessor = new NotificationProcessor(splitsWorker, segmentsWorker);

                // NotificationParser
                var notificationParser = new NotificationParser();

                // NotificationManagerKeeper
                var notificationManagerKeeper = new NotificationManagerKeeper(_telemetryRuntimeProducer);

                // EventSourceClient
                var headers = GetHeaders();
                headers.Add(Constants.Http.SplitSDKClientKey, ApiKey.Substring(ApiKey.Length - 4));
                headers.Add(Constants.Http.Accept, Constants.Http.EventStream);
                var sseHttpClient     = new SplitioHttpClient(ApiKey, _config.HttpConnectionTimeout, headers);
                var eventSourceClient = new EventSourceClient(notificationParser, _wrapperAdapter, sseHttpClient, _telemetryRuntimeProducer, _tasksManager);

                // SSEHandler
                var sseHandler = new SSEHandler(_config.StreamingServiceURL, splitsWorker, segmentsWorker, notificationProcessor, notificationManagerKeeper, eventSourceClient: eventSourceClient);

                // AuthApiClient
                var httpClient    = new SplitioHttpClient(ApiKey, _config.HttpConnectionTimeout, GetHeaders());
                var authApiClient = new AuthApiClient(_config.AuthServiceURL, ApiKey, httpClient, _telemetryRuntimeProducer);

                // PushManager
                var backoff     = new BackOff(_config.AuthRetryBackoffBase, attempt: 1);
                var pushManager = new PushManager(sseHandler, authApiClient, _wrapperAdapter, _telemetryRuntimeProducer, backoff);

                // SyncManager
                _syncManager = new SyncManager(_config.StreamingEnabled, synchronizer, pushManager, sseHandler, notificationManagerKeeper, _telemetryRuntimeProducer, _statusManager, _tasksManager, _wrapperAdapter, _telemetrySyncTask);
            }
            catch (Exception ex)
            {
                _log.Error($"BuildSyncManager: {ex.Message}");
            }
        }
示例#7
0
文件: FilterBot.cs 项目: versx/Brock
        public FilterBot(IEventLogger logger)
        {
            Commands = new CommandList();

            _logger = logger;
            _db     = Database.Load();
            if (_db == null)
            {
                _logger.Error("Failed to load database, exiting...");
                Environment.Exit(-1);
            }

            _config = File.Exists(Config.ConfigFilePath) ? Config.Load() : Config.CreateDefaultConfig(true);
            _rand   = new Random();

            _client = new DiscordClient
                      (
                new DiscordConfiguration
            {
                AutoReconnect         = true,
                LogLevel              = LogLevel.Error,
                UseInternalLogHandler = true,
                Token     = _config.AuthToken,
                TokenType = TokenType.Bot
            }
                      );

            _client.MessageCreated         += Client_MessageCreated;
            _client.Ready                  += Client_Ready;
            _client.DmChannelCreated       += Client_DmChannelCreated;
            _client.GuildMemberAdded       += Client_GuildMemberAdded;
            _client.GuildMemberRemoved     += Client_GuildMemberRemoved;
            _client.GuildBanAdded          += Client_GuildBanAdded;
            _client.GuildBanRemoved        += Client_GuildBanRemoved;
            _client.MessageReactionAdded   += Client_MessageReactionAdded;
            _client.MessageReactionRemoved += Client_MessageReactionRemoved;

            _reminderSvc           = new ReminderService(_client, _db, _logger);
            _notificationProcessor = new NotificationProcessor(_client, _db, _config, _logger);
            _lobbyManager          = new RaidLobbyManager(_client, _config, _logger, _notificationProcessor.GeofenceSvc);
            _weatherSvc            = new WeatherService(/*_config.AccuWeatherApiKey*/ _notificationProcessor.GeofenceSvc, _logger);

            //LoadAlarms(Path.Combine(Directory.GetCurrentDirectory(), DefaultAlarmsFileName));
        }
示例#8
0
        private void BuildSyncManager()
        {
            try
            {
                var synchronizer              = new Synchronizer(_splitFetcher, _selfRefreshingSegmentFetcher, _impressionsLog, _eventsLog, _metricsLog, _wrapperAdapter);
                var splitsWorker              = new SplitsWorker(_splitCache, synchronizer);
                var segmentsWorker            = new SegmentsWorker(_segmentCache, synchronizer);
                var notificationProcessor     = new NotificationProcessor(splitsWorker, segmentsWorker);
                var notificationParser        = new NotificationParser();
                var eventSourceClient         = new EventSourceClient(_config.StreamingReconnectBackoffBase, notificationParser: notificationParser);
                var notificationManagerKeeper = new NotificationManagerKeeper();
                var sseHandler    = new SSEHandler(_config.StreamingServiceURL, splitsWorker, segmentsWorker, notificationProcessor, notificationManagerKeeper, eventSourceClient: eventSourceClient);
                var authApiClient = new AuthApiClient(_config.AuthServiceURL, ApiKey, _config.HttpReadTimeout);
                var pushManager   = new PushManager(_config.AuthRetryBackoffBase, sseHandler, authApiClient, _wrapperAdapter);

                _syncManager = new SyncManager(_config.StreamingEnabled, synchronizer, pushManager, sseHandler, notificationManagerKeeper);
            }
            catch (Exception ex)
            {
                _log.Error($"BuildSyncManager: {ex.Message}");
            }
        }
        public async Task <IActionResult> SesNotificationAsync()
        {
            var body = string.Empty;

            using (var reader = new StreamReader(Request.Body))
            {
                body = await reader.ReadToEndAsync();
            }

            var notificationProcessor = new NotificationProcessor();
            var result = await notificationProcessor.ProcessNotificationAsync(body);

            //Your processing logic...
            if (result.NotificationType == "Bounce")
            {
                var webhook = result as EmailBounceWebhook;
                if (webhook.Bounce.BounceType.Equals("Permanent", StringComparison.OrdinalIgnoreCase))
                {
                }
            }

            return(StatusCode(StatusCodes.Status200OK));
        }
 private void SaveOrders()
 {
     using (IUnitOfWork uow = UnitOfWorkFactory.Instance.Start(DataStoreResolver.CRMDataStoreKey))
     {
         OrderFacade facade = new OrderFacade(uow);
         FacadeUpdateResult <OrderData> result = facade.SaveNewOrders(Orders);
         if (result.IsSuccessful)
         {
             List <object> ids = new List <object>();
             foreach (OrderData savedOrder in result.ResultList)
             {
                 ids.Add(savedOrder.Id);
             }
             // Retrieve order info after saving successful
             Orders = facade.RetrieveOrdersInfo(ids, new OrderInfoConverter());
             // Clear cart
             if (!WebContext.Current.ApplicationOption.IsTestMode)
             {
                 ClearCart();
             }
             LoadOrderConfirmation();
             // Send notification
             try
             {
                 NotificationProcessor.SendOrderConfirmation(txtEmail.Text.Trim(), Orders);
             }
             catch (Exception ex)
             {
                 ProcException(ex, "Order successful. But sending email failed. ");
             }
         }
         else
         {
             ProcUpdateResult(result.ValidationResult, result.Exception);
         }
     }
 }
        /// <summary>
        /// Processes the notifications and raises the required callbacks.
        /// This function should be called in order for the SDK to raise
        /// any required events and process state changes.
        /// </summary>
        /// <param name="client">The stateful client.</param>
        /// <param name="request">The http request that is incoming from service.</param>
        /// <returns>Http Response Message after processed by the SDK. This has to
        /// be returned to the server.</returns>
        private static async Task <HttpResponseMessage> ProcessNotificationAsync(ICommunicationsClient client, HttpRequestMessage request)
        {
            client.NotNull(nameof(client));
            request.NotNull(nameof(request));
            var stopwatch = Stopwatch.StartNew();

            var scenarioId = client.GraphLogger.ParseScenarioId(request);
            var requestId  = client.GraphLogger.ParseRequestId(request);

            CommsNotifications notifications = null;

            try
            {
                // Parse out the notification content.
                var content = await request.Content.ReadAsStringAsync().ConfigureAwait(false);

                var serializer = client.Serializer;
                notifications = NotificationProcessor.ExtractNotifications(content, serializer);
            }
            catch (ServiceException ex)
            {
                var statusCode = (int)ex.StatusCode >= 200
                    ? ex.StatusCode
                    : HttpStatusCode.BadRequest;
                return(client.LogAndCreateResponse(request, requestId, scenarioId, notifications, statusCode, stopwatch, ex));
            }
            catch (Exception ex)
            {
                var statusCode = HttpStatusCode.BadRequest;
                return(client.LogAndCreateResponse(request, requestId, scenarioId, notifications, statusCode, stopwatch, ex));
            }

            RequestValidationResult result;

            try
            {
                // Autenticate the incoming request.
                result = await client.AuthenticationProvider
                         .ValidateInboundRequestAsync(request)
                         .ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                var clientEx = new ClientException(
                    new Error
                {
                    Code    = ErrorConstants.Codes.ClientCallbackError,
                    Message = ErrorConstants.Messages.ClientErrorAuthenticatingRequest,
                },
                    ex);

                throw clientEx;
            }

            if (!result.IsValid)
            {
                var statusCode = HttpStatusCode.Unauthorized;
                return(client.LogAndCreateResponse(request, requestId, scenarioId, notifications, statusCode, stopwatch));
            }

            // The request is valid. Let's evaluate any policies on the
            // incoming call before sending it off to the SDK for processing.
            var call     = notifications?.Value?.FirstOrDefault()?.GetResourceData() as Call;
            var response = await EvaluateAndHandleIncomingCallPoliciesAsync(call).ConfigureAwait(false);

            if (response != null)
            {
                var level = client.GraphLogger.LogHttpRequest(request, response.StatusCode, notifications);
                client.GraphLogger.LogHttpResponse(level, request, response, stopwatch.ElapsedMilliseconds);
                stopwatch.Stop();
                return(response);
            }

            try
            {
                var additionalData = request.GetHttpAndContentHeaders().ToDictionary(
                    pair => pair.Key,
                    pair => (object)string.Join(",", pair.Value),
                    StringComparer.OrdinalIgnoreCase);
                client.ProcessNotifications(request.RequestUri, notifications, result.TenantId, requestId, scenarioId, additionalData);
            }
            catch (ServiceException ex)
            {
                var statusCode = (int)ex.StatusCode >= 200
                    ? ex.StatusCode
                    : HttpStatusCode.InternalServerError;
                return(client.LogAndCreateResponse(request, requestId, scenarioId, notifications, statusCode, stopwatch, ex));
            }
            catch (Exception ex)
            {
                var statusCode = HttpStatusCode.InternalServerError;
                return(client.LogAndCreateResponse(request, requestId, scenarioId, notifications, statusCode, stopwatch, ex));
            }

            return(client.LogAndCreateResponse(request, requestId, scenarioId, notifications, HttpStatusCode.Accepted, stopwatch));
        }
示例#12
0
 public JobProcessNotifications(NotificationProcessor notificationProcessor)
 {
     _notificationProcessor = notificationProcessor;
 }
        public void TestNotificationProcessingMultipleDBs()
        {
            var store1 = GetTestStore();
            var store2 = GetTestStore();
            var store3 = GetTestStore();
            const int numberToTest = 100;
            var stores = new [] {store1, store2, store3};

            StoreTestNotifications(numberToTest, stores);
            var logStub = MockRepository.GenerateStub<log4net.ILog>();
            var storeStub = MockRepository.GenerateStub<IDocumentStore>();

            var processor = new NotificationProcessor(
                new EmailNotificationDispatcher( logStub,new TestEmailSender{Store = store1}),
                new ToastDispatcher(storeStub, logStub),
                                       stores,
                                       new SmsDispatcher(logStub,new TestSmsSender()),
                                       logStub,
                                       100
                                       );
            var numberProcessed = processor.Process();
            Assert.AreEqual(numberProcessed, numberToTest*stores.Count());
            using (var session = store1.OpenSession())
            {
                var overdueNotifications = session.Query<Notification>().Where(n => !n.Sent && n.SendDate < DateTime.UtcNow).ToArray();
                Assert.AreEqual(0, overdueNotifications.Count());
            }
            
        }