Exemplo n.º 1
0
        public async Task <RequestEngineResult> DenyMovieById(int modelId, string denyReason)
        {
            var request = await MovieRepository.Find(modelId);

            if (request == null)
            {
                return(new RequestEngineResult
                {
                    ErrorMessage = "Request does not exist"
                });
            }

            request.Denied       = true;
            request.DeniedReason = denyReason;
            // We are denying a request
            NotificationHelper.Notify(request, NotificationType.RequestDeclined);
            await MovieRepository.Update(request);

            return(new RequestEngineResult
            {
                Message = "Request successfully deleted",
            });
        }
Exemplo n.º 2
0
        public async Task <RequestEngineResult> MarkAvailable(int modelId)
        {
            var request = await MusicRepository.Find(modelId);

            if (request == null)
            {
                return(new RequestEngineResult
                {
                    ErrorMessage = "Request does not exist"
                });
            }

            request.Available         = true;
            request.MarkedAsAvailable = DateTime.Now;
            NotificationHelper.Notify(request, NotificationType.RequestAvailable);
            await MusicRepository.Update(request);

            return(new RequestEngineResult
            {
                Message = "Request is now available",
                Result = true
            });
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Register(UserModel user)
        {
            var validUser = await registerService.RegisterUser(user);

            if (validUser.Content != null)
            {
                var userModel        = validUser.Content;
                var activationURL    = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/{"Registration"}/{"Activate"}?{"userID="}{userModel.UserID}";
                var notificationSent = await NotificationHelper.SendRegisterNotification(userModel.UserEmail, userModel.UserName, activationURL, config);

                if (!notificationSent)
                {
                    logger.LogError("Sending notification failed for userID:" + user.UserID);
                }
                ViewData["Notification"] = validUser.Message;
                return(RedirectToAction("Successfull", "Registration"));
            }
            else
            {
                SetNotification(validUser.Message, NotificationType.Failure, "Failed");
                return(View());
            }
        }
Exemplo n.º 4
0
        public ActionResult Create([Bind(Include = "answerBody")] Answer answer, int QA)
        {
            if (ModelState.IsValid)
            {
                answer.questionID = QA;
                answer.answererID = WebSecurity.CurrentUserId;
                answer.answerDate = DateTime.UtcNow;
                unitOfWork.AnswerRepository.Insert(answer);
                unitOfWork.Save();

                NotificationHelper.NotificationInsert(NotifType: NotificationType.QuestionAnswer,
                                                      elemId: answer.questionID);
                FeedHelper.FeedInsert(FeedType.Answer,
                                      answer.answerID,
                                      WebSecurity.CurrentUserId
                                      );

                UnitOfWork newAnswer = new UnitOfWork();
                var        nAnswer   = newAnswer.AnswerRepository.GetByID(answer.answerID);
                return(Json(new { Result = RenderPartialViewHelper.RenderPartialView(this, "AnswerPartial", nAnswer) }));
            }
            throw new ModelStateException(this.ModelState);
        }
Exemplo n.º 5
0
        private async Task <RequestEngineResult> AddMovieRequest(MovieRequests model, string movieName, string requestOnBehalf)
        {
            await MovieRepository.Add(model);

            var result = await RunSpecificRule(model, SpecificRules.CanSendNotification);

            if (result.Success)
            {
                await NotificationHelper.NewRequest(model);
            }

            await _requestLog.Add(new RequestLog
            {
                UserId      = requestOnBehalf.HasValue() ? requestOnBehalf : (await GetUser()).Id,
                RequestDate = DateTime.UtcNow,
                RequestId   = model.Id,
                RequestType = RequestType.Movie,
            });

            return(new RequestEngineResult {
                Result = true, Message = $"{movieName} has been successfully added!", RequestId = model.Id
            });
        }
Exemplo n.º 6
0
        public void LoadHistory()
        {
            try
            {
                _retrieverHistory = new AuditEntryRetriever(_dbSettings, _userObj);
                _dataCacheHistory = new DataCache(_retrieverHistory, 500);

                gridHistory.Columns.Clear();
                gridHistory.Rows.Clear();

                foreach (var column in _retrieverHistory.Columns)
                {
                    gridHistory.Columns.Add(column, column);
                }

                gridHistory.RowCount = _retrieverHistory.RowCount;
            }
            catch (Exception)
            {
                NotificationHelper.ShowNotification(this, NotificationHelper.NotificationType.Error,
                                                    "Failed to load history for this user. Please try again.");
            }
        }
Exemplo n.º 7
0
 public static void Run([TimerTrigger("0 8 0 * * *")] TimerInfo myTimer, ILogger log)
 {
     try
     {
         List <UserContactInfo> userContactInfoCollector = new List <UserContactInfo>();
         bool userContactsRetrieved = DbHelper.GetUserContactInfo(userContactInfoCollector);
         if (userContactsRetrieved)
         {
             string sendgridApi    = Environment.GetEnvironmentVariable("SendGrid_APIKEY", EnvironmentVariableTarget.Process);
             string assessmentLink = Environment.GetEnvironmentVariable("AssessmentBotLink", EnvironmentVariableTarget.Process);
             foreach (UserContactInfo userContact in userContactInfoCollector)
             {
                 NotificationHelper.SendEmail(userContact.EmailAddress, "*****@*****.**", "Contoso Health System Admin",
                                              assessmentLink, sendgridApi);
             }
         }
     }
     catch (Exception ex)
     {
         log.LogInformation(ex.Message);
         throw new Exception(ex.ToString());
     }
 }
Exemplo n.º 8
0
        private async Task <RequestEngineResult> AddAlbumRequest(AlbumRequest model)
        {
            await MusicRepository.Add(model);

            var result = await RunSpecificRule(model, SpecificRules.CanSendNotification);

            if (result.Success)
            {
                NotificationHelper.NewRequest(model);
            }

            await _requestLog.Add(new RequestLog
            {
                UserId      = (await GetUser()).Id,
                RequestDate = DateTime.UtcNow,
                RequestId   = model.Id,
                RequestType = RequestType.Album,
            });

            return(new RequestEngineResult {
                Result = true, Message = $"{model.Title} has been successfully added!", RequestId = model.Id
            });
        }
Exemplo n.º 9
0
        public async Task <ActionResult> Edit([Bind(Include = "Id,Body,Created,TicketId,AuthorId")] TicketComment ticketComment)
        {
            Ticket  ticket  = db.Tickets.Find(ticketComment.TicketId);
            Project project = db.Projects.First(p => p.Id == ticket.ProjectId);

            if ((User.IsInRole("Admin") ||
                 (User.IsInRole("ProjectManager") && project.Users.Any(u => u.Id == User.Identity.GetUserId())) ||
                 (User.IsInRole("Developer") && ticketComment.AuthorId == User.Identity.GetUserId()) ||
                 (User.IsInRole("Submitter") && ticketComment.AuthorId == User.Identity.GetUserId())) &&
                (ticket.IsArchived == false))
            {
                if (ModelState.IsValid)
                {
                    // Now add the TicketHistory for the TicketComment Edit
                    TicketComment oldComment    = db.TicketComments.AsNoTracking().First(t => t.Id == ticketComment.Id);
                    HistoryHelper ticketHistory = new HistoryHelper(User.Identity.GetUserId());
                    ticketHistory.AddHistoryEvent(ticketComment.TicketId, "Comment Edited", oldComment.Body, ticketComment.Body);

                    // Now send Notification, if ticket.AssignedUserId != Current User
                    if (ticket.AssignedUserId != null && ticket.AssignedUserId != User.Identity.GetUserId())
                    {
                        string             assignedUserEmailAddress = db.Users.Find(ticket.AssignedUserId).Email;
                        NotificationHelper notification             = new NotificationHelper(User.Identity.GetUserId());
                        await notification.AddCommentEditedNotification(ticket.Id, oldComment.Body, ticketComment.Body, assignedUserEmailAddress);
                    }

                    db.Entry(ticketComment).State = EntityState.Modified;
                    ticketComment.Updated         = DateTime.Now;
                    db.SaveChanges();

                    return(RedirectToAction("Details", "Tickets", new { id = ticket.Id }));
                }
                //ViewBag.TicketId = new SelectList(db.Tickets, "Id", "Title", ticketComment.TicketId);
                return(View(ticketComment));
            }
            return(RedirectToAction("Details", "Tickets", new { id = ticket.Id }));
        }
Exemplo n.º 10
0
        private void ExecuteBackupMsiCmd(object param)
        {
            if (string.IsNullOrEmpty(this.MsiBackupPath) || !Directory.Exists(this.MsiBackupPath))
            {
                NotificationHelper.WriteNotification("Chemin de backup invalide.");
            }
            else
            {
                var appList = this.AllSelected ? this._services.GetAllApplications() : (param as IEnumerable).Cast <Application>();
                NotificationHelper.WriteNotification(
                    string.Format("Début du backup de {0} application(s).", appList.Count())
                    );

                UIServices.SetBusyState();

                foreach (var app in appList)
                {
                    NotificationHelper.WriteNotification("Export de la liste des ressources pour " + app.Name + " dans " + this.MsiBackupPath + "...");

                    // TODO export MSI avec le resourcespec

                    string resourcesFileName;
                    var    trace = this._services.ExportResourceSpecFile(app.Name, this.MsiBackupPath, out resourcesFileName);
                    NotificationHelper.WriteNotification(trace);

                    this._services.ConfigResourcesSpecFile(
                        Path.Combine(this.MsiBackupPath, resourcesFileName),
                        this.ResourcesBindings,
                        this.ResourcesAssemblies,
                        this.ResourcesWebDirectories
                        );

                    trace = this._services.ExportMsiWithResourcesFilter(app.Name, this.MsiBackupPath, Path.Combine(this.MsiBackupPath, resourcesFileName));
                    NotificationHelper.WriteNotification(trace);
                }
            }
        }
Exemplo n.º 11
0
        public IActionResult DismissMinister(string authSessionCookie, string minister)
        {
            FirebaseToken firebaseToken = FirebaseAuth.DefaultInstance.VerifySessionCookieAsync(authSessionCookie).Result;
            string        firebaseUid   = firebaseToken.Uid;

            using (DatabaseContext database = new DatabaseContext())
            {
                User user = database.Users.Single(u => u.FirebaseUid == firebaseUid);

                Country country = database.Countries.Single(c => c.CountryName == user.CountryName);

                if (user.Ministry == MinistryHelper.MinistryCode.PrimeMinister)
                {
                    MinistryHelper.MinistryCode ministryCode = (MinistryHelper.MinistryCode)Enum.Parse(typeof(MinistryHelper.MinistryCode), minister);

                    if (!database.Users.Any(u => u.CountryName == country.CountryName && u.Ministry == ministryCode))
                    {
                        return(Content("Error: There is no minister to dismiss!"));
                    }

                    User ministerToDismiss = database.Users.Single(u => u.CountryName == country.CountryName && u.Ministry == ministryCode);
                    ministerToDismiss.CountryName = null;
                    ministerToDismiss.Ministry    = null;

                    Notification notification = NotificationHelper.GenerateDismissedMinisterNotification(user.Username, ministerToDismiss.Username, ministryCode);
                    database.Notifications.Add(notification);

                    database.SaveChanges();

                    return(Content("success"));
                }
                else
                {
                    return(StatusCode(403));
                }
            }
        }
Exemplo n.º 12
0
        public async Task <RequestEngineResult> ApproveChildRequest(int id)
        {
            var request = await TvRepository.GetChild().FirstOrDefaultAsync(x => x.Id == id);

            if (request == null)
            {
                return(new RequestEngineResult
                {
                    ErrorMessage = "Child Request does not exist"
                });
            }
            request.Approved = true;
            request.Denied   = false;

            foreach (var s in request.SeasonRequests)
            {
                foreach (var ep in s.Episodes)
                {
                    ep.Approved = true;
                }
            }

            await TvRepository.UpdateChild(request);

            if (request.Approved)
            {
                NotificationHelper.Notify(request, NotificationType.RequestApproved);
                await Audit.Record(AuditType.Approved, AuditArea.TvRequest, $"Approved Request {request.Title}", Username);

                // Autosend
                await TvSender.Send(request);
            }
            return(new RequestEngineResult
            {
                Result = true
            });
        }
Exemplo n.º 13
0
        public PortDuplicatorViewModel()
        {
            var container = ServiceLocator.Current.GetInstance <IUnityContainer>();

            // Initilisation et enregistrement du service
            var connectionString = container.Resolve <string>("BztMgmtDb");

            container.RegisterInstance <IPortDuplicatorServices>(
                new PortDuplicatorServices(connectionString)
                );

            this._services = ServiceLocator
                             .Current.GetInstance <IUnityContainer>()
                             .Resolve <IPortDuplicatorServices>();

            try {
                // initialisation de la liste de send ports
                this.SendPorts         = new ObservableCollection <SendPort>(this._services.GetAllSendPorts());
                this._sendPorts        = CollectionViewSource.GetDefaultView(this.SendPorts);
                this._sendPorts.Filter = x => string.IsNullOrEmpty(this.SndFilter) ? true : (((SendPort)x).Application.Name + ((SendPort)x).Name.ToUpper()).Contains(this.SndFilter.ToUpper());

                // initialisation de la liste de receive locations
                this.ReceiveLocations         = new ObservableCollection <ReceiveLocation>(this._services.GetAllreceiveLocations());
                this._receiveLocations        = CollectionViewSource.GetDefaultView(this.ReceiveLocations);
                this._receiveLocations.Filter =
                    x => string.IsNullOrEmpty(this.RcvLocFilter)
                                        ? true
                                        : (((ReceiveLocation)x).ReceivePort.Application.Name + ((ReceiveLocation)x).ReceivePort.Name + ((ReceiveLocation)x).Name.ToUpper()).Contains(this.RcvLocFilter.ToUpper());

                // commandes
                this.DuplicateSendPortCmd = new DuplicateSendPortCommand(this.DuplicateCallBack);
                this.DuplicateRcvLocCmd   = new DuplicateReceiveLocationCommand(this.DuplicateCallBack);
            }
            catch (Exception ex) {
                NotificationHelper.ShowError(ex);
            }
        }
Exemplo n.º 14
0
        public APIResponse Register(Register register)
        {
            APIResponse objResponse = new APIResponse();

            if (register != null)
            {
                var objuser = db.Users.FirstOrDefault(x => x.Email == register.Email);
                if (objuser == null)
                {
                    objuser               = new User();
                    objuser.Email         = register.Email;
                    objuser.Is_Active     = true;
                    objuser.Is_Subscribed = false;
                    objuser.Name          = register.Full_Name;
                    objuser.Password      = register.Password;
                    objuser.Device_ID     = "";

                    db.Users.Attach(objuser);
                    db.Entry(objuser).State = EntityState.Added;
                    db.SaveChanges();
                    NotificationHelper.SendRegistrationEmail(objuser.Email, objuser.Name);
                    objResponse.Message = "Registration Successfull, Please login";
                    objResponse.Status  = "1";
                }
                else
                {
                    objResponse.Message = "Email is already registered, Please login";
                    objResponse.Status  = "0";
                }
            }
            else
            {
                objResponse.Message = "Object is null";
                objResponse.Status  = "0";
            }
            return(objResponse);
        }
Exemplo n.º 15
0
        private async Task SendNotificationToApprover(string tenantId, string creatorId, string creatorFullName,
                                                      string creatorAvatar,
                                                      string newsId)
        {
            // Check if is send. Send news to approve for approve.
            var apiUrls = _configuration.GetApiUrl();

            if (apiUrls != null)
            {
                var listApprover = await new HttpClientService()
                                   .GetAsync <List <ApproverConfigViewModel> >($"{apiUrls.CoreApiUrl}/approver-configs/search/{tenantId}/{(int)ApproverConfigType.News}");

                if (listApprover != null && listApprover.Any())
                {
                    var notificationHelper = new NotificationHelper();

                    foreach (var approver in listApprover)
                    {
                        var notificationEvent = new NotificationEvent
                        {
                            TenantId       = tenantId,
                            Title          = $"<b>{creatorFullName}</b> {{send a news to you for approve.}}",
                            Content        = "",
                            SenderId       = creatorId,
                            SenderFullName = creatorFullName,
                            SenderAvatar   = creatorAvatar,
                            Url            = $"/news/detail/{newsId}",
                            ReceiverId     = approver.UserId,
                            Type           = NotificationType.Info,
                            IsSystem       = false
                        };

                        notificationHelper.Send(notificationEvent);
                    }
                }
            }
        }
Exemplo n.º 16
0
        // Handler for when the form is being closed
        private async void NotificationThread_FormClosing(object sender, FormClosingEventArgs e)
        {
            // If the (obsolete) setting Close to tray is turned off, or something other than the user
            // requested that this Ui should close, then allow it to close and terminate the application
            bool canCloseApp = (e.CloseReason == CloseReason.UserClosing && !Core.Settings.CloseToTray) || _userExiting || e.CloseReason != CloseReason.UserClosing;

            if (canCloseApp)
            {
                // Make sure the application is aware that it's closing
                _userExiting = true;

                // Remove the icon from the tray
                trayIcon.Visible = false;
                trayIcon.Dispose();

                // Unload any notifications that might be displayed
                NotificationHelper.ClearNotifications();

                // Stop any Scrobble related functions
                ScrobbleFactory.ScrobblingEnabled = false;

                // Give the scrobblers a chance to stop running cleanly
                await Task.Delay(2000).ConfigureAwait(false);

                ScrobbleFactory.Dispose();

                // Close any instance of the (obsolete) settings form
                _settingsUI?.Close();
            }
            else
            {
                // Close / Minimize to tray is turned on (default)
                // so cancel the disposal of the Ui, and hide it from the taskbar
                e.Cancel = true;
                MinimizeToTray();
            }
        }
Exemplo n.º 17
0
    internal static void StartNotification(
        Context context,
        MediaMetadata mediaMetadata,
        AndroidMedia.Session.MediaSession mediaSession,
        Object largeIcon,
        bool isPlaying)
    {
        var pendingIntent = PendingIntent.GetActivity(
            context,
            0,
            new Intent(context, typeof(MainActivity)),
            PendingIntentFlags.UpdateCurrent);
        MediaMetadata currentTrack = mediaMetadata;

        MediaStyle style = new MediaStyle();

        style.SetMediaSession(mediaSession.SessionToken);

        var builder = new Notification.Builder(context, CHANNEL_ID)
                      .SetStyle(style)
                      .SetContentTitle(currentTrack.GetString(MediaMetadata.MetadataKeyTitle))
                      .SetContentText(currentTrack.GetString(MediaMetadata.MetadataKeyArtist))
                      .SetSubText(currentTrack.GetString(MediaMetadata.MetadataKeyAlbum))
                      .SetSmallIcon(Resource.Drawable.player_play)
                      .SetLargeIcon(largeIcon as Bitmap)
                      .SetContentIntent(pendingIntent)
                      .SetShowWhen(false)
                      .SetOngoing(isPlaying)
                      .SetVisibility(NotificationVisibility.Public);

        builder.AddAction(NotificationHelper.GenerateActionCompat(context, Drawable.IcMediaPrevious, "Previous", MediaPlayerService.ActionPrevious));
        AddPlayPauseActionCompat(builder, context, isPlaying);
        builder.AddAction(NotificationHelper.GenerateActionCompat(context, Drawable.IcMediaNext, "Next", MediaPlayerService.ActionNext));
        style.SetShowActionsInCompactView(0, 1, 2);

        NotificationManagerCompat.From(context).Notify(NotificationId, builder.Build());
    }
Exemplo n.º 18
0
        public ActionResult Edit([Bind(Include = "Id,ProjectId,TicketTypeId,TicketStatusId,TicketPriorityId,OwnerUserId,AssignedToUserId,Title,Description,Created, Updated")] Ticket ticket)
        {
            if (ModelState.IsValid)
            {
                var oldTicket = db.Tickets.AsNoTracking().FirstOrDefault(t => t.Id == ticket.Id);
                db.Tickets.Attach(ticket);
                db.Entry(ticket).Property(x => x.TicketStatusId).IsModified   = true;
                db.Entry(ticket).Property(x => x.TicketTypeId).IsModified     = true;
                db.Entry(ticket).Property(x => x.TicketPriorityId).IsModified = true;
                db.Entry(ticket).Property(x => x.Title).IsModified            = true;
                db.Entry(ticket).Property(x => x.Description).IsModified      = true;

                if (ticket.AssignedToUserId != null)
                {
                    db.Entry(ticket).Property(x => x.AssignedToUserId).IsModified = true;
                }
                ticket.Updated = DateTime.Now;
                db.SaveChanges();

                NotificationHelper.CreateAssignmentNotification(oldTicket, ticket);
                NotificationHelper.ManageNotifications(oldTicket, ticket);
                //HistoryHelper
                var historyHelper = new HistoryHelper();
                historyHelper.RecordHistory(oldTicket, ticket);

                return(RedirectToAction("MyIndex"));
            }
            //new edit ends
            ViewBag.AssignedToUserId = new SelectList(db.Users, "Id", "FirstName", ticket.AssignedToUserId);

            ViewBag.OwnerUserId      = new SelectList(db.Users, "Id", "FirstName", ticket.OwnerUserId);
            ViewBag.ProjectId        = new SelectList(db.Projects, "Id", "Name", ticket.ProjectId);
            ViewBag.TicketPriorityId = new SelectList(db.TicketPriorities, "Id", "Name", ticket.TicketPriorityId);
            ViewBag.TicketStatusId   = new SelectList(db.TicketStatus, "Id", "StatusName", ticket.TicketStatusId);
            ViewBag.TicketTypeId     = new SelectList(db.TicketTypes, "Id", "Name", ticket.TicketTypeId);
            return(View(ticket));
        }
        public async Task <IActionResult> Delete(string categoryId)
        {
            if (this.categoryService.CategoryExists(categoryId) == false)
            {
                //Set notification
                NotificationHelper.SetNotification(TempData, NotificationType.Error, "Category doesn't exist");

                return(this.RedirectToAction(nameof(All)));
            }

            var products = this.categoryService.GetProductsForCategory(categoryId);

            if (products.Count > 0)
            {
                //Set notification
                NotificationHelper.SetNotification(TempData, NotificationType.Error, "This category could not be deleted because it is assigned to one or more products. Either remove all the products which use it or edit the category instead.");

                return(this.RedirectToAction(nameof(All)));
            }

            await this.categoryService.RemoveAsync(categoryId);

            return(this.RedirectToAction(nameof(All)));
        }
Exemplo n.º 20
0
        private async void AddFriend_Click(object sender, RoutedEventArgs e)
        {
            PostUsers_InvitationResult result = await HTTP.PostUsers_Invitation(App.AppVM.LocalUserVM.JWT, UIVM.SearchQuery, App.AppVM.LocalUserVM.LocalUser.Nickname + "(" + App.AppVM.LocalUserVM.LocalUser.Username + "): 交个朋友吧!");

            UIVM.SearchQuery = "";
            switch (result.StatusCode)
            {
            case PostUsers_InvitationResult.PostUsers_InvitationStatusCode.Success:
                NotificationHelper.ShowToast("已发送邀请,请等待对方接受。");
                break;

            case PostUsers_InvitationResult.PostUsers_InvitationStatusCode.NoThisUser:
                NotificationHelper.ShowToast("该用户不存在!");
                break;

            case PostUsers_InvitationResult.PostUsers_InvitationStatusCode.AlreadyContact:
                NotificationHelper.ShowToast("你和TA已经是好友啦!");
                break;

            default:
                NotificationHelper.ShowToast("未知错误,请稍后重试!");
                break;
            }
        }
Exemplo n.º 21
0
        public ActionResult SetTicketOnHold(int id)
        {
            var me     = User.Identity.GetUserId();
            var ticket = db.Tickets.Find(id);

            if (accessHelper.CanSeeDetails(ticket))
            {
                RedirectToAction("NotAllowedTicket", "Home");
            }
            var origin = db.Tickets.AsNoTracking().FirstOrDefault(tkt => tkt.Id == ticket.Id);

            if (ticket.AssignedToUserId == me)
            {
                ticket.TicketStatusId = db.TicketStatuses.Where(status => status.Name == "On Hold").FirstOrDefault().Id;
                ticket.Updated        = DateTime.Now;
                db.SaveChanges();
                NotificationHelper.CreateEditNotification(origin, ticket);
                return(RedirectToAction("Dashboard", "Home"));
            }
            else
            {
                return(RedirectToAction("DeveloperOnly", "Home"));
            }
        }
        public async Task <IActionResult> Remove(string productId, string errorReturnUrl)
        {
            if (this.productService.ProductExistsById(productId) == false)
            {
                this.ModelState.AddModelError("removeProduct_productId", "This product doesn't exist");
            }

            if (this.ModelState.IsValid == false)
            {
                //Add notification
                NotificationHelper.SetNotification(TempData, NotificationType.Error, "An error occured while removing product. Product wasn't removed");

                //Store needed info for get request in TempData
                TempData[GlobalConstants.ErrorsFromPOSTRequest] = ModelStateHelper.SerialiseModelState(this.ModelState);

                return(this.Redirect(errorReturnUrl));
            }

            await this.productService.RemoveProductAsync(productId);

            NotificationHelper.SetNotification(TempData, NotificationType.Success, "Successfully remove product.");

            return(this.RedirectToAction("All", "Products", new { area = "" }));
        }
        protected override async void OnStartup(StartupEventArgs e)
        {
            var serviceLocator = ServiceLocator.Default;

            serviceLocator.RegisterType <IRibbonService, RibbonService>();

#if DEBUG
            LogManager.AddDebugListener(false);
#endif
            Log.Info("Starting application");
            Log.Info("Initializing MVVM");
            await AppHelper.InitializeMVVM();

            Log.Info("Initializing Theme Helper");
            Initializations.InitializeThemeHelper();
            Log.Info("Initializing Shell");
            await AppHelper.InitializeShell();

            AppHelper.ShowFirstTimeSetup();
            Log.Info("Initializing Discord RPC");
            DiscordHelper.InitializeDiscordRPC();
            Log.Info("Initializing Github");
            Initializations.InitializeGitHub();
            Log.Info("Calling base.OnStartup");
            base.OnStartup(e);
            Log.Info("Initializing NodeNetwork");
            NNViewRegistrar.RegisterSplat();

            NotificationHelper.InitializeNotificationHelper();

            // Temp Fix for MainViewModel.OnClosing
            if (MainWindow != null)
            {
                MainWindow.Closing += OnClosing;
            }
        }
Exemplo n.º 24
0
        public void AddToastNotification(string message, NotificationType type, ToastNotificationOption options)
        {
            var positions = new NotificationHelper().position();

            var JsonSerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            if (options == null)
            {
                _tempData["options"] = JsonConvert
                                       .SerializeObject(new ToastNotificationOption(), JsonSerializerSettings);
            }
            else
            {
                _tempData["options"] = JsonConvert
                                       .SerializeObject(options, JsonSerializerSettings);
            }

            var msg = "toastr." + type + "('" + message + "')";

            _tempData["notification"] = msg;
        }
Exemplo n.º 25
0
        private void btnDeletePlaylist_Click(object sender, EventArgs e)
        {
            if (lbxPlaylist.SelectedItem == null)
            {
                NotificationHelper.Notice("Chưa chọn playlist để xóa");
                return;
            }

            if (NotificationHelper.Confirm("Bạn có muốn xóa playlist này?") == DialogResult.Yes)
            {
                try
                {
                    var playlist = lbxPlaylist.SelectedItem as Playlist;
                    DataHelper.DeletePlaylist(playlist.PlaylistId);
                    playlists.Remove(lbxPlaylist.SelectedItem as Playlist);
                    updateMediaSource(null);
                }
                catch (Exception ex)
                {
                    NotificationHelper.Notice("Không thể xóa playlist này");
                    NotificationHelper.Notice(ex.Message);
                }
            }
        }
Exemplo n.º 26
0
        private void deleteRecordMenuItem_Click(object sender, EventArgs e)
        {
            var rec = GetRecordBySelectedRow(_rowIdxSel);

            if (rec != null)
            {
                var confirm = NotificationHelper.ShowNotification(this, NotificationHelper.NotificationType.Warning, "Are you sure you wish to delete this record?", MessageBoxButtons.YesNoCancel);

                if (confirm == DialogResult.Yes)
                {
                    using (var oH = new ObjectHelper(_dbSettings, _user))
                    {
                        var deleteStatus = oH.DeleteRecord(rec);
                        if (!deleteStatus.Success)
                        {
                            NotificationHelper.ShowNotification(this, NotificationHelper.NotificationType.Error,
                                                                "Failed to delete this record. Please try again.");
                        }
                    }

                    RecordGridRefresh();
                }
            }
        }
Exemplo n.º 27
0
        public HttpResponseMessage PutComment(CommentModel commentModel)
        {
            AdModel   adModel;
            UserModel userModel;

            try
            {
                adModel = unitOfWork.AdRepository.Get(a => a.Id == commentModel.AdId).Select(x => Mapper.Map <AdModel>(x)).FirstOrDefault();
                adModel.CommentCounter++;
                var comment = Mapper.Map <Comment>(commentModel);
                comment.Counter      = 0;
                comment.PositiveVote = 0;
                comment.NegativeVote = 0;
                comment.Date         = DateTime.Now;
                //get username by userid
                userModel        = unitOfWork.UserRepository.Get(u => u.Id == comment.UserId).Select(x => Mapper.Map <UserModel>(x)).FirstOrDefault();
                comment.Username = userModel.Username;
                unitOfWork.CommentRepository.Insert(comment);
                var ad = Mapper.Map <Ad>(adModel);
                unitOfWork.AdRepository.Update(ad);
                unitOfWork.Save();
                //Send Notification about new comment:
                NotificationHelper nh = new NotificationHelper(ad.Id, ad.Name, ad.UserId);
                nh.Send();

                return(Create(comment));
            }
            catch (ObjectNotFoundException)
            {
                return(NotFound("Not Found. There is no Ad here"));
            }
            catch (Exception ex)
            {
                return(InternalServerError("Server Error: Can not insert Comments in database.", ex));
            }
        }
Exemplo n.º 28
0
        public AssembliesExplorerViewModel()
        {
            var container = ServiceLocator.Current.GetInstance <IUnityContainer>();

            // Initialisation et enregistrement du service
            var connectionString = container.Resolve <string>("BztMgmtDb");

            container.RegisterInstance <IAssembliesExplorerServices>(
                new AssembliesExplorerServices(connectionString)
                );

            this._services = ServiceLocator
                             .Current.GetInstance <IUnityContainer>()
                             .Resolve <IAssembliesExplorerServices>();

            try {
                this.Items         = new ObservableCollection <BtsAssembly>(this._services.GetAllAssemblies());
                this._items        = CollectionViewSource.GetDefaultView(this.Items);
                this._items.Filter = x => string.IsNullOrEmpty(this.ItemsFilter) ? true : (((BtsAssembly)x).Name.ToUpper()).Contains(this.ItemsFilter.ToUpper());
            }
            catch (Exception ex) {
                NotificationHelper.ShowError(ex);
            }
        }
Exemplo n.º 29
0
        private void LoadRecordTypes()
        {
            try
            {
                _retriever = new RecordTypeRetriever(_dbSettings);
                _dataCache = new DataCache(_retriever, 500);

                gridRecordTypes.Columns.Clear();
                gridRecordTypes.Rows.Clear();

                foreach (var column in _retriever.Columns)
                {
                    gridRecordTypes.Columns.Add(column, column);
                }

                gridRecordTypes.RowCount = _retriever.RowCount;
                txtRowCnt.Text           = _retriever.RowCount.ToString();
            }
            catch (Exception)
            {
                NotificationHelper.ShowNotification(this, NotificationHelper.NotificationType.Error,
                                                    "Failed to load record types. Please try again.");
            }
        }
Exemplo n.º 30
0
        private async Task <RequestEngineResult> AddMovieRequest(MovieRequests model, string movieName, string requestOnBehalf, bool isExisting, bool is4k)
        {
            if (is4k)
            {
                model.Has4KRequest = true;
            }
            if (!isExisting)
            {
                await MovieRepository.Add(model);
            }
            else
            {
                await MovieRepository.Update(model);
            }

            var result = await RunSpecificRule(model, SpecificRules.CanSendNotification, requestOnBehalf);

            if (result.Success)
            {
                await NotificationHelper.NewRequest(model);
            }

            await _mediaCacheService.Purge();

            await _requestLog.Add(new RequestLog
            {
                UserId      = requestOnBehalf.HasValue() ? requestOnBehalf : (await GetUser()).Id,
                RequestDate = DateTime.UtcNow,
                RequestId   = model.Id,
                RequestType = RequestType.Movie,
            });

            return(new RequestEngineResult {
                Result = true, Message = $"{movieName} has been successfully added!", RequestId = model.Id
            });
        }