示例#1
0
        /// <summary>
        /// 暂停指定任务计划
        /// </summary>
        /// <returns></returns>
        public static async Task <string> PauseScheduleJobAsync(ScheduleInfo scheduleInfo)
        {
            try
            {
                _scheduler = await GetSchedulerAsync();

                //使任务暂停
                await _scheduler.PauseJob(new JobKey(scheduleInfo.JobName, scheduleInfo.JobGroup));

                //更新数据库
                scheduleInfo.RunStatus = (int)JobStatus.Pause;
                Manager.UpdateScheduleStatus(scheduleInfo);
                var status = new StatusViewModel()
                {
                    Status = 0,
                    Msg    = "暂停任务计划成功",
                };

                return(JsonConvert.SerializeObject(status));
            }
            catch (Exception ex)
            {
                var status = new StatusViewModel()
                {
                    Status = -1,
                    Msg    = "暂停任务计划失败",
                };
                return(JsonConvert.SerializeObject(status));
            }
        }
        public async Task RetweetersAreLoaded()
        {
            // Arrange
            var status = DummyGenerator.CreateDummyStatus();

            status.ID = 123;

            var context = new Mock <IContextEntry>();

            context.Setup(c => c.Twitter.Search.SearchReplies(It.IsAny <Status>())).Returns(
                Task.FromResult(new List <Status>()));
            context.Setup(c => c.Twitter.Users.LookupUsers(It.IsAny <IEnumerable <ulong> >())).Returns(
                Task.FromResult(new List <UserEx>()));
            context.Setup(c => c.Twitter.Statuses.FindRetweeters(123, It.IsAny <int>())).Returns(
                Task.FromResult(new List <ulong>())).Verifiable();

            var statusVm = new StatusViewModel(status, context.Object, null, null);
            var vm       = new TweetDetailsViewModel
            {
                DisplayTweet = statusVm,
                Dispatcher   = new SyncDispatcher(),
                Context      = context.Object
            };

            // Act
            await vm.OnLoad(null);

            // Assert
            context.Verify(c => c.Twitter.Statuses.FindRetweeters(123, It.IsAny <int>()), Times.Once());
        }
示例#3
0
 public ComposeTweetData(StatusViewModel status = null, bool replyToAll = false, string text = null)
     : base(typeof(MessageDialog), typeof(IComposeTweetViewModel))
 {
     Status     = status;
     ReplyToAll = replyToAll;
     Text       = text;
 }
示例#4
0
        /// <summary>
        /// 恢复指定的任务计划**恢复的是暂停后的任务计划,如果是程序奔溃后 或者是进程杀死后的恢复,此方法无效
        /// </summary>
        /// <returns></returns>
        public static async Task <string> ResumeScheduleJobAsync(ScheduleInfo scheduleInfo)
        {
            try
            {
                scheduleInfo.RunStatus = (int)JobStatus.Waiting;
                //更新model
                Manager.UpdateScheduleStatus(scheduleInfo);
                _scheduler = await GetSchedulerAsync();

                //resumejob 恢复
                await _scheduler.ResumeJob(new JobKey(scheduleInfo.JobName, scheduleInfo.JobGroup));

                var status = new StatusViewModel()
                {
                    Status = 0,
                    Msg    = "恢复任务计划成功",
                };
                return(JsonConvert.SerializeObject(status));
            }
            catch (Exception ex)
            {
                var status = new StatusViewModel()
                {
                    Status = -1,
                    Msg    = "恢复任务计划失败",
                };
                return(JsonConvert.SerializeObject(status));
            }
        }
示例#5
0
        public async Task<IActionResult> AddEditStatus(int id, StatusViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Something Wrong");
                return PartialView("_AddEditStatus", model);
            }
            if (id > 0)
            {
                Status status = await _unitOfWork.Repository<Status>().GetByIdAsync(id);
                if (status != null)
                {
                    status.Name = model.Name;
                    status.Description = model.Description;
                    status.Level = model.Level;
                    status.ModifiedDate = DateTime.Now;
                    await _unitOfWork.Repository<Status>().UpdateAsync(status);
                }
            }
            else
            {
                Status statusUp = new Status();

                statusUp.Name = model.Name;
                statusUp.Description = model.Description;
                statusUp.Level = model.Level;
                statusUp.ModifiedDate = DateTime.Now;
                statusUp.AddedDate = DateTime.Now;
                await _unitOfWork.Repository<Status>().InsertAsync(statusUp);
            }
            return RedirectToAction("Index");
        }
示例#6
0
        public async Task <IActionResult> Cadastrar(StatusViewModel status)
        {
            status.Horario = DateTime.Now;
            _repository.Salvar(status.ViewModelToEntity());

            return(new OkObjectResult(status));
        }
示例#7
0
        private static void OnCurrentStatusPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
        {
            StatusPopup     popup  = source as StatusPopup;
            StatusViewModel status = (StatusViewModel)e.NewValue;

            popup.txtStatus.Text = status != null ? status.Code + " (" + status.Name + ")" : "";
        }
示例#8
0
        public ActionResult save([Bind(Include = "ID,Name")] StatusViewModel statusView)
        {
            bool status = false;

            if (statusView.Id == 0)
            {
                var statusdata = Mapper.Map <IEnumerable <Status>, IEnumerable <StatusViewModel> >(_statusService.GetAll());
                var mode       = (from s in statusdata where s.Id == statusView.Id select s.Name).ToString();
                if (mode == statusView.Name)
                {
                    status = false;
                    return(Json(new
                    {
                        status = status
                    }));
                }
                _statusService.AddStatus(Mapper.Map <StatusViewModel, Status>(statusView));
                _statusService.SaveChange();
                status = true;
            }
            else
            {
                //_statusService.UpdateStatus(Mapper.Map<StatusViewModel, Status>(statusView)).State = EntityState.Modified;
                //_statusService.SaveChange();
                status = true;
            }
            return(Json(new
            {
                status = status
            }));
        }
示例#9
0
        public ActionResult Create([Bind(Include = "ID,Nome,Descricao,DataCriacao,DateAlteracao,UsuarioCriacao,UsuarioEdicao,Ativo,Status,idCliente")] StatusViewModel StatusViewModel)
        {
            if (ModelState.IsValid)
            {
                StatusViewModel.DataCriacao    = DateTime.Now;
                StatusViewModel.DateAlteracao  = DateTime.Now;
                StatusViewModel.idCliente      = IDCliente;
                StatusViewModel.UsuarioCriacao = PixCoreValues.UsuarioLogado.IdUsuario;
                StatusViewModel.UsuarioEdicao  = PixCoreValues.UsuarioLogado.IdUsuario;

                using (var client = new WebClient())
                {
                    var keyUrl = ConfigurationManager.AppSettings["UrlAPI"].ToString();
                    var url    = keyUrl + "Seguranca/WpStatus/SalvarStatus/" + IDCliente + "/" + PixCoreValues.UsuarioLogado.IdUsuario;
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    var jss    = new System.Web.Script.Serialization.JavaScriptSerializer();
                    var Envio  = new { Status = StatusViewModel };
                    var data   = JsonConvert.SerializeObject(Envio); // jss.Serialize(Envio);
                    var result = client.UploadString(url, "POST", data);
                }
                return(RedirectToAction("Index"));
            }

            return(View(StatusViewModel));
        }
示例#10
0
        protected EditorViewModel(IViewModelServiceProvider serviceProvider, MostRecentlyUsedFileCollection mru, string editorName)
            : base(serviceProvider)
        {
            AssetsPlugin.RegisterPlugin(typeof(AssetsEditorPlugin));
            serviceProvider.Get <IEditorDialogService>();

            ClearMRUCommand           = new AnonymousCommand(serviceProvider, () => MRU.Clear());
            OpenSettingsWindowCommand = new AnonymousCommand(serviceProvider, OpenSettingsWindow);
            OpenWebPageCommand        = new AnonymousTaskCommand <string>(serviceProvider, OpenWebPage);
#if DEBUG
            DebugCommand = new AnonymousCommand(serviceProvider, DebugFunction);
#endif

            MRU = mru;
            MRU.MostRecentlyUsedFiles.CollectionChanged += MostRecentlyUsedFiles_CollectionChanged;
            UpdateRecentFiles();

            serviceProvider.Get <IEditorDialogService>().RegisterDefaultTemplateProviders();

            EditorName = editorName;
            if (Instance != null)
            {
                throw new InvalidOperationException("The EditorViewModel class can be instanced only once.");
            }

            Status = new StatusViewModel(ServiceProvider);
            Status.PushStatus("Ready");

            Instance = this;
        }
示例#11
0
        // GET: GetSecret
        public ActionResult GetSecret(string computer_key, string user, string pass)
        {
            var result        = new StatusViewModel();
            var signInManager = HttpContext.GetOwinContext().Get <ApplicationSignInManager>();
            var userManager   = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
            var dbUser        = userManager.FindByEmailAsync(user).Result;



            if (userManager.CheckPasswordAsync(dbUser, pass).Result)
            {
                // should check if it is an admin here too
                var computer = db.Computers.Where(c => c.key == computer_key).FirstOrDefault();
                if (computer != null)
                {
                    result.status  = "ok";
                    result.message = computer.secret;
                }
                else
                {
                    result.status  = "error";
                    result.message = "Key doesn't match computer";
                }
            }
            else
            {
                result.status  = "error";
                result.message = "Invalid user/pass";
            }
            return(new JsonResult()
            {
                Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
        public TextureManagementWindowViewModel(
            DomainActionBuilder actionBuilder,
            IDirectoryPicker directoryPicker,
            IEventPublisher eventPublisher,
            IFilePicker filePicker,
            IFindTextureManagementSettingsQuery findTextureManagementSettingsQuery,
            IImageProvider emptyImageProvider,
            ITaskRunner dispatcher)
        {
            _actionBuilder   = actionBuilder;
            _directoryPicker = directoryPicker;
            _eventPublisher  = eventPublisher;
            _filePicker      = filePicker;
            _findTextureManagementSettingsQuery = findTextureManagementSettingsQuery;
            _eventPublisher.Register(this);

            StatusViewModel = new StatusViewModel(dispatcher);
            TexturePreview  = new TexturePreviewViewModel(_actionBuilder, _eventPublisher, this, emptyImageProvider);

            AbortCommand         = new ActionCommand(AbortConversion, IsAbortConversionEnabled);
            CheckAllCommand      = new ActionCommand(CheckAll, IsCheckAllEnabled);
            ConvertMultiCommand  = new ActionCommand(() => _queue.QueueTask(ConvertMultiAsync), IsMultiConversionEnabled);
            ConvertSingleCommand = new ActionCommand(() => _queue.QueueTask(ConvertSingleAsync), IsSingleConversionEnabled);
            MoveToDestinationDirectoryCommand = new ActionCommand(MoveToDestinationDirectory, () => !DestinationDirectory.IsNullOrEmpty());
            MoveToSourceDirectoryCommand      = new ActionCommand(MoveToSourceDirectory, () => !SourceDirectory.IsNullOrEmpty());
            MultiChangedCommand             = new ActionCommand(() => _queue.QueueTask(OnChangedAsync), () => true);
            PickDestinationDirectoryCommand = new ActionCommand(() => _queue.QueueTask(PickDestinationDirectoryAsync), () => true);
            PickSourceDirectoryCommand      = new ActionCommand(() => _queue.QueueTask(PickSourceDirectoryAsync), () => true);
            SingleChangedCommand            = new ActionCommand(() => _queue.QueueTask(OnSingleChangedAsync), () => true);
            UncheckAllCommand = new ActionCommand(UncheckAll, IsUncheckAllEnabled);
        }
        protected override void OnNext()
        {
            if (CurrentStep == 0)
            {
                UpdateCanGoForward(false);

                SafeThreading.JoinableTaskFactory.Run(async() =>
                {
                    await SafeThreading.JoinableTaskFactory.SwitchToMainThreadAsync();
                    var output = await CleanupAndGenerateNewItemAsync();
                    if (output.HasChangesToApply)
                    {
                        base.OnNext();
                        await EnsureCodeViewerInitializedAsync();
                        WizardStatus.HasOverlayBox     = false;
                        NewItemSetup.EditionVisibility = Visibility.Collapsed;
                        SetChangesSummaryTitle();
                        NavigationService.Navigate(new ChangesSummaryView(output));
                    }
                    else
                    {
                        UpdateCanGoForward(true);
                        WizardStatus.SetStatus(StatusViewModel.Warning(string.Format(StringRes.NewItemHasNoChanges, NewItemSetup.ItemName, GetLocalizedTemplateTypeName(ConfigTemplateType).ToLower()), true, 5));
                    }
                });
            }
        }
        public void NewStatusIsOnlyRaisedWhenNotLoading()
        {
            // Arrange
            var context    = new Mock <IContextEntry>();
            var definition = new ColumnDefinition(ColumnType.User);
            var config     = new Mock <IConfig>();

            config.SetupGet(c => c.General).Returns(new GeneralConfig());
            var parser = new Mock <IStreamParser>();

            var  vm     = new TestColumn(context.Object, definition, config.Object, parser.Object);
            bool raised = false;

            vm.NewItem += (s, e) => raised = true;

            var status = new StatusViewModel(DummyGenerator.CreateDummyStatus(), context.Object, null, null);

            // Act
            vm.SetLoading(true);
            vm.RaiseStatusWrapper(status);
            bool whileLoading = raised;

            vm.SetLoading(false);
            vm.RaiseStatusWrapper(status);
            bool afterLoading = raised;

            // Assert
            Assert.IsFalse(whileLoading);
            Assert.IsTrue(afterLoading);
        }
示例#15
0
        internal Task LoadAsync(bool recreateModelAndMaterialFiles)
        {
            if (State == ModelDocumentState.Loading)
            {
                throw new EditorException("The previous model is still being loaded.");
            }

            State = ModelDocumentState.Loading;
            Reset();

            // Show status message.
            var status = new StatusViewModel
            {
                Message      = "Loading 3D model...",
                ShowProgress = true,
                Progress     = double.NaN,
            };

            _statusService.Show(status);

            var task = LoadAsync(Uri.LocalPath, recreateModelAndMaterialFiles);

            status.Track(task, "3D model loaded.", "Could not load 3D model.");

            return(task);
        }
示例#16
0
        public JsonResult checkin(string computer_key, string current_time)
        {
            if (CheckTime(current_time))
            {
                var computer = db.Computers.Where(x => x.key == computer_key).FirstOrDefault();
                var users    = db.SteamUsers.Where(x => x.inUseBy.id == computer.id).ToList();

                foreach (var i in users)
                {
                    i.inUse   = false;
                    i.inUseBy = null;
                }
                db.SaveChanges();
                var output = new StatusViewModel();
                output.status  = "success";
                output.message = "checked in" + " " + users.Count.ToString() + " " + "users";
                return(new JsonResult()
                {
                    Data = output
                });
            }
            else
            {
                var output = new StatusViewModel();
                output.status  = "failed";
                output.message = "request timing is off";
                return(new JsonResult()
                {
                    Data = output
                });
            }
        }
        public void Run()
        {
            this.workflowDesigner.Flush();
            MemoryStream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(this.workflowDesigner.Text));

            DynamicActivity activityToRun = ActivityXamlServices.Load(ms) as DynamicActivity;

            this.workflowApplication = new WorkflowApplication(activityToRun);

            this.workflowApplication.Extensions.Add(this.output);
            this.workflowApplication.Completed            = this.WorkflowCompleted;
            this.workflowApplication.Aborted              = this.WorkflowAborted;
            this.workflowApplication.OnUnhandledException = this.WorkflowUnhandledException;
            StatusViewModel.SetStatusText(Resources.RunningStatus, this.workflowName);

            try
            {
                this.running = true;
                this.workflowApplication.Run();
            }
            catch (Exception e)
            {
                this.output.WriteLine(ExceptionHelper.FormatStackTrace(e));
                StatusViewModel.SetStatusText(Resources.ExceptionStatus, this.workflowName);
                this.running = false;
            }
        }
示例#18
0
 protected void RaiseNewStatus(StatusViewModel status)
 {
     if (!IsLoading)
     {
         NewStatus?.Invoke(this, new StatusEventArgs(status));
     }
 }
示例#19
0
        public void RetweetsAreHandledCorrectly()
        {
            // Arrange
            var origUser = DummyGenerator.CreateDummyUser();

            origUser.UserID = 11;

            var originalStatus = DummyGenerator.CreateDummyStatus(origUser);

            originalStatus.ID = originalStatus.StatusID = 1;

            var rtUser = DummyGenerator.CreateDummyUser();

            rtUser.UserID = 22;
            var retweet = DummyGenerator.CreateDummyStatus(rtUser);

            retweet.RetweetedStatus = originalStatus;
            retweet.ID = retweet.StatusID = 2;

            // Act
            var vm = new StatusViewModel(retweet, null, null, null);

            // Assert
            Assert.AreEqual(22ul, vm.SourceUser.UserId);
            Assert.AreEqual(11ul, vm.User.UserId);

            Assert.AreEqual(1ul, vm.Model.ID);
        }
示例#20
0
        public void ReportingSpamCallsTwitterApi()
        {
            // Arrange
            var waitHandle = new ManualResetEventSlim(false);

            var context = new Mock <IContextEntry>();

            context.Setup(c => c.Twitter.ReportAsSpam(123)).Returns(Task.CompletedTask).Verifiable();

            var user = DummyGenerator.CreateDummyUser();

            user.UserID = 123;
            var status = DummyGenerator.CreateDummyStatus(user);

            var vm = new StatusViewModel(status, context.Object, null, null)
            {
                Dispatcher = new SyncDispatcher()
            };

            vm.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == nameof(StatusViewModel.IsLoading) && !vm.IsLoading)
                {
                    waitHandle.Set();
                }
            };

            // Act
            vm.ReportSpamCommand.Execute(null);
            waitHandle.Wait(1000);

            // Assert
            context.Verify(c => c.Twitter.ReportAsSpam(123), Times.Once());
        }
示例#21
0
        public void ReplyToAllIsAlwaysEnabled()
        {
            // Arrange
            var context = new Mock <IContextEntry>();

            var status = DummyGenerator.CreateDummyStatus();

            status.User.UserID = 123;
            status.Entities    = new Entities
            {
                UserMentionEntities = new List <UserMentionEntity>
                {
                    new UserMentionEntity {
                        Id = 123
                    }
                }
            };
            var vm = new StatusViewModel(status, context.Object, null, null);

            // Act
            bool single = vm.ReplyToAllCommand.CanExecute(null);

            status.User.UserID = 222;
            bool multiple = vm.ReplyToAllCommand.CanExecute(null);

            // Assert
            Assert.IsTrue(single);
            Assert.IsTrue(multiple);
        }
        async private void ToolbarItem_Save_Activated(object sender, EventArgs e)
        {
            var response = await DisplayAlert("Warning", "Are you sure you want to Create this Printer?", "Yes", "No");

            if (response)
            {
                var exists = await PrinterViewModel.SearchByName(ent_Name.Text);

                if (exists != null)
                {
                    await DisplayAlert("ERROR", "Name already Used. Please choose another", "OK");
                }
                else
                {
                    var status = await StatusViewModel.SearchByName(Status_Picker.Text);

                    var printColor = await PrintColorViewModel.SearchByName(Color_Picker.Text);

                    var printer = new PrinterViewModel()
                    {
                        Name           = ent_Name.Text,
                        StatusID       = status.ID,
                        ColorID        = printColor.ID,
                        Status         = status,
                        PrintColor     = printColor,
                        ProjectsQueued = 0,
                    };

                    await PrinterViewModel.Insert(printer);
                }
            }
        }
 public MainWindowViewModel(Dispatcher dispatcher)
 {
     EffectManager.Instance.SetDispatcher(dispatcher);
     StatusVm   = new StatusViewModel();
     LightingVm = new LightingViewModel();
     SettingsVm = new SettingsViewModel(dispatcher);
 }
示例#24
0
        public void ExecAsyncDisplaysErrorMessage()
        {
            // Arrange
            var waitHandle = new ManualResetEventSlim(false);

            var status  = DummyGenerator.CreateDummyStatus();
            var context = new Mock <IContextEntry>();

            context.Setup(c => c.Twitter.Statuses.RetweetAsync(It.IsAny <ulong>())).Throws(
                new TwitterQueryException("Error Message"));
            context.Setup(c => c.Notifier.DisplayMessage("Error Message", NotificationType.Error)).Verifiable();

            var vm = new StatusViewModel(status, context.Object, null, null);

            vm.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == nameof(StatusViewModel.IsLoading) && vm.IsLoading == false)
                {
                    waitHandle.Set();
                }
            };

            vm.Dispatcher = new SyncDispatcher();

            // Act
            vm.RetweetStatus(context.Object.Twitter);

            bool wasSet = waitHandle.Wait(1000);

            Thread.Sleep(50);

            // Assert
            Assert.IsTrue(wasSet);
            context.Verify(c => c.Notifier.DisplayMessage("Error Message", NotificationType.Error), Times.Once());
        }
        public void QuoteCommandOpensDialog()
        {
            // Arrange
            var statusVm = new StatusViewModel(DummyGenerator.CreateDummyStatus(), null, null, null);
            var context  = new Mock <IContextEntry>();

            context.SetupGet(c => c.UserId).Returns(1);
            context.Setup(c => c.ProfileImageUrl).Returns(new System.Uri("http://example.com/image.png"));

            var context2 = new Mock <IContextEntry>();

            context2.SetupGet(c => c.UserId).Returns(2);
            context2.Setup(c => c.ProfileImageUrl).Returns(new System.Uri("http://example.com/image.png"));

            var viewServices = new Mock <IViewServiceRepository>();

            viewServices.Setup(v => v.QuoteTweet(statusVm, It.IsAny <IEnumerable <ulong> >())).Returns(Task.CompletedTask).Verifiable();

            var vm = new RetweetDialogViewModel
            {
                Status = statusVm,
                ViewServiceRepository = viewServices.Object
            };

            vm.Accounts.Add(new AccountEntry(context.Object, false));
            vm.Accounts.Add(new AccountEntry(context2.Object, false));
            vm.Accounts.First().Use = true;

            // Act
            vm.QuoteCommand.Execute(null);

            // Assert
            viewServices.Verify(v => v.QuoteTweet(statusVm, It.IsAny <IEnumerable <ulong> >()), Times.Once());
        }
示例#26
0
        public StatusViewModel Atualizar(StatusViewModel status)
        {
            var retornoStatus = Mapper.Map <StatusViewModel>(_statusServices.Atualizar(Mapper.Map <Status>(status)));

            Commit();
            return(retornoStatus);
        }
示例#27
0
        private void TestStatus1()
        {
            // Simulate a short operation.
            var statusService = Editor.Services.GetInstance <IStatusService>();
            var status        = new StatusViewModel
            {
                Message      = "Operation in progress...",
                ShowProgress = true,
                Progress     = 0
            };

            statusService.Show(status);

            Observable.Interval(TimeSpan.FromMilliseconds(25))
            .Take(50)
            .ObserveOnDispatcher()              // StatusViewModel properties and methods need to be accessed on UI thread.
            .Subscribe(_ =>
            {
                status.Progress += 0.02;
            },
                       () =>
            {
                status.Message = "Operation completed successfully.";
                status.CloseAfterDefaultDurationAsync();
            });
        }
示例#28
0
        public StatusPageSW300()
        {
            InitializeComponent();

            BindingContext = MSProApp.Locator.StatusVM;
            MSProApp.Locator.StatusVM.CurrentPage = this;

            SetWaitingState();
            TrueIPDesc.FontSize     = Device.GetNamedSize(NamedSize.Small, typeof(Label));
            TrueIP.FontSize         = Device.GetNamedSize(NamedSize.Small, typeof(Label));
            LoadingMessage.FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label));
            ConnectionStatusDescription.FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label));

            RefreshActiveConnection.FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Button));
            ShowTipsBtn.FontSize             = Device.GetNamedSize(NamedSize.Micro, typeof(Button));


            MessagingCenter.Subscribe <StatusPage>(this, "BootstrappFinished", (sender) =>
            {
                RemoveWaitingState();
                StatusViewModel svm = MSProApp.Locator.StatusVM;
                Device.BeginInvokeOnMainThread(() =>
                {
                    TrueIP.Text = svm.GetTrueIP();
                });
            });
            MessagingCenter.Subscribe <StatusPage>(this, "FalseIPChanged", (sender) =>
            {
                StatusViewModel svm = MSProApp.Locator.StatusVM;
                Device.BeginInvokeOnMainThread(() =>
                {
                    FalseIPList.ItemsSource = svm.FalseIPsList;
                });
            });
        }
        /// <summary>
        /// Checks if the notification should be shown.
        /// </summary>
        /// <param name="currentStatus">The current status.</param>
        /// <param name="stateToCheck">The state to check.</param>
        /// <param name="notificationConfiguration">The notification configuration.</param>
        /// <returns>True if the notification should be shown, otherwise false.</returns>
        internal bool CheckNotificationShow(StatusViewModel currentStatus, ObservationState stateToCheck, NotificationConfiguration notificationConfiguration)
        {
            var enabledCheck = this.GetEnabledStateCheck(stateToCheck, notificationConfiguration);

            if (!enabledCheck())
            {
                return(false);
            }

            var connectorSnapshots = currentStatus.Parent.ConnectorSnapshots;

            if (connectorSnapshots == null || connectorSnapshots.Count == 1 || notificationConfiguration.OnlyIfChanged == false)
            {
                return(currentStatus.State == stateToCheck);
            }

            var historicalOrderedConnectorSnapshots = connectorSnapshots.Reverse().Skip(1);

            foreach (var historicalOrderedConnectorSnapshot in historicalOrderedConnectorSnapshots)
            {
                var snapshotEnabledCheck = this.GetEnabledStateCheck(historicalOrderedConnectorSnapshot.State, notificationConfiguration);
                if (snapshotEnabledCheck() && currentStatus.State == stateToCheck)
                {
                    if (historicalOrderedConnectorSnapshot.State != currentStatus.State)
                    {
                        return(true);
                    }

                    return(false);
                }
            }

            return(false);
        }
示例#30
0
        /// <inheritdoc/>
        public void Show(StatusViewModel viewModel)
        {
            if (!WindowsHelper.CheckAccess())
                throw new InvalidOperationException("Cross-thread operation not valid: The method needs to be invoked on the UI thread.");

            _statusConductor.ActivateItem(viewModel);
        }
示例#31
0
        public void ToastsAreNotRaisedWhenDisabledInConfig()
        {
            // Arrange
            var context = new Mock <IContextEntry>();
            var config  = new Mock <IConfig>();

            config.SetupGet(c => c.Notifications).Returns(new NotificationConfig {
                ToastsEnabled = false
            });
            var viewServices = new Mock <IViewServiceRepository>();

            viewServices.Setup(v => v.OpenNotificationFlyout(It.IsAny <NotificationViewModel>())).Verifiable();

            var notifier = new Notifier(config.Object, null, new SyncDispatcher(), viewServices.Object);

            var status = new StatusViewModel(DummyGenerator.CreateDummyStatus(), context.Object, null, null);

            // Act
            notifier.OnItem(status, new ColumnNotifications {
                Toast = true
            });

            // Assert
            viewServices.Verify(v => v.OpenNotificationFlyout(It.IsAny <NotificationViewModel>()), Times.Never());
        }
示例#32
0
        /// <inheritdoc/>
        protected override void OnStartup()
        {
            AddDataTemplates();
            AddStatusBarItems();

            // Set default status.
            var status = new StatusViewModel { Message = "Ready" };
            Show(status);
        }
示例#33
0
        public ApplicationViewModel()
        {
            BetManager = new BettingManager();
            Settings = new SettingsViewModel();
            Session = new SessionViewModel();
            Status = new StatusViewModel();
            Statistics = new StatisticsViewModel();

            RedBlackBalancesLine = new System.Windows.Shapes.Polyline
            {
                StrokeThickness = 2,
                Stroke = Brushes.Red
            };
            EvenOddBalancesLine = new System.Windows.Shapes.Polyline
            {
                StrokeThickness = 2,
                Stroke = Brushes.Black
            };
            To18From19BalancesLine = new System.Windows.Shapes.Polyline
            {
                StrokeThickness = 2,
                Stroke = Brushes.Green
            };
        }
示例#34
0
        public ActionResult Status(string id)
        {
            var model = new StatusViewModel();
            model.BuildingId = id;

            try
            {
                var forecasts = repository.FirstOrDefault(x => x.MeasurementId == id).Forecasts;
                foreach (var forecast in forecasts)
                {
                    model.Charts.Add(GetChart(forecast));
                }

                List<Tuple<DateTime, int>> winnerModels;
                model.Charts.Add(GetTrustIndexChart(id, out winnerModels));
                model.Charts.Add(GetWinnerModelsChart(winnerModels));

                int i = 0;
                foreach (var chart in model.Charts)
                {
                    chart.Id = (i++).ToString();
                }

                return View(model);
            }
            catch (Exception e)
            {
                return Content(e.Message);
            }
        }
示例#35
0
        internal Task LoadAsync(bool recreateModelAndMaterialFiles)
        {
            if (State == ModelDocumentState.Loading)
                throw new EditorException("The previous model is still being loaded.");

            State = ModelDocumentState.Loading;
            Reset();

            // Show status message.
            var status = new StatusViewModel
            {
                Message = "Loading 3D model...",
                ShowProgress = true,
                Progress = double.NaN,
            };
            _statusService.Show(status);

            var task = LoadAsync(Uri.LocalPath, recreateModelAndMaterialFiles);

            status.Track(task, "3D model loaded.", "Could not load 3D model.");

            return task;
        }
示例#36
0
        private void TestStatus1()
        {
            // Simulate a short operation.
            var statusService = Editor.Services.GetInstance<IStatusService>();
            var status = new StatusViewModel
            {
                Message = "Operation in progress...",
                ShowProgress = true,
                Progress = 0
            };
            statusService.Show(status);

            Observable.Interval(TimeSpan.FromMilliseconds(25))
                      .Take(50)
                      .ObserveOnDispatcher()    // StatusViewModel properties and methods need to be accessed on UI thread.
                      .Subscribe(_ =>
                      {
                          status.Progress += 0.02;
                      },
                      () =>
                      {
                          status.Message = "Operation completed successfully.";
                          status.CloseAfterDefaultDurationAsync();
                      });
        }
示例#37
0
        private async void ShowAssembler()
        {
            if (_isBusy)
                return;

            var document = _documentService.ActiveDocument as TextDocument;
            if (document == null || document.DocumentType.Name != ShaderDocumentFactory.FxFile)
                return;

            Logger.Debug("Generating assembly code for \"{0}\".", document.GetName());

            bool isSaved = !document.IsUntitled && !document.IsModified;
            if (!isSaved)
                isSaved = _documentService.Save(document);

            if (!isSaved || document.Uri == null)
            {
                Logger.Debug("Document was not saved. Generating assembly code canceled by user.");
                return;
            }

            var status = new StatusViewModel
            {
                Message = "Generating assembly code...",
                ShowProgress = true,
                Progress = double.NaN
            };
            _statusService.Show(status);

            // Disable buttons to avoid reentrance.
            _isBusy = true;
            UpdateCommands();

            try
            {
                var fxc = Editor.Services.GetInstance<Fxc>().ThrowIfMissing();
                string outputFile = await Task.Run(() => fxc.Run(document.Uri.LocalPath));

                status.Progress = 100;
                status.IsCompleted = true;

                if (!string.IsNullOrWhiteSpace(outputFile))
                {
                    status.Message = "Generating assembly code succeeded.";

                    // Show assembler output as a new document with standard syntax-highlighting.
                    var assemblerDocument = (TextDocument)_documentService.New(_shaderDocumentFactory.DocumentTypes.First());
                    assemblerDocument.AvalonEditDocument.Insert(0, File.ReadAllText(outputFile));

                    // The user usually don't wants to save the assembler output. Clearing 
                    // the undo stack resets IsModified. The user won't be prompted to save 
                    // the document.
                    assemblerDocument.AvalonEditDocument.UndoStack.ClearAll();

                    // Set document name.
                    string format = Path.GetFileNameWithoutExtension(document.Uri.LocalPath) + ".asm ({0})";
                    string name;
                    int index = 0;
                    do
                    {
                        name = string.Format(format, index);
                        index++;
                    } while (_documentService.Documents.Any(doc => doc.GetName() == name));

                    assemblerDocument.UntitledName = name;

                    if (File.Exists(outputFile))
                        File.Delete(outputFile);
                }
                else
                {
                    _outputService.Show();

                    status.Message = "Generating assembly code failed.";
                    status.ShowProgress = false;
                }
            }
            catch (Exception exception)
            {
                Logger.Warn(exception, "Generating assembly code failed.");

                _outputService.WriteLine(Invariant($"Exception: {exception.Message}"));
                _outputService.Show();

                status.Message = "Generating assembly code failed.";
                status.ShowProgress = false;
            }

            _isBusy = false;
            UpdateCommands();

            status.CloseAfterDefaultDurationAsync().Forget();
        }
示例#38
0
        private void TestStatus2()
        {
            var statusService = Editor.Services.GetInstance<IStatusService>();

            // Simulate a short operation.
            var status = new StatusViewModel
            {
                Message = "Operation in progress...",
                CancellationTokenSource = new CancellationTokenSource(),
            };

            var task = DummyOperationAsync(status.CancellationTokenSource.Token, status);
            statusService.Show(status);
            status.Track(task, "Operation completed successfully.", "Operation failed.", "Operation canceled.");
        }
示例#39
0
        private async void Analyze()
        {
            if (_isBusy)
                return;

            var document = _documentService.ActiveDocument as TextDocument;
            if (document == null || document.DocumentType.Name != ShaderDocumentFactory.FxFile)
                return;

            Logger.Debug("Analyzing effect {0}.", document.GetName());

            bool isSaved = !document.IsUntitled && !document.IsModified;
            if (!isSaved)
                isSaved = _documentService.Save(document);

            if (!isSaved || document.Uri == null)
            {
                Logger.Debug("Document was not saved. Analysis canceled by user.");
                return;
            }

            _outputService.Clear();

            var status = new StatusViewModel
            {
                Message = "Analyzing...",
                ShowProgress = true,
                Progress = double.NaN,
            };
            _statusService.Show(status);

            // Disable buttons to avoid reentrance.
            _isBusy = true;
            UpdateCommands();

            try
            {
                var shaderPerf = Editor.Services.GetInstance<ShaderPerf>().ThrowIfMissing();
                var success = await Task.Run(() => shaderPerf.Run(document));

                status.Progress = 100;
                status.IsCompleted = true;

                if (success)
                {
                    status.Message = "Analysis succeeded.";
                }
                else
                {
                    _outputService.Show();
                    status.Message = "Analysis failed.";
                    status.ShowProgress = false;
                }
            }
            catch (Exception exception)
            {
                Logger.Warn(exception, "Analysis failed.");

                _outputService.WriteLine(Invariant($"Exception: {exception.Message}"));
                _outputService.Show();

                status.Message = "Analysis failed.";
                status.ShowProgress = false;
            }

            // Enable buttons.
            _isBusy = false;
            UpdateCommands();

            status.CloseAfterDefaultDurationAsync().Forget();
        }
示例#40
0
        /// <summary>
        /// Called when an object is dropped on the main window of the application.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="eventArgs">
        /// The <see cref="DragEventArgs"/> instance containing the event data.
        /// </param>
        private async void OnDrop(object sender, DragEventArgs eventArgs)
        {
            // Avoid re-entrance.
            if (_inDrop)
                return;

            Logger.Debug("Object dropped on main window via drag-and-drop.");

            try
            {
                _inDrop = true;
                if (eventArgs.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    string[] fileNames = eventArgs.Data.GetData(DataFormats.FileDrop) as string[];
                    if (fileNames != null && fileNames.Length > 0)
                    {
                        eventArgs.Handled = true;

                        // Show status message and Cancel button.
                        var token = new CancellationTokenSource();
                        var status = new StatusViewModel
                        {
                            Message = "Opening files...",
                            Progress = 0,
                            ShowProgress = true,
                            CancellationTokenSource = token
                        };
                        _statusService.Show(status);

                        // Determine on which DockPane the files were dropped.
                        var targetObject = eventArgs.Source as DependencyObject;
                        var targetPane = targetObject?.GetVisualAncestors()
                                                      .OfType<DockTabPane>()
                                                      .Select(dockTabPane => dockTabPane.DataContext as IDockTabPane)
                                                      .FirstOrDefault();

                        for (int i = 0; i < fileNames.Length; i++)
                        {
                            string fileName = fileNames[i];

                            if (token.IsCancellationRequested || Keyboard.IsKeyDown(Key.Escape))
                            {
                                Logger.Info("Opening files via drag-and-drop canceled.");
                                status.Message = "Opening files canceled.";
                                status.IsCompleted = true;
                                status.ShowProgress = false;
                                await status.CloseAfterDefaultDurationAsync();
                                return;
                            }

                            Logger.Info(CultureInfo.InvariantCulture, "Opening file \"{0}\" via drag-and-drop.", fileName);

                            try
                            {
                                // Open document.
                                var document = Open(new Uri(fileName));

                                // Update status.
                                status.Progress = (double)(i + 1) / fileNames.Length;

                                // Move document to target pane.
                                if (targetPane != null && document != null)
                                {
                                    var viewModel = document.ViewModels.FirstOrDefault();
                                    Editor.DockStrategy.Dock(viewModel, targetPane, DockPosition.Inside);
                                }
                            }
                            catch (Exception exception)
                            {
                                Logger.Warn(exception, CultureInfo.InvariantCulture, "Could not open file \"{0}\" via drag-and-drop.", fileName);
                            }

                            // Redraw GUI and keep application responsive.
                            await Dispatcher.Yield();

                            if (Editor.IsShuttingDown)
                                break;
                        }

                        await status.CloseAsync();
                    }
                }
            }
            finally
            {
                _inDrop = false;
            }
        }
示例#41
0
 public static void CreateStatus()
 {
     if (_status == null)
     {
         _status = new StatusViewModel();
     }
 }
 public ValidationResult Gravar(StatusViewModel status)
 {
     var statusSalvar = Mapper.Map<Status>(status);
     return _service.Gravar(statusSalvar);
 }
        public ActionResult Share(long id)
        {
            try
            {
                var oPost = oCore.iRepositories.IPostRepository.Select(id);
                if (oPost == null || !oPost.IsActive || !oPost.IsStatus)
                {
                    return PartialView("~/Views/Posts/ShareConfirm.cshtml", new Tuple<Post, bool, string>(oPost, false, Resources.Resources.OperationError));
                }

                var oModel = new StatusViewModel()
                {
                    id = oPost.id,
                    categoryId = oPost.categoryId
                };

                ViewBag.SharingPost = oPost;

                return PartialView(oModel);
            }
            catch (Exception ex)
            {
                //Salva o erro no arquivo de log do sistema
                ex.Save(new StackTrace(ex, true), ErrorLog.system);
            }

            return PartialView("~/Views/Posts/ShareConfirm.cshtml", new Tuple<Post, bool, string>(null, false, Resources.Resources.ProcessError));
        }
示例#44
0
        private async Task<IEnumerable<Document>> OpenAsync(IList<string> fileNames)
        {
            if (fileNames.Count == 1)
            {
                // ---- Single document.
                var document = Open(new Uri(fileNames[0]));
                return (document != null) ? new[] { document } : Enumerable.Empty<Document>();
            }
            else
            {
                // ----- Multiple documents: Show status message and Cancel button.
                var numberOfFiles = fileNames.Count;
                var documents = new List<Document>(numberOfFiles);
                var status = new StatusViewModel
                {
                    Message = "Opening files...",
                    Progress = 0,
                    ShowProgress = true,
                    CancellationTokenSource = new CancellationTokenSource()
                };
                _statusService.Show(status);
                var token = status.CancellationTokenSource.Token;

                for (int i = 0; i < numberOfFiles; i++)
                {
                    string fileName = fileNames[i];

                    if (token.IsCancellationRequested || Keyboard.IsKeyDown(Key.Escape))
                    {
                        Logger.Info("Opening files canceled.");
                        status.Message = "Opening files canceled.";
                        status.ShowProgress = false;
                        status.IsCompleted = true;
                        status.CloseAfterDefaultDurationAsync().Forget();
                        return documents;
                    }

                    if (Editor.IsShuttingDown)
                        break;

                    // Open document.
                    var document = Open(new Uri(fileName));

                    // Update status.
                    status.Progress = (double)(i + 1) / numberOfFiles;

                    if (document != null)
                    {
                        documents.Add(document);

                        // Redraw GUI and keep app responsive.
                        await Dispatcher.Yield();

                        if (Editor.IsShuttingDown)
                            break;
                    }
                }

                status.CloseAsync().Forget();
                return documents;
            }
        }
示例#45
0
        private async void Build()
        {
            // Abort if a build is already in progress.
            if (_isBusy)
                return;

            var document = _documentService.ActiveDocument as TextDocument;
            if (document == null || document.DocumentType.Name != ShaderDocumentFactory.FxFile)
                return;

            Logger.Debug("Building effect {0}.", document.GetName());

            // Document must be saved to file system before we can build it.
            bool isSaved = !document.IsUntitled && !document.IsModified;
            if (!isSaved)
                isSaved = _documentService.Save(document);

            // Abort if the save operation was canceled.
            if (!isSaved || document.Uri == null)
            {
                Logger.Debug("Document was not saved. Build canceled by user.");
                return;
            }

            // Delete old Error window items.
            _outputService.Clear();
            RemoveErrors(document);

            // Push a new message to the status bar.
            var status = new StatusViewModel
            {
                Message = "Building effect...",
                ShowProgress = true,
                Progress = double.NaN,
            };
            _statusService.Show(status);

            // Disable buttons to avoid re-entrance.
            _isBusy = true;
            UpdateCommands();

            int successes = 0;
            int failures = 0;
            int exceptions = 0;

            var goToLocationCommand = new DelegateCommand<Error>(GoToLocation);
            if (IsFxcEffectProcessorEnabled)
            {
                try
                {
                    Logger.Info("Building effect using FXC.");
                    _outputService.WriteLine($"----- Build started: {document.GetName()}, Compiler: FXC -----");

                    var result = await BuildFxcAsync(Editor.Services, document, goToLocationCommand);
                    if (result.Item1)
                        successes++;
                    else
                        failures++;

                    AddErrors(document, result.Item2, result.Item1);
                }
                catch (Exception exception)
                {
                    exceptions++;
                    Logger.Warn(exception, "Build using FXC failed.");
                    _outputService.WriteLine(Invariant($"Exception: {exception.Message}"));
                    _outputService.Show();
                }
            }

            if (IsMonoGameEffectProcessorEnabled)
            {
                try
                {
                    Logger.Info("Building effect using MonoGame.");
                    _outputService.WriteLine($"----- Build started: {document.GetName()}, Compiler: MonoGame -----");

                    var result = await BuildMonoGameAsync(Editor.Services, Editor.ApplicationName, document, goToLocationCommand);
                    if (result.Item1)
                        successes++;
                    else
                        failures++;

                    AddErrors(document, result.Item2, result.Item1);
                }
                catch (Exception exception)
                {
                    exceptions++;

                    Logger.Warn(exception, "Build using MonoGame failed.");
                    _outputService.WriteLine(Invariant($"Exception: {exception.Message}"));
                    _outputService.Show();
                }
            }

            if (IsXnaEffectProcessorEnabled)
            {
                try
                {
                    Logger.Info("Building effect using XNA.");
                    _outputService.WriteLine($"----- Build started: {document.GetName()}, Compiler: XNA -----");

                    var result = await BuildXnaAsync(Editor.Services, document, goToLocationCommand);
                    if (result.Item1)
                        successes++;
                    else
                        failures++;

                    AddErrors(document, result.Item2, result.Item1);
                }
                catch (Exception exception)
                {
                    exceptions++;
                    Logger.Warn(exception, "Build using XNA failed.");
                    _outputService.WriteLine(Invariant($"Exception: {exception.Message}"));
                    _outputService.Show();
                }
            }

            _outputService.WriteLine($"========== Build completed: {successes} succeeded, {failures + exceptions} failed ==========");

            if (failures + exceptions == 0)
            {
                status.Progress = 100;
                status.IsCompleted = true;
            }
            else
            {
                status.Message = "Build failed.";
                status.ShowProgress = false;
                _outputService.Show();

                if (failures > 0)
                    _errorService?.Show();
            }

            // Enable buttons.
            _isBusy = false;
            UpdateCommands();

            status.CloseAfterDefaultDurationAsync().Forget();
        }
        public ActionResult SaveSharing(long id, StatusViewModel oModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var result = oCore.businessControllers.bcImage.Share(oUserProfile.oAccount, ImageUsage.Status, id, oModel.description);
                    if (result.Item2)
                    {
                        return PartialView("~/Views/Posts/ShareConfirm.cshtml", new Tuple<Post, bool, string>(result.Item1.Post, result.Item2, result.Item3));
                    }
                    else
                    {
                        ModelState.AddModelError("description", Resources.Resources.OperationPerformingError);
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("description", Resources.Resources.OperationError);

                //Salva o erro no arquivo de log do sistema
                ex.Save(new StackTrace(ex, true), ErrorLog.system);
            }

            var oPost = oCore.iRepositories.IPostRepository.Select(id);
            if (oPost == null || !oPost.IsActive || !oPost.IsStatus)
            {
                return PartialView("~/Views/Posts/ShareConfirm.cshtml", new Tuple<Post, bool, string>(oPost, false, Resources.Resources.OperationError));
            }

            oModel.id = oPost.id;
            oModel.categoryId = oPost.categoryId;
            ViewBag.SharingPost = oPost;

            return PartialView("Share", oModel);
        }