示例#1
0
        public async Task <ActionResult> Edit([Bind(Include = "Id,Title,Description,Created,Updated,ProjectId,TicketTypeId,TicketPriorityId,TicketStatusId,OwnerUserId,AssignedToUserId")] Tickets tickets)
        {
            var th       = new TicketsHelper(urh, db);
            var OGticket = db.Ticket.AsNoTracking().First(t => t.Id == tickets.Id);

            if (ModelState.IsValid)
            {
                //tickets.AssignedToUserId = Developer;
                db.Entry(tickets).State = EntityState.Modified;

                db.SaveChanges();

                var newTicket = db.Ticket.AsNoTracking().First(t => t.Id == tickets.Id);

                th.AddTicketHistory(OGticket, newTicket, User.Identity.GetUserId());

                var nh = new NotificationsHelper();
                await nh.HandleNotifications(OGticket, newTicket);

                return(RedirectToAction("Index"));
            }

            ViewBag.AssignedToUserId = new SelectList(db.Users, "Id", "DisplayName", tickets.AssignedToUserId);
            ViewBag.OwnerUserId      = new SelectList(db.Users, "Id", "DisplayName", tickets.OwnerUserId);
            ViewBag.ProjectId        = new SelectList(db.Project, "Id", "Name", tickets.ProjectId);
            ViewBag.TicketPriorityId = new SelectList(db.TicketPriority, "Id", "Name", tickets.TicketPriorityId);
            ViewBag.TicketStatusId   = new SelectList(db.TicketStatus, "Id", "Name", tickets.TicketStatusId);
            ViewBag.TicketTypeId     = new SelectList(db.TicketType, "Id", "Name", tickets.TicketTypeId);

            var developers = urh.UsersInRole("Developer");

            ViewBag.Developer = new MultiSelectList(urh.UsersInRole("Developer"), "Id", "DisplayName");

            return(View(tickets));
        }
示例#2
0
        private async void ResendMessageIfNeeded()
        {
            DateTime nowLocal = TimeZoneInfo.ConvertTimeFromUtc(SystemTime.Now(), TimeZoneInfo.Local);
            DateTime todayUtc = SystemTime.Now().Date;
            DateTime lastReceivedMessageDateTimeUtc =
                MessageUtils.GetDateTimeFromSecureStorageForKey(SecureStorageKeys.LAST_SENT_NOTIFICATION_UTC_KEY, nameof(ResendMessageIfNeeded));
            DateTime lastReceivedMessageDateTimeLocal = lastReceivedMessageDateTimeUtc.ToLocalTime();

            if (lastReceivedMessageDateTimeUtc < todayUtc &&
                nowLocal.Date.Subtract(lastReceivedMessageDateTimeLocal.Date).TotalHours >= Conf.HOURS_UNTIL_RESEND_MESSAGES)
            {
                if (nowLocal.Hour >= Conf.HOUR_WHEN_MESSAGE_SHOULD_BE_RESEND)
                {
                    List <MessageSQLiteModel> unreadMessages = await MessageUtils.GetAllUnreadMessages();

                    List <MessageSQLiteModel> unreadMessagesNotOlderThanMsgRetentionTime =
                        unreadMessages.FindAll(message =>
                    {
                        double totalMinutes = SystemTime.Now().Subtract(message.TimeStamp).TotalMinutes;
                        return(totalMinutes <
                               Conf.MAX_MESSAGE_RETENTION_TIME_IN_MINUTES);
                    })
                        .ToList();

                    if (unreadMessagesNotOlderThanMsgRetentionTime.Count > 0)
                    {
                        NotificationsHelper.CreateNotification(NotificationsEnum.NewMessageReceived, 0);
                        MessageUtils.SaveDateTimeToSecureStorageForKey(
                            SecureStorageKeys.LAST_SENT_NOTIFICATION_UTC_KEY,
                            SystemTime.Now(),
                            nameof(ResendMessageIfNeeded));
                    }
                }
            }
        }
        public async Task <ActionResult> SendBulkVerificationEmail()
        {
            var users = from u in db.Tokens
                        where u.User.Verified == false
                        select new SendBulkTokenEmailModel
            {
                TitleID   = u.User.TitleID,
                Intials   = u.User.Intials,
                Surname   = u.User.Surname,
                UserName  = u.User.UserName,
                TokenID   = u.Id,
                Email     = u.User.Email,
                IssueDate = u.IssueDate
            };

            foreach (var user in users)
            {
                string clientName = user.TitleID + " " + user.Intials + " " + user.Surname;

                bool success = NotificationsHelper.SendEmailWithVerificationToken(user.Email, clientName, user.UserName, ControllerContext);

                if (!success)
                {
                    Trace.WriteLine("Failed to send verification email to: " + user.Email + " during bulk email sending", "Verification Bulk Emails");
                }
            }

            ViewBag.Title = "Bulk Verification Emails";

            return(View(await users.ToListAsync()));
        }
示例#4
0
 public void LoadSettings(UserSettings userSettings, bool load)
 {
     if (!load)
     {
         return;
     }
     try
     {
         userSettings = GetLocalUserSettings(userSettings);
     }
     catch (Exception)
     {
         if (!FilesHelper.FileExists(userSettings.SettingsFileLocation))
         {
             NotificationsHelper.DisplayMessage(Messages.Preparing);
             PrepareEnvironment(new UserSettings());
         }
         else if (!CommandsHelper.ShouldExecuteTasks())
         {
             NotificationsHelper.DisplayMessage(Messages.Ready);
         }
         else
         {
             NotificationsHelper.DisplayMessage(Messages.ErrorInSettings);
         }
     }
 }
        public override void OnReceive(Context context, Intent intent)
        {
            var strAlarm = intent.GetStringExtra("alarm");
            var alarm    = JsonConvert.DeserializeObject <Alarm>(strAlarm);

            switch (DateTime.Now.DayOfWeek)
            {
            case DayOfWeek.Monday:
                if (alarm.Monday)
                {
                    SendNotification(alarm);
                }
                break;

            case DayOfWeek.Tuesday:
                if (alarm.Tuesday)
                {
                    SendNotification(alarm);
                }
                break;

            case DayOfWeek.Wednesday:
                if (alarm.Wednesday)
                {
                    SendNotification(alarm);
                }
                break;

            case DayOfWeek.Thursday:
                if (alarm.Thursday)
                {
                    SendNotification(alarm);
                }
                break;

            case DayOfWeek.Friday:
                if (alarm.Friday)
                {
                    SendNotification(alarm);
                }
                break;

            case DayOfWeek.Saturday:
                if (alarm.Saturday)
                {
                    SendNotification(alarm);
                }
                break;

            case DayOfWeek.Sunday:
                if (alarm.Sunday)
                {
                    SendNotification(alarm);
                }
                break;
            }

            NotificationsHelper.RescheduleNotification(alarm);
        }
示例#6
0
 private void SendReApproveConsentsNotificationIfNeeded()
 {
     if (ConsentsHelper.IsNotFullyOnboarded &&
         !LocalPreferencesHelper.TermsNotificationWasShown)
     {
         NotificationsHelper.CreateNotificationOnlyIfInBackground(NotificationsEnum.ReApproveConsents);
     }
 }
示例#7
0
 private void SendReApproveConsentsNotificationIfNeeded()
 {
     if (ConsentsHelper.IsNotFullyOnboarded &&
         (SystemTime.Now() - LocalPreferencesHelper.LastDateTimeTermsNotificationWasShown).Days > 0)
     {
         NotificationsHelper.CreateNotificationOnlyIfInBackground(NotificationsEnum.ReApproveConsents);
     }
 }
示例#8
0
 private void SendReApproveConsentsNotificationIfNeeded()
 {
     if (OnboardingStatusHelper.Status == OnboardingStatus.OnlyMainOnboardingCompleted &&
         !LocalPreferencesHelper.TermsNotificationWasShown)
     {
         NotificationsHelper.CreateNotificationOnlyIfInBackground(NotificationsEnum.ReApproveConsents);
     }
 }
 private void ExecuteDownloadTask(Task task)
 {
     NotificationsHelper.DisplayMessage(Messages.StartsDownloading);
     if (_downloadFileTaskHandler.DownloadFileAndReturnStatus(task.Value, _userSettings.DownloadLocation))
     {
         task.TaskStatus = TaskStatus.Done;
     }
 }
        public override void OnReceive(Context context, Intent intent)
        {
            var user = User.Load();

            if (user != null)
            {
                NotificationsHelper.SetNotificationsAfterReboot(user);
            }
        }
示例#11
0
        public static void Main(string[] args)
        {
            RegisterServices();
            var tasksHandler = DependencyInjectionHelper.InjectDependency <ITasksHandler>();

            CommandsHelper.AnalyseCommandArgs(args);
            tasksHandler.ExecuteTasks();
            NotificationsHelper.DisplayMessage(Messages.Finish);
            SystemsHelper.Sleep();
        }
示例#12
0
 // GET: Notifications
 public ActionResult Index()
 {
     if (NotificationsHelper.GetUnreadNotifications().Count() > 0)
     {
         string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
         var    notifications  = showStuff.MyStuffOnly(controllerName);
         return(View(notifications));
     }
     TempData["NoNotifications"] = "You have no unread Notifications.";
     return(RedirectToAction("Index", "Home"));
 }
 public void Setup()
 {
     _mockToastNotificationService = new MockToastNotificationService();
     _mockTileNotificationService  = new MockTileNotificationService();
     _subject = new NotificationsHelper
     {
         EventAggregator          = new MockEventAggregator(),
         TileNotificationService  = _mockTileNotificationService,
         ToastNotificationService = _mockToastNotificationService
     };
 }
示例#14
0
        private void ExtractTasks()
        {
            var tasks = FilesHelper.ReadAllLines(_userSettings.TasksLocation).ToList();

            if (tasks.Count <= 0)
            {
                return;
            }
            NotificationsHelper.DisplayMessage(Messages.Welcome(tasks.Count, _userSettings.TasksLocation));
            foreach (var taskString in tasks)
            {
                var task = new Task();
                task.Parse(taskString, _userSettings.TaskTypeSplitter);
                ProcessTask(task, tasks.IndexOf(taskString));
            }
        }
示例#15
0
        public bool DownloadFileAndReturnStatus(string url, string downloadLocation)
        {
            var doesSucceed = NetworkHelper.DownloadFile(url, downloadLocation);

            if (doesSucceed)
            {
                NotificationsHelper.DisplayMessage(Messages.SuccessfulDownload(PathsHelper.GetFileNameFromPath(url)));
            }
            else
            {
                NotificationsHelper.DisplayMessage(Messages.FailedDownload(PathsHelper.GetFileNameFromPath(url)));
                NotificationsHelper.DisplayMessage(Messages.StartAgain);
                return(true);
            }

            return(false);
        }
示例#16
0
        public IActionResult Create(MessageBoard.ViewModels.Guestbooks.Create model)
        {
            if (!ModelState.IsValid)
            {
                foreach (var value in ModelState.Values)
                {
                    foreach (var error in value.Errors)
                    {
                        if (error.Exception == null)
                        {
                            _logger.LogError($"{error.ErrorMessage}");
                        }
                        else
                        {
                            _logger.LogError($"{error.Exception.Message}");
                        }
                    }
                }

                return(Problem("建立留言時發生錯誤"));
            }

            var newData = _mapper.Map <Guestbook>(model);

            try
            {
                var member = _memberService.GetDataById(this.UserId);
                if (member == null)
                {
                    throw new Exception("使用者資料錯誤,請重新登入!");
                }

                newData.CreatorId = this.UserId;
                _GuestbookService.InsertGuestbook(newData);

                NotificationsHelper.AddNotification(new NotificationsHelper.Notification {
                    Message = "留言建立成功"
                });
                return(Ok());
            }
            catch (Exception ex)
            {
                return(Problem(ex.Message));
            }
        }
示例#17
0
        /// <summary>
        /// Runs when the web application is started.
        /// </summary>
        protected void Application_Start()
        {
            // Trace listeners should always be the first thing here.
            RegisterTraceListeners(Trace.Listeners);

            Trace.TraceInformation(string.Format("MvcApplication.Application_Start(): app started! [Debug={0}]", DebugConfig.IsDebug));

            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);

            RouteTable.Routes.MapHubs();
            RegisterRoutes(RouteTable.Routes);

            ModelBinders.Binders.DefaultBinder  = new CerebelloDefaultBinder();
            DefaultModelBinder.ResourceClassKey = "ModelStrings";

            // Will create a thread to send notifications
            NotificationsHelper.CreateNotificationsJob();

            SetupDependencyInjector();
        }
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "devicenotificationsregistrations/")] HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                log.Info("New device registration incoming");
                var content = await req.Content.ReadAsStringAsync();

                DeviceInstallation deviceUpdate = await req.Content.ReadAsAsync <DeviceInstallation>();

                await NotificationsHelper.RegisterDevice(deviceUpdate);

                await NotificationsHelper.SendBroadcastNotification("Nuevo dispositivo");

                log.Info("New device registered");
                return(req.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                log.Info($"Error during device registration: {ex.Message}");
            }
            return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error during device registration"));
        }
        protected override T PrepareContent <T> (NotificationModel model)
        {
            NotificationLocal  local = GetLocal(model.locals);
            NotificationRepeat nr    = NotificationsHelper.GetRepeatType(model);
            var n = new AndroidNotification
            {
                Title               = local.title,
                Text                = local.body,
                ShowTimestamp       = true,
                Color               = Color.red,
                ShouldAutoCancel    = true,
                Group               = GroupId,
                GroupSummary        = true,
                GroupAlertBehaviour = GroupAlertBehaviours.GroupAlertAll
            };

            if (nr != NotificationRepeat.None)
            {
                n.RepeatInterval = nr.ToTimeSpanInterval();
            }

            return((T)(object)n);
        }
示例#20
0
 public void ExecuteTasks()
 {
     if (CommandsHelper.ShouldOpenSettings())
     {
         SystemsHelper.OpenFile(_userSettings.SettingsFileLocation);
     }
     if (CommandsHelper.ShouldOpenTasks())
     {
         SystemsHelper.OpenFile(_userSettings.TasksLocation);
     }
     if (CommandsHelper.ShouldOpenDownloadsDirectory())
     {
         SystemsHelper.OpenDirectory(_userSettings.DownloadLocation);
     }
     if (CommandsHelper.ShouldExecuteTasks())
     {
         ExtractTasks();
     }
     else
     {
         NotificationsHelper.DisplayMessage(Messages.CommandNotRecognized);
     }
 }
示例#21
0
        private static void PrepareEnvironment(UserSettings userSettings)
        {
            try
            {
                if (!FilesHelper.FileExists(userSettings.TasksLocation))
                {
                    FilesHelper.OpenOrCreateFile(userSettings.TasksLocation);
                }
                if (!FilesHelper.FileExists(userSettings.SettingsFileLocation))
                {
                    FilesHelper.OpenOrCreateFile(userSettings.SettingsFileLocation);
                    FilesHelper.WriteAllText(userSettings.SettingsFileLocation, JsonHelper.Serialize(userSettings));
                }

                if (!DirectoriesHelper.DirectoryExists(userSettings.DownloadLocation))
                {
                    DirectoriesHelper.CreateDirectory(userSettings.DownloadLocation);
                }
            }
            catch
            {
                NotificationsHelper.DisplayMessage(Messages.ErrorInitiatingConfiguration);
            }
        }
示例#22
0
        public MainPageViewModel(INavigationService navigationService)
            : base(navigationService)
        {
            Title = "Quick Task";
            this.PageAppearingCommand = new Command(async() =>
            {
                IsBusy = true;
                await LoadOpenRequests();
                IsBusy            = false;
                UserInfo userInfo = new UserInfo()
                {
                    UserId             = "123456",
                    Password           = "******",
                    AccountId          = "123456",
                    PushRegistrationId = Settings.Current.RegistrationId,
                };
                await NotificationsHelper.RegisterAccountForPNS(userInfo);
            });

            this.RefreshCommand = new Command(async() =>
            {
                IsRefreshing = true;
                await LoadOpenRequests();
                IsRefreshing = false;
            });

            this.SelectedCommand = new Command <Parent>(async(parentInfo) =>
            {
                if (parentInfo != null)
                {
                    NavigationParameters _navParameters = new NavigationParameters();
                    _navParameters.Add("BatchGuid", parentInfo.BatchGuid.ToString());
                    await NavigationService.NavigateAsync("JobDetail", _navParameters);
                }
            });
        }
        public async Task <bool> SaveUserRegitration()
        {
            this.IsValid = true;

            if (string.IsNullOrEmpty(this.FullName))
            {
                await MessageHelper.ShowMessage("Please provide your Name");

                IsValid = false;
                return(false);
            }

            else if (this.City == null)
            {
                await MessageHelper.ShowMessage("Please choose your City");

                IsValid = false;
                return(false);
            }

            else if (string.IsNullOrEmpty(this.Email))
            {
                await MessageHelper.ShowMessage("Please provide your Email");

                IsValid = false;
                return(false);
            }

            else if (this.SelectedAudienceType == null)
            {
                await MessageHelper.ShowMessage("What describes you best?");

                IsValid = false;
                return(false);
            }

            else if (this.SelectedAudienceOrgType == null)
            {
                await MessageHelper.ShowMessage("Please select your Organization");

                IsValid = false;
                return(false);
            }

            else if (this.SecondaryTechnologies.FirstOrDefault(x => x.IsSelected) == null)
            {
                await MessageHelper.ShowMessage("Please select your Technologies you are interested in");

                IsValid = false;
                return(false);
            }



            string email = this.Email;
            Regex  regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
            Match  match = regex.Match(email);

            if (!match.Success)
            {
                await MessageHelper.ShowMessage("Please enter valid email address");

                IsValid = false;
                return(false);
            }


            try
            {
                this.OperationInProgress = true;

                var pf = new ProfileRequest()
                {
                    FullName           = this.FullName,
                    Email              = this.Email,
                    AuthProvider       = this.AuthProvider,
                    AuthProviderUserId = this.AuthProviderUserId,
                    City = this.City,
                    SelectedAudienceType    = this.SelectedAudienceType,
                    SelectedAudienceOrgType = this.SelectedAudienceOrgType,
                    SecondaryTechnologies   = this.SecondaryTechnologies,
                    DeviceId       = this.DeviceId,
                    DevicePlatform = NotificationsHelper.Platform,
                    PushEnabled    = this.PushEnabled,
                    PushId         = await NotificationsHelper.GetPushId(),
                    Town           = this.Town,
                    Location       = this.Location
                }
                ;

                // Fetch data about the user
                //saves and updates data on server
                var result =
                    await ServiceProxy.CallService("api/Profile", JsonConvert.SerializeObject(pf));

                if (result.IsSuccess)
                {
                    ProfileResponse response = JsonConvert.DeserializeObject <ProfileResponse>(result.response);

                    if (response.UserId != 0) // check if user is exsting or not ,,, if 0 means update failed.
                    {
                        this.DeviceId = response.DeviceId;
                        this.UserId   = response.UserId.ToString();
                        await LocalStorage.SaveJsonToFile(this, "registration");

                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return(false);
            }
            finally
            {
                this.OperationInProgress = false;
            }

            return(false);
        }
示例#24
0
 private static void ExecuteCmdTask(Task task)
 {
     NotificationsHelper.DisplayMessage(Messages.ExecutingTask);
     SystemsHelper.ExecuteCommand(task.Value);
     task.TaskStatus = TaskStatus.Done;
 }
示例#25
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                #region validate email
                Institution   institution   = db.Institutions.Find(model.Institution);
                Resident      resident      = db.Residents.Find(1);
                Faculty       faculty       = db.Faculties.Find(1);
                Qualification qualification = db.Qualifications.Find(1);

                bool   emailValid = false;
                string username   = "";
                string extension  = "";

                try
                {
                    username  = model.Email.Substring(0, model.Email.IndexOf('@')).ToLower();
                    extension = model.Email.Substring(model.Email.IndexOf('@') + 1).ToLower();

                    // validate the email extension the student entered
                    if (institution.Extension1.Equals(extension) || institution.Extension2.Equals(extension) ||
                        institution.Extension3.Equals(extension) || institution.Extension4.Equals(extension) ||
                        institution.Extension5.Equals(extension))
                    {
                        emailValid = true;
                    }
                    else
                    {
                        emailValid = false;
                        ModelState.AddModelError("Email", "The student email address entered is not valid");
                    }
                }
                catch (Exception e)
                {
                    emailValid = false;
                    Trace.WriteLine(e.Message, "Invalid Email During Registration: " + model.Email);
                    ModelState.AddModelError("Email", "The student email address entered is not valid");
                }
                #endregion

                #region create user and send verification email
                if (emailValid)
                {
                    // set text info to be able to capitalize the product name
                    TextInfo ti = CultureInfo.CurrentCulture.TextInfo;

                    var user = new ApplicationUser()
                    {
                        UserName         = username,
                        Email            = model.Email,
                        Institution      = institution,
                        Faculty          = faculty,
                        Qualification    = qualification,
                        Resident         = resident,
                        Verified         = false,
                        RegistrationDate = DateTime.Now,
                        LastSeen         = DateTime.Now
                    };

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

                    if (result.Succeeded)
                    {
                        // get user info
                        var unverifiedUser = UserManager.FindByName(user.UserName);
                        var userFullName   = user.TitleID + " " + user.Intials + " " + user.Surname;

                        // send verification email
                        bool success = NotificationsHelper.SendEmailWithVerificationToken(user.Email, userFullName, user.UserName, ControllerContext);
                        if (!success)
                        {
                            ModelState.AddModelError("", "An error occured while sending the verifiaction email. We will try to send the verification again soon.");
                        }
                        else
                        {
                            Session.Add("currentInstitution", institution.abbreviation);
                            Session.Add("verifyName", userFullName);
                            return(RedirectToAction("Verification", "Account"));
                        }
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
                #endregion
            }

            // recreate form data
            model.Institutions = GetInstitutions();
            // If we got this far, something failed, redisplay form
            return(View("~/Views/Home/Index.cshtml", model));
        }
示例#26
0
        public async Task <ActionResult> RequestResetToken(RequestTokenModel model)
        {
            var success = false;

            if (ModelState.IsValid)
            {
                ApplicationUser user = null;
                #region validate email
                bool   emailValid = false;
                string username   = "";
                string extension  = "";
                string email      = model.Email.ToLower();
                try
                {
                    username  = model.Email.Substring(0, model.Email.IndexOf('@')).ToLower();
                    extension = model.Email.Substring(model.Email.IndexOf('@') + 1).ToLower();

                    var userInfo = (from u in db.Users
                                    where u.UserName.Equals(username) && u.Email.Equals(email) && u.Verified == true
                                    select u);

                    // validate the email extension and username the student entered
                    var count = await userInfo.CountAsync();

                    if (count > 0)
                    {
                        emailValid = true;
                        user       = await userInfo.FirstAsync();
                    }
                    else
                    {
                        emailValid = false;
                        ModelState.AddModelError("Email", "The student email address entered is not valid");
                    }
                }
                catch (Exception e)
                {
                    emailValid = false;
                    Trace.WriteLine(e.Message, "Reset Token Request");
                    ModelState.AddModelError("Email", "The student email address entered is not valid");
                }
                #endregion

                #region send reset email
                if (emailValid)
                {
                    string clientName = user.TitleID + " " + user.Intials + " " + user.Surname;

                    success = NotificationsHelper.SendPasswordResetEmail(user.Email, clientName, this.ControllerContext);
                    if (!success)
                    {
                        Trace.WriteLine(String.Format("*** WARNING:  A reset email to '{0}' failed.", user.Email));
                        ModelState.AddModelError("", "An error occured while sending a reset password email. Please try again later");
                    }
                }
                #endregion
            }

            ViewBag.Success = success;
            return(View());
        }
示例#27
0
 private void CreatePermissionsNotificationIfNeeded() =>
 NotificationsHelper.CreatePermissionsNotification();
        public static async Task Run(
            [BlobTrigger("images/{name}.{extension}")] CloudBlockBlob blobImage, string name, string extension, TraceWriter log)
        {
            var tc = new TelemetryClient();

            tc.InstrumentationKey = Settings.APPINSIGHTS_INSTRUMENTATIONKEY;

            Person p = new Person();
            string notificationMessage = "Error";
            bool   hasError            = true;;
            string json       = string.Empty;
            string deviceId   = string.Empty;
            var    collection = await client_document.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Settings.DatabaseId), new DocumentCollection { Id = Settings.PersonCollectionId }, new RequestOptions { OfferThroughput = 1000 });

            //get json file from storage
            CloudBlockBlob blobJson = await StorageHelper.GetBlockBlob($"{name}.json", Settings.AzureWebJobsStorage, "metadata", false);

            try
            {
                using (var memoryStream = new MemoryStream())
                {
                    blobJson.DownloadToStream(memoryStream);
                    json = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
                    p    = JsonConvert.DeserializeObject <Person>(json);
                }

                deviceId = p.ReportedByDeviceId;
                await NotificationsHelper.AddToRequest(deviceId, name);

                //validate record has not been processed before
                var query = client_document.CreateDocumentQuery <Person>(collection.Resource.SelfLink, new SqlQuerySpec()
                {
                    QueryText = $"SELECT * FROM Person p WHERE p.picture = '{name}.{extension}'"
                });
                int count = query.ToList().Count;
                if (count > 0)
                {
                    return;
                }
                log.Info(blobImage.Uri.AbsoluteUri);
                //determine if image has a face
                List <JObject> list = await client_face.DetectFaces(blobImage.Uri.AbsoluteUri);

                //validate image extension
                if (blobImage.Properties.ContentType != "image/jpeg")
                {
                    log.Info($"no valid content type for: {name}.{extension}");
                    await blobImage.DeleteAsync();

                    await blobJson.DeleteAsync();

                    notificationMessage = "Formato de fotografía incorrecto";
                    hasError            = true;
                    await NotificationsHelper.SendNotification(hasError, notificationMessage, name, deviceId);

                    return;
                }

                //if image has no faces
                if (list.Count == 0)
                {
                    log.Info($"there are no faces in the image: {name}.{extension}");
                    await blobImage.DeleteAsync();

                    await blobJson.DeleteAsync();

                    notificationMessage = $"La fotografía de {p.Name} {p.Lastname} no contiene rostros";
                    hasError            = true;
                    await NotificationsHelper.SendNotification(hasError, notificationMessage, name, deviceId);

                    return;
                }

                //if image has more than one face
                if (list.Count > 1)
                {
                    log.Info($"multiple faces detected in the image: {name}.{extension}");
                    await blobImage.DeleteAsync();

                    await blobJson.DeleteAsync();

                    notificationMessage = $"La fotografía de {p.Name} {p.Lastname} contiene mas de un rostro";
                    hasError            = true;
                    await NotificationsHelper.SendNotification(hasError, notificationMessage, name, deviceId);

                    return;
                }



                //register person in Face API
                CreatePerson resultCreatePerson = await client_face.AddPersonToGroup(p.Name + " " + p.Lastname);

                AddPersonFace resultPersonFace = await client_face.AddPersonFace(blobImage.Uri.AbsoluteUri, resultCreatePerson.personId);

                AddFaceToList resultFaceToList = await client_face.AddFaceToList(blobImage.Uri.AbsoluteUri);

                //Add custom settings
                p.IsActive        = 1;
                p.IsFound         = 0;
                p.FaceAPIFaceId   = resultFaceToList.persistedFaceId;
                p.FaceAPIPersonId = resultCreatePerson.personId;
                p.Picture         = $"{name}.jpg";

                await client_document.CreateDatabaseIfNotExistsAsync(new Database { Id = Settings.DatabaseId });

                var result = await client_document.CreateDocumentAsync(collection.Resource.SelfLink, p);

                var document = result.Resource;
            }
            catch (Exception ex)
            {
                tc.TrackException(ex);
                await blobImage.DeleteAsync();

                await blobJson.DeleteAsync();

                log.Info($"Error in file: {name}.{extension} - {ex.Message} {ex.StackTrace}");
                notificationMessage = $"Ocurrió un error durante el registro de {p.Name} {p.Lastname}";
                hasError            = true;
                await NotificationsHelper.SendNotification(hasError, notificationMessage, name, deviceId);

                return;
            }

            await blobJson.DeleteAsync();

            log.Info("person registered successfully");
            notificationMessage = $"El registro de {p.Name} {p.Lastname} se realizo correctamente";
            hasError            = false;
            await NotificationsHelper.SendNotification(hasError, notificationMessage, name, deviceId);
        }
示例#29
0
        /// <summary>
        /// Fetches the new keys if any.
        /// </summary>
        /// <returns>Paths to the temporary location where the zips are stored</returns>
        public async Task <IEnumerable <string> > PullNewKeys(ExposureNotificationWebService service, CancellationToken cancellationToken)
        {
            PullKeysParams requestParams = PullKeysParams.GenerateParams();

            LocalPreferencesHelper.DidFirstFileOfTheDayEndedWith204 = false;

            List <string> zipLocations      = new List <string>();
            bool          lastPull          = false;
            int?          lastBatchReceived = null;
            int?          lastReceivedStatusCodeFromRequest = null;

            while (!lastPull)
            {
                string requestUrl = requestParams.ToBatchFileRequest();

                ApiResponse <Stream> response = await service.GetDiagnosisKeys(requestUrl, cancellationToken);

                HttpHeaders headers = response.Headers;
                lastReceivedStatusCodeFromRequest = response.StatusCode;
                bool headersAreValid = true;

                if (response == null || (!response.IsSuccessfull))
                {
                    if (response?.StatusCode == 410)
                    {
                        NotificationsHelper.CreateNotification(NotificationsEnum.ApiDeprecated, 0);
                        string warning = "410 Api was deprecated";
                        _developerTools.AddToPullHistoryRecord(warning, requestUrl);
                        LogUtils.LogMessage(LogSeverity.WARNING, $"{_logPrefix}.{nameof(DownloadZips)}: {warning}");
                    }
                    else
                    {
                        //Failed to fetch new keys due to server error. This is already logged in the webservice.
                        _developerTools.AddToPullHistoryRecord($"{response.StatusCode} Server Error", requestUrl);
                    }
                    break; //Abort pulling
                }

                // If the server says 204: No Content, it means that there were no new keys (I.e. the request batch does not exist)
                if (response.StatusCode == 204)
                {
                    if (requestParams.Date.Date < SystemTime.Now().Date)
                    {
                        //If there were no new keys for a day which is not today, then move on to fetch keys for the next date.
                        requestParams.Date        = requestParams.Date.AddDays(1);
                        requestParams.BatchNumber = 1;
                        lastPull = false;
                    }
                    else
                    {
                        //There were no new keys to fetch for today
                        _developerTools.AddToPullHistoryRecord($"204 No Content - No new keys", requestUrl);
                        string warning = $"API {response.Endpoint} returned 204 No Content - No new keys since last pull";
                        LogUtils.LogMessage(LogSeverity.WARNING, $"{_logPrefix}.{nameof(DownloadZips)}: {warning}");
                        lastPull = true;
                    }
                }
                else
                {
                    try
                    {
                        int  lastBatchReceivedValue = int.Parse(headers.GetValues(LastBatchReturnedHeader).First());
                        bool moreBatchesExist       = bool.Parse(headers.GetValues(MoreBatchesExistHeader).First());

                        //If both headers parse (no exceptions), then save lastBatchValue to be persisted
                        lastBatchReceived = lastBatchReceivedValue;

                        if (moreBatchesExist)
                        {
                            //There are still more batches to fetch for the given date
                            requestParams.BatchNumber = (int)lastBatchReceived + 1;
                            lastPull = false;
                        }
                        else if (requestParams.Date.Date < SystemTime.Now().Date)
                        {
                            //If there were no new keys for a day which is not today, then move on to fetch keys for the next date.
                            requestParams.Date        = requestParams.Date.AddDays(1);
                            requestParams.BatchNumber = 1;
                            lastPull = false;
                        }
                        else
                        {
                            //There are no more batches to fetch for today. Try again in some hours.
                            lastPull = true;
                        }
                    }
                    catch (Exception e)
                    {
                        headersAreValid = false;
                        HandleErrorWhenPulling(e, $"Failed to parse {MoreBatchesExistHeader} or {LastBatchReturnedHeader} header.", requestUrl);
                        break; //Abort pulling
                    }
                }

                // Copy the zip stream in the response into a temp file
                if (response.StatusCode == 200 && headersAreValid)
                {
                    try
                    {
                        _developerTools.AddToPullHistoryRecord("200 OK", requestUrl);
                        string tmpFile = Path.Combine(ServiceLocator.Current.GetInstance <IFileSystem>().CacheDirectory, Guid.NewGuid() + ".zip");

                        FileStream tmpFileStream = File.Create(tmpFile);
                        await response.Data.CopyToAsync(tmpFileStream);

                        tmpFileStream.Close();

                        zipLocations.Add(tmpFile);
                    }
                    catch (Exception e)
                    {
                        HandleErrorWhenPulling(e, "Failed to save zip locally", requestUrl);
                        break; //Abort pulling
                    }
                }
            }

            if (zipLocations.Any() && lastBatchReceived != null)
            {
                //Persist the last batch that was fetched, to know which one to fetch next time the background task runs.
                LocalPreferencesHelper.LastPullKeysBatchNumberNotSubmitted = (int)lastBatchReceived;

                //Also save the last batchtype fetched
                LocalPreferencesHelper.LastPulledBatchType = requestParams.BatchType;
            }

            // Edge case for when pulling across multiple days ends up in 204 for the first file
            if (requestParams.Date.Date == SystemTime.Now().Date &&
                requestParams.BatchNumber == 1 &&
                lastReceivedStatusCodeFromRequest == 204)
            {
                LocalPreferencesHelper.DidFirstFileOfTheDayEndedWith204 = true;
            }

            return(zipLocations);
        }
示例#30
0
        public TestPageOld()
        {
            InitializeComponent();

            Logout                 = new RelayCommand(() => VKHelper.Reset());
            GetUniqueDeviceID      = new RelayCommand(async() => await(new MessageDialog(CoreHelper.GetUniqueDeviceID(), "UniqueDeviceID")).ShowAsync());
            GetDeviceName          = new RelayCommand(async() => await(new MessageDialog(CoreHelper.GetDeviceName(), "DeviceName")).ShowAsync());
            GetOperatingSystemName = new RelayCommand(async() => await(new MessageDialog(CoreHelper.GetOperatingSystemName(), "OperatingSystem")).ShowAsync());
            CaptchaForce           = new RelayCommand(async() => await(new CaptchaForceRequest()).ExecuteAsync());
            ShowLocalFolderPath    = new RelayCommand(async() => await(new MessageDialog(ApplicationData.Current.LocalFolder.Path, "LocalFolder Path")).ShowAsync());
            TurnOnNotification     = new RelayCommand(async() =>
            {
                bool result = await NotificationsHelper.Connect();
                await(new MessageDialog(result ? "Success" : "Fail", "Push notifications")).ShowAsync();
            });

            TestMessageFlags = new RelayCommand(async() =>
            {
                var flags = (VKMessageFlags)243;
                await(new MessageDialog(flags.ToString(), "243 as VKMessageFlags")).ShowAsync();
                flags = (VKMessageFlags)241;
                await(new MessageDialog(flags.ToString(), "241 as VKMessageFlags")).ShowAsync();
            });
            StartLongPolling = new RelayCommand(() =>
            {
                ServiceHelper.VKLongPollService.StartLongPolling();
                StopLongPolling.RaiseCanExecuteChanged();
                StartLongPolling.RaiseCanExecuteChanged();
            }, () => true);
            StopLongPolling = new RelayCommand(() =>
            {
                ServiceHelper.VKLongPollService.StopLongPolling();
                StartLongPolling.RaiseCanExecuteChanged();
                StopLongPolling.RaiseCanExecuteChanged();
            }, () => true);

            ShowToast = new RelayCommand(() =>
            {
                ((ChromeFrame)Frame).ShowPopup(new PopupMessage
                {
                    Title     = "Добро пожаловать в OneVK", Content = "Это уведомление вернет вас на тестовую страницу",
                    Parameter = new NavigateToPageMessage()
                    {
                        Page = AppViews.TestView
                    },
                    Type = PopupMessageType.Info
                });
            });

            GoToBotView = new RelayCommand(() =>
            {
                Messenger.Default.Send <NavigateToPageMessage>(new NavigateToPageMessage
                {
                    Page      = AppViews.BotView,
                    Operation = NavigationType.New
                });
            });
            GoToBlankPage = new RelayCommand(() => Frame.Navigate(typeof(BlankPage1)));

            ClearBadgeTile = new RelayCommand(() =>
            {
                BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear();
            });

            SendBadgeTile = new RelayCommand(() =>
            {
                var badge = new BadgeNumericNotificationContent(7).CreateNotification();
                BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badge);
            });

            SendMessageTile = new RelayCommand(() =>
            {
                var tile           = TileContentFactory.CreateTileSquare150x150IconWithBadge();
                tile.ImageIcon.Src = "ms-appx:///Assets/BadgeIcon.png";
                TileUpdateManager.CreateTileUpdaterForApplication().Update(tile.CreateNotification());

                var badge = new BadgeNumericNotificationContent(7).CreateNotification();
                BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badge);
            });

            SendToast = new RelayCommand(() =>
            {
                var toast               = ToastContentFactory.CreateToastText02();
                toast.Audio.Content     = ToastAudioContent.IM;
                toast.Duration          = ToastDuration.Long;
                toast.TextHeading.Text  = "OneVK";
                toast.TextBodyWrap.Text = "Это тестовое уведомление";

                ToastNotificationManager.CreateToastNotifier().Show(toast.CreateNotification());
            });

            StartVKSaver = new RelayCommand(async() =>
            {
                IVKSaverCommand command = new VKSaverStartAppCommand();
                await command.TryExecute();
            });
        }