public AutoCreationController( IDispatcherExecute dispatcher, CreationViewModel viewModel, ITypesManager typesManager, SessionConfiguration sessionConfiguration, OptionsModel options, IFactory<SessionCreator> sessionCreatorFactory, IDispatcherExecute execute, CommonServices svc) { _dispatcher = dispatcher; _viewModel = viewModel; _typesManager = typesManager; _sessionConfiguration = sessionConfiguration; _options = options; _sessionCreatorFactory = sessionCreatorFactory; _execute = execute; _svc = svc; _viewModel.CommandCreateMutants = new SmartCommand(CommandOk, () => _viewModel.TypesTreeMutate.Assemblies != null && _viewModel.TypesTreeMutate.Assemblies.Count != 0 && _viewModel.TypesTreeToTest.TestAssemblies != null && _viewModel.TypesTreeToTest.TestAssemblies.Count != 0 && _viewModel.MutationsTree.MutationPackages.Count != 0) .UpdateOnChanged(_viewModel.TypesTreeMutate, _ => _.Assemblies) .UpdateOnChanged(_viewModel.TypesTreeToTest, _ => _.TestAssemblies) .UpdateOnChanged(_viewModel.MutationsTree, _ => _.MutationPackages); }
public SessionController( IDispatcherExecute dispatcher, CommonServices svc, MutantDetailsController mutantDetailsController, IMutantsContainer mutantsContainer, ITestsContainer testsContainer, IFactory<ResultsSavingController> resultsSavingFactory, IFactory<TestingProcess> testingProcessFactory, IRootFactory<TestingMutant> testingMutantFactory, MutationSessionChoices choices, OptionsModel options) { _dispatcher = dispatcher; _svc = svc; _mutantDetailsController = mutantDetailsController; _mutantsContainer = mutantsContainer; _testsContainer = testsContainer; _resultsSavingFactory = resultsSavingFactory; _testingProcessFactory = testingProcessFactory; _testingMutantFactory = testingMutantFactory; _choices = choices; _sessionState = SessionState.NotStarted; _sessionEventsSubject = new Subject<SessionEventArgs>(); _subscriptions = new List<IDisposable>(); _options = options; }
public ProjectModel(TaskRunner runner, OptionsModel options) { _runner = runner; _options = options; _runner.TaskComplete += new Action<ITask, Exception>(OnTaskComplete); _depFileSystemWatchers = new Dependent(UpdateFileSystemWatchers); _updater = new GuiUpdateHelper(_depFileSystemWatchers); }
public void TestOptions() { var opt = new OptionsModel(); opt.OtherParams = "--debugfiles true --nunitnetversion net40 --loglevel INFO"; var parser = opt.ParsedParams; parser.DebugFiles.ShouldEqual(true); parser.LogLevel.ShouldEqual("INFO"); parser.NUnitNetVersion.ShouldEqual("net40"); }
private readonly OptionsModel _options;//AKB public MutantsContainer( IMutationExecutor mutationExecutor, OriginalCodebase originalCodebase, OptionsModel options//AKB ) { _mutationExecutor = mutationExecutor; _originalCodebase = originalCodebase; _options = options;//AKB }
public MutationExecutor( OptionsModel options, MutationSessionChoices choices, CommonServices svc ) { _svc = svc; _operatorUtils = new OperatorUtils(); _options = options; _filter = choices.Filter; _mutOperators = choices.SelectedOperators; _sharedTargets = new MultiDictionary<IMutationOperator, MutationTarget>(); }
public void IntegrationTestingMiscUtilLight() { var cci = new CciModuleSource(TestProjects.MiscUtil); var choices = new MutationSessionChoices(); var tt = cci.Module.Module.GetAllTypes(); // var type = (NamedTypeDefinition)cci.Module.Module.GetAllTypes().Single(t => t.Name.Value == "Range"); // var method = new MethodIdentifier(type.Methods.First(m => m.Name.Value == "Contains")); MethodIdentifier method = null; choices.SelectedOperators.Add(new IdentityOperator2()); choices.Filter = method == null ? MutationFilter.AllowAll() : new MutationFilter( new List<TypeIdentifier>(), method.InList()); var options = new OptionsModel(); var muexe = new MutationExecutor(options, choices, null); var mucon = new MutantsContainer(muexe, new OriginalCodebase(cci.InList())); var nodes = mucon.InitMutantsForOperators(ProgressCounter.Inactive()); Mutant mutant = nodes.Cast<CheckedNode>() .SelectManyRecursive(n => n.Children ?? new NotifyingCollection<CheckedNode>()) .OfType<Mutant>().First();//.Take(4); var cciWhite = new CciModuleSource(TestProjects.MiscUtil); var resu = muexe.ExecuteMutation(mutant, cciWhite).Result; string filePath = @"C:\PLIKI\VisualMutator\testprojects\MiscUtil-Integration-Tests\TestGround\MiscUtil.dll"; string filePathTests = @"C:\PLIKI\VisualMutator\testprojects\MiscUtil-Integration-Tests\TestGround\MiscUtil.UnitTests.dll"; using (var file = File.OpenWrite(filePath)) { resu.MutatedModules.WriteToStream(resu.MutatedModules.Modules.Single(), file, filePath); } var runContext = new NUnitTestsRunContext( options, _kernel.Get<IProcesses>(), _kernel.Get<CommonServices>(), new NUnitResultsParser(), TestProjects.NUnitConsolePath, filePathTests, new TestsSelector()); var testResult = runContext.RunTests().Result; var count = testResult.ResultMethods .GroupBy(t => t.State) .ToDictionary(t => t.Key); var countStrings = count.Select(pair => pair.Key.ToString() + ": " + pair.Value.Count()); _log.Info(string.Format("All test results: " + string.Join(" ", countStrings))); count[TestNodeState.Failure].Count().ShouldEqual(0); }
public TestingMutant( MutantMaterializer mutantMaterializer, OptionsModel options, MutationSessionChoices choices, NUnitXmlTestService testService, TestServiceManager testServiceManager, //-------- IObserver<SessionEventArgs> sessionEventsSubject, Mutant mutant) { _mutantMaterializer = mutantMaterializer; _options = options; _choices = choices; _sessionEventsSubject = sessionEventsSubject; _testServiceManager = testServiceManager; _mutant = mutant; }
public WhiteCache( IProjectClonesManager fileManager, OptionsModel options, // ------ int threadsCount, int maxCount ) { _fileManager = fileManager; _options = options; _threadsCount = threadsCount; _moduleNameToFileName = new Dictionary<string, string>(); _fileNameToModuleName = new Dictionary<string, string>(); _whiteCaches = new ConcurrentDictionary<string, BlockingCollection<CciModuleSource>>(); _clients = new ConcurrentQueue<WhiteClient>(); _maxCount = maxCount; _initialMaxCount = maxCount; _log.Debug("Whitecache Initializing with max count: "+ _initialMaxCount); _paths = new BlockingCollection<ProjectFilesClone>(); }
public MutantsCache( OptionsModel options, IWhiteSource whiteCache, MutationSessionChoices choices, IMutationExecutor mutationExecutor) { _options = options; _whiteCache = whiteCache; _choices = choices; _mutationExecutor = mutationExecutor; _disableCache = !_options.MutantsCacheEnabled; var config = new NameValueCollection { {"physicalMemoryLimitPercentage", "40"}, {"cacheMemoryLimitMegabytes", "256"} }; _cache = new MemoryCache("CustomCache", config); _map = new ConcurrentDictionary<string, ConcurrentBag<TaskCompletionSource<MutationResult>>>(); }
public TestingProcess( OptionsModel optionsModel, IRootFactory<TestingMutant> mutantTestingFactory, // ------- on creation Subject<SessionEventArgs> sessionEventsSubject, ICollection<Mutant> allMutants) { _optionsModel = optionsModel; _mutantTestingFactory = mutantTestingFactory; _sessionEventsSubject = sessionEventsSubject; _allMutantsCount = allMutants.Count; _testedNonEquivalentMutantsCount = 0; _testedMutantsCount = 0; //AKB _numberOfFirstOrderMutants = 0; _numberOfMarkedEq = 0; _log.Info("Testing process: all:" + _allMutantsCount); _mutantsWorkers = new WorkerCollection<Mutant>(allMutants, _optionsModel.ProcessingThreadsCount, TestOneMutant); }
public NUnitTestsRunContext( OptionsModel options, IProcesses processes, CommonServices svc, NUnitResultsParser parser, //---------- string nUnitConsolePath, string assemblyPath, TestsSelector testsSelector) { _options = options; _parser = parser; _processes = processes; _svc = svc; _assemblyPath = assemblyPath; _nUnitConsolePath = nUnitConsolePath; _testsSelector = testsSelector; _cancellationTokenSource = new CancellationTokenSource(); // var testsSelector = new TestsSelector(); // _selectedTests = testsSelector.GetIncludedTests(loadContext.Namespaces); // _log.Debug("Created tests to run: " + _selectedTests.TestsDescription); }
public OutlookFolderViewModel(OptionsModel model, IOptionTasks optionTasks, IViewOptions viewOptions) { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (optionTasks == null) { throw new ArgumentNullException(nameof(optionTasks)); } if (viewOptions == null) { throw new ArgumentNullException(nameof(viewOptions)); } _model = model; _optionTasks = optionTasks; ViewOptions = viewOptions; ModelOptions = model.ModelFactory.ModelOptions; RegisterPropertyChangePropagation(_model, nameof(_model.EnableChangeTriggeredSynchronization), nameof(EnableChangeTriggeredSynchronization)); RegisterPropertyChangePropagation(_model, nameof(_model.SelectedFolderOrNull), nameof(SelectedFolderName)); SelectFolderCommand = new DelegateCommand(_ => SelectFolder()); }
/// <summary> /// Return the appropriate Presenter to use for the Program object /// </summary> /// <param name="view"></param> /// <returns></returns> public static Presenter getDependency(View view) { if (view is MenuView) { Model model = new MenuModel(); return(new MenuPresenter(view, model)); } else if (view is OptionsView) { Model model = new OptionsModel(); return(new OptionsPresenter(view, model)); } else if (view is HighscoresView) { return(null); } else if (view is PlayView) { Model model = new PlayModel(); return(new PlayPresenter(view, model)); } return(null); }
/// <summary> /// 创建默认配置文件 /// </summary> private void CreateDefaultConfig() { options = new OptionsModel(); options.General = new GeneralModel(); options.General.Data = false; options.General.Noreset = false; options.General.Sound = true; options.General.Startup = false; options.General.LeaveListener = true; options.General.WarnTime = 20; options.Style = new StyleModel(); options.Style.Theme = systemResources.Themes[0]; options.Style.TipContent = "您已持续用眼{t}分钟,休息一会吧!请将注意力集中在至少6米远的地方20秒!"; options.Style.TipWindowAnimation = systemResources.Animations[0]; options.KeyboardShortcuts = new KeyboardShortcutModel(); options.Behavior = new BehaviorModel(); SaveOldOptions(); xmlExtensions.Save(options); }
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) { OptionsModel options = (OptionsModel)e.Item.DataItem; ((HtmlTableCell)e.Item.FindControl("Eval_Status")).InnerHtml = bll_options.GetStatus(options, "enab"); if (e.Item.ItemIndex == 0) { ((HtmlGenericControl)e.Item.FindControl("Eval_MoveUp")).InnerHtml = "<a class=\"icon icon_empty\"></a>"; } else { ((HtmlGenericControl)e.Item.FindControl("Eval_MoveUp")).InnerHtml = "<a href=\"javascript:;\" onclick=\"operate('moveup'," + options.Pkid.ToString() + ",'" + param + "');\" class=\"icon icon_moveup\" title=\"上移\"></a>"; } if (e.Item.ItemIndex == total - 1) { ((HtmlGenericControl)e.Item.FindControl("Eval_MoveDown")).InnerHtml = "<a class=\"icon icon_empty\"></a>"; } else { ((HtmlGenericControl)e.Item.FindControl("Eval_MoveDown")).InnerHtml = "<a href=\"javascript:;\" onclick=\"operate('movedown'," + options.Pkid.ToString() + ",'" + param + "');\" class=\"icon icon_movedown\" title=\"下移\"></a>"; } }
public void SetResourceUrl(OptionsModel options, AddressBookData resource) { options.CalenderUrl = resource.Uri.ToString(); }
public ServerSettingsTemplateViewModel(IOutlookAccountPasswordProvider outlookAccountPasswordProvider, OptionsModel prototypeModel, ProfileModelOptions modelOptions) { _outlookAccountPasswordProvider = outlookAccountPasswordProvider ?? throw new ArgumentNullException(nameof(outlookAccountPasswordProvider)); _prototypeModel = prototypeModel ?? throw new ArgumentNullException(nameof(prototypeModel)); ModelOptions = modelOptions ?? throw new ArgumentNullException(nameof(modelOptions)); RegisterPropertyChangePropagation(prototypeModel, nameof(prototypeModel.CalenderUrl), nameof(CalenderUrl)); RegisterPropertyChangePropagation(prototypeModel, nameof(prototypeModel.UserName), nameof(UserName)); RegisterPropertyChangePropagation(prototypeModel, nameof(prototypeModel.UseAccountPassword), nameof(UseAccountPassword)); RegisterPropertyChangePropagation(prototypeModel, nameof(prototypeModel.Password), nameof(Password)); RegisterPropertyChangePropagation(prototypeModel, nameof(prototypeModel.EmailAddress), nameof(EmailAddress)); }
public void FixTimeRangeUsage(OptionsModel options, OlItemType?folderType) { }
public void FixSynchronizationMode(OptionsModel options, TestResult result) { }
public Task <string> TestWebDavConnection(OptionsModel options) { throw new NotImplementedException(); }
public EventMappingConfigurationViewModel(IReadOnlyList <string> availableCategories, EventMappingConfigurationModel model, OptionsModel optionsModel) { if (availableCategories == null) { throw new ArgumentNullException(nameof(availableCategories)); } if (model == null) { throw new ArgumentNullException(nameof(model)); } if (optionsModel == null) { throw new ArgumentNullException(nameof(optionsModel)); } AvailableCategories = availableCategories; _model = model; _optionsModel = optionsModel; SetServerCalendarColorCommand = new DelegateCommand(_ => { ComponentContainer.EnsureSynchronizationContext(); SetServerCalendarColorAsync(); }); GetServerCalendarColorCommand = new DelegateCommand(_ => { ComponentContainer.EnsureSynchronizationContext(); GetServerCalendarColorAsync(); }); Items = new[] { new CustomPropertyMappingViewModel(model) }; RegisterPropertyChangePropagation(_model, nameof(_model.CategoryShortcutKey), nameof(CategoryShortcutKey)); RegisterPropertyChangePropagation(_model, nameof(_model.CreateEventsInUtc), nameof(CreateEventsInUtc)); RegisterPropertyChangePropagation(_model, nameof(_model.UseIanaTz), nameof(UseIanaTz)); RegisterPropertyChangePropagation(_model, nameof(_model.EventTz), nameof(EventTz)); RegisterPropertyChangePropagation(_model, nameof(_model.IncludeHistoricalData), nameof(IncludeHistoricalData)); RegisterPropertyChangePropagation(_model, nameof(_model.UseGlobalAppointmentId), nameof(UseGlobalAppointmentId)); RegisterPropertyChangePropagation(_model, nameof(_model.EventCategory), nameof(EventCategory)); RegisterPropertyChangePropagation(_model, nameof(_model.EventCategoryColor), nameof(EventCategoryColor)); RegisterPropertyChangePropagation(_model, nameof(_model.IncludeEmptyEventCategoryFilter), nameof(IncludeEmptyEventCategoryFilter)); RegisterPropertyChangePropagation(_model, nameof(_model.InvertEventCategoryFilter), nameof(InvertEventCategoryFilter)); RegisterPropertyChangePropagation(_model, nameof(_model.MapAttendees), nameof(MapAttendees)); RegisterPropertyChangePropagation(_model, nameof(_model.MapAttendees), nameof(MapAttendees)); RegisterPropertyChangePropagation(_model, nameof(_model.MapBody), nameof(MapBody)); RegisterPropertyChangePropagation(_model, nameof(_model.MapRtfBodyToXAltDesc), nameof(MapRtfBodyToXAltDesc)); RegisterPropertyChangePropagation(_model, nameof(_model.MapXAltDescToRtfBody), nameof(MapXAltDescToRtfBody)); RegisterPropertyChangePropagation(_model, nameof(_model.MapClassConfidentialToSensitivityPrivate), nameof(MapClassConfidentialToSensitivityPrivate)); RegisterPropertyChangePropagation(_model, nameof(_model.MapClassConfidentialToSensitivityPrivate), nameof(MapClassConfidentialToSensitivityPrivate)); RegisterPropertyChangePropagation(_model, nameof(_model.MapReminder), nameof(MapReminder)); RegisterPropertyChangePropagation(_model, nameof(_model.MapSensitivityPrivateToClassConfidential), nameof(MapSensitivityPrivateToClassConfidential)); RegisterPropertyChangePropagation(_model, nameof(_model.MapClassPublicToSensitivityPrivate), nameof(MapClassPublicToSensitivityPrivate)); RegisterPropertyChangePropagation(_model, nameof(_model.ScheduleAgentClient), nameof(ScheduleAgentClient)); RegisterPropertyChangePropagation(_model, nameof(_model.SendNoAppointmentNotifications), nameof(SendNoAppointmentNotifications)); RegisterPropertyChangePropagation(_model, nameof(_model.UseEventCategoryColorAndMapFromCalendarColor), nameof(UseEventCategoryColorAndMapFromCalendarColor)); RegisterPropertyChangePropagation(_model, nameof(_model.CleanupDuplicateEvents), nameof(CleanupDuplicateEvents)); RegisterPropertyChangePropagation(_model, nameof(_model.UseEventCategoryAsFilter), nameof(UseEventCategoryAsFilter)); RegisterPropertyChangePropagation(_model, nameof(_model.UseEventCategoryAsFilterAndMapColor), nameof(UseEventCategoryAsFilterAndMapColor)); }
public ActionResult SecuredPayment(double cryptoamount) { var transaction = new CryptoTransaction(); var account = new CryptoAccount(); var accountId = AccountId(); transaction.Create(new TransactionVm() { Status = TransactionStatus.PENDING, Amount = Convert.ToDecimal(cryptoamount), accountId = AccountId(), CurrencyDomination = "BTC", TransactionType = TransactionTypeStatus.Credit }); OptionsModel options = new OptionsModel() { public_key = GoUrlKeys.PublicKey, private_key = GoUrlKeys.PrivateKey, webdev_key = "", orderID = transaction.savedId.ToString(), userID = UserId(), userFormat = "COOKIE", //amount = 0, amountUSD = Convert.ToDecimal(cryptoamount), period = "2 HOUR", language = "en" }; ViewBag.transId = transaction.savedId.ToString(); using (Cryptobox cryptobox = new Cryptobox(options)) { ViewBag.JsonUrl = cryptobox.cryptobox_json_url(); ViewBag.Message = ""; DisplayCryptoboxModel model = cryptobox.GetDisplayCryptoboxModel(); if (HttpContext.Request.Form["cryptobox_refresh_"] != null) { ViewBag.Message = "<div class='gourl_msg'>"; if (cryptobox.is_paid()) { ViewBag.Message += "<div style=\"margin:50px\" class=\"well\"><i class=\"fa fa-info-circle fa-3x fa-pull-left fa-border\" aria-hidden=\"true\"></i> " + Controls.localisation[model.language].MsgNotReceived.Replace("%coinName%", model.coinName) .Replace("%coinNames%", model.coinLabel == "BCH" || model.coinLabel == "DASH" ? model.coinName : model.coinName + "s") .Replace("%coinLabel%", model.coinLabel) + "</div>"; transaction.SetStatus(transaction.savedId, TransactionStatus.INPROGESS); } else if (cryptobox.is_processed()) { ViewBag.Message += "<div style=\"margin:70px\" class=\"alert alert-success\" role=\"alert\"> " + (model.boxType == "paymentbox" ? Controls.localisation[model.language].MsgReceived : Controls.localisation[model.language].MsgReceived2) .Replace("%coinName%", model.coinName) .Replace("%coinLabel%", model.coinLabel) .Replace("%amountPaid%", model.amoutnPaid.ToString()) + "</div>"; cryptobox.set_status_processed(); transaction.SetStatus(transaction.savedId, TransactionStatus.SUCCESSFUL); } ViewBag.Message = "</div>"; } return(View(model)); } }
private IEnumerable<Mutant> SetupMutations(OriginalCodebase original, List<FilePathAbsolute> paths, List<string> toMutate, List<IMutationOperator> operators, MethodIdentifier method= null) { var options = new OptionsModel(); options.OtherParams = "--debugfiles true"; _kernel.Bind<IProjectClonesManager>().To<ProjectClonesManager>().InSingletonScope(); _kernel.Bind<ProjectFilesClone>().ToSelf().AndFromFactory(); _kernel.Bind<FilesManager>().ToSelf().InSingletonScope(); _kernel.Bind<TestServiceManager>().ToSelf().InSingletonScope(); _kernel.Bind<XUnitTestService>().ToSelf().InSingletonScope(); _kernel.Bind<XUnitResultsParser>().ToSelf().InSingletonScope(); _kernel.Bind<WhiteCache>().ToSelf().AndFromFactory(); _kernel.Bind<INUnitWrapper>().To<NUnitWrapper>().InSingletonScope(); _kernel.Bind<OriginalCodebase>().ToConstant(original); _kernel.Bind<ICodeDifferenceCreator>().To<CodeDifferenceCreator>().InSingletonScope(); _kernel.Bind<ICodeVisualizer>().To<CodeVisualizer>().InSingletonScope(); _kernel.Bind<IMutantsCache>().To<MutantsCache>().InSingletonScope(); _kernel.Bind<NUnitTestsRunContext>().ToSelf().AndFromFactory(); _kernel.Bind<XUnitTestsRunContext>().ToSelf().AndFromFactory(); _kernel.Bind<OptionsModel>().ToConstant(options); _kernel.Bind<IMutationExecutor>().To<MutationExecutor>().InSingletonScope(); _kernel.Bind<TestingMutant>().ToSelf().AndFromFactory(); _kernel.Bind<TestLoader>().ToSelf().AndFromFactory(); _kernel.BindMock<IHostEnviromentConnection>(mock => { mock.Setup(_ => _.GetProjectAssemblyPaths()).Returns(paths); mock.Setup(_ => _.GetTempPath()).Returns(Path.GetTempPath()); }); _kernel.Get<ISettingsManager>()["NUnitConsoleDirPath"] = TestProjects.NUnitConsoleDirPath; _kernel.Get<ISettingsManager>()["XUnitConsoleDirPath"] = TestProjects.XUnitConsoleDirPath; _kernel.Bind<IWhiteSource>().ToConstant(new WhiteDummy(toMutate)); var testsClone = _kernel.Get<IProjectClonesManager>().CreateClone("Tests"); var testsTask = _kernel.Get<TestsLoader>().LoadTests(testsClone.Assemblies.AsStrings().ToList()); var strategy = new AllTestsSelectStrategy(testsTask); var choices = new MutationSessionChoices { Filter = method == null ? MutationFilter.AllowAll() : new MutationFilter( new List<TypeIdentifier>(), method.InList()), SelectedOperators = operators, TestAssemblies = strategy.SelectTests(null).Result }; _kernel.Bind<MutationSessionChoices>().ToConstant(choices); var exec = _kernel.Get<MutationExecutor>(); var container = new MutantsContainer(exec, original); IList<AssemblyNode> assemblies = container.InitMutantsForOperators(ProgressCounter.Inactive()); var mutants = assemblies.Cast<CheckedNode>() .SelectManyRecursive(n => n.Children ?? new NotifyingCollection<CheckedNode>()) .OfType<Mutant>();//.Take(4); return mutants; }
public SwisscomServerSettingsViewModel(OptionsModel model, IOptionTasks optionTasks, IViewOptions viewOptions) : base(model, optionTasks, viewOptions) { }
public EasyProjectServerSettingsTemplateViewModel(IOutlookAccountPasswordProvider outlookAccountPasswordProvider, OptionsModel prototypeModel) { if (prototypeModel == null) { throw new ArgumentNullException(nameof(prototypeModel)); } _outlookAccountPasswordProvider = outlookAccountPasswordProvider; _prototypeModel = prototypeModel; RegisterPropertyChangePropagation(prototypeModel, nameof(prototypeModel.CalenderUrl), nameof(CalenderUrl)); RegisterPropertyChangePropagation(prototypeModel, nameof(prototypeModel.UserName), nameof(UserName)); RegisterPropertyChangePropagation(prototypeModel, nameof(prototypeModel.UseAccountPassword), nameof(UseAccountPassword)); RegisterPropertyChangePropagation(prototypeModel, nameof(prototypeModel.Password), nameof(Password)); RegisterPropertyChangePropagation(prototypeModel, nameof(prototypeModel.EmailAddress), nameof(EmailAddress)); }
public static async Task <ServiceProvider> CreateAsync(ApiPortVSPackage serviceProvider) { var builder = new ContainerBuilder(); builder.RegisterType <VsBrowserReportViewer>() .As <IReportViewer>() .SingleInstance(); builder.RegisterType <ToolbarListReportViewer>() .As <IReportViewer>() .InstancePerLifetimeScope(); builder.RegisterType <ApiPortVsAnalyzer>() .As <IVsApiPortAnalyzer>() .InstancePerLifetimeScope(); // Service registration builder.RegisterInstance(new ProductInformation("ApiPort_VS")) .AsSelf(); builder.RegisterInstance(new AssemblyRedirectResolver(AssemblyDirectory)) .AsSelf(); builder.RegisterType <VisualStudioProxyProvider>() .As <IProxyProvider>() .SingleInstance(); builder.RegisterType <ApiPortService>() .As <IApiPortService>() .WithParameter(TypedParameter.From(DefaultEndpoint)) .SingleInstance(); builder.RegisterType <ApiPortClient>() .AsSelf() .SingleInstance(); builder.Register(_ => OptionsModel.Load()) .As <OptionsModel>() .OnRelease(m => m.Save()) .SingleInstance(); builder.RegisterType <TargetMapper>() .As <ITargetMapper>() .OnActivated(h => h.Instance.LoadFromConfig()) .InstancePerLifetimeScope(); builder.RegisterType <WindowsFileSystem>() .As <IFileSystem>() .SingleInstance(); // Register output services builder.RegisterType <ReportGenerator>() .As <IReportGenerator>() .SingleInstance(); builder.RegisterType <OutputWindowWriter>() .AsSelf() .As <IOutputWindowWriter>() .As <TextWriter>() .SingleInstance(); builder.RegisterType <StatusBarProgressReporter>() .As <IProgressReporter>() .SingleInstance(); builder.RegisterType <ReportFileWriter>() .As <IFileWriter>() .SingleInstance(); builder.Register(GetOutputViewModel) .As <OutputViewModel>() .SingleInstance(); // Register menu handlers builder.RegisterType <AnalyzeMenu>() .AsSelf() .SingleInstance(); builder.RegisterType <FileListAnalyzer>() .AsSelf() .InstancePerLifetimeScope(); builder.RegisterType <ProjectAnalyzer>() .AsSelf() .InstancePerLifetimeScope(); // Register option pane services builder.RegisterType <OptionsPageControl>() .AsSelf() .InstancePerLifetimeScope(); builder.RegisterType <OptionsViewModel>() .AsSelf() .InstancePerLifetimeScope(); // Metadata manipulation registrations builder.RegisterType <CciDependencyFinder>() .As <IDependencyFinder>() .InstancePerLifetimeScope(); builder.RegisterType <CciSourceLineMapper>() .As <ISourceLineMapper>() .InstancePerLifetimeScope(); // VS type registration // Registers all of the Visual Studio Package components. await RegisterVisualStudioComponentsAsync(builder, serviceProvider); return(new ServiceProvider(builder.Build())); }
public void SetResourceUrl(OptionsModel options, TaskListData resource) { options.CalenderUrl = resource.Id; }
public ServiceProvider(ApiPortVSPackage serviceProvider) { var builder = new ContainerBuilder(); // VS type registration builder.RegisterType <ErrorListProvider>() .AsSelf() .SingleInstance(); builder.RegisterInstance(serviceProvider) .As <IResultToolbar>() .As <IServiceProvider>(); builder.Register(_ => Package.GetGlobalService(typeof(SVsWebBrowsingService))) .As <IVsWebBrowsingService>(); builder.RegisterType <VsBrowserReportViewer>() .As <IReportViewer>() .SingleInstance(); builder.RegisterType <ToolbarListReportViewer>() .As <IReportViewer>() .InstancePerLifetimeScope(); builder.Register(x => new AssemblyRedirects(s_appConfigFilePath)) .AsSelf() .SingleInstance() .AutoActivate(); builder.RegisterType <ApiPortVsAnalyzer>() .As <IVsApiPortAnalyzer>() .InstancePerLifetimeScope(); builder.Register(_ => Package.GetGlobalService(typeof(SVsSolutionBuildManager))) .As <IVsSolutionBuildManager2>(); builder.RegisterType <ProjectBuilder>() .AsSelf(); // Service registration builder.RegisterInstance(new ProductInformation("ApiPort_VS")) .AsSelf(); builder.RegisterType <ApiPortService>(). As <IApiPortService>(). WithParameter(TypedParameter.From <string>(DefaultEndpoint)) .SingleInstance(); builder.RegisterType <ApiPortClient>() .AsSelf() .SingleInstance(); builder.Register(_ => OptionsModel.Load()) .As <OptionsModel>() .OnRelease(m => m.Save()) .SingleInstance(); builder.RegisterType <TargetMapper>() .As <ITargetMapper>() .OnActivated(h => h.Instance.LoadFromConfig()) .InstancePerLifetimeScope(); builder.RegisterType <WindowsFileSystem>() .As <IFileSystem>() .SingleInstance(); // Register output services builder.RegisterType <ReportGenerator>() .As <IReportGenerator>() .SingleInstance(); builder.RegisterType <OutputWindowWriter>() .AsSelf() .As <TextWriter>() .SingleInstance(); builder.RegisterType <TextWriterProgressReporter>() .As <IProgressReporter>() .SingleInstance(); builder.RegisterType <ReportFileWriter>() .As <IFileWriter>() .SingleInstance(); builder.RegisterAdapter <IServiceProvider, DTE>(provider => (DTE)provider.GetService(typeof(DTE))); builder.RegisterAdapter <IServiceProvider, IVsOutputWindowPane>(provider => { var outputWindow = provider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow; IVsOutputWindowPane windowPane; if (outputWindow.GetPane(ref OutputWindowGuid, out windowPane) == S_OK) { return(windowPane); } if (outputWindow.CreatePane(ref OutputWindowGuid, LocalizedStrings.PortabilityOutputTitle, 1, 0) == S_OK) { if (outputWindow.GetPane(ref OutputWindowGuid, out windowPane) == S_OK) { return(windowPane); } } // If a custom window couldn't be opened, open the general purpose window return(provider.GetService(typeof(SVsGeneralOutputWindowPane)) as IVsOutputWindowPane); }).SingleInstance(); builder.RegisterInstance(AnalysisOutputToolWindowControl.Model) .As <OutputViewModel>() .SingleInstance(); // Register menu handlers builder.RegisterType <AnalyzeMenu>() .AsSelf() .SingleInstance(); builder.RegisterType <FileListAnalyzer>() .AsSelf() .InstancePerLifetimeScope(); builder.RegisterType <ProjectAnalyzer>() .AsSelf() .InstancePerLifetimeScope(); // Register option pane services builder.RegisterType <OptionsPageControl>() .AsSelf() .InstancePerLifetimeScope(); builder.RegisterType <OptionsViewModel>() .AsSelf() .InstancePerLifetimeScope(); // Metadata manipulation registrations builder.RegisterType <CciDependencyFinder>() .As <IDependencyFinder>() .InstancePerLifetimeScope(); builder.RegisterType <CciSourceLineMapper>() .As <ISourceLineMapper>() .InstancePerLifetimeScope(); _container = builder.Build(); }
private static void AintAllDelDesc(bool loadworld) { try { if (NiecMod.KillNiec.AssemblyCheckByNiec.IsInstalled("DGSCore")) { //bool checkkillsimxxx = false; try { //Sleep(3.0); foreach (SimDescription sdtyf in NiecMod.Nra.NFinalizeDeath.TattoaX()) { try { if (!Sims3.NiecModList.Persistable.ListCollon.NiecSimDescriptions.Contains(sdtyf)) { Sims3.NiecModList.Persistable.ListCollon.NiecSimDescriptions.Add(sdtyf); } } catch { } } } catch { } //Sleep(3.0); try { CommandSystem.ExecuteCommandString("dgsunsafekill false"); } catch { } try { CommandSystem.ExecuteCommandString("dgspx false"); PlumbBob.ForceSelectActor(null); try { PlumbBob.sSingleton.mSelectedActor = null; } catch { } } catch { } try { List <MiniSimDescription> asdr = new List <MiniSimDescription>(MiniSimDescription.sMiniSims.Values); foreach (MiniSimDescription esdtyef in asdr) { try { if (esdtyef == null) { continue; } if (esdtyef.mProtectionFlags != null) { esdtyef.mProtectionFlags.Clear(); } esdtyef.Instantiated = false; esdtyef.mGenealogy = null; try { foreach (MiniRelationship miniRelationship in esdtyef.mMiniRelationships) { if (miniRelationship == null) { continue; } try { MiniSimDescription miniSimDescription2 = MiniSimDescription.Find(miniRelationship.SimDescriptionId); if (miniSimDescription2 != null) { if (miniSimDescription2.mProtectionFlags != null) { miniSimDescription2.mProtectionFlags.Clear(); } miniSimDescription2.Instantiated = false; miniSimDescription2.RemoveMiniRelatioship(esdtyef.mSimDescriptionId); miniSimDescription2.mGenealogy = null; } } catch { } } } catch { } if (esdtyef.mMiniRelationships != null) { esdtyef.mMiniRelationships.Clear(); } //MiniSimDescription.sMiniSims.Remove(esdtyef.mSimDescriptionId); } catch { } } } catch { } foreach (SimDescription sdtyef in Sims3.NiecModList.Persistable.ListCollon.NiecSimDescriptions) { try { if (sdtyef == null) { continue; } //sdtyef.RemoveOutfits(OutfitCategories.All, true); //sdtyef.RemoveOutfit(OutfitCategories.All, 0, true); if (!sdtyef.mIsValidDescription && !loadworld) { continue; } try { try { if (sdtyef.OccultManager != null) { sdtyef.OccultManager.RemoveAllOccultTypes(); } } catch { } sdtyef.OccultManager = null; } catch { } try { if (sdtyef.IsPregnant) { NRaas.CommonSpace.Helpers.CASParts.RemoveOutfits(sdtyef, OutfitCategories.All, false); } else { NRaas.CommonSpace.Helpers.CASParts.RemoveOutfits(sdtyef, OutfitCategories.All, true); } } catch { } sdtyef.Protected = false; MiniSimDescription inim = MiniSimDescription.Find(sdtyef.mSimDescriptionId); if (inim != null) { if (inim.mProtectionFlags != null) { inim.mProtectionFlags.Clear(); } inim.Instantiated = false; inim.mGenealogy = null; inim.ClearMiniRelationships(); } } catch { } try { Niec.iCommonSpace.KillPro.RemoveSimDescriptionRelationships(sdtyef); } catch { } try { Niec.iCommonSpace.KillPro.CleanseGenealogy(sdtyef); sdtyef.mGenealogy = null; } catch { } try { Niec.iCommonSpace.KillPro.RemoveSimDescriptionRelationships(sdtyef); } catch { } } List <Sim> asdo = new List <Sim>(); try { try { foreach (Sim simau in Sims3.Gameplay.Queries.GetObjects <Sim>()) { try { if (!asdo.Contains(simau)) { asdo.Add(simau); } } catch { } } foreach (Sim simau in LotManager.Actors) { try { if (!asdo.Contains(simau)) { asdo.Add(simau); } } catch { } } } catch { } try { foreach (Sim simaue in asdo) { try { NFinalizeDeath.ForceCancelAllInteractionsWithoutCleanup(simaue); } catch { } try { simaue.Genealogy.ClearAllGenealogyInformation(); } catch { } try { simaue.Genealogy.ClearMiniSimDescription(); } catch { } try { simaue.Destroy(); } catch { } try { (simaue as ScriptObject).Destroy(); } catch { } } } catch { } } catch { } finally { try { asdo.Clear(); } catch { } asdo = null; } foreach (SimDescription description in Sims3.NiecModList.Persistable.ListCollon.NiecSimDescriptions) { try { if (description == null) { continue; } if (!description.mIsValidDescription && !loadworld) { try { while (true) { Urnstone urnstone = null; urnstone = HelperNra.TFindGhostsGrave(description); if (urnstone != null) { urnstone.DeadSimsDescription = null; try { urnstone.Dispose(); } catch { } try { urnstone.Destroy(); } catch { } } else { break; } } } catch { } continue; } } catch { } try { if (description.IsPregnant) { NRaas.CommonSpace.Helpers.CASParts.RemoveOutfits(description, OutfitCategories.All, false); } else { NRaas.CommonSpace.Helpers.CASParts.RemoveOutfits(description, OutfitCategories.All, true); } } catch { } try { description.Genealogy.ClearMiniSimDescription(); } catch { } try { description.Genealogy.ClearDerivedData(); } catch { } try { description.Genealogy.ClearSimDescription(); } catch { } try { description.Genealogy.ClearAllGenealogyInformation(); } catch { } try { if (description.CreatedSim != null) { NFinalizeDeath.ForceCancelAllInteractionsWithoutCleanup(description.CreatedSim); } } catch { } try { Household household = description.Household; if (household != null) { household.Remove(description, !household.IsSpecialHousehold); } } catch { } try { while (true) { Urnstone urnstone = null; urnstone = HelperNra.TFindGhostsGrave(description); if (urnstone != null) { urnstone.DeadSimsDescription = null; try { urnstone.Dispose(); } catch { } try { urnstone.Destroy(); } catch { } } else { break; } } } catch { } try { MiniSimDescription.RemoveMSD(description.SimDescriptionId); } catch { } try { description.Dispose(); } catch { } /* * try * { * NRaas.CommonSpace.Helpers.Annihilation.Cleanse(description); * } * catch * { } */ description.mIsValidDescription = false; } try { //Sleep(3.0); foreach (Service allService in Services.AllServices) { try { if (!(allService is GrimReaper)) { allService.ClearServicePool(); } } catch { } } } catch { } try { //Sleep(3.0); foreach (Service allService in Services.AllServices) { try { if (!(allService is GrimReaper)) { Service.Destroy(allService); } } catch { } } } catch { } try { try { try { SimDescription.sLoadedSimDescriptions.Clear(); } catch { } SimDescription.sLoadedSimDescriptions = null; SimDescription.sLoadedSimDescriptions = new List <SimDescription>(); } catch { StyledNotification.Format afra = new StyledNotification.Format("Failed 1", StyledNotification.NotificationStyle.kSystemMessage); StyledNotification.Show(afra); } if (!loadworld) { try { Sims3.NiecModList.Persistable.ListCollon.NiecSimDescriptions.Clear(); Sims3.NiecModList.Persistable.ListCollon.NiecSimDescriptions = null; Sims3.NiecModList.Persistable.ListCollon.NiecSimDescriptions = new List <SimDescription>(); } catch { StyledNotification.Format afra = new StyledNotification.Format("Failed 2", StyledNotification.NotificationStyle.kSystemMessage); StyledNotification.Show(afra); } } try { MiniSimDescription.sMiniSims.Clear(); MiniSimDescription.sMiniSims = null; MiniSimDescription.sMiniSims = new Dictionary <ulong, MiniSimDescription>(); } catch { StyledNotification.Format afra = new StyledNotification.Format("Failed 3", StyledNotification.NotificationStyle.kSystemMessage); StyledNotification.Show(afra); } if (NiecMod.KillNiec.AssemblyCheckByNiec.IsInstalled("DGSCore")) { try { CommandSystem.ExecuteCommandString("dgsnocreate true"); StyledNotification.Format afra = new StyledNotification.Format("Termination Status: Perfect Execution!", StyledNotification.NotificationStyle.kGameMessageNegative); afra.mTNSCategory = NotificationManager.TNSCategory.Chatty; StyledNotification.Show(afra); } catch { } try { CommandSystem.ExecuteCommandString("dgsnocreate true"); } catch { } OptionsModel optionsModel = Sims3.Gameplay.UI.Responder.Instance.OptionsModel as OptionsModel; if (optionsModel != null) { optionsModel.SaveName = "ClearSave " + "No Name"; } try { GameStates.TransitionToEditTown(); } catch { } } } catch { } } } catch { } return; }
public ActionResult CrassFat(OptionsModel options) //сюда передаю данные польз-ля { if (!ModelState.IsValid) { return(CrassFat()); } List <ExerciseViewModel> result; var selectedIds = options.CategoryItems .Where(w => w.IsSelected).Select(s => s.Id); //коллекция содержит id выбранных групп мышц using (var db = new TreKaContext()) { //выборка только нужных упражнений var data = db.Exercises.Include(i => i.Category) .Where(w => (selectedIds.Contains(w.CategoryId)) || w.CategoryId == null).ToList(); result = data.Select(s => new ExerciseViewModel { ExerciseName = s.ExerciseName, Repetition = s.Repetition }).ToList(); } Random rnd = new Random(); while (result.Count > 3) //сокращение кол-ва упражнений до 3 (случайным способом) { result.RemoveAt(rnd.Next(0, result.Count)); } var kLevel = options.СoefficientOfSelectedLevel; //коеффициент уровня подготовки #region Присвоение возрастного коэффициента (kAge) var kAge = new double(); var age = options.Age; if ((age >= 0 && age <= 14) || (age >= 36 && age <= 50)) { kAge = 0.8; } else if (age >= 15 && age <= 35) { kAge = 1; } else { kAge = 0.4; } #endregion #region Присвоение коэффициента ИМТ (kBMI) var kBMI = new double(); var BMI = (options.Weight / (options.Height * options.Height)); if (BMI <= 16) { kBMI = 0.8; } else if (BMI >= 17 && BMI <= 18) { kBMI = 0.9; } else if (BMI >= 19 && BMI <= 24) { kBMI = 1; } else if (BMI >= 25 && BMI <= 30) { kBMI = 0.9; } else if (BMI >= 31 && BMI <= 35) { kBMI = 0.8; } else if (BMI >= 36 && BMI <= 40) { kBMI = 0.7; } else { kBMI = 0.6; } #endregion foreach (var c in result) { c.Repetition = Convert.ToInt32(Math.Floor(c.Repetition * kBMI * kAge * kLevel)); } return(View("ReadySet", result)); }
public ActionResult MakePayment(double cryptoamount) { var transaction = new CryptoTransaction(); var account = new CryptoAccount(); var accountId = AccountId(); transaction.Create(new TransactionVm() { Status = TransactionStatus.PENDING, Amount = Convert.ToDecimal(cryptoamount), accountId = accountId, CurrencyDomination = "BTC", TransactionType = TransactionTypeStatus.Credit }); OptionsModel options = new OptionsModel() { public_key = GoUrlKeys.PublicKey, private_key = GoUrlKeys.PrivateKey, webdev_key = "", orderID = transaction.savedId.ToString(), userID = UserId(), userFormat = "COOKIE", //amount = 0, amountUSD = Convert.ToDecimal(cryptoamount), period = "2 HOUR", language = "en" }; using (Cryptobox cryptobox = new Cryptobox(options)) { if (cryptobox.is_paid()) { //initiate a pendint transaction if (!cryptobox.is_confirmed()) { ViewBag.message = "Thank you for order (order #" + options.orderID + ", payment #" + cryptobox.payment_id() + "). Awaiting transaction/payment confirmation"; } else { if (!cryptobox.is_processed()) { ViewBag.message = "Thank you for order (order #" + options.orderID + ", payment #" + cryptobox.payment_id() + "). Payment Confirmed<br/> (User will see this message one time after payment has been made)"; cryptobox.set_status_processed(); transaction.SetStatus(transaction.savedId, TransactionStatus.SUCCESSFUL); } else { ViewBag.message = "Thank you for order (order #" + options.orderID + ", payment #" + cryptobox.payment_id() + "). Payment Confirmed<br/> (User will see this message during " + options.period + " period after payment has been made)"; transaction.SetStatus(transaction.savedId, TransactionStatus.INPROGESS); } } } else { ViewBag.message = "This invoice has not been paid yet"; transaction.SetStatus(transaction.savedId, TransactionStatus.PENDING); } DisplayCryptoboxModel model = cryptobox.GetDisplayCryptoboxModel(); return(View(model)); } }
public Task <string> TestGoogleConnection(OptionsModel options, string url) { throw new NotImplementedException(); }
/// <summary> /// Creates the resultat individuel. /// </summary> /// <param name="nbTotalVote">The nb total vote.</param> /// <param name="option">The option.</param> /// <returns></returns> private static ResultatIndividualMajorityVotingProcessModel CreateResultatIndividuel(decimal nbTotalVote, OptionsModel option) { var nbVote = option.Suffrages.Count(s => s.Value == ChoosenValue); return(new ResultatIndividualMajorityVotingProcessModel { Option = option, Votes = nbVote, Percentage = 100 * nbVote / nbTotalVote }); }
public void OptionsViewModel_TargetCount_NoExcel() { var service = Substitute.For <IApiPortService>(); var progressReporter = Substitute.For <IProgressReporter>(); var targetMapper = Substitute.For <ITargetMapper>(); var dependencyFinder = Substitute.For <IDependencyFinder>(); var reportGenerator = Substitute.For <IReportGenerator>(); var ignoreAssemblyInfoList = Substitute.For <IEnumerable <IgnoreAssemblyInfo> >(); var writer = Substitute.For <IFileWriter>(); var client = new ApiPortClient(service, progressReporter, targetMapper, dependencyFinder, reportGenerator, ignoreAssemblyInfoList, writer); var options = Substitute.For <IApiPortOptions>(); var resultFormats = Enumerable.Range(0, 5) .Select(x => new SelectedResultFormat { DisplayName = Invariant($"{nameof(SelectedResultFormat.DisplayName)} {x}"), FileExtension = Invariant($".{x}"), MimeType = Invariant($"type-{x}") }) .ToList(); var platforms = Enumerable.Range(0, 20).Select(platform => { var name = Invariant($"Platform {platform}"); var versions = Enumerable.Range(1, 5) .Select(version => new TargetPlatformVersion { PlatformName = name, Version = new Version(version, 0) }) .ToList(); return(new TargetPlatform { Name = name, Versions = versions }); }).ToList(); // Select the Excel format and another one. foreach (var format in resultFormats.Take(3)) { format.IsSelected = true; } var model = new OptionsModel { Formats = resultFormats, Platforms = platforms, OutputDirectory = Path.GetTempPath() }; using (var viewModel = new OptionsViewModel(service, targetMapper, model)) { var allPlatforms = platforms.SelectMany(x => x.Versions).ToArray(); int count = 1; while (count < (ApiPortClient.MaxNumberOfTargets + 2)) { allPlatforms[count].IsSelected = true; Assert.False(viewModel.HasError); Assert.True(string.IsNullOrEmpty(viewModel.ErrorMessage)); count++; } } }
public ActionResult Save(OptionsModel options) { HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache); OptionsHelper.SaveOptions(options, this); return(new EmptyResult()); }
public void OptionsViewModel_TargetCount_WhenSelectedAndNot() { var service = Substitute.For <IApiPortService>(); var progressReporter = Substitute.For <IProgressReporter>(); var targetMapper = Substitute.For <ITargetMapper>(); var dependencyFinder = Substitute.For <IDependencyFinder>(); var reportGenerator = Substitute.For <IReportGenerator>(); var ignoreAssemblyInfoList = Substitute.For <IEnumerable <IgnoreAssemblyInfo> >(); var writer = Substitute.For <IFileWriter>(); var client = new ApiPortClient(service, progressReporter, targetMapper, dependencyFinder, reportGenerator, ignoreAssemblyInfoList, writer); var options = Substitute.For <IApiPortOptions>(); var platforms = Enumerable.Range(0, 20).Select(platform => { var name = Invariant($"Platform {platform}"); var versions = Enumerable.Range(1, 5) .Select(version => new TargetPlatformVersion { PlatformName = name, Version = new Version(version, 0), IsSelected = true }) .ToList(); return(new TargetPlatform { Name = name, Versions = versions }); }).ToList(); var excel = new SelectedResultFormat { DisplayName = "Excel", IsSelected = true, FileExtension = ".xlsx", MimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }; var resultFormats = Enumerable.Range(0, 5) .Select(x => new SelectedResultFormat { DisplayName = Invariant($"{nameof(SelectedResultFormat.DisplayName)} {x}"), FileExtension = Invariant($".{x}"), MimeType = Invariant($"type-{x}") }) .ToList(); // Select the Excel format and another one. resultFormats.Add(excel); foreach (var format in resultFormats.Take(3)) { format.IsSelected = true; } var model = new OptionsModel { Formats = resultFormats, Platforms = platforms, OutputDirectory = Path.GetTempPath() }; using (var viewModel = new OptionsViewModel(service, targetMapper, model)) { // Check that when we select > MaxTargets and Excel is selected, it is in an error state. Assert.True(viewModel.HasError); Assert.True(!string.IsNullOrEmpty(viewModel.ErrorMessage)); // Uncheck the excel format excel.IsSelected = false; // Assert that the viewModel no longer has an error. Assert.False(viewModel.HasError); Assert.True(string.IsNullOrEmpty(viewModel.ErrorMessage)); } }
/// <summary> /// 保存旧选项数据 /// </summary> public void SaveOldOptions() { string optionsStr = JsonConvert.SerializeObject(options); oldOptions_ = JsonConvert.DeserializeObject <OptionsModel>(optionsStr); }
public void OptionsViewModel_TargetCount_Excel() { var service = Substitute.For <IApiPortService>(); var progressReporter = Substitute.For <IProgressReporter>(); var targetMapper = Substitute.For <ITargetMapper>(); var dependencyFinder = Substitute.For <IDependencyFinder>(); var reportGenerator = Substitute.For <IReportGenerator>(); var ignoreAssemblyInfoList = Substitute.For <IEnumerable <IgnoreAssemblyInfo> >(); var writer = Substitute.For <IFileWriter>(); var client = new ApiPortClient(service, progressReporter, targetMapper, dependencyFinder, reportGenerator, ignoreAssemblyInfoList, writer); var options = Substitute.For <IApiPortOptions>(); var resultFormats = Enumerable.Range(0, 5) .Select(x => new SelectedResultFormat { DisplayName = Invariant($"{nameof(SelectedResultFormat.DisplayName)} {x}"), FileExtension = Invariant($".{x}"), MimeType = Invariant($"type-{x}") }) .ToList(); var platforms = Enumerable.Range(0, 20).Select(platform => { var name = Invariant($"Platform {platform}"); var versions = Enumerable.Range(1, 5) .Select(version => new TargetPlatformVersion { PlatformName = name, Version = new Version(version, 0) }) .ToList(); return(new TargetPlatform { Name = name, Versions = versions }); }).ToList(); // Select the Excel format and another one. resultFormats.Add(new SelectedResultFormat { DisplayName = "Excel", IsSelected = true, FileExtension = ".xlsx", MimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }); resultFormats.First().IsSelected = true; var model = new OptionsModel { Formats = resultFormats, Platforms = platforms, OutputDirectory = Path.GetTempPath() }; using (var viewModel = new OptionsViewModel(service, targetMapper, model)) { var allPlatforms = platforms.SelectMany(x => x.Versions).ToArray(); int count = 1; while (count < (ApiPortClient.MaxNumberOfTargets + 2)) { allPlatforms[count].IsSelected = true; if (count > ApiPortClient.MaxNumberOfTargets) { Assert.True(viewModel.HasError); Assert.True(!string.IsNullOrEmpty(viewModel.ErrorMessage), "There should be an error message set after too many targets selected and the Excel format is selected."); } else { Assert.False(viewModel.HasError); Assert.True(string.IsNullOrEmpty(viewModel.ErrorMessage)); } count++; } } }
protected override void Reset() { OptionsModel.Reset(); }
public async Task <string> TestWebDavConnection(OptionsModel options) { string url = options.CalenderUrl; if (options.SelectedFolderOrNull == null) { MessageBox.Show(Strings.Get($"Please select an Outlook folder to specify the item type for this profile"), ConnectionTestCaption); return(url); } var outlookFolderType = options.SelectedFolderOrNull.DefaultItemType; string serverUrl = url; StringBuilder errorMessageBuilder = new StringBuilder(); if (string.IsNullOrEmpty(url) && (!string.IsNullOrEmpty(options.EmailAddress) || !string.IsNullOrEmpty(options.UserName))) { var lookupEmail = !string.IsNullOrEmpty(options.EmailAddress) ? options.EmailAddress : options.UserName; if (!ValidateEmailAddress(errorMessageBuilder, lookupEmail, true)) { MessageBox.Show(errorMessageBuilder.ToString(), Strings.Get($"The Email address is invalid"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(url); } bool success; serverUrl = DoSrvLookup(lookupEmail, outlookFolderType, out success); } if (!ValidateWebDavUrl(serverUrl, errorMessageBuilder, false)) { MessageBox.Show(errorMessageBuilder.ToString(), Strings.Get($"The CalDav/CardDav URL is invalid"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(url); } var enteredUri = new Uri(serverUrl); var webDavClient = options.CreateWebDavClient(enteredUri); Uri autoDiscoveredUrl; if (ConnectionTester.RequiresAutoDiscovery(enteredUri)) { var autodiscoveryResult = await DoAutoDiscovery(enteredUri, webDavClient, true, true, outlookFolderType); switch (autodiscoveryResult.Status) { case AutoDiscoverResultStatus.UserCancelled: return(url); case AutoDiscoverResultStatus.ResourceSelected: autoDiscoveredUrl = autodiscoveryResult.RessourceUrl; break; case AutoDiscoverResultStatus.NoResourcesFound: var autodiscoveryResult2 = await DoAutoDiscovery(enteredUri.AbsolutePath.EndsWith("/")?enteredUri : new Uri(enteredUri.ToString() + "/"), webDavClient, false, false, outlookFolderType); switch (autodiscoveryResult2.Status) { case AutoDiscoverResultStatus.UserCancelled: return(url); case AutoDiscoverResultStatus.ResourceSelected: autoDiscoveredUrl = autodiscoveryResult2.RessourceUrl; break; case AutoDiscoverResultStatus.NoResourcesFound: MessageBox.Show(Strings.Get($"No resources were found via autodiscovery!"), ConnectionTestCaption); return(url); default: throw new NotImplementedException(autodiscoveryResult2.Status.ToString()); } break; default: throw new NotImplementedException(autodiscoveryResult.Status.ToString()); } } else { var result = await ConnectionTester.TestConnection(enteredUri, webDavClient); if (result.ResourceType != ResourceType.None) { FixSynchronizationMode(options, result); FixWebDavCollectionSync(options, result); UpdateServerEmailAndSchedulingSettings(options, result); DisplayTestReport( result, options.SynchronizationMode, _enumDisplayNameProvider.Get(options.SynchronizationMode), outlookFolderType); return(url); } else { var autodiscoveryResult = await DoAutoDiscovery(enteredUri, webDavClient, false, false, outlookFolderType); switch (autodiscoveryResult.Status) { case AutoDiscoverResultStatus.UserCancelled: return(url); case AutoDiscoverResultStatus.ResourceSelected: autoDiscoveredUrl = autodiscoveryResult.RessourceUrl; break; case AutoDiscoverResultStatus.NoResourcesFound: var autodiscoveryResult2 = await DoAutoDiscovery(enteredUri, webDavClient, true, true, outlookFolderType); switch (autodiscoveryResult2.Status) { case AutoDiscoverResultStatus.UserCancelled: return(url); case AutoDiscoverResultStatus.ResourceSelected: autoDiscoveredUrl = autodiscoveryResult2.RessourceUrl; break; case AutoDiscoverResultStatus.NoResourcesFound: MessageBox.Show(Strings.Get($"No resources were found via autodiscovery!"), ConnectionTestCaption); return(url); default: throw new NotImplementedException(autodiscoveryResult2.Status.ToString()); } break; default: throw new NotImplementedException(autodiscoveryResult.Status.ToString()); } } } var finalResult = await ConnectionTester.TestConnection(autoDiscoveredUrl, webDavClient); FixSynchronizationMode(options, finalResult); FixWebDavCollectionSync(options, finalResult); UpdateServerEmailAndSchedulingSettings(options, finalResult); DisplayTestReport( finalResult, options.SynchronizationMode, _enumDisplayNameProvider.Get(options.SynchronizationMode), outlookFolderType); return(autoDiscoveredUrl.ToString()); }
public void FixTimeRangeUsage(OptionsModel options, OlItemType?folderType) { options.UseSynchronizationTimeRange = folderType != OlItemType.olContactItem; }
public async Task <string> TestGoogleConnection(OptionsModel options, string url) { if (options.SelectedFolderOrNull == null) { MessageBox.Show(Strings.Get($"Please select an Outlook folder to specify the item type for this profile"), ConnectionTestCaption); return(url); } var outlookFolderType = options.SelectedFolderOrNull.DefaultItemType; StringBuilder errorMessageBuilder = new StringBuilder(); if (!ValidateEmailAddress(errorMessageBuilder, options.EmailAddress, false)) { MessageBox.Show(errorMessageBuilder.ToString(), Strings.Get($"The Email address is invalid"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(url); } if (outlookFolderType == OlItemType.olTaskItem) { return(await TestGoogleTaskConnection(options, errorMessageBuilder, outlookFolderType, url)); } if (outlookFolderType == OlItemType.olContactItem && options.UseGoogleNativeApi) { return(await TestGoogleContactsConnection(options, outlookFolderType, url)); } if (!ValidateWebDavUrl(url, errorMessageBuilder, false)) { MessageBox.Show(errorMessageBuilder.ToString(), Strings.Get($"The CalDav/CardDav URL is invalid"), MessageBoxButtons.OK, MessageBoxIcon.Error); return(url); } var enteredUri = new Uri(url); var webDavClient = options.CreateWebDavClient(enteredUri); Uri autoDiscoveredUrl; if (ConnectionTester.RequiresAutoDiscovery(enteredUri)) { var autoDiscoveryResult = await DoAutoDiscovery(enteredUri, webDavClient, false, true, outlookFolderType); switch (autoDiscoveryResult.Status) { case AutoDiscoverResultStatus.UserCancelled: return(url); case AutoDiscoverResultStatus.ResourceSelected: autoDiscoveredUrl = autoDiscoveryResult.RessourceUrl; break; default: autoDiscoveredUrl = null; break; } } else { autoDiscoveredUrl = null; } var finalUrl = autoDiscoveredUrl?.ToString() ?? url; var result = await ConnectionTester.TestConnection(new Uri(finalUrl), webDavClient); if (result.ResourceType != ResourceType.None) { FixSynchronizationMode(options, result); FixWebDavCollectionSync(options, result); } if (outlookFolderType == OlItemType.olContactItem) { // Google Addressbook doesn't have any properties. As long as there doesn't occur an exception, the test is successful. MessageBox.Show(Strings.Get($"Connection test successful."), ConnectionTestCaption); } else { DisplayTestReport( result, options.SynchronizationMode, _enumDisplayNameProvider.Get(options.SynchronizationMode), outlookFolderType); } return(finalUrl); }