private IPublishService CreatePublisher(string name) { var options = _optionsMonitor.Get(name); var publisher = new PublishService(_provider.GetService <ILogger <PublishService> >(), options); return(publisher); }
public async Task <object> Handle(DesignHub hub, InvokeArgs args) { var modelID = args.GetString(); var methodName = args.GetString(); var methodArgs = args.GetString(); var breakpoints = args.GetString(); //先编译服务模型,将编译结果保存至当前会话的调试目录内 var debugFolder = Path.Combine(Runtime.RuntimeContext.Current.AppPath, "debug", hub.Session.SessionID.ToString()); if (Directory.Exists(debugFolder)) { Directory.Delete(debugFolder, true); } Directory.CreateDirectory(debugFolder); var serviceNode = hub.DesignTree.FindModelNode(ModelType.Service, ulong.Parse(modelID)); await PublishService.CompileServiceAsync(hub, (ServiceModel)serviceNode.Model, debugFolder); //释放第三方组件库 TODO:暂简单实现 var debugLibPath = Path.Combine(debugFolder, "lib"); await Store.ModelStore.ExtractAppAssemblies(serviceNode.AppNode.Model.Name, debugLibPath); //启动调试进程 var appName = serviceNode.AppNode.Model.Name; hub.DebugService.DebugSourcePath = $"{appName}.Services.{serviceNode.Model.Name}.cs"; hub.DebugService.StartDebugger($"{appName}.{serviceNode.Model.Name}.{methodName}", methodArgs, breakpoints); return(null); }
public void PublishService_Send_CallProducer() { var moqProducer = A.Fake <IProducer>(); var moqProducerSettings = new ProducerSettings() { Producer = moqProducer }; var moqSerializer = A.Fake <ISerializer <string> >(); A.CallTo(() => moqSerializer.Serialize(A <string> ._)) .Returns(new byte[] { 0x0, 0x1, 0x2 }); var moqPublishSettings = new PublishSettings <string>() { Serializer = moqSerializer }; var moqOptionsSnapshot = A.Fake <IOptionsSnapshot <PublishSettings <string> > >(); A.CallTo(() => moqOptionsSnapshot.Get(A <string> ._)).Returns(moqPublishSettings); var publishSerivce = new PublishService <string>(moqProducerSettings, moqOptionsSnapshot, "topicName"); publishSerivce.Send("test msg"); A.CallTo(() => moqProducer.Send("topicName", A <byte[]> .That.IsSameSequenceAs(new byte[] { 0x0, 0x1, 0x2 }))) .MustHaveHappenedOnceExactly(); }
private void Refresh() { _fresherr = null; UnableToolBarAll(); if (_message != null) { RefreshView(_message as Dictionary <string, object>); } else { Thread t = new Thread(delegate() { try { PublishService ps = new PublishService(ClientReportContext.Login.U8Login); ps.RunTask(_publishid); } catch (Exception fex) { _fresherr = fex.Message; } this.BeginInvoke(new FreshDelegate(Fresh)); } ); t.Start(); } }
public void PublishService_SendBatch_CallSerializer() { var moqProducerSettings = new ProducerSettings() { Producer = A.Fake <IProducer>() }; var moqSerializer = A.Fake <ISerializer <string> >(); var moqPublishSettings = new PublishSettings <string>() { Serializer = moqSerializer }; var moqOptionsSnapshot = A.Fake <IOptionsSnapshot <PublishSettings <string> > >(); A.CallTo(() => moqOptionsSnapshot.Get(A <string> ._)).Returns(moqPublishSettings); var publishSerivce = new PublishService <string>(moqProducerSettings, moqOptionsSnapshot, "topicName"); publishSerivce.SendBatch("test msg", "test msg1", "test msg2"); A.CallTo( () => moqSerializer.Serialize(A <string> .That.IsSameAs("test msg")) ).MustHaveHappenedOnceExactly(); A.CallTo( () => moqSerializer.Serialize(A <string> .That.IsSameAs("test msg1")) ).MustHaveHappenedOnceExactly(); A.CallTo( () => moqSerializer.Serialize(A <string> .That.IsSameAs("test msg2")) ).MustHaveHappenedOnceExactly(); }
public void OneTimeSetUp() { publisherlogger = new Mock <ILogger <PublishService> >(); subscriberlogger = new Mock <ILogger <QueueService> >(); publisher = new PublishService(publisherlogger.Object, ExposedRabbitService.validConfig); queue = new QueueService(ExposedRabbitService.validConfig, subscriberlogger.Object); handler.Handler = Process; }
public Result Ini(ProjModel projModel) { Result res = new Result(); try { _projModel = projModel; _dirSimpleNames = ProjModel.ToDirSimpleNames(projModel.PublishDir); if (_projModel.ProjType == "Library") { lbAppType.Text = "IIS"; _appViews = PublishService.GetAllIISAppNames(); if (_appViews == null || !_appViews.Any()) { throw new Exception("未连接到可用的IIS服务"); } } else { lbAppType.Text = "Exe"; _appViews = PublishService.GetExeAppView(_projModel.LibName); if (_appViews == null || !_appViews.Any()) { throw new Exception("未找到该进程"); } } cbAppName.DataSource = _appViews; cbAppName.DisplayMember = "AppAlias"; cbAppName.ValueMember = "AppPhysicalPath"; cbAppName.SelectedIndex = _appViews.FindIndex(n => n.Id == _projModel.LastChooseInfo.LastChooseAppName); showLbText(lbAppPath, (cbAppName.SelectedItem as AppView)?.AppPhysicalPath ?? string.Empty); cbAppPublishDir.DataSource = _dirSimpleNames; cbAppPublishDir.DisplayMember = "Name"; cbAppPublishDir.ValueMember = "FullName"; string lastChoosePublishDir = _projModel.LastChooseInfo.LastChoosePublishDir ?? _dirSimpleNames[0].FullName; _projModel.LastChooseInfo.LastChoosePublishDir = lastChoosePublishDir; cbAppPublishDir.SelectedIndex = cbAppPublishDir.FindString(_dirSimpleNames.Count > 0 ? new DirectoryInfo(_projModel.LastChooseInfo.LastChoosePublishDir ?? _dirSimpleNames[0].FullName) .Name : string.Empty); lbChoosedFiles.Text = $"(已选择{_projModel?.LastChooseInfo?.LastChoosePublishFiles?.Where(n => !n.EndsWith("pdb"))?.Count() ?? 0}个文件)"; isIni = false; res.IsSucceed = true; } catch (Exception e) { res.Message = e.Message; } return(res); }
public PublishServiceTest() { var publishs = new List<Publish> { new Publish {PublishID="001" }, new Publish {PublishID="002" } }; db.Publish = new FakeDbSet<Publish>(publishs); service = new PublishService(db); }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void Execute(object sender, EventArgs e) { try { ThreadHelper.ThrowIfNotOnUIThread(); var projInfo = ThreadHelper.JoinableTaskFactory.Run(GetSelectedProjInfoAsync); if (projInfo == null) { throw new Exception("您还未选中项目"); } if (projInfo.Kind != "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") { throw new Exception("当前插件仅支持C#程序"); } var projModel = projInfo.AnalysisProject(); if (projModel == null) { throw new Exception("项目信息解析失败"); } OptionPageGrid settingInfo = PublishService.GetSettingPage(); if (string.IsNullOrWhiteSpace(settingInfo?.IpAdress)) { throw new Exception("请先完善设置信息"); } // 尝试连接服务器 //var isConnected = PublishService.CheckConnection(); //if (!isConnected) //{ // throw new Exception("尝试连接服务器失败"); //} //var publishForm = new PublishForm(); //publishForm.Show(); //publishForm.Ini(projModel); var form = new DeployForm(); var iniRes = form.Ini(projModel); if (iniRes.IsSucceed) { form.Show(); } else { MessageBox.Show(iniRes.Message); } } catch (Exception exception) { MessageBox.Show(exception.Message); } }
private void OpenView(string instanceid, StaticArgs e) { if (instanceid != null && instanceid.Trim().ToUpper() == "E13B77F9-4122-4BF1-8C38-97313111C36D") { PortalView(); } else { _publishid = instanceid; if (CheckRealTimeQuery(instanceid)) { _brealtime = true; PublishService ps = new PublishService(ClientReportContext.Login.U8Login); _context.FilterArgs = ps.GetFilterArgs(_publishid); if (!string.IsNullOrEmpty(_currentduration)) { if (_context.FilterArgs.FltSrv.Contains("CurrentDuration")) { _context.FilterArgs.FltSrv["CurrentDuration"].Value1 = _currentduration; } else if (_context.FilterArgs.FltSrv.Contains("AutoCurrentDuration")) { _context.FilterArgs.FltSrv["AutoCurrentDuration"].Value1 = _currentduration; } } RealTimeQuery(true); } else { SetInfos(instanceid); if (!string.IsNullOrEmpty(_staticid)) { UnableToolBarAll(); tlbtime.Text = U8ResService.GetResStringEx("U8.UAP.Report.数据生成时间") + _datatime.ToLongDateString() + " " + _datatime.ToLongTimeString(); tlbtime.ToolTipText = tlbtime.Text; _context.Initialize(_staticid, ReportStates.Static, ReportType.IndicatorReport); if (e == null) { e = new StaticArgs(); } e.staticid = _context.StaticID; e.eventfilter = _eventfilter; RunWithCache(e); } else { EmptyView(); } } } }
private void bwUploadZip_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { try { var now = DateTime.Now; string pathTmp = _projModel.LibDebugPath; if (_projModel.ProjType == "Library") { pathTmp = new DirectoryInfo(pathTmp).Parent?.FullName ?? pathTmp; } string zipFullPath = Path.Combine(pathTmp, _projModel.LibName + ".zip"); if (bwUploadZip.CancellationPending) { e.Cancel = true; return; } bwUploadZip.ReportProgress(50, "压缩文件中..."); ZipHelper.BatchZip(_projModel.LastChooseInfo.LastChoosePublishFiles, zipFullPath, _projModel.LastChooseInfo.LastChoosePublishDir, (progressValue) => { bwUploadZip.ReportProgress(50 + (int)(progressValue * 0.4), "压缩文件中..."); if (bwUploadZip.CancellationPending) { e.Cancel = true; return(true); } return(false); }); NameValueCollection dic = new NameValueCollection(); dic.Add("Type", _projModel.ProjType == "Library" ? "iis" : "exe"); dic.Add("AppId", e.Argument.ToString()); if (bwUploadZip.CancellationPending) { e.Cancel = true; return; } bwUploadZip.ReportProgress(90, "文件上传中..."); string url = $"{PublishService.GetSettingPage().GetApiUrl()}/UploadZip"; string uploadResStr = HttpHelper.HttpPostData(url, 30000, _projModel.LibName + ".zip", zipFullPath, dic); var uploadRes = uploadResStr.DeserializeObject <Result>(); string msg = uploadRes.IsSucceed ? "部署成功" : "部署失败:" + uploadRes.Message; var timeSpan = (DateTime.Now - now).TotalMilliseconds; bwUploadZip.ReportProgress(100, msg + ",耗时:" + timeSpan); } catch (Exception exception) { bwUploadZip.ReportProgress(0, $"发布失败:{exception.Message }"); } }
static async Task Main(string[] args) { var settings = new RabbitMqConfig { HostName = "localhost", Port = 5672, UserName = "******", Password = "******", VirtualHost = "/", ExchangePrefix = "myTestExchange", }; using var consumeMngr = ConsumeManager.Create(settings); consumeMngr.AddConsumer("myTestQueue2", new Action <TestDto>(TestConsumer.ProcessMessage), true); consumeMngr.ConnectionRecoveredEvent += RabbitConnectionRecovered; consumeMngr.ConnectionShutdownEvent += RabbitConnectionShutdown; var pubSrv = PublishService.Create(settings); Console.WriteLine("App started"); var id = 0; while (true) { Console.WriteLine(); var message = Console.ReadLine(); if (message == "q" || message == "quit") { break; } var dto = new TestDto { Id = ++id, Guid = Guid.NewGuid(), Message = message }; await pubSrv.PublishAsync(dto); pubSrv.Publish(dto); } consumeMngr.ConnectionRecoveredEvent -= RabbitConnectionRecovered; consumeMngr.ConnectionShutdownEvent -= RabbitConnectionShutdown; }
public async Task <object> Handle(DesignHub hub, InvokeArgs args) { string commitMessage = args.GetString(); if (hub.PendingChanges == null || hub.PendingChanges.Length == 0) { return(null); } //将PendingChanges转为PublishPackage var package = new PublishPackage(); for (int i = 0; i < hub.PendingChanges.Length; i++) { var change = hub.PendingChanges[i]; switch (change) { case ModelBase model: package.Models.Add(model); break; case ModelFolder folder: package.Folders.Add(folder); break; case StagedItems.StagedSourceCode code: package.SourceCodes.Add(code.ModelId, code.CodeData); break; case StagedItems.StagedViewRuntimeCode viewAsm: { //先找到名称 var viewModelNode = hub.DesignTree.FindModelNode(ModelType.View, viewAsm.ModelId); string asmName = $"{viewModelNode.AppNode.Model.Name}.{viewModelNode.Model.Name}"; package.ViewAssemblies.Add(asmName, viewAsm.CodeData); } break; default: Log.Warn($"Unknow pending change: {change.GetType()}"); break; } } PublishService.ValidateModels(hub, package); await PublishService.CompileModelsAsync(hub, package); await PublishService.PublishAsync(hub, package, commitMessage); //最后清空临时用的PendingChanges hub.PendingChanges = null; return(null); }
public void PublishService_GetOptionByTopicName() { var moqProducerSettings = new ProducerSettings() { Producer = A.Fake <IProducer>() }; var moqOptionsSnapshot = A.Fake <IOptionsSnapshot <PublishSettings <string> > >(); A.CallTo(() => moqOptionsSnapshot.Get(A <string> .That.Not.IsEqualTo("topicName"))) .Throws(new Exception("Not valid copnfiguration name.")); var publishSerivce = new PublishService <string>(moqProducerSettings, moqOptionsSnapshot, "topicName"); }
public void Given_NullParameter_Constructor_ShouldThrow_ArgumentNullException() { Action action1 = () => { var service = new PublishService(null, this._markdownHelper.Object, this._fileHelper.Object, this._httpClientHelper.Object); }; action1.ShouldThrow <ArgumentNullException>(); Action action2 = () => { var service = new PublishService(this._settings.Object, null, this._fileHelper.Object, this._httpClientHelper.Object); }; action2.ShouldThrow <ArgumentNullException>(); Action action3 = () => { var service = new PublishService(this._settings.Object, this._markdownHelper.Object, null, this._httpClientHelper.Object); }; action3.ShouldThrow <ArgumentNullException>(); Action action4 = () => { var service = new PublishService(this._settings.Object, this._markdownHelper.Object, this._fileHelper.Object, null); }; action4.ShouldThrow <ArgumentNullException>(); }
void Publish() { // Create the Instance of the Service Class. serverContract = new ServerContract(); // Create the Service Host using the INSTANCE I just created. WCF.Server.ServerHost <WCF.Contracts.ServerContract> WCFServerHost = new WCF.Server.ServerHost <WCF.Contracts.ServerContract>(serverContract, baseAddress); // I am using NetTcpBinding in case someone would like to know. // Get the Singleton Instance [InstanceMode.Singleton Pattern] PublishService = (ServerContract)WCF_Server.SingletonInstance; List <products> productList = new List <products>(new Product(), new Product()); System.ServiceModel.Channels.CommunicationObject comm = WCF_Server; if (comm.State == CommunicationState.Opened) { PublishService.PushProductsToClients(productList); } }
private static async Task DeleteApplicationNode(DesignHub hub, ApplicationNode appNode) { //TODO:*****暂简单实现,待实现: 签出所有子节点,判断有无其他应用的引用 //TODO:考虑删除整个应用前自动导出备份 //先组包用现有PublishService发布(删除) var pkg = new PublishPackage(); var modelNodes = appNode.GetAllModelNodes(); foreach (var modelNode in modelNodes) { if (modelNode.Model.PersistentState != PersistentState.Detached) { modelNode.Model.MarkDeleted(); pkg.Models.Add(modelNode.Model); //不用加入需要删除的相关代码及组件 } //删除所有Roslyn相关 RemoveRoslynFromModelNode(hub, modelNode); } //加入待删除的根级文件夹 var rootFolders = appNode.GetAllRootFolders(); foreach (var rootFolder in rootFolders) { rootFolder.IsDeleted = true; pkg.Folders.Add(rootFolder); } //TODO:暂使用PublishService.PublishAsync,且与删除ApplicationModel非事务 await PublishService.PublishAsync(hub, pkg, $"Delete Application: {appNode.Model.Name}"); //删除ApplicationModel await Store.ModelStore.DeleteApplicationAsync(appNode.Model); //TODO:清理Staged(只清理当前删除的App相关的) //最后从设计树移除ApplicationNode hub.DesignTree.AppRootNode.Nodes.Remove(appNode); }
private static async Task UpdateApp(DesignHub ctx, AppPackage from, ApplicationModel localAppModel) { //TODO:考虑删除本地已签出的所有变更 //TODO:1.签出本地对应App的所有节点,包括模型根节点 var local = new AppPackage(); await ModelStore.LoadToAppPackage(localAppModel.Id, localAppModel.Name, local); var publish = new PublishPackage(); //----比对文件夹---- var folderComparer = new FolderComparer(); var newFolders = from.Folders.Except(local.Folders, folderComparer); foreach (var newFolder in newFolders) { newFolder.Import(); publish.Folders.Add(newFolder); } //var removedFolders = local.Folders.Except(from.Folders, folderComparer); //foreach (var removedFolder in removedFolders) //{ // removedFolder.Remove(); // publish.Folders.Add(removedFolder); //} var otherFolders = local.Folders.Intersect(from.Folders, folderComparer); foreach (var folder in otherFolders) { if (folder.UpdateFrom(from.Folders.Single(t => t.TargetModelType == folder.TargetModelType && t.Id == folder.Id))) { publish.Folders.Add(folder); } } //----比对模型---- var modelComparer = new ModelComparer(); var newModels = from.Models.Except(local.Models, modelComparer); foreach (var newModel in newModels) { newModel.Import(); publish.Models.Add(newModel); //导入相关代码及Assembly if (newModel.ModelType == ModelType.Service) { publish.SourceCodes.Add(newModel.Id, from.SourceCodes[newModel.Id]); var key = $"{from.Application.Name}.{newModel.Name}"; publish.ServiceAssemblies.Add(key, from.ServiceAssemblies[key]); } else if (newModel.ModelType == ModelType.View) { publish.SourceCodes.Add(newModel.Id, from.SourceCodes[newModel.Id]); var key = $"{from.Application.Name}.{newModel.Name}"; publish.ViewAssemblies.Add(key, from.ViewAssemblies[key]); } } //if (localAppModel.ID != SysGlobal.SysString) //注意:系统应用包不移除仅本地有的模型 //{ var removedModles = local.Models.Except(from.Models, modelComparer); foreach (var removedModel in removedModles) { removedModel.MarkDeleted(); publish.Models.Add(removedModel); //删除模型的相关代码组件等由PublishService处理,不用再加入 } //} var otherModels = local.Models.Intersect(from.Models, modelComparer); foreach (var model in otherModels) { if (model.UpdateFrom(from.Models.Single(t => t.ModelType == model.ModelType && t.Id == model.Id))) { publish.Models.Add(model); } if (model.ModelType == ModelType.Service) { publish.SourceCodes.Add(model.Id, from.SourceCodes[model.Id]); var key = $"{from.Application.Name}.{model.Name}"; publish.ServiceAssemblies.Add(key, from.ServiceAssemblies[key]); } else if (model.ModelType == ModelType.View) { publish.SourceCodes.Add(model.Id, from.SourceCodes[model.Id]); var key = $"{from.Application.Name}.{model.Name}"; publish.ViewAssemblies.Add(key, from.ViewAssemblies[key]); } } //发布变更的包 await PublishService.PublishAsync(ctx, publish, "Import"); }
public MainWindow CreateKeyboard() { ////Apply resource language (and listen for changes) Action <OptiKey.Enums.Languages> applyResourceLanguage = language => OptiKey.Properties.Resources.Culture = language.ToCultureInfo(); Settings.Default.OnPropertyChanges(s => s.UiLanguage).Subscribe(applyResourceLanguage); applyResourceLanguage(Settings.Default.UiLanguage); MainWindow mainWindow; //Define MainViewModel before services so I can setup a delegate to call into the MainViewModel //This is to work around the fact that the MainViewModel is created after the services. OptiKey.UI.ViewModels.MainViewModel mainViewModel = null; Action <KeyValue> fireKeySelectionEvent = kv => { if (mainViewModel != null) //Access to modified closure is a good thing here, for once! { mainViewModel.FireKeySelectionEvent(kv); } }; //Create services var errorNotifyingServices = new List <INotifyErrors>(); IAudioService audioService = new AudioService(); IDictionaryService dictionaryService = new DictionaryService(OptiKey.Enums.AutoCompleteMethods.NGram); IPublishService publishService = new PublishService(); ISuggestionStateService suggestionService = new SuggestionStateService(); ICalibrationService calibrationService = OptiKey.App.CreateCalibrationService(); ICapturingStateManager capturingStateManager = new CapturingStateManager(audioService); ILastMouseActionStateManager lastMouseActionStateManager = new LastMouseActionStateManager(); IKeyStateService keyStateService = new KeyStateService(suggestionService, capturingStateManager, lastMouseActionStateManager, calibrationService, fireKeySelectionEvent); IInputService inputService = CreateInputService(keyStateService, dictionaryService, audioService, calibrationService, capturingStateManager, errorNotifyingServices); IKeyboardOutputService keyboardOutputService = new KeyboardOutputService(keyStateService, suggestionService, publishService, dictionaryService, fireKeySelectionEvent); IMouseOutputService mouseOutputService = new MouseOutputService(publishService); errorNotifyingServices.Add(audioService); errorNotifyingServices.Add(dictionaryService); errorNotifyingServices.Add(publishService); errorNotifyingServices.Add(inputService); //Release keys on application exit //ReleaseKeysOnApplicationExit(keyStateService, publishService); //Compose UI mainWindow = new MainWindow(audioService, dictionaryService, inputService, keyStateService); //for testing just hard code the size and position of the mainWindow ////get the size of the screen Rectangle screenSize = Screen.PrimaryScreen.Bounds; double windowWidth = screenSize.Width - toolBarOffset; double windowHeight = screenSize.Height * 0.40; Rect windowDimensions = new Rect(0, (screenSize.Height - windowHeight) - taskBarOffset, windowWidth, windowHeight); //Settings.Default.MainWindowFloatingSizeAndPosition = windowDimensions; IWindowManipulationService mainWindowManipulationService = new WindowManipulationService( mainWindow, () => Settings.Default.MainWindowOpacity, () => Settings.Default.MainWindowState, () => Settings.Default.MainWindowPreviousState, //() => Settings.Default.MainWindowFloatingSizeAndPosition, () => windowDimensions, () => Settings.Default.MainWindowDockPosition, () => Settings.Default.MainWindowDockSize, () => Settings.Default.MainWindowFullDockThicknessAsPercentageOfScreen, () => Settings.Default.MainWindowCollapsedDockThicknessAsPercentageOfFullDockThickness, () => Settings.Default.MainWindowMinimisedPosition, o => Settings.Default.MainWindowOpacity = o, state => Settings.Default.MainWindowState = state, state => Settings.Default.MainWindowPreviousState = state, rect => Settings.Default.MainWindowFloatingSizeAndPosition = rect, pos => Settings.Default.MainWindowDockPosition = pos, size => Settings.Default.MainWindowDockSize = size, t => Settings.Default.MainWindowFullDockThicknessAsPercentageOfScreen = t, t => Settings.Default.MainWindowCollapsedDockThicknessAsPercentageOfFullDockThickness = t); errorNotifyingServices.Add(mainWindowManipulationService); mainWindow.WindowManipulationService = mainWindowManipulationService; mainViewModel = new MainViewModel( audioService, calibrationService, dictionaryService, keyStateService, suggestionService, capturingStateManager, lastMouseActionStateManager, inputService, keyboardOutputService, mouseOutputService, mainWindowManipulationService, errorNotifyingServices); mainWindow.MainView.DataContext = mainViewModel; //Setup actions to take once main view is loaded (i.e. the view is ready, so hook up the services which kicks everything off) Action postMainViewLoaded = mainViewModel.AttachServiceEventHandlers; if (mainWindow.MainView.IsLoaded) { postMainViewLoaded(); } else { RoutedEventHandler loadedHandler = null; loadedHandler = (s, a) => { postMainViewLoaded(); mainWindow.MainView.Loaded -= loadedHandler; //Ensure this handler only triggers once }; mainWindow.MainView.Loaded += loadedHandler; } //Show the main window ResourceDictionary resourses = new ResourceDictionary(); mainWindow.Resources = resourses; ThemeResourceDictionary themeDictionary = new ThemeResourceDictionary(); resourses.MergedDictionaries.Add(themeDictionary); //setSize //Display splash screen and check for updates (and display message) after the window has been sized and positioned for the 1st time EventHandler sizeAndPositionInitialised = null; sizeAndPositionInitialised = async(_, __) => { mainWindowManipulationService.SizeAndPositionInitialised -= sizeAndPositionInitialised; //Ensure this handler only triggers once inputService.RequestResume(); //Start the input service }; if (mainWindowManipulationService.SizeAndPositionIsInitialised) { sizeAndPositionInitialised(null, null); } else { mainWindowManipulationService.SizeAndPositionInitialised += sizeAndPositionInitialised; } mainWindow.Closed += (_, __) => ReleaseKeysOnApplicationExit(keyStateService, publishService); mainWindow.IsVisibleChanged += (_, __) => ReleaseKeysOnApplicationExit(keyStateService, publishService); return(mainWindow); }
private void PublishMessage(string message) { var publishService = new PublishService(); publishService.PublishMessage(_projectId, _topicId, message); }
public void Setup() { _publishedProviderId = NewRandomString(); _publishedProviderIds = new[] { _publishedProviderId }; _publishedFundingStatusUpdateService = Substitute.For <IPublishedFundingStatusUpdateService>(); _publishingResiliencePolicies = new ResiliencePolicies { PublishedFundingRepository = Policy.NoOpAsync(), CalculationsApiClient = Policy.NoOpAsync(), SpecificationsApiClient = Policy.NoOpAsync(), SpecificationsRepositoryPolicy = Policy.NoOpAsync(), PublishedIndexSearchResiliencePolicy = Policy.NoOpAsync() }; _specificationsApiClient = Substitute.For <ISpecificationsApiClient>(); _specificationService = new SpecificationService(_specificationsApiClient, _publishingResiliencePolicies); _specificationFundingStatusService = Substitute.For <ISpecificationFundingStatusService>(); _jobsRunning = Substitute.For <IJobsRunning>(); _logger = Substitute.For <ILogger>(); _publishedFundingChangeDetectorService = Substitute.For <IPublishedFundingChangeDetectorService>(); _publishedFundingGenerator = Substitute.For <IPublishedFundingGenerator>(); _publishedProviderContentsGeneratorResolver = Substitute.For <IPublishedProviderContentsGeneratorResolver>(); _publishedFundingContentsPersistanceService = Substitute.For <IPublishedFundingContentsPersistanceService>(); _publishedProviderContentsPersistanceService = Substitute.For <IPublishedProviderContentPersistanceService>(); _publishedProviderStatusUpdateService = Substitute.For <IPublishedProviderStatusUpdateService>(); _publishedFundingSearchRepository = Substitute.For <ISearchRepository <PublishedFundingIndex> >(); _calculationsApiClient = Substitute.For <ICalculationsApiClient>(); _providerService = Substitute.For <IProviderService>(); _jobManagement = Substitute.For <IJobManagement>(); _prerequisiteCheckerLocator = Substitute.For <IPrerequisiteCheckerLocator>(); _prerequisiteCheckerLocator.GetPreReqChecker(PrerequisiteCheckerType.ReleaseAllProviders) .Returns(new PublishAllPrerequisiteChecker(_specificationFundingStatusService, _jobsRunning, _jobManagement, _logger)); _prerequisiteCheckerLocator.GetPreReqChecker(PrerequisiteCheckerType.ReleaseBatchProviders) .Returns(new PublishBatchPrerequisiteChecker(_specificationFundingStatusService, _jobsRunning, _jobManagement, _logger)); _generateCsvJobsLocator = Substitute.For <IGeneratePublishedFundingCsvJobsCreationLocator>(); _mapper = Substitute.For <IMapper>(); _transactionFactory = new TransactionFactory(_logger, new TransactionResiliencePolicies { TransactionPolicy = Policy.NoOpAsync() }); _publishedProviderVersionService = Substitute.For <IPublishedProviderVersionService>(); _publishedFundingDataService = Substitute.For <IPublishedFundingDataService>(); _policiesService = Substitute.For <IPoliciesService>(); _organisationGroupGenerator = Substitute.For <IOrganisationGroupGenerator>(); _publishedFundingChangeDetectorService = Substitute.For <IPublishedFundingChangeDetectorService>(); _publishedFundingDateService = Substitute.For <IPublishedFundingDateService>(); _publishedFundingDataService = Substitute.For <IPublishedFundingDataService>(); _createPublishIntegrityJob = Substitute.For <ICreatePublishIntegrityJob>(); _publishedFundingService = new PublishedFundingService(_publishedFundingDataService, _publishingResiliencePolicies, _policiesService, _organisationGroupGenerator, _publishedFundingChangeDetectorService, _publishedFundingDateService, _mapper, _logger); _publishService = new PublishService(_publishedFundingStatusUpdateService, _publishingResiliencePolicies, _specificationService, _prerequisiteCheckerLocator, _publishedFundingChangeDetectorService, _publishedFundingGenerator, _publishedProviderContentsGeneratorResolver, _publishedFundingContentsPersistanceService, _publishedProviderContentsPersistanceService, _publishedProviderStatusUpdateService, _providerService, _publishedFundingSearchRepository, _calculationsApiClient, _logger, _jobManagement, _generateCsvJobsLocator, _transactionFactory, _publishedProviderVersionService, _publishedFundingService, _publishedFundingDataService, _policiesService, _createPublishIntegrityJob ); }
private void App_OnStartup(object sender, StartupEventArgs e) { try { Log.Info("Boot strapping the services and UI."); // We manually close this because automatic closure steals focus from the // dynamic splash screen. splashScreen.Close(TimeSpan.FromSeconds(0.5f)); //Apply theme applyTheme(); //Define MainViewModel before services so I can setup a delegate to call into the MainViewModel //This is to work around the fact that the MainViewModel is created after the services. MainViewModel mainViewModel = null; Action <KeyValue> fireKeySelectionEvent = kv => { if (mainViewModel != null) //Access to modified closure is a good thing here, for once! { mainViewModel.FireKeySelectionEvent(kv); } }; CleanupAndPrepareCommuniKateInitialState(); ValidateDynamicKeyboardLocation(); // Handle plugins. Validate if directory exists and is accessible and pre-load all plugins, building a in-memory list of available ones. ValidatePluginsLocation(); if (Settings.Default.EnablePlugins) { PluginEngine.LoadAvailablePlugins(); } var presageInstallationProblem = PresageInstallationProblemsDetected(); //Create services var errorNotifyingServices = new List <INotifyErrors>(); IAudioService audioService = new AudioService(); IDictionaryService dictionaryService = new DictionaryService(Settings.Default.SuggestionMethod); IPublishService publishService = new PublishService(); ISuggestionStateService suggestionService = new SuggestionStateService(); ICalibrationService calibrationService = CreateCalibrationService(); ICapturingStateManager capturingStateManager = new CapturingStateManager(audioService); ILastMouseActionStateManager lastMouseActionStateManager = new LastMouseActionStateManager(); IKeyStateService keyStateService = new KeyStateService(suggestionService, capturingStateManager, lastMouseActionStateManager, calibrationService, fireKeySelectionEvent); IInputService inputService = CreateInputService(keyStateService, dictionaryService, audioService, calibrationService, capturingStateManager, errorNotifyingServices); IKeyboardOutputService keyboardOutputService = new KeyboardOutputService(keyStateService, suggestionService, publishService, dictionaryService, fireKeySelectionEvent); IMouseOutputService mouseOutputService = new MouseOutputService(publishService); errorNotifyingServices.Add(audioService); errorNotifyingServices.Add(dictionaryService); errorNotifyingServices.Add(publishService); errorNotifyingServices.Add(inputService); ReleaseKeysOnApplicationExit(keyStateService, publishService); //Compose UI var mainWindow = new MainWindow(audioService, dictionaryService, inputService, keyStateService); IWindowManipulationService mainWindowManipulationService = CreateMainWindowManipulationService(mainWindow); errorNotifyingServices.Add(mainWindowManipulationService); mainWindow.WindowManipulationService = mainWindowManipulationService; //Subscribing to the on closing events. mainWindow.Closing += dictionaryService.OnAppClosing; mainViewModel = new MainViewModel( audioService, calibrationService, dictionaryService, keyStateService, suggestionService, capturingStateManager, lastMouseActionStateManager, inputService, keyboardOutputService, mouseOutputService, mainWindowManipulationService, errorNotifyingServices); mainWindow.SetMainViewModel(mainViewModel); //Setup actions to take once main view is loaded (i.e. the view is ready, so hook up the services which kicks everything off) Action postMainViewLoaded = () => { mainViewModel.AttachErrorNotifyingServiceHandlers(); mainViewModel.AttachInputServiceEventHandlers(); }; mainWindow.AddOnMainViewLoadedAction(postMainViewLoaded); //Show the main window mainWindow.Show(); if (Settings.Default.LookToScrollShowOverlayWindow) { // Create the overlay window, but don't show it yet. It'll make itself visible when the conditions are right. new LookToScrollOverlayWindow(mainViewModel); } //Display splash screen and check for updates (and display message) after the window has been sized and positioned for the 1st time EventHandler sizeAndPositionInitialised = null; sizeAndPositionInitialised = async(_, __) => { mainWindowManipulationService.SizeAndPositionInitialised -= sizeAndPositionInitialised; //Ensure this handler only triggers once await ShowSplashScreen(inputService, audioService, mainViewModel, OptiKey.Properties.Resources.OPTIKEY_SYMBOL_DESCRIPTION); await mainViewModel.RaiseAnyPendingErrorToastNotifications(); await AttemptToStartMaryTTSService(inputService, audioService, mainViewModel); await AlertIfPresageBitnessOrBootstrapOrVersionFailure(presageInstallationProblem, inputService, audioService, mainViewModel); inputService.RequestResume(); //Start the input service await CheckForUpdates(inputService, audioService, mainViewModel); }; if (mainWindowManipulationService.SizeAndPositionIsInitialised) { sizeAndPositionInitialised(null, null); } else { mainWindowManipulationService.SizeAndPositionInitialised += sizeAndPositionInitialised; } Current.Exit += (o, args) => { mainWindowManipulationService.PersistSizeAndPosition(); Settings.Default.Save(); }; } catch (Exception ex) { Log.Error("Error starting up application", ex); throw; } }
public void Given_Parameters_Constructor_ShouldThrow_NoException() { Action action = () => { var service = new PublishService(this._settings.Object, this._markdownHelper.Object, this._fileHelper.Object, this._httpClientHelper.Object); }; action.ShouldNotThrow <Exception>(); }
public async Task GenServiceCodeTest() { var mockRuntimeCtx = new Core.Tests.MockRuntimeContext(); mockRuntimeCtx.AddModel(Core.Tests.TestHelper.CityModel); mockRuntimeCtx.AddModel(Core.Tests.TestHelper.CustomerModel); mockRuntimeCtx.AddModel(Core.Tests.TestHelper.OrderModel); RuntimeContext.Init(mockRuntimeCtx, 10410); var session = new MockDeveloperSession(); var ctx = new DesignHub(session); var apps = new List <ApplicationModel>() { Core.Tests.TestHelper.SysAppModel }; var models = new List <ModelBase> { Core.Tests.TestHelper.EmploeeModel, Core.Tests.TestHelper.VehicleStateModel, Core.Tests.TestHelper.OrgUnitModel, Core.Tests.TestHelper.CityModel, Core.Tests.TestHelper.CustomerModel, Core.Tests.TestHelper.OrderModel, Core.Tests.TestHelper.AdminPermissionModel, Core.Tests.TestHelper.DeveloperPermissionModel }; await ctx.DesignTree.LoadForTest(apps, models); //模拟添加存储模型,参照NewDataStore Handler var storeNode = ctx.DesignTree.StoreRootNode.AddModel(Core.Tests.TestHelper.SqlStoreModel, ctx); ctx.TypeSystem.CreateStoreDocument(storeNode); //模拟添加服务模型, 参照NewServiceModel Handler var serviceRootNode = ctx.DesignTree.FindModelRootNode(Consts.SYS_APP_ID, ModelType.Service); var parentNode = serviceRootNode; //测试被调用的服务 var modelId = (ulong)Consts.SYS_APP_ID << 32; modelId |= (ulong)ModelType.Service << 24; modelId |= (ulong)1 << 3; modelId |= (ulong)ModelLayer.DEV << 1; var model = new ServiceModel(modelId, "TestService"); var node = new ModelNode(model, ctx); parentNode.Nodes.Add(node); serviceRootNode.AddModelIndex(node); node.CheckoutInfo = new CheckoutInfo(node.NodeType, node.CheckoutInfoTargetID, model.Version, ctx.Session.Name, ctx.Session.LeafOrgUnitID); var souceCode = Resources.LoadStringResource("Resources.Code.TestService.cs"); await ctx.TypeSystem.CreateModelDocumentAsync(node, souceCode); //测试生成用的服务 var modelId1 = (ulong)Consts.SYS_APP_ID << 32; modelId1 |= (ulong)ModelType.Service << 24; modelId1 |= (ulong)1 << 5; modelId1 |= (ulong)ModelLayer.DEV << 1; var model1 = new ServiceModel(modelId1, "HelloService"); var node1 = new ModelNode(model1, ctx); parentNode.Nodes.Add(node1); serviceRootNode.AddModelIndex(node1); node1.CheckoutInfo = new CheckoutInfo(node1.NodeType, node1.CheckoutInfoTargetID, model1.Version, ctx.Session.Name, ctx.Session.LeafOrgUnitID); var souceCode1 = Resources.LoadStringResource("Resources.Code.HelloService.cs"); await ctx.TypeSystem.CreateModelDocumentAsync(node1, souceCode1); //生成服务代码 var data = await PublishService.CompileServiceAsync(ctx, model1); Assert.NotNull(data); }
private async void App_OnStartup(object sender, StartupEventArgs e) { try { Log.Info("Boot strapping the services and UI."); //Apply theme applyTheme(); //Define MainViewModel before services so I can setup a delegate to call into the MainViewModel //This is to work around the fact that the MainViewModel is created after the services. MainViewModel mainViewModel = null; Action <KeyValue> fireKeySelectionEvent = kv => { if (mainViewModel != null) //Access to modified closure is a good thing here, for once! { mainViewModel.FireKeySelectionEvent(kv); } }; //Create services var errorNotifyingServices = new List <INotifyErrors>(); IAudioService audioService = new AudioService(); IDictionaryService dictionaryService = new DictionaryService(); IPublishService publishService = new PublishService(); ISuggestionStateService suggestionService = new SuggestionStateService(); ICalibrationService calibrationService = CreateCalibrationService(); ICapturingStateManager capturingStateManager = new CapturingStateManager(audioService); ILastMouseActionStateManager lastMouseActionStateManager = new LastMouseActionStateManager(); IKeyStateService keyStateService = new KeyStateService(suggestionService, capturingStateManager, lastMouseActionStateManager, calibrationService, fireKeySelectionEvent); IInputService inputService = CreateInputService(keyStateService, dictionaryService, audioService, calibrationService, capturingStateManager, errorNotifyingServices); IKeyboardOutputService keyboardOutputService = new KeyboardOutputService(keyStateService, suggestionService, publishService, dictionaryService, fireKeySelectionEvent); IMouseOutputService mouseOutputService = new MouseOutputService(publishService); errorNotifyingServices.Add(audioService); errorNotifyingServices.Add(dictionaryService); errorNotifyingServices.Add(publishService); errorNotifyingServices.Add(inputService); //Release keys on application exit ReleaseKeysOnApplicationExit(keyStateService, publishService); //Compose UI var mainWindow = new MainWindow(audioService, dictionaryService, inputService); IWindowManipulationService mainWindowManipulationService = new WindowManipulationService( mainWindow, () => Settings.Default.MainWindowOpacity, () => Settings.Default.MainWindowState, () => Settings.Default.MainWindowPreviousState, () => Settings.Default.MainWindowFloatingSizeAndPosition, () => Settings.Default.MainWindowDockPosition, () => Settings.Default.MainWindowDockSize, () => Settings.Default.MainWindowFullDockThicknessAsPercentageOfScreen, () => Settings.Default.MainWindowCollapsedDockThicknessAsPercentageOfFullDockThickness, () => Settings.Default.MainWindowMinimisedPosition, o => Settings.Default.MainWindowOpacity = o, state => Settings.Default.MainWindowState = state, state => Settings.Default.MainWindowPreviousState = state, rect => Settings.Default.MainWindowFloatingSizeAndPosition = rect, pos => Settings.Default.MainWindowDockPosition = pos, size => Settings.Default.MainWindowDockSize = size, t => Settings.Default.MainWindowFullDockThicknessAsPercentageOfScreen = t, t => Settings.Default.MainWindowCollapsedDockThicknessAsPercentageOfFullDockThickness = t); errorNotifyingServices.Add(mainWindowManipulationService); mainViewModel = new MainViewModel( audioService, calibrationService, dictionaryService, keyStateService, suggestionService, capturingStateManager, lastMouseActionStateManager, inputService, keyboardOutputService, mouseOutputService, mainWindowManipulationService, errorNotifyingServices); mainWindow.MainView.DataContext = mainViewModel; //Setup actions to take once main view is loaded (i.e. the view is ready, so hook up the services which kicks everything off) Action postMainViewLoaded = mainViewModel.AttachServiceEventHandlers; if (mainWindow.MainView.IsLoaded) { postMainViewLoaded(); } else { RoutedEventHandler loadedHandler = null; loadedHandler = (s, a) => { postMainViewLoaded(); mainWindow.MainView.Loaded -= loadedHandler; //Ensure this handler only triggers once }; mainWindow.MainView.Loaded += loadedHandler; } //Show the main window mainWindow.Show(); //Display splash screen and check for updates (and display message) after the window has been sized and positioned for the 1st time EventHandler sizeAndPositionInitialised = null; sizeAndPositionInitialised = async(_, __) => { mainWindowManipulationService.SizeAndPositionInitialised -= sizeAndPositionInitialised; //Ensure this handler only triggers once await ShowSplashScreen(inputService, audioService, mainViewModel); inputService.RequestResume(); //Start the input service await CheckForUpdates(inputService, audioService, mainViewModel); }; if (mainWindowManipulationService.SizeAndPositionIsInitialised) { sizeAndPositionInitialised(null, null); } else { mainWindowManipulationService.SizeAndPositionInitialised += sizeAndPositionInitialised; } } catch (Exception ex) { Log.Error("Error starting up application", ex); throw; } }
public PublishController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; publishService = new PublishService(); }