Exemplo n.º 1
0
        protected virtual async Task SendWeChatTemplateMessagAsync(NotificationInfo notification, UserIdentifier identifier)
        {
            var templateId = GetOrDefaultTemplateId(notification.Data);

            Logger.LogDebug($"Get wechat weapp template id: {templateId}");

            var redirect = GetOrDefault(notification.Data, "RedirectPage", null);

            Logger.LogDebug($"Get wechat weapp redirect page: {redirect ?? "null"}");

            var weAppState = GetOrDefault(notification.Data, "WeAppState", Options.DefaultWeAppState);

            Logger.LogDebug($"Get wechat weapp state: {weAppState ?? null}");

            var weAppLang = GetOrDefault(notification.Data, "WeAppLanguage", Options.DefaultWeAppLanguage);

            Logger.LogDebug($"Get wechat weapp language: {weAppLang ?? null}");

            var weChatWeAppNotificationData = new WeChatWeAppSendNotificationData(identifier.UserName,
                                                                                  templateId, redirect, weAppState, weAppLang);

            // 写入模板数据
            weChatWeAppNotificationData.WriteStandardData(NotificationData.ToStandardData(Options.DefaultMsgPrefix, notification.Data));

            Logger.LogDebug($"Sending wechat weapp notification: {notification.Name}");
            // 发送小程序订阅消息
            await NotificationSender.SendAsync(weChatWeAppNotificationData);
        }
Exemplo n.º 2
0
        static async Task MainAsync()
        {
            var key = ConfigurationManager.AppSettings["BotKey"];
            NotificationSender notificationSender = new NotificationSender(key);

            IList <Party> partiesToNotify = new List <Party>();

            var party = PartyManager.GetParties()[0];

            partiesToNotify.Add(party);

            Console.WriteLine("Write Notification. Your Message, High|Normal|Low");
            Console.Write("> ");
            var messageLine = Console.ReadLine();
            var message     = messageLine.Split(',');

            while (message[0].ToLower() != "stop")
            {
                Log($"Sending notification {message[0]}");

                Microsoft.Bot.Connector.DirectLine.ResourceResponse resourceResponse =
                    await notificationSender.NotifyAsync(partiesToNotify, $"{message[0]}", message[1].ToLower().Trim());

                Log($"{((resourceResponse == null) ? "Received no response" : $"Received resource response with ID {resourceResponse.Id}")}");

                Console.Write("> ");
                messageLine = Console.ReadLine();
                message     = messageLine.Split(',');
#if DEBUG
                // The following will dump the activity info into Output (console)
                Microsoft.Bot.Connector.DirectLine.Activity activity = await notificationSender.GetLatestReplyAsync();
#endif
            }
        public NotificationSenderUnitTests()
        {
            _templateRender            = new LiquidTemplateRenderer();
            _messageServiceMock        = new Mock <INotificationMessageService>();
            _messageSenderMock         = new Mock <INotificationMessageSender>();
            _serviceMock               = new Mock <INotificationService>();
            _logNotificationSenderMock = new Mock <ILogger <NotificationSender> >();
            _emailSendingOptionsMock   = new Mock <IOptions <EmailSendingOptions> >();

            _senderFactoryMock = new Mock <INotificationMessageSenderProviderFactory>();
            _smtpEmailNotificationMessageSenderMock = new Mock <SmtpEmailNotificationMessageSender>(_emailSendingOptionsMock.Object);
            _senderFactoryMock.Setup(s => s.GetSenderForNotificationType(nameof(EmailNotification))).Returns(_messageSenderMock.Object);

            _sender = new NotificationSender(_templateRender, _messageServiceMock.Object, _logNotificationSenderMock.Object, _senderFactoryMock.Object);

            if (!AbstractTypeFactory <NotificationTemplate> .AllTypeInfos.SelectMany(x => x.AllSubclasses).Contains(typeof(EmailNotificationTemplate)))
            {
                AbstractTypeFactory <NotificationTemplate> .RegisterType <EmailNotificationTemplate>().MapToType <NotificationTemplateEntity>();
            }

            if (!AbstractTypeFactory <NotificationMessage> .AllTypeInfos.SelectMany(x => x.AllSubclasses).Contains(typeof(EmailNotificationMessage)))
            {
                AbstractTypeFactory <NotificationMessage> .RegisterType <EmailNotificationMessage>().MapToType <NotificationMessageEntity>();
            }
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);

                string param = args[i];

                if (param.ToLower() == "resetseq")
                {
                    _resetSequenceNumber = true;
                }
            }
            _resetSequenceNumber = true;

            //Console.Title = "Fix Orders Service (Fix Client)";
            SystemLogger.Initialize();
            SystemConfigurations.Initialize();
            NotificationSender.Initialize();

            Program prog = new Program();

            if (Environment.UserInteractive)
            {
                prog.OnStart(args);
                while (true)
                {
                    Console.ReadKey();
                }
            }
            else
            {
                ServiceBase.Run(prog);
            }
        }
Exemplo n.º 5
0
        private async Task <IActionResult> ManageSuccessfullLogin(LoginViewModel model, string returnUrl)
        {
            ApplicationUser user = await _userManager.FindByNameAsync(model.UserName);

            if (user != null && !string.IsNullOrWhiteSpace(user.UserName))
            {
                SetProfileOnSession(new Guid(user.Id), user.UserName);

                await SetStaffRoles(user);

                SetPreferences(user);

                SetCache(user);
            }

            string logMessage = String.Format("User {0} logged in.", model.UserName);

            if (!model.UserName.Equals("programad"))
            {
                await NotificationSender.SendTeamNotificationAsync(logMessage);
            }

            _logger.LogInformation(logMessage);

            return(RedirectToLocal(returnUrl));
        }
        public void when_publish_SendNotificationMessage_it_will_go_to_email_service_endpoint()
        {
            var emailServiceEndpointUri = new Queue(ConfigurationManager.AppSettings["EmailServiceHost"], ConfigurationManager.AppSettings["EmailServiceEndpoint"]);

            IEndpoint emailServiceEndpoint = _endpointResolver.GetEndpoint(emailServiceEndpointUri.ToString());

            int startingNummberOfEmailMessages = 0;
            emailServiceEndpoint.Receive(message =>
                                             {
                                                 startingNummberOfEmailMessages++;
                                                 return null;
                                             }, new TimeSpan(0,1,0));

            INotificationSender notificationSender = new NotificationSender(emailServiceEndpointUri, _endpointResolver);

            IEnumerable<EmailAddress> emails = new List<EmailAddress>
                                                   {
                                                       new EmailAddress
                                                           {
                                                               Address = "*****@*****.**",
                                                               DisplayName = "test"
                                                           }
                                                   };

            notificationSender.SendNotification("test", emails, "test");

            int finalNummberOfEmailMessages = 0;
            emailServiceEndpoint.Receive(message =>
                                             {
                                                 finalNummberOfEmailMessages++;
                                                 return null;
                                             }, new TimeSpan(0, 1, 0));

            Assert.That(finalNummberOfEmailMessages, Is.EqualTo(startingNummberOfEmailMessages + 1));
        }
Exemplo n.º 7
0
        public JsonResult Save(GamificationLevelViewModel vm)
        {
            bool isNew = vm.Id == Guid.Empty;

            try
            {
                vm.UserId = CurrentUserId;

                OperationResultVo <Guid> saveResult = gamificationLevelAppService.Save(CurrentUserId, vm);

                if (saveResult.Success)
                {
                    string url = Url.Action("index", "gamificationlevel", new { area = "staff" });

                    if (isNew && EnvName.Equals(ConstantHelper.ProductionEnvironmentName))
                    {
                        NotificationSender.SendTeamNotificationAsync("New Gamification Level created!");
                    }

                    return(Json(new OperationResultRedirectVo <Guid>(saveResult, url)));
                }
                else
                {
                    return(Json(new OperationResultVo(false)));
                }
            }
            catch (Exception ex)
            {
                return(Json(new OperationResultVo(ex.Message)));
            }
        }
Exemplo n.º 8
0
        static async Task MainAsync()
        {
            NotificationSender notificationSender = new NotificationSender("INSERT YOUR DIRECT LINE SECRET HERE");

            IList <Party> partiesToNotify = new List <Party>();

            /*
             * You can set the parties to notify here. In order to do that you need to access the
             * database of users collected by the bot somehow. You could also send a backchannel
             * message to the bot asking for suitable parties. However, that is not the point of
             * this sample so I will leave the implementation to you.
             */

            for (int i = 0; i < NumberOfNotificationsToSend; ++i)
            {
                Log($"Sending notification {(i + 1)}/{NumberOfNotificationsToSend}...");

                Microsoft.Bot.Connector.DirectLine.ResourceResponse resourceResponse =
                    await notificationSender.NotifyAsync(partiesToNotify, $"Notification test {(i + 1)}");

                Log($"{((resourceResponse == null) ? "Received no response" : $"Received resource response with ID {resourceResponse.Id}")}");

#if DEBUG
                // The following will dump the activity info into Output (console)
                Microsoft.Bot.Connector.DirectLine.Activity activity = await notificationSender.GetLatestReplyAsync();
#endif

                Thread.Sleep(3000);
            }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            // Nice docs (although Java): http://reactivex.io/RxJava/javadoc/rx/Observable.html
            // The challenge:
            // The ChangeReceiver will fire an event every time a change is received.
            // Events can be:
            // "Ignore!" -> don't do anything
            // "Change!" -> send notification to staff and customers
            // "StaffOnly!" -> send notification to staff
            // "CustomerOnly!" -> send notification to customer only
            //
            // Staff must be notified within 3 seconds.
            // Customers most be notified between 5 and 7 seconds.
            using (var pub = new ChangeReceiver("tcp://*:5555"))
            {
                Console.WriteLine("Listening...");

                var staffSender    = new NotificationSender("tcp://localhost:5556");
                var customerSender = new NotificationSender("tcp://localhost:5557");

                var obs = Observable.FromEventPattern <Tuple <Guid, string> >(pub, "ChangeRecieved").Select(ep => ep.EventArgs);
                obs.Subscribe <Tuple <Guid, string> >(Handler);
                obs.Select(t => t.Item1).Subscribe(guid => customerSender.Send(guid));

                //var err = Observable.FromEventPattern<Exception>(pub, "OnError").Select(ep => ep.EventArgs);
                //err.Subscribe<Exception>(Error);

                pub.Start();
                Console.ReadLine();
                Console.WriteLine("Closing down.");
            }
        }
Exemplo n.º 10
0
        public override void OnReceive(Context context, Intent intent)
        {
            File currentSummary       = new File(context.FilesDir, CurrentSummaryFile);
            File sentSummary          = new File(context.FilesDir, SentSummaryFile);
            NotificationSender sender = new NotificationSender(context, SummaryCategory);

            if (currentSummary.Exists())
            {
                try
                {
                    string text;
                    using (StreamReader reader = new StreamReader(context.OpenFileInput(CurrentSummaryFile)))
                    {
                        text = reader.ReadToEnd();
                    }
                    Log.Debug(nameof(AlarmReceiver), text);
                    sender.PutNormalizeExtra(ExtraSummaryText, text);
                    sender.Send(NotificationType.SummaryNotification, text);
                    if (sentSummary.Exists())
                    {
                        sentSummary.Delete();
                    }
                    currentSummary.RenameTo(sentSummary);
                }
                catch (Exception e)
                {
                    Log.Error(nameof(AlarmReceiver), e.StackTrace);
                }
            }
            else
            {
                Log.Debug(nameof(AlarmReceiver), $"File {currentSummary.AbsolutePath} not exist");
            }
        }
Exemplo n.º 11
0
        public async Task <IActionResult> SimplePost(string text, string images, IEnumerable <PollOptionViewModel> pollOptions, SupportedLanguage?language, Guid?gameId)
        {
            UserContentViewModel vm = new UserContentViewModel
            {
                Language = language ?? SupportedLanguage.English,
                Content  = text,
                Poll     = new PollViewModel
                {
                    PollOptions = pollOptions.ToList()
                },
                GameId = gameId
            };

            ProfileViewModel profile = await ProfileAppService.GetByUserId(CurrentUserId, ProfileType.Personal);

            SetAuthorDetails(vm);

            SetContentImages(vm, images);

            OperationResultVo <Guid> result = userContentAppService.Save(CurrentUserId, vm);

            NotifyFollowers(profile, vm.GameId, vm.Id);

            if (EnvName.Equals(ConstantHelper.ProductionEnvironmentName))
            {
                await NotificationSender.SendTeamNotificationAsync("New simple post!");
            }

            return(Json(result));
        }
Exemplo n.º 12
0
 public NotificationsController(BTCPayServerEnvironment env, ApplicationDbContext db, NotificationSender notificationSender, UserManager <ApplicationUser> userManager)
 {
     _env = env;
     _db  = db;
     _notificationSender = notificationSender;
     _userManager        = userManager;
 }
Exemplo n.º 13
0
        public async Task <IActionResult> Save(UserContentViewModel vm)
        {
            try
            {
                bool isNew = vm.Id == Guid.Empty;

                ProfileViewModel profile = await ProfileAppService.GetByUserId(CurrentUserId, ProfileType.Personal);

                SetAuthorDetails(vm);

                OperationResultVo <Guid> saveResult = userContentAppService.Save(CurrentUserId, vm);

                if (!saveResult.Success)
                {
                    return(Json(saveResult));
                }
                else
                {
                    NotifyFollowers(profile, vm.GameId, vm.Id);

                    string url = Url.Action("Index", "Home", new { area = string.Empty, id = vm.Id, pointsEarned = saveResult.PointsEarned });

                    if (isNew && EnvName.Equals(ConstantHelper.ProductionEnvironmentName))
                    {
                        await NotificationSender.SendTeamNotificationAsync("New complex post!");
                    }

                    return(Json(new OperationResultRedirectVo(url)));
                }
            }
            catch (Exception ex)
            {
                return(Json(new OperationResultVo(ex.Message)));
            }
        }
        private async void Return()
        {
            Helper.EnableScreenSaver();

            if (downloader.Handle.IsSeed)
            {
                downloader.StopAndMove();
            }
            else
            {
                Task.Run(() => {
                    while (downloader.Handle != null && !downloader.Status.IsSeeding)
                    {
                        Thread.Sleep(2000);
                    }
                    downloader.StopAndMove();
                    NotificationSender sender = new NotificationSender("Stream finished", Helper.GenerateName(downloader.TorrentSource.Series, downloader.TorrentSource.Episode));
                    sender.Show();
                });
            }
            MainWindow.ShowContent();
            MouseMove -= Page_MouseMove;
            timer.Stop();
            MainWindow.videoPlayback = false;
            MainWindow.SwitchState(MainWindow.PlayerState.Normal);
            MainWindow.RemovePage();
            MainWindow.SetPage(new SeriesEpisodes(downloader.TorrentSource.Series));
            Mouse.OverrideCursor = null;
        }
        public async Task FunctionHandler(S3NotificationEvent input, ILambdaContext context)
        {
            var data      = input?.GetFileData();
            var retriever = new S3ObjectRetriever(data.Value.objectsKey,
                                                  RegionEndpoint.GetBySystemName(data.Value.region));

            using var connection = new DbConnection();
            await connection.GetConnection().OpenAsync().ConfigureAwait(false);

            var    logSaver = new LogSaver(connection.GetConnection());
            string logId    = await logSaver.GetAssociatedLogIdAsync(data.Value.objectsKey).ConfigureAwait(false);

            if (!String.IsNullOrEmpty(logId))
            {
                var entries = retriever.GetObjectDataAsync().Select(
                    logLine => EntryParser.ProcessLogLine(logLine));
                await logSaver.SaveLogsAsync(logId, entries).ConfigureAwait(false);

                if (NotificationSender.IsNotificationNecessary(data.Value.objectsKey))
                {
                    await NotificationSender.TryPublishNotification(data.Value.objectsKey).ConfigureAwait(false);
                }
            }
            else
            {
                throw new Exception($"Log with given object name " +
                                    $"({data.Value.objectsKey}) has no associated record in database");
            }
        }
Exemplo n.º 16
0
        public IActionResult Save(GameViewModel vm, IFormFile thumbnail)
        {
            try
            {
                bool isNew = vm.Id == Guid.Empty;

                SetAuthorDetails(vm);
                ClearImagesUrl(vm);

                OperationResultVo <Guid> saveResult = gameAppService.Save(CurrentUserId, vm);

                if (!saveResult.Success)
                {
                    return(Json(saveResult));
                }
                else
                {
                    string url = Url.Action("Details", "Game", new { area = string.Empty, id = vm.Id.ToString(), pointsEarned = saveResult.PointsEarned });

                    if (isNew && EnvName.Equals(ConstantHelper.ProductionEnvironmentName))
                    {
                        NotificationSender.SendTeamNotificationAsync($"New game Created: {vm.Title}");
                    }

                    return(Json(new OperationResultRedirectVo(url)));
                }
            }
            catch (Exception ex)
            {
                return(Json(new OperationResultVo(ex.Message)));
            }
        }
Exemplo n.º 17
0
        public async Task <IActionResult> Apply(Guid jobPositionId, string coverLetter)
        {
            try
            {
                Infra.CrossCutting.Identity.Models.ApplicationUser user = await UserManager.GetUserAsync(User);

                OperationResultVo serviceResult = jobPositionAppService.Apply(CurrentUserId, jobPositionId, user.Email, coverLetter);

                if (serviceResult.Success)
                {
                    string url = Url.Action("Details", "JobPosition", new { area = "Work", id = jobPositionId });

                    OperationResultVo <Guid> result = serviceResult as OperationResultVo <Guid>;
                    Infra.CrossCutting.Identity.Models.ApplicationUser poster = await UserManager.FindByIdAsync(result.Value.ToString());

                    await NotificationSender.SendEmailApplicationAsync(poster.Email, user.Email, Url.JobPositionDetailsCallbackLink(jobPositionId.ToString(), Request.Scheme));

                    return(Json(new OperationResultRedirectVo(url, SharedLocalizer[serviceResult.Message])));
                }
                else
                {
                    return(Json(new OperationResultVo(SharedLocalizer[serviceResult.Message])));
                }
            }
            catch (Exception ex)
            {
                return(Json(new OperationResultVo(ex.Message)));
            }
        }
        private async void Download_MouseUp(object sender, MouseButtonEventArgs e)
        {
            MainWindow.AddPage(new PleaseWait());
            var     ser     = Database.GetSeries((int)episode.seriesId);
            Torrent torrent = await Torrent.SearchSingle(ser, episode, Settings.DownloadQuality);

            if (torrent != null)
            {
                TorrentDownloader downloader = new TorrentDownloader(torrent);
                await downloader.Download();

                NotificationSender se = new NotificationSender("Download started", Helper.GenerateName(Database.GetSeries((int)episode.seriesId), episode));
                se.ClickedEvent += (s, ev) => {
                    Dispatcher.Invoke(() => {
                        MainWindow.RemoveAllPages();
                        MainWindow.SetPage(new DownloadsView());
                    }, DispatcherPriority.Send);
                };
                se.Show();
            }
            else
            {
                await MessageBox.Show("Sorry, torrent not found");
            }
            MainWindow.RemovePage();
        }
Exemplo n.º 19
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = await _userManager.FindByEmailAsync(model.Email);

                bool emailAlreadyConfirmed = await _userManager.IsEmailConfirmedAsync(user);

                if (user == null || !emailAlreadyConfirmed)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(RedirectToAction(nameof(ForgotPasswordConfirmation)));
                }

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                string code = await _userManager.GeneratePasswordResetTokenAsync(user);

                string callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);

                await NotificationSender.SendEmailPasswordResetAsync(model.Email, callbackUrl);

                return(RedirectToAction(nameof(ForgotPasswordConfirmation)));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 20
0
        public JsonResult SaveGiveaway(GiveawayViewModel vm)
        {
            bool isNew = vm.Id == Guid.Empty;

            try
            {
                vm.UserId = CurrentUserId;

                OperationResultVo <Guid> saveResult = giveawayAppService.SaveGiveaway(CurrentUserId, vm);

                if (saveResult.Success)
                {
                    string url = Url.Action("edit", "giveaway", new { area = "tools", id = vm.Id, pointsEarned = saveResult.PointsEarned });

                    if (isNew && EnvName.Equals(ConstantHelper.ProductionEnvironmentName))
                    {
                        NotificationSender.SendTeamNotificationAsync("New Giveaway created!");
                    }

                    return(Json(new OperationResultRedirectVo <Guid>(saveResult, url)));
                }
                else
                {
                    return(Json(new OperationResultVo(false)));
                }
            }
            catch (Exception ex)
            {
                return(Json(new OperationResultVo(ex.Message)));
            }
        }
Exemplo n.º 21
0
        public JsonResult SaveCourse(CourseViewModel vm)
        {
            bool isNew = vm.Id == Guid.Empty;

            try
            {
                vm.UserId = CurrentUserId;

                OperationResultVo <Guid> saveResult = studyAppService.SaveCourse(CurrentUserId, vm);

                if (saveResult.Success)
                {
                    //GenerateFeedPost(vm);

                    string url = Url.Action("details", "course", new { area = "learn", id = vm.Id });

                    if (isNew)
                    {
                        url = Url.Action("edit", "course", new { area = "learn", id = vm.Id, pointsEarned = saveResult.PointsEarned });

                        NotificationSender.SendTeamNotificationAsync("New Course created!");
                    }

                    return(Json(new OperationResultRedirectVo <Guid>(saveResult, url)));
                }
                else
                {
                    return(Json(new OperationResultVo(false)));
                }
            }
            catch (Exception ex)
            {
                return(Json(new OperationResultVo(ex.Message)));
            }
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            IMessageSender emailSender        = new EmailSender();
            IMessageSender databaseSender     = new DatabaseSender();
            IMessageSender notificationSender = new NotificationSender();

            Message message = new ErrorMessage();

            message.Subject       = "Test Message";
            message.Body          = "Hi, This is a Test Message";
            message.MessageSender = emailSender;
            message.Send();

            Console.WriteLine("-------------------------------------");

            message.MessageSender = databaseSender;
            message.Send();

            Console.WriteLine("-------------------------------------");

            Message warning = new WarningMessage();

            warning.Subject       = "Test Message";
            warning.Body          = "Hi, This is a Test Message";
            warning.MessageSender = notificationSender;
            warning.Send();

            Console.WriteLine("-------------------------------------");
        }
Exemplo n.º 23
0
 public void SetFilled()
 {
     Refilled   = true;
     RefillDate = DateTime.Now;
     NotificationSender.SendFilledNotification(this);
     DatabaseRefillService.Update(this);
 }
Exemplo n.º 24
0
    public static void WriteError(Exception ex)
    {
        try
        {
            string fileName = DateTime.Now.ToShortDateString().Replace("/", "-");

            string path = "~/ErrorLogs/" + fileName + ".txt";
            if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
            }
            using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                w.WriteLine("\r\nLog Entry : ");
                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
                             " Error Message: " + ex.Message + " Inner Exception : " + ex.InnerException;
                w.WriteLine(err);
                w.WriteLine("Trace: " + ex.StackTrace);
                w.WriteLine("__________________________");
                w.Flush();
                w.Close();

                // Notify Support Team :
                NotificationSender.SendEmailNotification("*****@*****.**",
                                                         "*****@*****.**", "mrjteacher Crash", err);
            }
        }
        catch (Exception exception)
        {
        }
    }
Exemplo n.º 25
0
        static int Main(string[] args)
        {
            try
            {
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                AppDomain.CurrentDomain.ProcessExit += (s, e) =>
                {
                    logger.LogInformation("Process exit");
                    cancellationTokenSource.Cancel();
                };
                IConfiguration configuration = (new ConfigurationBuilder()).AddUserSecrets(Assembly.GetExecutingAssembly()).Build();
                RemindersRepository = new Repository.DB.ReminderDbRepository();
                ITelegramBotClient telegramClient     = new TelegramBotClient(configuration["token"]);
                ConversationHolder conversationHolder = new ConversationHolder();
                telegramClient.OnUpdate              += conversationHolder.OnUpdate;
                telegramClient.OnReceiveError        += conversationHolder.OnApiError;
                telegramClient.OnReceiveGeneralError += conversationHolder.OnError;
                telegramClient.StartReceiving(new UpdateType[] { UpdateType.Message, UpdateType.CallbackQuery }, cancellationTokenSource.Token);

                NotificationSender notificationSender = new NotificationSender(telegramClient);
                notificationSender.SendNotificationsAsync(cancellationTokenSource.Token);

                cancellationTokenSource.Token.WaitHandle.WaitOne();
            }
            catch (Exception ex)
            {
                logger.LogError(ex.ToString());
            }
            return(0);
        }
 public NewVersionCheckerHostedService(SettingsRepository settingsRepository, BTCPayServerEnvironment env,
                                       NotificationSender notificationSender, IVersionFetcher versionFetcher, Logs logs) : base(logs)
 {
     _settingsRepository = settingsRepository;
     _env = env;
     _notificationSender = notificationSender;
     _versionFetcher     = versionFetcher;
 }
Exemplo n.º 27
0
 public void Notification_StartMessageProcessing()
 {
     NotificationSender.TestMode = true;
     InsertMessages(0, 50);
     NotificationSender.StartMessageProcessing();
     System.Threading.Thread.Sleep(5 * 1000);
     Assert.IsTrue(Message.GetAllMessages().Count() == 0);
 }
Exemplo n.º 28
0
 public TopicVM(TopicService topicService, ProductRepository productRepository, EditableTopic topic, NotificationSender notificationSender) : this()
 {
     this.topicService = topicService;
     this.productRepository = productRepository;
     this.notificationSender = notificationSender;
     EditableTopic = topic;
     LastTopicSaved = topic.Clone();
 }
Exemplo n.º 29
0
 public ProjectController(IUserRepository userRepository, IProjectRepository projectRepository, OrganizationRepository organizationRepository, BillingManager billingManager, NotificationSender notificationSender)
 {
     _userRepository         = userRepository;
     _projectRepository      = projectRepository;
     _organizationRepository = organizationRepository;
     _billingManager         = billingManager;
     _notificationSender     = notificationSender;
 }
Exemplo n.º 30
0
        public void Sender_WithNoControllerAndNoPageModel_ShouldReturnFalse()
        {
            var sender = new NotificationSender();

            var result = sender.SendNotification("test", MessageType.Success, null, null);

            Assert.AreEqual(false, result);
        }
Exemplo n.º 31
0
    private void Awake()
    {
        notificationSender = GetComponent <NotificationSender>();

        if (appIcons.Length != appNames.Length)
        {
            Debug.LogError("App icon count doesn't match up with the app names");
        }
    }
Exemplo n.º 32
0
        private async Task <IActionResult> HandleSucessfullExternalLogin(string returnUrl, ExternalLoginInfo externalLoginInfo, ApplicationUser user, ApplicationUser existingUser)
        {
            if (existingUser == null)
            {
                await SetInitialRoles(user);
            }
            else
            {
                SetEmailConfirmed(existingUser);
                await SetStaffRoles(user);
            }

            SetPreferences(user);

            Guid             userGuid = new Guid(user.Id);
            ProfileViewModel profile  = await profileAppService.GetByUserId(userGuid, ProfileType.Personal);

            if (profile == null)
            {
                profile        = profileAppService.GenerateNewOne(ProfileType.Personal);
                profile.UserId = userGuid;

                profile.Handler = user.UserName;

                profile.Name = SelectName(externalLoginInfo);
            }

            await SetExternalProfilePicture(externalLoginInfo, user, profile);

            if (string.IsNullOrWhiteSpace(profile.ProfileImageUrl) || profile.ProfileImageUrl == Constants.DefaultAvatar)
            {
                UploadFirstAvatar(profile.UserId, ProfileType.Personal);
            }

            profileAppService.Save(CurrentUserId, profile);

            await SetProfileOnSession(new Guid(user.Id), user.UserName);

            await _signInManager.SignInAsync(user, isPersistent : false);

            string logMessage = String.Format("User {0} linked a {1} account.", user.UserName, externalLoginInfo.LoginProvider);

            if (existingUser == null)
            {
                logMessage = String.Format("User {0} registered with a {1} account.", user.UserName, externalLoginInfo.LoginProvider);
            }

            if (EnvName.Equals(ConstantHelper.ProductionEnvironmentName))
            {
                await NotificationSender.SendTeamNotificationAsync(logMessage);
            }

            _logger.LogInformation(logMessage);

            return(RedirectToLocal(returnUrl));
        }