Inheritance: NotificationServiceBase
        public void context()
        {
            registrationRepository = Createregistrationrepository();
            notificationService = MockRepository.GenerateStub<NotificationService>();
            var controller = new RegistrationController(registrationRepository, notificationService);
            registrationModel = CreateRegistrationInformation();

            observe();
            actionResult = controller.VerifyPersonalInformation(registrationModel.RegistrationCode, registrationModel.DateOfBirth, registrationModel.ZipCode);
        }
        public void context()
        {
            registrationRepository = MockRepository.GenerateStub<RegistrationRepository>();
            notificationService = MockRepository.GenerateStub<NotificationService>();

            var controller = new RegistrationController(registrationRepository, notificationService);

            observe();

            actionResult = controller.EnterRegCode(RegistrationCode);
        }
        public void MainMethod()
        {
            Console.WriteLine("Dependency Inversion principle states:");
            Console.WriteLine("1. High Level modules should not depend on low level modules.Both should depend on Abstractions");
            Console.WriteLine("2. Abstractions Should not depend on details.Details should depend on abstractions");
            Console.WriteLine("Dependency Injection pattern in an application/implementation of this principle and enables us in creation of object outside the dependent object");
            Console.WriteLine("DI has 3 flavors : Constructor injection, Property injection and Method Injection");

            Email email = new Email();
            NotificationService notificationService = new NotificationService(email);
            notificationService.PromotionalNotification();
        }
 void client_RegisterUserCompleted(object sender, NotificationService.RegisterUserCompletedEventArgs e)
 {
     bool result = e.Result;
     if (result)
     {
         usernameTextBox.Text = String.Empty;
         passwordTextBox.Password = String.Empty;
         MessageBox.Show("Account created successfully. Please go to settings to use the new account");
     }
     else
     {
         MessageBox.Show("Unable to create account. Please try again.");
     }
 }
    protected void Button1_Click(object sender, EventArgs e)
    {
        NotificationService service = new NotificationService(true, "c:\\aps_developer_identity.p12", "password!123", 1);

        service.SendRetries = 5;

        service.ReconnectDelay = 5000;

        service.Error += new NotificationService.OnError(service_Error);

        service.NotificationTooLong += new NotificationService.OnNotificationTooLong(service_NotificationTooLong);

        service.BadDeviceToken += new NotificationService.OnBadDeviceToken(service_BadDeviceToken);

        service.NotificationFailed += new NotificationService.OnNotificationFailed(service_NotificationFailed);

        service.NotificationSuccess += new NotificationService.OnNotificationSuccess(service_NotificationSuccess);

        service.Connecting += new NotificationService.OnConnecting(service_Connecting);

        service.Connected += new NotificationService.OnConnected(service_Connected);

        service.Disconnected += new NotificationService.OnDisconnected(service_Disconnected);

        Notification alertNotification = new Notification("b0a2f562eeb993d98961834abecad051f7804132b5b058509eaab396d546414a");

        alertNotification.Payload.Alert.Body = string.Format("Testing...");

        alertNotification.Payload.Sound = "default";

        alertNotification.Payload.Badge = 1;

        if (service.QueueNotification(alertNotification))

            Console.WriteLine("Notification Queued!");

        else

            Console.WriteLine("Notification Failed to be Queued!");

        Console.WriteLine("Cleaning Up...");

        service.Close();

        service.Dispose();

        Console.WriteLine("Done!");

        Console.ReadLine();
    }
 void client_GetNotificationsCompleted(object sender, NotificationService.GetNotificationsCompletedEventArgs e)
 {
     if (e.Result.Count < 1)
     {
         string[] data = new string[1];
         data[0] = "There are no notifications";
         notificationsListBox.ItemsSource = data;
     }
     else
     {
         notificationsListBox.ItemsSource = e.Result;
     }
     radBusyIndicator.IsRunning = false;
 }
        public void WhenSendANotification_AMessageIsSent()
        {
            var phoneNumber = "+5555555555";
            var message = "Message";
            var callbackUrl = "http://callback.com";
            var twilioClientMock = new Mock<TwilioRestClient>("AccountSid", "AuthToken");
            twilioClientMock
                .Setup(c => c.SendMessage(phoneNumber, message, callbackUrl));

            var notificationServices = new NotificationService(twilioClientMock.Object);
            notificationServices.SendSmsNotification(phoneNumber, message, callbackUrl);

            twilioClientMock.Verify(
                c => c.SendMessage(It.IsAny<string>(), phoneNumber, message, callbackUrl), Times.Once);
        }
 void client_VerifyUserAccountExistsCompleted(object sender, NotificationService.VerifyUserAccountExistsCompletedEventArgs e)
 {
     bool result = e.Result;
     if (result)
     {
         MessageBox.Show("Username already in use. Please try another user account");
     }
     else
     {
         try
         {
             client.RegisterUserAsync(usernameTextBox.Text, passwordTextBox.Password);
         }
         catch
         {
             MessageBox.Show("Unable to connect to Riveu Server. Please verify internet connection and try again.");
         }
     }
 }
 void client_AuthenticateUserCompleted(object sender, NotificationService.AuthenticateUserCompletedEventArgs e)
 {
     try
     {
         if (e.Result)
         {
             client.GetNotificationsAsync(username);
         }
         else
         {
             MessageBox.Show("Invalid Credentials. Please configure the settings.");
             radBusyIndicator.IsRunning = false;
         }
     }
     catch
     {
         MessageBox.Show("Unable to connect to the Riveu server. Please verify internet connection and try again.");
         radBusyIndicator.IsRunning = false;
     }
 }
Exemple #10
0
        // **************************************************************************
        //  MININGCORE POOL SERVICES
        // **************************************************************************
        private static async Task StartMiningcorePoolServices()
        {
            var coinTemplates = PoolCoinTemplates.LoadCoinTemplates();

            logger.Info($"{coinTemplates.Keys.Count} coins loaded from {string.Join(", ", clusterConfig.CoinTemplates)}");

            // Populate pool configs with corresponding template
            foreach (var poolConfig in clusterConfig.Pools.Where(x => x.Enabled))
            {
                // Foreach coin definition
                if (!coinTemplates.TryGetValue(poolConfig.Coin, out var template))
                {
                    logger.ThrowLogPoolStartupException($"Pool {poolConfig.Id} references undefined coin '{poolConfig.Coin}'");
                }

                poolConfig.Template = template;
            }

            // Notifications
            notificationService = container.Resolve <NotificationService>();

            // start btStream receiver
            btStreamReceiver = container.Resolve <BtStreamReceiver>();
            btStreamReceiver.Start(clusterConfig);

            if (clusterConfig.ShareRelay == null)
            {
                // start share recorder
                shareRecorder = container.Resolve <ShareRecorder>();
                shareRecorder.Start(clusterConfig);

                // start share receiver (for external shares)
                shareReceiver = container.Resolve <ShareReceiver>();
                shareReceiver.Start(clusterConfig);
            }
            else
            {
                // start share relay
                shareRelay = container.Resolve <ShareRelay>();
                shareRelay.Start(clusterConfig);
            }

            // start API
            if (clusterConfig.Api == null || clusterConfig.Api.Enabled)
            {
                Api.ApiService.StartApiService(clusterConfig);
                metricsPublisher = container.Resolve <MetricsPublisher>();
            }
            else
            {
                logger.Warn("API is disabled");
            }

            // start payment processor
            if (clusterConfig.PaymentProcessing?.Enabled == true && clusterConfig.Pools.Any(x => x.PaymentProcessing?.Enabled == true))
            {
                payoutManager = container.Resolve <PayoutManager>();
                payoutManager.Configure(clusterConfig);
                payoutManager.Start();
            }
            else
            {
                logger.Warn("Payment processing is Disabled");
            }

            if (clusterConfig.ShareRelay == null)
            {
                // start pool stats updater
                statsRecorder = container.Resolve <StatsRecorder>();
                statsRecorder.Configure(clusterConfig);
                statsRecorder.Start();
            }
            else
            {
                logger.Info("Share Relay is Active!");
            }

            // start stratum pools
            await Task.WhenAll(clusterConfig.Pools.Where(x => x.Enabled).Select(async poolConfig =>
            {
                // resolve pool implementation
                var poolImpl = container.Resolve <IEnumerable <Meta <Lazy <IMiningPool, CoinFamilyAttribute> > > >()
                               .First(x => x.Value.Metadata.SupportedFamilies.Contains(poolConfig.Template.Family)).Value;

                // create and configure
                var stratumPool = poolImpl.Value;
                stratumPool.Configure(poolConfig, clusterConfig);
                pools[poolConfig.Id] = stratumPool;

                // pre-start attachments
                shareReceiver?.AttachPool(stratumPool);
                statsRecorder?.AttachPool(stratumPool);
                //apiServer?.AttachPool(stratumPool);

                await stratumPool.StartAsync(cts.Token);
            }));

            // keep running
            await Observable.Never <Unit>().ToTask(cts.Token);
        }
Exemple #11
0
 public StartCallController(IMemoryCache memoryCache)
 {
     this._notificationService = new NotificationService();
     this.memoryCache          = memoryCache;
 }
        public void Setup()
        {
            base.Setup();

            _geocodingMock = new Mock <IGeocoding>();
            var taxihailNetworkServiceClientMock = new Mock <ITaxiHailNetworkServiceClient>();

            var notificationService = new NotificationService(() => new BookingDbContext(DbName),
                                                              null,
                                                              TemplateServiceMock.Object,
                                                              EmailSenderMock.Object,
                                                              ConfigurationManager,
                                                              new ConfigurationDao(() => new ConfigurationDbContext(DbName)),
                                                              new OrderDao(() => new BookingDbContext(DbName), new TestServerSettings()),
                                                              new AccountDao(() => new BookingDbContext(DbName)),
                                                              new StaticMap(),
                                                              null,
                                                              _geocodingMock.Object,
                                                              taxihailNetworkServiceClientMock.Object,
                                                              new Logger(),
                                                              new CryptographyService(WinRTCrypto.CryptographicEngine, WinRTCrypto.SymmetricKeyAlgorithmProvider, WinRTCrypto.HashAlgorithmProvider, new Logger()));

            notificationService.SetBaseUrl(new Uri("http://www.example.net"));

            Sut.Setup(new EmailCommandHandler(notificationService));

            var returnAddressValue = new Address {
                FullAddress = "full dropoff"
            };

            _geocodingMock
            .Setup(x => x.TryToGetExactDropOffAddress(It.IsAny <OrderStatusDetail>(), 45, -73, It.IsAny <Address>(), It.IsAny <string>()))
            .Returns(returnAddressValue);

            _geocodingMock
            .Setup(x => x.TryToGetExactDropOffAddress(It.Is <OrderStatusDetail>(
                                                          o => o.VehicleLatitude.GetValueOrDefault() == 45 && o.VehicleLongitude.GetValueOrDefault() == -73),
                                                      null,
                                                      null,
                                                      It.IsAny <Address>(),
                                                      It.IsAny <string>())
                   )
            .Returns(returnAddressValue);

            _geocodingMock
            .Setup(x => x.TryToGetExactDropOffAddress(
                       It.Is <OrderStatusDetail>(o => !o.VehicleLongitude.HasValue && !o.VehicleLatitude.HasValue),
                       null,
                       null,
                       It.IsAny <Address>(),
                       It.IsAny <string>())
                   )
            .Returns(new Address()
            {
                FullAddress = "hardcoded dropoff"
            });

            _geocodingMock
            .Setup(x => x.TryToGetExactDropOffAddress(
                       It.Is <OrderStatusDetail>(o => !o.VehicleLongitude.HasValue && !o.VehicleLatitude.HasValue),
                       null,
                       null,
                       null,
                       It.IsAny <string>())
                   )
            .Returns(new Address()
            {
                FullAddress = "-"
            });

            TemplateServiceMock
            .Setup(x => x.InlineCss(It.IsAny <string>()))
            .Returns(string.Empty);
        }
Exemple #13
0
 public AccountManager(ApiClient client, UserSession.UserSession userSession, NotificationService notificationService)
 {
     this.client = client;
     this.notificationService = notificationService;
     this.userSession         = userSession;
 }
 public void ThrowOnApplicationIDNullTest() {
     var service = new NotificationService();
     if(!service.AreWin8NotificationsAvailable)
         return;
     try {
         service.CreatePredefinedNotification("", "", "");
         Assert.Fail();
     } catch(ArgumentNullException e) {
         Assert.AreEqual("ApplicationId", e.ParamName);
     }
 }
Exemple #15
0
 public NotificationController()
 {
     notificationService = new NotificationService();
 }
Exemple #16
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        //Variables you may need to edit:
        //---------------------------------

        //True if you are using sandbox certificate, or false if using production
        bool sandbox = true;



        string testDeviceToken = "81ec52e62140a8c7281d4ddd5ccf13e80fee79e4bdcf8edcecaa73e79e1db0d1";//测试IPHONE4S正式



        //Put your PKCS12 .p12 or .pfx filename here.
        // Assumes it is in the same directory as your app
        string p12File = "test.p12";

        //This is the password that you protected your p12File
        //  If you did not use a password, set it as null or an empty string
        string p12FilePassword = "******";

        //Number of notifications to send
        int count = 1;

        //Number of milliseconds to wait in between sending notifications in the loop
        // This is just to demonstrate that the APNS connection stays alive between messages
        int sleepBetweenNotifications = 15000;


        //Actual Code starts below:
        //--------------------------------


        string p12Filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p12File);

        NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);

        service.SendRetries    = 5;    //5 retries before generating notificationfailed event
        service.ReconnectDelay = 5000; //5 seconds

        service.Error += new NotificationService.OnError(service_Error);
        service.NotificationTooLong += new NotificationService.OnNotificationTooLong(service_NotificationTooLong);

        service.BadDeviceToken      += new NotificationService.OnBadDeviceToken(service_BadDeviceToken);
        service.NotificationFailed  += new NotificationService.OnNotificationFailed(service_NotificationFailed);
        service.NotificationSuccess += new NotificationService.OnNotificationSuccess(service_NotificationSuccess);
        service.Connecting          += new NotificationService.OnConnecting(service_Connecting);
        service.Connected           += new NotificationService.OnConnected(service_Connected);
        service.Disconnected        += new NotificationService.OnDisconnected(service_Disconnected);

        //The notifications will be sent like this:
        //		Testing: 1...
        //		Testing: 2...
        //		Testing: 3...
        // etc...
        for (int i = 1; i <= count; i++)
        {
            //if (i == 2)
            //{
            //    testDeviceToken = "5d4442387f100bec54e78b416a127504efe76a36bfba0a24b71b0854fcf4a4d9";
            //}
            //if (i == 3)
            //{
            //    testDeviceToken = "5d4442387f100bec54e78b416a127504efe76a36bfba0a24b71b0854fcf4a4d9";
            //}
            //if (i == 10)
            //{
            //    testDeviceToken = "5d4442387f100bec54e78b416a127504efe76a36bfba0a24b71b0854fcf4a4d9";
            //}
            //Create a new notification to send
            Notification alertNotification = new Notification(testDeviceToken);

            // alertNotification.Payload.Alert.Body = string.Format("Testing {0}...", i);
            alertNotification.Payload.Alert.Body = txtAlert.Value;
            alertNotification.Payload.Sound      = txtSound.Value;
            alertNotification.Payload.Badge      = Convert.ToInt32(txtBadge.Value);
            alertNotification.Payload.AddCustom(txtName1.Value, txtVaule1.Value);
            alertNotification.Payload.AddCustom(txtName2.Value, txtVaule2.Value);
            alertNotification.Payload.AddCustom(txtName3.Value, txtVaule3.Value);

            //Queue the notification to be sent
            if (service.QueueNotification(alertNotification))
            {
                Console.WriteLine("Notification Queued!");
            }
            else
            {
                Console.WriteLine("Notification Failed to be Queued!");
            }

            ////Sleep in between each message
            //if (i < count)
            //{
            //    Console.WriteLine("Sleeping " + sleepBetweenNotifications + " milliseconds before next Notification...");
            //    System.Threading.Thread.Sleep(sleepBetweenNotifications);
            //}
        }

        Console.WriteLine("Cleaning Up...");

        //First, close the service.
        //This ensures any queued notifications get sent befor the connections are closed
        service.Close();

        //Clean up
        service.Dispose();

        Console.WriteLine("Done!");
        Console.WriteLine("Press enter to exit...");
        Console.ReadLine();
    }
        public static void PusMsgHelping(DataSet dsPusMsgList)
        {
            int iMaxRows = int.Parse(ConfigurationManager.AppSettings["MaxRows"].ToString());
            bool bSleep = (dsPusMsgList.Tables[0].Rows.Count > iMaxRows) ? true : false;
            //Variables you may need to edit:
            //---------------------------------

            //True if you are using sandbox certificate, or false if using production
            bool sandbox = ("0".Equals(ConfigurationManager.AppSettings["Sandbox"].ToString())) ? true : false;

            //Put your device token in here
            //  string testDeviceToken = "bc9eb0ca6fedb7967ab7563a36fc197b90df3c99aae38db335cb152b7377fdb9";

            //Put your PKCS12 .p12 or .pfx filename here.
            // Assumes it is in the same directory as your app
            string p12File = GetAppValue("p12File");// "aps_production_identity.p12";

            //This is the password that you protected your p12File
            //  If you did not use a password, set it as null or an empty string
            string p12FilePassword = GetAppValue("p12FilePassword");//"123456";

            //Number of notifications to send
            //int count = 1000;

            //Number of milliseconds to wait in between sending notifications in the loop
            // This is just to demonstrate that the APNS connection stays alive between messages

            //string numberFileName = GetAppValue("tokenFile");

            string content = "";// GetAppValue("content");

            //bool isTest = GetAppValue("isTest") == "true" ? true : false;

            //Actual Code starts below:
            //--------------------------------

            string p12Filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p12File);

            //string numFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, numberFileName);

            //string[] numberList = ReadFile(numFile).Contains(',') ? ReadFile(numFile).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) : new string[] { };

            //NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1, bSleep);
            NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);

            service.SendRetries = 1; //5 retries before generating notificationfailed event
            service.ReconnectDelay = 5000; //5 seconds

            service.Error += new NotificationService.OnError(service_Error);
            service.NotificationTooLong += new NotificationService.OnNotificationTooLong(service_NotificationTooLong);

            service.BadDeviceToken += new NotificationService.OnBadDeviceToken(service_BadDeviceToken);
            service.NotificationFailed += new NotificationService.OnNotificationFailed(service_NotificationFailed);
            service.NotificationSuccess += new NotificationService.OnNotificationSuccess(service_NotificationSuccess);
            service.Connecting += new NotificationService.OnConnecting(service_Connecting);
            service.Connected += new NotificationService.OnConnected(service_Connected);
            service.Disconnected += new NotificationService.OnDisconnected(service_Disconnected);

            //The notifications will be sent like this:
            //		Testing: 1...
            //		Testing: 2...
            //		Testing: 3...
            // etc...
            //for (int i = 0; i < numberList.Length; i++)
            int sleepBetweenNotifications = (bSleep) ? Convert.ToInt32(GetAppValue("sleepBetweenNotificationsshot")) : Convert.ToInt32(GetAppValue("sleepBetweenNotifications")); //100;

            string strResult = string.Empty;

            CommonEntity commonEntity = new CommonEntity();
            commonEntity.LogMessages = new Common.Logger.LogMessage();
            commonEntity.LogMessages.Userid = "JOB System";
            commonEntity.LogMessages.Username = "******";

            commonEntity.CommonDBEntity = new List<CommonDBEntity>();

            for (int i = 0; i < dsPusMsgList.Tables[0].Rows.Count ; i++)
            {
                try
                {
                    //if (!PushTicketMsgDA.CheckPushPlanActionHistory(taskID, dsPusMsgList.Tables[0].Rows[i]["DEVICETOKEN"].ToString().Trim()))
                    //{
                    //    continue;
                    //}
                    CommonDBEntity dbParm = new CommonDBEntity();
                    dbParm.Event_Type = "Que Ticket Push发送";

                    if ("0".Equals(dsPusMsgList.Tables[0].Rows[i]["TYPE"].ToString().Trim()))
                    {
                        content = String.Format(GetAppValue("oneContent"), dsPusMsgList.Tables[0].Rows[i]["amount"].ToString().Trim());
                    }
                    else
                    {
                        content = String.Format(GetAppValue("twoContent"), dsPusMsgList.Tables[0].Rows[i]["amount"].ToString().Trim());
                    }
                    dbParm.Event_Content = "Que Push发送Telphone: " + dsPusMsgList.Tables[0].Rows[i]["TELPHONE"].ToString().Trim() + "Que Push发送Devicetoken: " + dsPusMsgList.Tables[0].Rows[i]["DEVICETOKEN"].ToString().Trim() + "Que Push发送内容: " + content;
                    //Create a new notification to send
                    Notification alertNotification = new Notification(dsPusMsgList.Tables[0].Rows[i]["DEVICETOKEN"].ToString().Trim());

                    alertNotification.Payload.Alert.Body = string.Format(content);
                    alertNotification.Payload.Sound = "default";
                    alertNotification.Payload.Badge = 1;

                    //Queue the notification to be sent
                    if (service.QueueNotification(alertNotification, bSleep))
                    {
                        strResult = "发送成功";
                        Console.WriteLine("Notification Queued!");
                        writeFile(logFile1, content + "Notification Queued!" + dsPusMsgList.Tables[0].Rows[i]["DEVICETOKEN"].ToString().Trim());
                    }
                    else
                    {
                        strResult = "发送失败";
                        Console.WriteLine("Notification Failed to be Queued!");
                        writeFile(logFile1, content + "Notification Failed to be Queued!" + dsPusMsgList.Tables[0].Rows[i]["DEVICETOKEN"].ToString().Trim());
                    }

                    dbParm.Event_ID = dsPusMsgList.Tables[0].Rows[i]["TELPHONE"].ToString().Trim();
                    dbParm.Event_Result = strResult;
                    commonEntity.CommonDBEntity.Add(dbParm);
                    //PushTicketMsgDA.InsertPushPlanActionHistory(taskID, dsPusMsgList.Tables[0].Rows[i]["TELPHONE"].ToString().Trim(), dsPusMsgList.Tables[0].Rows[i]["DEVICETOKEN"].ToString().Trim(), strResult);

                    //Sleep in between each message
                    //if (i < numberList.Length)
                    //{
                    Console.WriteLine("Sleeping " + sleepBetweenNotifications + " milliseconds before next Notification...");
                    System.Threading.Thread.Sleep(sleepBetweenNotifications);
                    //}
                }
                catch (Exception ex)
                {
                    //  Log King
                    CommonDA.InsertEventHistoryError(dsPusMsgList.Tables[0].Rows[i]["TELPHONE"].ToString().Trim(), "Que Push发送Telphone: " + dsPusMsgList.Tables[0].Rows[i]["TELPHONE"].ToString().Trim() + "Que Push发送Devicetoken: " + dsPusMsgList.Tables[0].Rows[i]["DEVICETOKEN"].ToString().Trim() + "Que Push发送异常: " + ex.Message);
                    Console.WriteLine(ex.Message);
                    continue;
                }
            }

            Console.WriteLine("Cleaning Up...");
            writeFile(logFile, "Cleaning Up...");
            //First, close the service.
            //This ensures any queued notifications get sent befor the connections are closed
            service.Close();

            //Clean up
            service.Dispose();

            Console.WriteLine("Done!");
            writeFile(logFile, "Done");
            //Console.WriteLine("Press enter to exit...");
            //writeFile(logFile, "Press enter to exit...");
            //Console.ReadLine();

            CommonDA.InsertEventHistory(commonEntity);
        }
 public LoginDataController(IDataProtectionProvider provider, ApiService apiService, EncryptionService encryptionService, ICacheService cacheService, IConfiguration config, NotificationService notify)
 {
     dataProtectionHelper = new DataProtectionHelper(provider);
     _apiService          = apiService;
     _encryptionService   = encryptionService;
     _cacheService        = cacheService;
     _config = config;
     _notify = notify;
 }
Exemple #19
0
        public void sendLink(String Email)
        {
            try
            {
                //LoanViewModel lvm = new LoanViewModel();
                //String email = lvm.AccountsModel.Email;
                var result = DataReaders.checkEmail(Email);
                WebLog.Log("Email +" + result);
                if (result != null)
                {
                    WebLog.Log("Email +" + result);
                    users.Email = result;
                    WebLog.Log("Email +" + users.Email);
                    users.id = DataReaders.selectUserIDs(users);
                    WebLog.Log("Email +" + users.id);
                    if (users.id != 0)
                    {
                        string encrypt = "";
                        try
                        {
                            encrypt = $"tK_{ Classes.Utility.RandomString(56).ToUpper()}" + users.id;
                            users   = DataReaders.getUser(Email);
                            WebLog.Log("users +" + users.Email);
                            string resetLink = ConfigurationManager.AppSettings["ResetPasswordLink"] + encrypt;
                            WebLog.Log("resetLink +" + resetLink);
                            string resetLink1 = "Click The Following Link:<a href='" + resetLink + "'>'" + resetLink + "'</a> to change your password";
                            WebLog.Log("resetLink1 +" + resetLink1);
                            WebLog.Log("resetLink: " + resetLink);
                            var bodyTxt = System.IO.File.ReadAllText(Server.MapPath("~/EmailNotifications/ResetPasswordEmailNotification.html"));
                            bodyTxt = bodyTxt.Replace("$MerchantName", $"{users.firstname} {users.lastname}");
                            bodyTxt = bodyTxt.Replace("$Message", $"{resetLink1}");
                            var msgHeader = $"Reset Your Password";
                            WebLog.Log("resetLink: " + resetLink);

                            WebLog.Log("bodyTxt:" + bodyTxt);

                            var sendMail = NotificationService.SendMail(msgHeader, bodyTxt, users.Email, null, null);
                            users.ResetPassword = encrypt;
                            users.DateTim       = Classes.Utility.GetCurrentDateTime();
                            DataCreators.UpdateUsers(users);
                            TempData["message"] = "Check Your Email For Password Reset Link";
                        }
                        catch (Exception ex)
                        {
                            ex.Message.ToString();
                            WebLog.Log(ex.Message.ToString());
                        }
                    }
                    else
                    {
                        TempData["message"] = "Please Try Again";
                    }
                }
                else
                {
                    TempData["message"] = "Account Does Not Exist";
                }
            }
            catch (Exception ex)
            {
                //Response.Write(ex.Message.ToString());
                WebLog.Log(ex.Message.ToString());
            }
        }
Exemple #20
0
 void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
 {
     NotificationService.Alert("Unhandled exception detected in UI thread",
                               "exception");
     logger.LogException(e.Exception);
 }
Exemple #21
0
 void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
 {
     NotificationService.Alert("Unhandled exception throwed when processing asyncronous operation",
                               "exception");
     logger.LogException(e.Exception);
 }
Exemple #22
0
 public CollectionSubscriptionBuilder(NotificationService notificationService, CollectionSubscription <T> subscription)
     : base(notificationService, subscription)
 {
     _subscription = subscription ?? throw new ArgumentNullException(nameof(subscription));
 }
Exemple #23
0
        public StatusBarModel(NotificationService notifications)
        {
            _notificationService = notifications;

            _notificationService.OnNotify += OnNotify;
        }
        protected override void RunCallback()
        {
            var dbFactory = new DbFactory();
            var time      = new TimeService(dbFactory);
            var log       = GetLogger();

            var settings = new SettingsService(dbFactory);

            var styleHistoryService = new StyleHistoryService(log, time, dbFactory);
            var itemHistoryService  = new ItemHistoryService(log, time, dbFactory);
            var styleManager        = new StyleManager(log, time, styleHistoryService);
            var notificationService = new NotificationService(log, time, dbFactory);
            var actionService       = new SystemActionService(log, time);

            var lastSyncDate          = _reportSettings.GetLastSyncDate(settings, _api.Market, _api.MarketplaceId);
            var isManualSyncRequested = _reportSettings.IsManualSyncRequested(settings, _api.Market, _api.MarketplaceId);

            LogWrite("Market=" + _api.Market + ", marketplaceId=" + _api.MarketplaceId);
            LogWrite("Last sync date=" + lastSyncDate.ToString() + ", isManualSyncRequested=" + isManualSyncRequested);

            if (!lastSyncDate.HasValue ||
                (DateTime.UtcNow - lastSyncDate) > _reportSettings.RequestInterval ||
                isManualSyncRequested == true)
            {
                if (_reportSettings.RequestMode == ReportRequestMode.Sheduled)
                {
                    //TODO: add
                    //http://docs.developer.amazonservices.com/en_US/reports/Reports_Overview.html
                    //NOTE: Trying to get last existing report from Amazon

                    LogWrite("Check Sheduled");
                    _reportService = new AmazonReportService(_reportSettings.ReportType,
                                                             CompanyId,
                                                             _api,
                                                             log,
                                                             time,
                                                             dbFactory,
                                                             _syncInfo,
                                                             styleManager,
                                                             notificationService,
                                                             styleHistoryService,
                                                             itemHistoryService,
                                                             actionService,
                                                             _reportSettings.GetParser(),
                                                             _reportSettings.ReportDirectory);

                    var lastReports = _reportService.GetReportList();
                    if (lastReports.Any())
                    {
                        var reportId = lastReports[0].ReportId;

                        LogWrite("Getting last exist report, ReportId=" + reportId);
                        if (_reportService.SaveScheduledReport(reportId))
                        {
                            using (var db = dbFactory.GetRWDb())
                            {
                                LogWrite("Add sheduled report");
                                db.InventoryReports.AddSheduledReport(reportId, (int)_reportSettings.ReportType, _api.MarketplaceId, _reportService.ReportFileName);

                                ProcessReport(settings);

                                _reportSettings.SetLastSyncDate(settings, _api.Market, _api.MarketplaceId, DateTime.UtcNow);
                                db.InventoryReports.MarkProcessedByReportId(_reportService.ReportId, ReportProcessingResultType.Success);
                                _reportService = null;
                            }
                        }
                    }
                    else
                    {
                        LogWrite("Do not have any reports of type=" + _reportService.ReportType.ToString());
                        _reportSettings.SetLastSyncDate(settings, _api.Market, _api.MarketplaceId, DateTime.UtcNow);
                        _reportService = null;
                    }
                }

                if (_reportSettings.RequestMode == ReportRequestMode.Requested)
                {
                    if (_reportService == null)
                    {
                        LogWrite("Create reportService");
                        _syncInfo = new DbSyncInformer(dbFactory,
                                                       log,
                                                       time,
                                                       SyncType.Listings,
                                                       _api.MarketplaceId,
                                                       _api.Market,
                                                       String.Empty);

                        _reportService = new AmazonReportService(_reportSettings.ReportType,
                                                                 CompanyId,
                                                                 _api,
                                                                 log,
                                                                 time,
                                                                 dbFactory,
                                                                 _syncInfo,
                                                                 styleManager,
                                                                 notificationService,
                                                                 styleHistoryService,
                                                                 itemHistoryService,
                                                                 actionService,
                                                                 _reportSettings.GetParser(),
                                                                 _reportSettings.ReportDirectory);

                        using (var db = dbFactory.GetRWDb())
                        {
                            var lastUnsavedReport = db.InventoryReports.GetLastUnsaved((int)_reportService.ReportType, _api.MarketplaceId);
                            if (lastUnsavedReport == null ||
                                (time.GetUtcTime() - lastUnsavedReport.RequestDate) > _reportSettings.AwaitInterval)
                            {
                                LogWrite("Request report");
                                _syncInfo.SyncBegin(null);
                                _syncInfo.AddInfo("", "Request report from Amazon");

                                _reportService.RequestReport();
                                db.InventoryReports.AddRequestedReport(_reportService.ReportRequestId, (int)_reportService.ReportType, _api.MarketplaceId);
                            }
                            else
                            {
                                LogWrite("Use last report request, id=" + lastUnsavedReport.Id + ", marketplaceId=" + lastUnsavedReport.MarketplaceId);
                                _syncInfo.OpenLastSync();
                                _syncInfo.AddInfo("", "Use last Amazon report request");

                                _reportService.UseReportRequestId(lastUnsavedReport.RequestIdentifier);
                            }
                        }
                    }
                    else
                    {
                        using (var db = dbFactory.GetRWDb())
                        {
                            LogWrite("Save report");
                            if (_reportService.SaveRequestedReport())
                            {
                                LogWrite("Save success, reportId=" + _reportService.ReportId + ", reportName=" + _reportService.ReportFileName);
                                db.InventoryReports.Update(_reportService.ReportRequestId, _reportService.ReportFileName, _reportService.ReportId);

                                ProcessReport(settings);

                                db.InventoryReports.MarkProcessedByReportId(_reportService.ReportId, ReportProcessingResultType.Success);
                                _reportSettings.SetLastSyncDate(settings, _api.Market, _api.MarketplaceId, time.GetUtcTime());
                                _reportService = null;
                            }
                            else
                            {
                                LogWrite("Could not save report");

                                var requestStatus = _reportService.GetRequestStatus();
                                if (requestStatus == null)
                                {
                                    LogWrite("Request status empty, reportId=" + _reportService);

                                    db.InventoryReports.MarkProcessedByRequestId(_reportService.ReportRequestId, ReportProcessingResultType.Cancelled);
                                    _reportSettings.SetLastSyncDate(settings, _api.Market, _api.MarketplaceId, time.GetUtcTime());
                                    _reportService = null;
                                }
                                else
                                {
                                    if (requestStatus.Status == "_CANCELLED_")
                                    {
                                        LogWrite("Mark as cancelled (requestStatus = _CANCELLED_");

                                        db.InventoryReports.MarkProcessedByRequestId(_reportService.ReportRequestId, ReportProcessingResultType.Cancelled);
                                        _reportSettings.SetLastSyncDate(settings, _api.Market, _api.MarketplaceId, DateTime.UtcNow);
                                        _reportService = null;
                                    }
                                    else
                                    {
                                        if (_reportService.SaveReportAttempts > _reportSettings.MaxRequestAttempt)
                                        {
                                            LogWrite("Mark as failed (MaxAttampts), saveReportAttempts > maxRequestAttempt");

                                            db.InventoryReports.MarkProcessedByRequestId(_reportService.ReportRequestId, ReportProcessingResultType.MaxAttampts);
                                            _reportSettings.SetLastSyncDate(settings, _api.Market, _api.MarketplaceId, DateTime.UtcNow);
                                            _reportService = null;
                                        }
                                        else
                                        {
                                            Thread.Sleep(TimeSpan.FromMinutes(Int32.Parse(AppSettings.ReportRequestAttemptIntervalMinutes)));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #25
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        //Variables you may need to edit:
        //---------------------------------

        //True if you are using sandbox certificate, or false if using production
        bool sandbox = true;

        string testDeviceToken = "81ec52e62140a8c7281d4ddd5ccf13e80fee79e4bdcf8edcecaa73e79e1db0d1";//测试IPHONE4S正式

        //Put your PKCS12 .p12 or .pfx filename here.
        // Assumes it is in the same directory as your app
        string p12File = "test.p12";

        //This is the password that you protected your p12File
        //  If you did not use a password, set it as null or an empty string
        string p12FilePassword = "******";

        //Number of notifications to send
        int count = 1;

        //Number of milliseconds to wait in between sending notifications in the loop
        // This is just to demonstrate that the APNS connection stays alive between messages
        int sleepBetweenNotifications = 15000;

        //Actual Code starts below:
        //--------------------------------

        string p12Filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p12File);

        NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);

        service.SendRetries = 5; //5 retries before generating notificationfailed event
        service.ReconnectDelay = 5000; //5 seconds

        service.Error += new NotificationService.OnError(service_Error);
        service.NotificationTooLong += new NotificationService.OnNotificationTooLong(service_NotificationTooLong);

        service.BadDeviceToken += new NotificationService.OnBadDeviceToken(service_BadDeviceToken);
        service.NotificationFailed += new NotificationService.OnNotificationFailed(service_NotificationFailed);
        service.NotificationSuccess += new NotificationService.OnNotificationSuccess(service_NotificationSuccess);
        service.Connecting += new NotificationService.OnConnecting(service_Connecting);
        service.Connected += new NotificationService.OnConnected(service_Connected);
        service.Disconnected += new NotificationService.OnDisconnected(service_Disconnected);

        //The notifications will be sent like this:
        //		Testing: 1...
        //		Testing: 2...
        //		Testing: 3...
        // etc...
        for (int i = 1; i <= count; i++)
        {
            //if (i == 2)
            //{
            //    testDeviceToken = "5d4442387f100bec54e78b416a127504efe76a36bfba0a24b71b0854fcf4a4d9";
            //}
            //if (i == 3)
            //{
            //    testDeviceToken = "5d4442387f100bec54e78b416a127504efe76a36bfba0a24b71b0854fcf4a4d9";
            //}
            //if (i == 10)
            //{
            //    testDeviceToken = "5d4442387f100bec54e78b416a127504efe76a36bfba0a24b71b0854fcf4a4d9";
            //}
            //Create a new notification to send
            Notification alertNotification = new Notification(testDeviceToken);

            // alertNotification.Payload.Alert.Body = string.Format("Testing {0}...", i);
            alertNotification.Payload.Alert.Body = txtAlert.Value;
            alertNotification.Payload.Sound = txtSound.Value;
            alertNotification.Payload.Badge = Convert.ToInt32(txtBadge.Value);
            alertNotification.Payload.AddCustom(txtName1.Value, txtVaule1.Value);
            alertNotification.Payload.AddCustom(txtName2.Value, txtVaule2.Value);
            alertNotification.Payload.AddCustom(txtName3.Value, txtVaule3.Value);

            //Queue the notification to be sent
            if (service.QueueNotification(alertNotification))
                Console.WriteLine("Notification Queued!");
            else
                Console.WriteLine("Notification Failed to be Queued!");

            ////Sleep in between each message
            //if (i < count)
            //{
            //    Console.WriteLine("Sleeping " + sleepBetweenNotifications + " milliseconds before next Notification...");
            //    System.Threading.Thread.Sleep(sleepBetweenNotifications);
            //}
        }

        Console.WriteLine("Cleaning Up...");

        //First, close the service.
        //This ensures any queued notifications get sent befor the connections are closed
        service.Close();

        //Clean up
        service.Dispose();

        Console.WriteLine("Done!");
        Console.WriteLine("Press enter to exit...");
        Console.ReadLine();
    }
Exemple #26
0
        /// <summary>
        /// 执行定时任务
        /// </summary>
        /// <param name="task">定时任务</param>
        /// <param name="executeDate">执行时间</param>
        public void Execute(ScheduledTaskModel task, DateTime executeDate)
        {
            if (task == null)
            {
                Log.Error("无效的定时任务。");
                throw new InvalidOperationException("无效的定时任务。");
            }

            using (var dbContext = new MissionskyOAEntities())
            {
                #region 推送消息

                var sql = @"SELECT * FROM BookBorrow
                            WHERE ISNULL([Status], 0) = {0} --借阅中
                            AND DATEDIFF(DAY, ReturnDate, GETDATE()) >= 0 --已到预计归还日期
	                        ;"    ;

                //推送消息
                var notification = new NotificationModel()
                {
                    CreatedUserId = 0,
                    MessageType   = NotificationType.PushMessage,
                    BusinessType  = BusinessType.Approving,
                    Title         = "Missionsky OA Notification",
                    MessagePrams  = "test",
                    Scope         = NotificationScope.User,
                    CreatedTime   = DateTime.Now
                };

                var entities =
                    dbContext.BookBorrows.SqlQuery(string.Format(sql, (int)UserBorrowStatus.Borrowing)).ToList();
                //当前需要归还的借阅图书
                entities.ForEach(borrow =>
                {
                    var user = dbContext.Users.FirstOrDefault(it => it.Id == borrow.UserId);
                    var book = dbContext.Books.FirstOrDefault(it => it.Id == borrow.BookId);

                    if (user != null && book != null)
                    {
                        notification.Target        = user.Email;
                        notification.TargetUserIds = new List <int> {
                            user.Id
                        };
                        notification.MessageContent = string.Format("请及时归还您借阅的图书《{0}》。", book.Name);
                        NotificationService.Add(notification, Global.IsProduction); //消息推送
                    }
                });

                #endregion

                //更新定时任务
                var history = new ScheduledTaskHistoryModel()
                {
                    TaskId      = task.Id,
                    Result      = true,
                    Desc        = task.Name,
                    CreatedTime = executeDate
                };

                ScheduledTaskService.UpdateTask(dbContext, history);

                dbContext.SaveChanges();

                Log.Info(string.Format("定时任务执行成功: {0}。", task.Name));
            }
        }
        public void LoadDoesNotRoundtripOnIncludedCustomer()
        {
            var newSession = RavenDBConfiguration.Instance().OpenNewSession();

            var customer1 = new Customer
            {
                FirstName = "Test1",
                LastName  = "User",
                Phones    =
                    new List <CustomerPhone> {
                    new CustomerPhone {
                        Number = "11111111", PhoneType = PhoneTypes.WorkPhone1
                    }
                }
            };

            newSession.Store(customer1);

            var customer2 = new Customer
            {
                FirstName = "Test2",
                LastName  = "User",
                Phones    =
                    new List <CustomerPhone> {
                    new CustomerPhone {
                        Number = "22222222", PhoneType = PhoneTypes.WorkPhone1
                    }
                }
            };

            newSession.Store(customer2);

            var unitResident = new UnitResident
            {
                CommunityCode    = "101",
                SubCommunityCode = "101",
                BuildingId       = "01",
                UnitId           = "0420",
                UnitAddress      = "4501 Connecticut Ave NW #420",
                LastName         = "",
                FirstName        = ""
            };

            var package1 = new Package
            {
                UnitResident  = unitResident,
                CommunityCode = "101",
                CustomerIds   = new List <string> {
                    customer1.Id, customer2.Id
                },
                PackageType = "FedEx",
                Status      = PackageStatusCodes.Received.ToString()
            };

            newSession.Store(package1);
            newSession.SaveChanges();


            var service        = new NotificationService();
            var currentSession = AbstractRavenService.GetCurrentDocumentSession();

            var packages = service.GetPackageInventory("101", string.Empty, false, false, null, null, 10);

            Assert.AreEqual(1, currentSession.Advanced.NumberOfRequests);

            Assert.IsNotNull(packages);
            foreach (var package in packages)
            {
                Assert.IsTrue(package.Customers.Count > 0);
            }
        }
        public bool userBookingSelectInterface(Boolean existingUser, Boolean logout, Boolean bookAgain,
                                               Boolean confirm, UserData employee,
                                               InventoryService inventoryService,
                                               TransactionService transactionService, NotificationService notificationService,
                                               Ticket ticket, Route newRoute, UserData newUser)
        {
            try {
                string choice = "";
                while (!bookAgain)
                {
                    Console.WriteLine("Hello, " + newUser.Name + " you may edit your current bookings:" + " \n");
                    // Print - Ticket Number , Source, Destination, Status
                    InventoryServiceImpl.printAllTickets();
                    Console.WriteLine("Update which ticket?: ");
                    choice = inputService.pickTicketListConsoleRead();
                    ticket = InventoryService.tickets[Int16.Parse(choice)];
                    Console.WriteLine("Edit Ticket " + ticket.TicketNumber + "\n");
                    Console.WriteLine(" - Change Seating [1]");
                    Console.WriteLine(" - Cancel Ticket [2]");
                    Console.WriteLine(" - Back to Login [3]");

                    choice = inputService.pickRequestOptionConsoleRead();
                    switch (Int16.Parse(choice))
                    {
                    case 1:
                        // Create request to update the seating
                        inventoryService.printAvaliableSeats(newRoute);
                        choice = inputService.pickNewSeatingConsoleRead();
                        string oldSeat = ticket.Seat;
                        ticket.Seat   = newRoute.seats[Int16.Parse(choice)];
                        ticket.status = Ticket.Status.Pending;
                        newRoute.seats.RemoveAt(Int16.Parse(choice));
                        newRoute.seats.Add(oldSeat);
                        inventoryService.createRequest(new Request(ticket));
                        Console.WriteLine("Request to change seat created.");
                        break;

                    case 2:
                        ticket.status = Ticket.Status.Canceled;
                        inventoryService.createRequest(new Request(ticket));
                        Console.WriteLine("Request to Cancel ticket created.");
                        break;

                    case 3:
                        bookAgain = true;
                        logout    = true;
                        break;

                    default:
                        break;
                    }
                }
            } catch (Exception e)
            {
                return(false);
            }
            return(logout);
        }
 private void CreateArticle(string articleFile, StreamWriter writer)
 {
     string articleInfo = File.ReadAllText(articleFile, Encoding.GetEncoding(1251));
     var article = new Article();
     article.Title = GetInfoField(articleInfo, "title");
     writer.WriteLine("Title: {0}", article.Title);
     article.Text = GetInfoField(articleInfo, "description");
     article.Source = GetInfoField(articleInfo, "source");
     var authors = GetInfoField(articleInfo, "users").Split(',');
     article.Authors = new List<User>();
     foreach (var author in authors)
     {
         article.Authors.Add(new User { Email = author.TrimEnd('\r') });
     }
     var disciplineIds = GetDisciplines(GetInfoField(articleInfo, "disciplines").Split(','));
     article.Disciplines = new List<Discipline>();
     foreach (var disciplineId in disciplineIds)
     {
         article.Disciplines.Add(new Discipline() { Id = disciplineId });
     }
     using (var dataContext = new EfDataContext())
     {
         var publicationService = new PublicationService(dataContext);
         publicationService.Publish(article);
         var notificationService = new NotificationService(dataContext);
         notificationService.NotifyAboutNewArticle(article);
     }
     AddComments(article, articleInfo);
 }
        public bool userCreatingReservationInterface(Boolean existingUser, Boolean logout, Boolean bookAgain,
                                                     Boolean confirm, UserData employee,
                                                     InventoryService inventoryService,
                                                     TransactionService transactionService, NotificationService notificationService,
                                                     Ticket ticket, Route newRoute, UserData newUser)
        {
            try
            {
                string choice = "";
                while (!logout)
                {
                    confirm   = false;
                    bookAgain = false;

                    if (existingUser)
                    {
                        Console.WriteLine("Would you like to go to current bookings or book a new flight?");
                        Console.WriteLine(" - Current Bookings [1] ");
                        Console.WriteLine(" - Book New Flight [2] \n");
                        choice = inputService.pickNewBooking();
                    }

                    // If existing user and wants to book new Flight or new user
                    TransactionController transaction = new TransactionController(new InputServiceImpl());
                    transaction.transactionInterface(existingUser, logout, bookAgain, confirm, employee, inventoryService,
                                                     transactionService, notificationService, ticket, newRoute, newUser);

                    // Make Notification, go to user existing flights
                    logout = userBookingSelectInterface(existingUser, logout, bookAgain, confirm, employee, inventoryService,
                                                        transactionService, notificationService, ticket, newRoute, newUser);
                }
            } catch (Exception e)
            {
                return(false);
            }

            return(true);
        }
Exemple #31
0
        private void InitializeCommands()
        {
            CloseWindowCommand = new RelayCommand(() => Application.Current.MainWindow.Close());

            MinimizeWindowCommand = new RelayCommand(() => WindowState = WindowState.Minimized);

            MaximizeWindowCommand = new RelayCommand(() => WindowState = IsWindowMaximized ? WindowState.Normal : WindowState.Maximized);

            GoToPageCommand = new RelayCommand <string>(page => OnNavigateToPage(new NavigateToPageMessage()
            {
                Page = page
            }));

            GoToSettingsCommand = new RelayCommand(() =>
            {
                ShowSidebar = false;
                OnNavigateToPage(new NavigateToPageMessage()
                {
                    Page = "/Settings.SettingsView"
                });
            });

            PrevAudioCommand = new RelayCommand(AudioService.Prev);

            NextAudioCommand = new RelayCommand(AudioService.SkipNext);

            PlayPauseCommand = new RelayCommand(() =>
            {
                if (IsPlaying)
                {
                    AudioService.Pause();
                }
                else
                {
                    AudioService.Play();
                }
            });

            GoBackCommand = new RelayCommand(() =>
            {
                var frame = Application.Current.MainWindow.GetVisualDescendents().OfType <Frame>().FirstOrDefault(f => f.Name == "RootFrame");
                if (frame == null)
                {
                    return;
                }

                if (frame.CanGoBack)
                {
                    frame.GoBack();
                }

                UpdateCanGoBack();
            });

            SearchCommand = new RelayCommand <string>(query =>
            {
                if (!string.IsNullOrWhiteSpace(query))
                {
                    MessengerInstance.Send(new NavigateToPageMessage()
                    {
                        Page       = "/Search.SearchResultsView",
                        Parameters = new Dictionary <string, object>()
                        {
                            { "query", query }
                        }
                    });
                }
            });

            SearchKeyUpCommand = new RelayCommand <KeyEventArgs>(args =>
            {
                if (args.Key == Key.Enter)
                {
                    var textBox = args.Source as TextBox;
                    if (textBox != null && !string.IsNullOrWhiteSpace(textBox.Text))
                    {
                        SearchCommand.Execute(textBox.Text);
                    }
                }
            });

            RestartCommand = new RelayCommand(() =>
            {
                Process.Start(Application.ResourceAssembly.Location);
                Application.Current.Shutdown();
            });

            AddRemoveAudioCommand = new RelayCommand <VkAudio>(audio =>
            {
                audio.IsAddedByCurrentUser = !audio.IsAddedByCurrentUser;
                LikeDislikeAudio(audio);
            });

            EditAudioCommand = new RelayCommand <VkAudio>(audio =>
            {
                var flyout           = new FlyoutControl();
                flyout.FlyoutContent = new EditAudioView(audio);
                flyout.Show();
            });

            ShowLyricsCommand = new RelayCommand <VkAudio>(audio =>
            {
                var flyout           = new FlyoutControl();
                flyout.FlyoutContent = new LyricsView(audio);
                flyout.Show();
            });

            CopyInfoCommand = new RelayCommand <Audio>(audio =>
            {
                if (audio == null)
                {
                    return;
                }

                try
                {
                    Clipboard.SetData(DataFormats.UnicodeText, audio.Artist + " - " + audio.Title);
                }
                catch (Exception ex)
                {
                    LoggingService.Log(ex);
                }
            });

            PlayAudioNextCommand = new RelayCommand <Audio>(track =>
            {
                AudioService.PlayNext(track);
            });

            AddToNowPlayingCommand = new RelayCommand <Audio>(track =>
            {
                NotificationService.Notify(MainResources.NotificationAddedToNowPlaying);
                AudioService.Playlist.Add(track);
            });

            RemoveFromNowPlayingCommand = new RelayCommand <Audio>(track =>
            {
                AudioService.Playlist.Remove(track);
            });

            ShareAudioCommand = new RelayCommand <VkAudio>(audio =>
            {
                ShowShareBar = true;

                //костыль #2
                var shareControl = Application.Current.MainWindow.GetVisualDescendent <ShareBarControl>();
                if (shareControl == null)
                {
                    return;
                }

                var shareViewModel = ((ShareViewModel)((FrameworkElement)shareControl.Content).DataContext);
                shareViewModel.Tracks.Add(audio);
            });

            SwitchUIModeCommand = new RelayCommand(() =>
            {
                if (CurrentUIMode == UIMode.Normal)
                {
                    SwitchUIMode(Settings.Instance.LastCompactMode == UIMode.CompactLandscape ? UIMode.CompactLandscape : UIMode.Compact);
                }
                else
                {
                    SwitchUIMode(UIMode.Normal);
                }
            });

            SwitchToUIModeCommand = new RelayCommand <string>(s =>
            {
                UIMode mode;
                if (Enum.TryParse(s, true, out mode))
                {
                    SwitchUIMode(mode);
                }
            });

            StartTrackRadioCommand = new RelayCommand <Audio>(track =>
            {
                RadioService.StartRadioFromSong(track.Title, track.Artist);
                MessengerInstance.Send(new NavigateToPageMessage()
                {
                    Page = "/Main.NowPlayingView"
                });
            });

            ShowArtistInfoCommand = new RelayCommand <string>(async artist =>
            {
                NotificationService.Notify(MainResources.NotificationLookingArtist);

                try
                {
                    var response = await DataService.GetArtistInfo(null, artist);
                    if (response != null)
                    {
                        MessengerInstance.Send(new NavigateToPageMessage()
                        {
                            Page       = "/Search.ArtistView",
                            Parameters = new Dictionary <string, object>()
                            {
                                { "artist", response }
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Log(ex);
                    NotificationService.Notify(MainResources.NotificationArtistNotFound);
                }
            });

            ShowLocalSearchCommand = new RelayCommand(() =>
            {
                var frame = Application.Current.MainWindow.GetVisualDescendents().OfType <Frame>().FirstOrDefault();
                if (frame == null)
                {
                    return;
                }

                var page = (Page)frame.Content;
                if (page != null)
                {
                    var localSearchBox = page.GetVisualDescendents().OfType <LocalSearchControl>().FirstOrDefault();
                    if (localSearchBox != null)
                    {
                        localSearchBox.IsActive = true;
                    }
                }
            });

            AddToAlbumCommand = new RelayCommand <VkAudio>(track =>
            {
                var flyout           = new FlyoutControl();
                flyout.FlyoutContent = new AddToAlbumView(track);
                flyout.Show();
            });
        }
Exemple #32
0
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            RegisterCoreComponents();
            RegisterFactories();
            RegisterRepositories();
            RegisterServices();
            InitializeServices();
            RegisterViews();
            RegisterViewModels();

            void RegisterCoreComponents()
            {
                containerRegistry.RegisterInstance <IContainerProvider>(Container);
                containerRegistry.RegisterInstance <ILocalizationInfo>(new LocalizationInfo());
            }

            void RegisterFactories()
            {
                containerRegistry.RegisterSingleton <ISQLiteConnectionFactory, SQLiteConnectionFactory>();
            }

            void RegisterRepositories()
            {
                containerRegistry.RegisterSingleton <IFolderRepository, FolderRepository>();
                containerRegistry.RegisterSingleton <ITrackRepository, TrackRepository>();
                containerRegistry.RegisterSingleton <IAlbumArtworkRepository, AlbumArtworkRepository>();
                containerRegistry.RegisterSingleton <IQueuedTrackRepository, QueuedTrackRepository>();
            }

            void RegisterServices()
            {
                containerRegistry.RegisterSingleton <ICacheService, CacheService>();
                containerRegistry.RegisterSingleton <IUpdateService, UpdateService>();
                containerRegistry.RegisterSingleton <IAppearanceService, AppearanceService>();
                containerRegistry.RegisterSingleton <II18nService, I18nService>();
                containerRegistry.RegisterSingleton <IDialogService, DialogService>();
                containerRegistry.RegisterSingleton <IIndexingService, IndexingService>();
                containerRegistry.RegisterSingleton <IPlaybackService, PlaybackService>();
                containerRegistry.RegisterSingleton <IWin32InputService, Win32InputService>();
                containerRegistry.RegisterSingleton <ISearchService, SearchService>();
                containerRegistry.RegisterSingleton <ITaskbarService, TaskbarService>();
                containerRegistry.RegisterSingleton <ICollectionService, CollectionService>();
                containerRegistry.RegisterSingleton <IFoldersService, FoldersService>();
                containerRegistry.RegisterSingleton <IJumpListService, JumpListService>();
                containerRegistry.RegisterSingleton <IFileService, FileService>();
                containerRegistry.RegisterSingleton <ICommandService, CommandService>();
                containerRegistry.RegisterSingleton <IMetadataService, MetadataService>();
                containerRegistry.RegisterSingleton <IEqualizerService, EqualizerService>();
                containerRegistry.RegisterSingleton <IProviderService, ProviderService>();
                containerRegistry.RegisterSingleton <IScrobblingService, LastFmScrobblingService>();
                containerRegistry.RegisterSingleton <IPlaylistService, PlaylistService>();
                containerRegistry.RegisterSingleton <IExternalControlService, ExternalControlService>();
                containerRegistry.RegisterSingleton <IWindowsIntegrationService, WindowsIntegrationService>();
                containerRegistry.RegisterSingleton <ILyricsService, LyricsService>();
                containerRegistry.RegisterSingleton <IShellService, ShellService>();
                containerRegistry.RegisterSingleton <ILifetimeService, LifetimeService>();

                INotificationService notificationService;

                // NotificationService contains code that is only supported on Windows 10
                if (Core.Base.Constants.IsWindows10 && Container.Resolve <IPlaybackService>().SupportsWindowsMediaFoundation)
                {
                    // On some editions of Windows 10, constructing NotificationService still fails
                    // (e.g. Windows 10 Enterprise N 2016 LTSB). Hence the try/catch block.
                    try
                    {
                        notificationService = new NotificationService(
                            Container.Resolve <IPlaybackService>(),
                            Container.Resolve <ICacheService>(),
                            Container.Resolve <IMetadataService>());
                    }
                    catch (Exception ex)
                    {
                        LogClient.Error("Constructing NotificationService failed. Falling back to LegacyNotificationService. Exception: {0}", ex.Message);
                        notificationService = new LegacyNotificationService(
                            Container.Resolve <IPlaybackService>(),
                            Container.Resolve <ICacheService>(),
                            Container.Resolve <IMetadataService>());
                    }
                }
                else
                {
                    notificationService = new LegacyNotificationService(
                        Container.Resolve <IPlaybackService>(),
                        Container.Resolve <ICacheService>(),
                        Container.Resolve <IMetadataService>());
                }

                containerRegistry.RegisterInstance(notificationService);
            }

            void InitializeServices()
            {
                // Making sure resources are set before we need them
                Container.Resolve <II18nService>().ApplyLanguageAsync(SettingsClient.Get <string>("Appearance", "Language"));
                // Container.Resolve<IAppearanceService>().ApplyTheme(SettingsClient.Get<bool>("Appearance", "EnableLightTheme"));
                Container.Resolve <IAppearanceService>().ApplyTheme(false);
                Container.Resolve <IAppearanceService>().ApplyColorSchemeAsync(
                    SettingsClient.Get <string>("Appearance", "ColorScheme"),
                    SettingsClient.Get <bool>("Appearance", "FollowWindowsColor"),
                    SettingsClient.Get <bool>("Appearance", "FollowAlbumCoverColor")
                    );
                Container.Resolve <IExternalControlService>();
            }

            void RegisterViews()
            {
                // Misc.
                containerRegistry.Register <object, Oobe>(typeof(Oobe).FullName);
                containerRegistry.Register <object, TrayControls>(typeof(TrayControls).FullName);
                containerRegistry.Register <object, Shell>(typeof(Shell).FullName);
                containerRegistry.Register <object, Empty>(typeof(Empty).FullName);
                containerRegistry.Register <object, FullPlayer>(typeof(FullPlayer).FullName);
                containerRegistry.Register <object, CoverPlayer>(typeof(CoverPlayer).FullName);
                containerRegistry.Register <object, MicroPlayer>(typeof(MicroPlayer).FullName);
                containerRegistry.Register <object, NanoPlayer>(typeof(NanoPlayer).FullName);
                containerRegistry.Register <object, NowPlaying>(typeof(NowPlaying).FullName);
                containerRegistry.Register <object, WindowControls>(typeof(WindowControls).FullName);

                // Collection
                containerRegistry.Register <object, CollectionMenu>(typeof(CollectionMenu).FullName);
                containerRegistry.Register <object, Collection>(typeof(Collection).FullName);
                containerRegistry.Register <object, CollectionAlbums>(typeof(CollectionAlbums).FullName);
                containerRegistry.Register <object, CollectionArtists>(typeof(CollectionArtists).FullName);
                containerRegistry.Register <object, CollectionPlaylists>(typeof(CollectionPlaylists).FullName);
                containerRegistry.Register <object, CollectionFolders>(typeof(CollectionFolders).FullName);
                containerRegistry.Register <object, CollectionGenres>(typeof(CollectionGenres).FullName);
                containerRegistry.Register <object, CollectionTracks>(typeof(CollectionTracks).FullName);

                // Settings
                containerRegistry.Register <object, SettingsMenu>(typeof(SettingsMenu).FullName);
                containerRegistry.Register <object, Settings>(typeof(Settings).FullName);
                containerRegistry.Register <object, SettingsAppearance>(typeof(SettingsAppearance).FullName);
                containerRegistry.Register <object, SettingsBehaviour>(typeof(SettingsBehaviour).FullName);
                containerRegistry.Register <object, SettingsOnline>(typeof(SettingsOnline).FullName);
                containerRegistry.Register <object, SettingsPlayback>(typeof(SettingsPlayback).FullName);
                containerRegistry.Register <object, SettingsStartup>(typeof(SettingsStartup).FullName);

                // Information
                containerRegistry.Register <object, InformationMenu>(typeof(InformationMenu).FullName);
                containerRegistry.Register <object, Information>(typeof(Information).FullName);
                containerRegistry.Register <object, InformationHelp>(typeof(InformationHelp).FullName);
                containerRegistry.Register <object, InformationAbout>(typeof(InformationAbout).FullName);

                // Now playing
                containerRegistry.Register <object, NowPlayingArtistInformation>(typeof(NowPlayingArtistInformation).FullName);
                containerRegistry.Register <object, NowPlayingLyrics>(typeof(NowPlayingLyrics).FullName);
                containerRegistry.Register <object, NowPlayingPlaylist>(typeof(NowPlayingPlaylist).FullName);
                containerRegistry.Register <object, NowPlayingShowcase>(typeof(NowPlayingShowcase).FullName);
            }

            void RegisterViewModels()
            {
            }
        }
Exemple #33
0
 public void Setup()
 {
     _notificationService = new NotificationService();
     _eventId             = Guid.NewGuid();
 }
 public PatientController(PatientService patientService, NotificationService notificationService, UserService userService)
 {
     _userService         = userService;
     _patientService      = patientService;
     _notificationService = notificationService;
 }
Exemple #35
0
 public HttpResponseMessage TestSMTP(SMTPTest smtpTest)
 {
     NotificationService.ErrorNotification(smtpTest.smtpSection, smtpTest.sendTo);
     return Request.CreateResponse(HttpStatusCode.OK);
 }
 protected void Reject()
 {
     if (!ClanService.RejectRequest(Selected.ID, out string message, out HttpStatusCode code))
     {
         NotificationService.ShowError(message, "Failed to reject join request!");
     }
Exemple #37
0
 public PostRepository(IGraphClientFactory factory, IHostingEnvironment hostingEnvironment, NotificationService notificationService)
 {
     this._client             = factory.Create();
     this._hostingEnvironment = hostingEnvironment;
     _notificationService     = notificationService;
 }
Exemple #38
0
            public async ThreadingTask UnschedulesAllNotifications()
            {
                await DataSource.Logout();

                await NotificationService.Received().UnscheduleAllNotifications();
            }
 public LocalNotificationService(
     LocalServiceFactory serviceFactory,
     Dispatcher dispatcher)
 {
     notificationService = new NotificationService(() => serviceFactory.NotificationWindowManager, dispatcher);
 }
        public void ConvertTimeSpanToMilliseconds() {
            var service = new NotificationService();
            service.CustomNotificationDuration = TimeSpan.MaxValue;
            var toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
            Assert.AreEqual(int.MaxValue, toast.duration);

            service.CustomNotificationDuration = TimeSpan.MinValue;
            toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
            Assert.AreEqual(0, toast.duration);

            service.CustomNotificationDuration = TimeSpan.FromMilliseconds((double)int.MaxValue + int.MaxValue);
            toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
            Assert.AreEqual(int.MaxValue, toast.duration);

            service.CustomNotificationDuration = TimeSpan.FromMilliseconds(int.MaxValue);
            toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
            Assert.AreEqual(int.MaxValue, toast.duration);

            service.CustomNotificationDuration = TimeSpan.FromMilliseconds(150);
            toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
            Assert.AreEqual(150, toast.duration);

            service.CustomNotificationDuration = TimeSpan.FromMilliseconds(1);
            toast = (NotificationService.MvvmCustomNotification)service.CreateCustomNotification(null);
            Assert.AreEqual(1, toast.duration);
        }
 public IList<NotificationTimeDto> NotificationTimes2()
 {
     var notificationService = new NotificationService();
     return notificationService.GetNotificationTimes();
 }
 public IList<NotificationTimeDto> NotificationTimesDateTime(int id)
 {
     var notificationService = new NotificationService();
     return notificationService.ComputeNotificationTimeForAgendaItem(id);
 }
Exemple #43
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute( IJobExecutionContext context )
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            var groupGuid = dataMap.Get( "NotificationGroup" ).ToString().AsGuid();

            var rockContext = new RockContext();
            var group = new GroupService( rockContext ).Get( groupGuid );

            if ( group != null )
            {
                var installedPackages = InstalledPackageService.GetInstalledPackages();

                var sparkLinkRequest = new SparkLinkRequest();
                sparkLinkRequest.RockInstanceId = Rock.Web.SystemSettings.GetRockInstanceId();
                sparkLinkRequest.OrganizationName = GlobalAttributesCache.Value( "OrganizationName" );
                sparkLinkRequest.VersionIds = installedPackages.Select( i => i.VersionId ).ToList();
                sparkLinkRequest.RockVersion = VersionInfo.VersionInfo.GetRockSemanticVersionNumber();

                var notifications = new List<Notification>();

                var sparkLinkRequestJson = JsonConvert.SerializeObject( sparkLinkRequest );

                var client = new RestClient( "https://www.rockrms.com/api/SparkLink/update" );
                //var client = new RestClient( "http://localhost:57822/api/SparkLink/update" );
                var request = new RestRequest( Method.POST );
                request.AddParameter( "application/json", sparkLinkRequestJson, ParameterType.RequestBody );
                IRestResponse response = client.Execute( request );
                if ( response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Accepted )
                {
                    foreach ( var notification in JsonConvert.DeserializeObject<List<Notification>>( response.Content ) )
                    {
                        notifications.Add( notification );
                    }
                }

                if ( sparkLinkRequest.VersionIds.Any() )
                {
                    client = new RestClient( "https://www.rockrms.com/api/Packages/VersionNotifications" );
                    //client = new RestClient( "http://localhost:57822/api/Packages/VersionNotifications" );
                    request = new RestRequest( Method.GET );
                    request.AddParameter( "VersionIds", sparkLinkRequest.VersionIds.AsDelimited( "," ) );
                    response = client.Execute( request );
                    if ( response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Accepted )
                    {
                        foreach ( var notification in JsonConvert.DeserializeObject<List<Notification>>( response.Content ) )
                        {
                            notifications.Add( notification );
                        }
                    }
                }

                if ( notifications.Count == 0 )
                {
                    return;
                }

                var notificationService = new NotificationService( rockContext);
                foreach ( var notification in notifications.ToList() )
                {
                    if (notificationService.Get(notification.Guid) == null )
                    {
                        notificationService.Add( notification );
                    }
                    else
                    {
                        notifications.Remove( notification );
                    }
                }
                rockContext.SaveChanges();

                var notificationRecipientService = new NotificationRecipientService( rockContext );
                foreach (var notification in notifications )
                {
                    foreach ( var member in group.Members )
                    {
                        if ( member.Person.PrimaryAliasId.HasValue )
                        {
                            var recipientNotification = new Rock.Model.NotificationRecipient();
                            recipientNotification.NotificationId = notification.Id;
                            recipientNotification.PersonAliasId = member.Person.PrimaryAliasId.Value;
                            notificationRecipientService.Add( recipientNotification );
                        }
                    }
                }
                rockContext.SaveChanges();

            }
        }
 public void FindNotificationTimes()
 {
     var rs = new NotificationService();
     rs.FindNotificationTimes();
 }
        public void ThrowOnAutoHeight() {
            var style = new Style();
            style.Setters.Add(new Setter(FrameworkElement.HeightProperty, double.NaN));

            var service = new NotificationService();
            service.CustomNotificationStyle = style;
            var toast = service.CreateCustomNotification(null);
            try {
                toast.ShowAsync();
                Assert.Fail();
            } catch(InvalidOperationException) { }
        }
 public IList<NotificationPreferenceDto> NotificationTimesMinutes(int id)
 {
     var notificationService = new NotificationService();
     return notificationService.GetNotificationTimesForAgendaItem(id);
 }
 public RegistrationController(RegistrationRepository repository, NotificationService notificationService)
 {
     _repository = repository;
     _notificationService = notificationService;
 }
        public void LoadDoesNotRoundtripOnIncludedCustomer()
        {
            var newSession = RavenDBConfiguration.Instance().OpenNewSession();

            var customer1 = new Customer
            {
                FirstName = "Test1",
                LastName = "User",
                Phones =
                    new List<CustomerPhone> { new CustomerPhone { Number = "11111111", PhoneType = PhoneTypes.WorkPhone1 } }
            };
            newSession.Store(customer1);

            var customer2 = new Customer
            {
                FirstName = "Test2",
                LastName = "User",
                Phones =
                    new List<CustomerPhone> { new CustomerPhone { Number = "22222222", PhoneType = PhoneTypes.WorkPhone1 } }
            };
            newSession.Store(customer2);

            var unitResident = new UnitResident
            {
                CommunityCode = "101",
                SubCommunityCode = "101",
                BuildingId = "01",
                UnitId = "0420",
                UnitAddress = "4501 Connecticut Ave NW #420",
                LastName = "",
                FirstName = ""
            };

            var package1 = new Package
            {
                UnitResident = unitResident,
                CommunityCode = "101",
                CustomerIds = new List<string> { customer1.Id, customer2.Id },
                PackageType = "FedEx",
                Status = PackageStatusCodes.Received.ToString()
            };
            newSession.Store(package1);
            newSession.SaveChanges();

            var service = new NotificationService();
            var currentSession = AbstractRavenService.GetCurrentDocumentSession();

            var packages = service.GetPackageInventory("101", string.Empty, false, false, null, null, 10);

            Assert.AreEqual(1, currentSession.Advanced.NumberOfRequests);

            Assert.IsNotNull(packages);
            foreach (var package in packages)
            {
                Assert.IsTrue(package.Customers.Count > 0);
            }
        }
 public NotificationController()
 {
     _NotificationService     = new NotificationService();
     _NotificationUserService = new NotificationUserService();
 }
 private void AddComments(IEntity article, string articleInfo)
 {
     var comments = Regex.Matches(articleInfo, "(?<=text:).*");
     var authors = Regex.Matches(articleInfo, "(?<=author:).*");
     for (int i = 0; i < comments.Count; i++)
     {
         var comment = new Comment();
         comment.ArticleId = article.Id;
         comment.Text = comments[i].Value;
         using (var academyEntities = new AcademyEntities())
         {
             var email = authors[i].Value.TrimEnd('\r');
             comment.UserId = academyEntities.Users.Single(
                 x => x.Email.Equals(email)).Id;
         }
         using (var context = new EfDataContext())
         {
             var publicationService = new PublicationService(context);
             publicationService.Comment(comment);
             var notificationService = new NotificationService(context);
             notificationService.NotifyAboutNewComment(comment);
         }
     }
 }
Exemple #51
0
 public Tutor(StorageService storage, CookieService cookie, ProfileService profile, ScheduleService schedule, FollowService follow, NotificationService notification, EncryptionService encryption)
 {
     storageService      = storage;
     cookieService       = cookie;
     profileService      = profile;
     scheduleService     = schedule;
     followService       = follow;
     notificationService = notification;
     encryptionService   = encryption;
 }
Exemple #52
0
        public bool Execute()
        {
            string userName  = _txtUsername.Text.Trim();
            string userEmail = _txtEmail.Text.Trim();

            if (userName.Length == 0)
            {
                NotificationService.NotifyInputError(
                    _txtUsername,
                    Resources.ErrInvalidUserName,
                    Resources.ErrUserNameCannotBeEmpty);
                return(false);
            }
            if (userEmail.Length == 0)
            {
                NotificationService.NotifyInputError(
                    _txtEmail,
                    Resources.ErrInvalidEmail,
                    Resources.ErrEmailCannotBeEmpty);
                return(false);
            }
            try
            {
                if (_radSetUserGlobally.Checked)
                {
                    if (_oldUserName != userName || _oldUserEmail != userEmail)
                    {
                        if (_repository != null)
                        {
                            var cpUserName = _repository.Configuration.TryGetParameter(GitConstants.UserNameParameter);
                            if (cpUserName != null)
                            {
                                try
                                {
                                    cpUserName.Unset();
                                }
                                catch (GitException)
                                {
                                }
                            }
                            var cpUserEmail = _repository.Configuration.TryGetParameter(GitConstants.UserEmailParameter);
                            if (cpUserEmail != null)
                            {
                                try
                                {
                                    cpUserEmail.Unset();
                                }
                                catch (GitException)
                                {
                                }
                            }
                        }
                        try
                        {
                            _repositoryProvider.GitAccessor.SetConfigValue.Invoke(
                                new SetConfigValueParameters(GitConstants.UserEmailParameter, userEmail)
                            {
                                ConfigFile = ConfigFile.User,
                            });
                        }
                        catch (ConfigParameterDoesNotExistException)
                        {
                        }
                        try
                        {
                            _repositoryProvider.GitAccessor.SetConfigValue.Invoke(
                                new SetConfigValueParameters(GitConstants.UserNameParameter, userName)
                            {
                                ConfigFile = ConfigFile.User,
                            });
                        }
                        catch (ConfigParameterDoesNotExistException)
                        {
                        }
                        if (_repository != null)
                        {
                            _repository.Configuration.Refresh();
                        }
                    }
                    if (_repository != null)
                    {
                        _repository.OnUserIdentityChanged();
                    }
                }
                else
                {
                    _repository.Configuration.SetUserIdentity(userName, userEmail);
                }
            }
            catch (GitException exc)
            {
                GitterApplication.MessageBoxService.Show(
                    this,
                    exc.Message,
                    Resources.ErrFailedToSetParameter,
                    MessageBoxButton.Close,
                    MessageBoxIcon.Error);
                return(false);
            }
            return(true);
        }
Exemple #53
0
 public PageController()
 {
     pageService = new PageService();
     userService = new UserService();
     nfService = new NotificationService();
 }
Exemple #54
0
        public void multipleShiftsMultipleWeeks()
        {
            //shift to cover
            PendingShift pendingShift = new PendingShift()
            {
                Shift = new Shift()
                {
                    ActiveRoute = true,
                    ShiftQualificationNumber = 0,
                    Date      = new DateTime(2021, 4, 7, 0, 0, 0),
                    TimeStart = new DateTime(2021, 1, 2, 12, 0, 0),
                    TimeEnd   = new DateTime(2021, 1, 2, 13, 0, 0)
                }
            };

            //user to assign to
            List <User> users = new List <User>
            {
                new User()
                {
                    Group = new Group()
                    {
                        QualificationNumber = 1
                    },
                    Shifts = new List <Shift>
                    {
                        new Shift()
                        {
                            ActiveRoute = true,
                            ShiftQualificationNumber = 0,
                            Date      = new DateTime(2021, 4, 5, 0, 0, 0),
                            TimeStart = new DateTime(2021, 6, 5, 10, 0, 0),
                            TimeEnd   = new DateTime(2021, 1, 1, 18, 0, 0)
                        },
                        new Shift()
                        {
                            ActiveRoute = true,
                            ShiftQualificationNumber = 0,
                            Date      = new DateTime(2021, 4, 6, 0, 0, 0),
                            TimeStart = new DateTime(2021, 1, 1, 10, 0, 0),
                            TimeEnd   = new DateTime(2021, 1, 1, 18, 0, 0)
                        },
                        //one the week after
                        new Shift()
                        {
                            ActiveRoute = true,
                            ShiftQualificationNumber = 0,
                            Date      = new DateTime(2021, 4, 12, 0, 0, 0),
                            TimeStart = new DateTime(2021, 6, 5, 10, 0, 0),
                            TimeEnd   = new DateTime(2021, 1, 1, 18, 0, 0)
                        },
                        //one the week before
                        new Shift()
                        {
                            ActiveRoute = true,
                            ShiftQualificationNumber = 0,
                            Date      = new DateTime(2021, 4, 4, 0, 0, 0),
                            TimeStart = new DateTime(2021, 1, 1, 10, 0, 0),
                            TimeEnd   = new DateTime(2021, 1, 1, 18, 0, 0)
                        }
                    }
                }
            };

            //act
            NotificationService notificationService = new NotificationService();
            List <User>         validUsers          = notificationService.GetValidUsers(pendingShift, users, 3);

            //Assert
            Assert.IsTrue(validUsers.Count == 1);
        }
 public void SettingApplicationIDToNullTest() {
     var service = new NotificationService();
     service.ApplicationId = "";
     service.ApplicationId = null;
     Assert.IsTrue(true);
 }
Exemple #56
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            using (var db = ApplicationDbContext.Create())
            {
                var org = OrganizationHelper.GetOrganizationByHost(Request, db);
                if (org == null ||
                    !org.IsAnonymousRegistrationAllowed)
                {
                    throw new HttpException(403, "Forbidden");
                }

                if (!model.IsTermsOfServiceAgreed)
                {
                    model.SkippedTermsOfService = true;
                    InitializeRegisterModel(model, org);
                    return(View(model));
                }

                if (ModelState.IsValid)
                {
                    var user = new ApplicationUser();
                    user.UserName  = model.Email;
                    user.Email     = model.Email;
                    user.FirstName = model.FirstName;
                    user.LastName  = model.LastName;

                    IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        await SignInAsync(user, isPersistent : false);

                        db.Users.Attach(user);
                        org.ApplicationUsers.Add(user);

                        db.SaveChanges();


                        // Notify permission assigners of the new user.
                        var usersToNotify = OrganizationHelper.GetUsersWithRight(db, org.Id, Right.CanAssignRights)
                                            .ToList();
                        foreach (var notifyUser in usersToNotify)
                        {
                            try
                            {
                                NotificationService.SendActionEmail(
                                    notifyUser.Email, notifyUser.FullName,
                                    org.ReplyToAddress, org.Name,
                                    "[New User] " + model.Email,
                                    string.Format("{0} {1} has created a new account with user name {2}.", model.FirstName, model.LastName, model.Email),
                                    "Please assign any appropriate rights to the new user.",
                                    "Assign Rights ",
                                    Request.Url.Scheme + "://" + Request.Url.Host + "/User/Permissions/" + model.Email,
                                    org.NotificationEmailClosing,
                                    Request.Url.Scheme + "://" + Request.Url.Host + "/User/EmailPreferences/" + notifyUser.UserName,
                                    db);
                            }
                            catch (Exception ex)
                            {
                                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                            }
                        }

                        // Send an email with this link
                        string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                        var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                        NotificationService.SendActionEmail(
                            user.Email, string.Format("{0} {1}", model.FirstName, model.LastName),
                            org.ReplyToAddress, org.Name,
                            "Confirm your account",
                            "Welcome to " + org.Name + ".",
                            "We are ready to activate your account. All we need to do is make sure this is your email address.",
                            "Verify Address", callbackUrl,
                            "If you didn't create an account, just delete this email.",
                            Request.Url.Scheme + "://" + Request.Url.Host + "/User/EmailPreferences/" + user.UserName,
                            db);

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public void UpdateCustomToastPositionTest() {
            var service = new NotificationService();
            var toast = service.CreateCustomNotification(null);
            Assert.AreEqual(NotificationPosition.TopRight, CustomNotifier.positioner.position);
            service.CustomNotificationPosition = NotificationPosition.BottomRight;
            Assert.AreEqual(NotificationPosition.BottomRight, CustomNotifier.positioner.position);

            service = new NotificationService();
            service.CustomNotificationPosition = NotificationPosition.BottomRight;
            toast = service.CreateCustomNotification(null);
            Assert.AreEqual(NotificationPosition.BottomRight, CustomNotifier.positioner.position);
            service.CustomNotificationPosition = NotificationPosition.TopRight;
            Assert.AreEqual(NotificationPosition.TopRight, CustomNotifier.positioner.position);
        }
    public void sendMessageToIOS(string message,string tokenid,int messageid)
    {
        bool sandbox = true;
        string p12File = "test.p12";
        string p12FilePassword = "******";

        string p12Filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p12File);

        NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);

        service.SendRetries = 5; //5 retries before generating notificationfailed event
        service.ReconnectDelay = 5000; //5 seconds
        if (!string.IsNullOrEmpty(tokenid))
        {
            Notification alertNotification = new Notification(tokenid);
            alertNotification.Payload.Alert.Body = "您有一条来自服务器的新消息!";
            alertNotification.Payload.Sound = "default";
            alertNotification.Payload.Badge = 1;
            alertNotification.Payload.AddCustom("kind", "1");
            alertNotification.Payload.AddCustom("messageId", messageid);
            alertNotification.Payload.AddCustom("fromId", -1);
            //alertNotification.Payload.AddCustom(txtName3.Value, txtVaule3.Value);
            //Queue the notification to be sent
            if (service.QueueNotification(alertNotification))
            { }
            else

            { }
        }
        else
        {
            APP_DEVICELIST conf = new APP_DEVICELIST();
            conf.KIND = 0;
            conf.STATUS = 0;
            List<APP_DEVICELIST> devicelist = BLLTable<APP_DEVICELIST>.Select(new APP_DEVICELIST(),conf);
            foreach (APP_DEVICELIST device in devicelist)
            {
                Notification alertNotification = new Notification(device.TOKEN_ID);

                alertNotification.Payload.Alert.Body = "您有一条来自服务器的新消息!";
                alertNotification.Payload.Sound = "default";
                alertNotification.Payload.Badge = 1;
                alertNotification.Payload.AddCustom("kind", "1");
                alertNotification.Payload.AddCustom("messageId", Convert.ToString(messageid));
                alertNotification.Payload.AddCustom("fromId", -1);
                //alertNotification.Payload.AddCustom(txtName3.Value, txtVaule3.Value);

                //Queue the notification to be sent
                if (service.QueueNotification(alertNotification))
                { }
                else

                { }
            }
        }
        service.Close();

        service.Dispose();
    }