public static void ExecuteMethod_ObtainLockRemoveFromContainerAndDeleteProcess(string processID, Process process, ProcessContainer ownerProcessContainer) { if (process == null) { if (ownerProcessContainer != null && ownerProcessContainer.ProcessIDs != null) { ownerProcessContainer.ProcessIDs.Remove(processID); ownerProcessContainer.StoreInformation(); } } else { string lockEtag = process.ObtainLockOnObject(); if (lockEtag == null) return; try { if (ownerProcessContainer != null) { ownerProcessContainer.ProcessIDs.Remove(process.ID); ownerProcessContainer.StoreInformation(); } process.DeleteInformationObject(); } finally { process.ReleaseLockOnObject(lockEtag); } } }
private void HandleTick(object sender, EventArgs e) { DispatcherTimer timer = sender as DispatcherTimer; ProcessContainer process = timer.Tag as ProcessContainer; if (timer != null && process != null) { timer.Stop(); processList.Remove(process); scheduledList.Remove(process); Process.GetProcessById(process.Id).Kill(); } }
public void EncodeTest() { //Arrange var cloudStorageConfiguration = new CloudStorageConfiguration(CloudStorageAccount.DevelopmentStorageAccount, new Version()); var queueVideoRepository = new QueueVideoRepository(cloudStorageConfiguration.StorageAccount.CreateCloudQueueClient()); var videoRepository = new FakeVideoRepository(_blobSource, _blobDestination); var screenshotRepository = new FakeScreenshotRepository(_blobDestination); var mediaInfoReader = new MediaInfoReader(); var encoder = new Encoder(); var fileSystemWrapper = new FileSystemWrapper(); var queueProcess = new QueueProcess(1000, queueVideoRepository); var downloadProcess = new DownloadProcess(5, videoRepository, fileSystemWrapper); var encoderProcess = new EncodeProcess(5, encoder, videoRepository, mediaInfoReader, queueVideoRepository, fileSystemWrapper); var uploadProcess = new UploadProcess(5, videoRepository, screenshotRepository, fileSystemWrapper); var finishProcess = new FinishProcess(queueVideoRepository, videoRepository, fileSystemWrapper); var queueContainer = new ProcessContainer <object, QueueInformation, DownloadInformation>(queueProcess, downloadProcess); var downloadContainer = new ProcessContainer <QueueInformation, DownloadInformation, EncodeInformation>(downloadProcess, encoderProcess); var encoderContainer = new ProcessContainer <DownloadInformation, EncodeInformation, UploadInformation>(encoderProcess, uploadProcess); var uploadContainer = new ProcessContainer <EncodeInformation, UploadInformation, object>(uploadProcess, finishProcess); var processManager = new EncodeProcessManager(queueVideoRepository.DeleteMessageLocal); processManager.Add(queueContainer); processManager.Add(downloadContainer); processManager.Add(encoderContainer); processManager.Add(uploadContainer); var timer = new Timer(UpdateMessages, queueVideoRepository, (int)queueVideoRepository.InvisibleTime.TotalMilliseconds / 2, (int)queueVideoRepository.InvisibleTime.TotalMilliseconds / 2); //Act & Assert Task task = processManager.Start(); StartQueueWork(); Thread.Sleep(30000); while (queueVideoRepository.ApproximateMessageCount > 0) { Thread.Sleep(60000); } //Thread.Sleep(50*60*1000); processManager.Stop(); task.Wait(); }
public void EncodeTest() { //Arrange var cloudStorageConfiguration = new CloudStorageConfiguration(CloudStorageAccount.DevelopmentStorageAccount, new Version()); var queueVideoRepository = new QueueVideoRepository(cloudStorageConfiguration.StorageAccount.CreateCloudQueueClient()); var videoRepository = new FakeVideoRepository(_blobSource, _blobDestination); var screenshotRepository = new FakeScreenshotRepository(_blobDestination); var mediaInfoReader = new MediaInfoReader(); var encoder = new Encoder(); var fileSystemWrapper = new FileSystemWrapper(); var queueProcess = new QueueProcess(1000, queueVideoRepository); var downloadProcess = new DownloadProcess(5, videoRepository, fileSystemWrapper); var encoderProcess = new EncodeProcess(5, encoder, videoRepository, mediaInfoReader, queueVideoRepository, fileSystemWrapper); var uploadProcess = new UploadProcess(5, videoRepository, screenshotRepository, fileSystemWrapper); var finishProcess = new FinishProcess(queueVideoRepository, videoRepository, fileSystemWrapper); var queueContainer = new ProcessContainer<object, QueueInformation, DownloadInformation>(queueProcess, downloadProcess); var downloadContainer = new ProcessContainer<QueueInformation, DownloadInformation, EncodeInformation>(downloadProcess, encoderProcess); var encoderContainer = new ProcessContainer<DownloadInformation, EncodeInformation, UploadInformation>(encoderProcess, uploadProcess); var uploadContainer = new ProcessContainer<EncodeInformation, UploadInformation, object>(uploadProcess, finishProcess); var processManager = new EncodeProcessManager(queueVideoRepository.DeleteMessageLocal); processManager.Add(queueContainer); processManager.Add(downloadContainer); processManager.Add(encoderContainer); processManager.Add(uploadContainer); var timer = new Timer(UpdateMessages, queueVideoRepository, (int) queueVideoRepository.InvisibleTime.TotalMilliseconds/2, (int) queueVideoRepository.InvisibleTime.TotalMilliseconds/2); //Act & Assert Task task = processManager.Start(); StartQueueWork(); Thread.Sleep(30000); while (queueVideoRepository.ApproximateMessageCount > 0) { Thread.Sleep(60000); } //Thread.Sleep(50*60*1000); processManager.Stop(); task.Wait(); }
/// <summary> /// Initializes a new instance of the <see cref="ProcessContainerVM"/> class. /// </summary> /// <param name="process"> The process to be contained. </param> public ProcessContainerVM(ProcessContainer process) { this.processContainer = process; this.Modules = new ObservableCollection <ProcessModuleContainerVm>(); if (this.processContainer.Modules != null) { foreach (var item in this.processContainer.Modules) { this.Modules.Add(new ProcessModuleContainerVm(item)); } } this.isChecked = false; }
internal static void Run(string[] args) { var commands = new List <Action <TransactionScopeContainer> > { container => CreateAdminUserAndPermissions(container), container => { string password = null; for (int i = 0; i < args.Length; i++) { if (args[i] == "-pass" && i < args.Length - 1) { password = args[i + 1]; break; } } SetUpAdminAccount(password); } }; var processContainer = new ProcessContainer( addCustomConfiguration: configurationBuilder => configurationBuilder.AddConfigurationManagerConfiguration()); // If the first command fails ("CreateAdminUserAndPermissions"), this program will still try to execute "SetUpAdminAccount" then report the exception later. var exceptions = new List <Exception>(); foreach (var command in commands) { try { using (var container = processContainer.CreateTransactionScopeContainer()) { command(container); container.CommitChanges(); } } catch (Exception ex) { exceptions.Add(ex); } } if (exceptions.Any()) { ExceptionsUtility.Rethrow(exceptions.First()); } }
/// <summary> /// 根据游戏核心id来启动游戏 /// </summary> /// <param name="id"></param> public virtual void Launch(string id) { if (this.ProcessContainer?.ProcessState == Model.ProcessState.Running) { throw new GameHasRanException() { ProcessContainer = this.ProcessContainer } } ; else { this.ProcessContainer?.Dispose(); } var core = this.CoreLocator.GetGameCoreFromId(id); if (core == null) { throw new GameCoreNotFoundException() { Id = id } } ; this.ArgumentsBuilder = new ArgumentsBuilder(core, this.LaunchConfig); if (string.IsNullOrEmpty(this.LaunchConfig.NativesFolder)) { this.LaunchConfig.NativesFolder = $"{PathHelper.GetVersionFolder(core.Root, id)}{PathHelper.X}natives"; } var nativesDecompressor = new NativesDecompressor(core.Root, id); nativesDecompressor.Decompress(core.Natives, this.LaunchConfig.NativesFolder); this.ProcessContainer = new ProcessContainer( new ProcessStartInfo { WorkingDirectory = Directory.Exists(LaunchConfig.WorkingFolder) ? LaunchConfig.WorkingFolder : core.Root, Arguments = ArgumentsBuilder.BulidArguments(), FileName = this.LaunchConfig.JavaPath, }); ProcessContainer.Start(); }
/// <summary> /// 恢复根进程 /// </summary> public static void Resume(this ProcessContainer processContainer) { if (processContainer.Process.Equals(null)) { throw new NullReferenceException(); } foreach (Process process in Process.GetProcesses()) { if (process.Id.Equals(processContainer.Process.Id)) { NativeWin32MethodExtend.ResumeProcess(processContainer.Process.Id); processContainer.ProcessState = Model.ProcessState.Running; } } throw new InvalidOperationException("The process has not been started or has exited. 该进程尚未启动或已退出。"); }
public string GetData(int value) { string applicationFolder = @""; ConsoleLogger.MinLevel = EventType.Info; // Use EventType.Trace for more detailed log. using (var container = ProcessContainer.CreateTransactionScopeContainer(applicationFolder)) { var context = container.Resolve <Common.ExecutionContext>(); var repository = context.Repository; // <<<< Copy-paste the example code here >>>> } return(string.Format("You entered: {0}", value)); }
private void ClearCreation(bool removeProcess = false) { string name = input_name.Text; input_name.Text = ""; input_process.Text = ""; input_startfrom.Text = ""; input_target.Text = ""; toggle_web.Checked = false; toggle_autostart.Checked = false; editingContainer = null; if (removeProcess) { ServerFactory.RemoveByName(name); } }
public async Task StartTest() { var receivedException = (Exception?)null; using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await using var container = new ProcessContainer(nameof(ProcessContainerTests)); container.ExceptionOccurred += (sender, exception) => { Console.WriteLine($"ExceptionOccurred: {exception}"); receivedException = exception; // ReSharper disable once AccessToDisposedClosure cancellationTokenSource.Cancel(); }; await container.InitializeAsync(cancellationTokenSource.Token); await container.StartAsync(cancellationTokenSource.Token); //await container.LoadAssemblyAsync("test", cancellationTokenSource.Token); var instance = await container.CreateObjectAsync <ISimpleEventClass>(typeof(SimpleEventClass), cancellationTokenSource.Token); instance.Event1 += (sender, args) => Console.WriteLine($"Hello, I'm the event. My value is {args}"); instance.RaiseEvent1(); Assert.AreEqual(321 + 123, instance.Method1(123)); Assert.AreEqual("Hello, input = 123", instance.Method2("123")); try { await Task.Delay(TimeSpan.FromSeconds(1), cancellationTokenSource.Token); } catch (OperationCanceledException) { } if (receivedException != null) { Assert.Fail(receivedException.ToString()); } }
private void InitializeRhetosTransactionScopeContainer() { if (_rhetosTransactionScope == null) { if (_processContainer == null) { lock (_containerInitializationLock) if (_processContainer == null) { _processContainer = new ProcessContainer(SearchForRhetosServerRootFolder(), new ConsoleLogProvider(), configurationBuilder => configurationBuilder.AddConfigurationManagerConfiguration()); } } _rhetosTransactionScope = _processContainer.CreateTransactionScopeContainer(InitializeSession); if (_commitChanges) { _rhetosTransactionScope.CommitChanges(); } } }
private void Datagrid_view_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0) { return; } if (lastInteraction.CompareTo(DateTime.Now) > 0) { return; } lastInteraction = DateTime.Now.AddSeconds(5); DataGridViewRow gridRow = datagrid_view.Rows[e.RowIndex]; ProcessContainer procContainer = gridRow.DataBoundItem as ProcessContainer; if (e.ColumnIndex == 4) { if (procContainer.IsRunning) { procContainer.CloseProcess(); gridRow.Cells["StartStatus"].Value = "Start"; } else { procContainer.CreateProcess(); gridRow.Cells["StartStatus"].Value = "Stop"; } datagrid_view.RefreshEdit(); } else if (e.ColumnIndex == 5) { EditContainer(procContainer); } }
public ProcessContainer AddProcess(ProcessBase process) { if (process.Debug == true) { //uruchamiamy proces w trybie debug var kontenerProcesu = new DebugProcesContainer() { Id = process.Id }; kontenerProcesu.Process = process; kontenerProcesu.Thread = new Thread(debugThread); kontenerProcesu.Thread.Name = "proces " + process.Id; process.Status = EnumProcessStatus.WaitingForExecution; debugProcesess.Add(kontenerProcesu); kontenerProcesu.Thread.Start(kontenerProcesu); return(kontenerProcesu); } else { process.Status = EnumProcessStatus.WaitingForExecution; var wm = new VirtualMachine.VirtualMachine(); //dodaje tylko do kolejki uruchomienia - nie uruchamiam w tym wątku wm.Start(process, doExecuting: false); var xml = wm.Serialize(); var serializedProcess = new ProcessContainer(); serializedProcess.Id = process.Id; serializedProcess.Status = process.Status; serializedProcess.ExecutionDate = process.ExecutionDate; serializedProcess.VirtualMachineXml = xml; dal.AddProcess(serializedProcess); return(serializedProcess); } }
/// <summary> /// 安装(异步) /// </summary> /// <returns></returns public async Task <ForgeInstallerResultModel> InstallAsync() { using var archive = ZipFile.OpenRead(this.ForgeInstallerPackagePath); var processOutputs = new List <string>(); var processErrorOutputs = new List <string>(); #region Get version.json OnProgressChanged(0.1, $"Installing Forge Loader - Initializing"); var versionJson = await ZipFileHelper.GetStringFromJsonEntryAsync (archive.Entries.First(x => x.Name.Equals("version.json", StringComparison.OrdinalIgnoreCase))); var versionModel = JsonConvert.DeserializeObject <CoreModel>(versionJson); var versionJsonFile = new FileInfo ($"{PathHelper.GetVersionFolder(this.CoreLocator.Root, versionModel.Id)}{PathHelper.X}{versionModel.Id}.json"); if (!versionJsonFile.Directory.Exists) { versionJsonFile.Directory.Create(); } File.WriteAllText(versionJsonFile.FullName, versionJson); OnProgressChanged(0.15, $"Installing Forge Loader - Initializing"); #endregion #region Get install_profile.json var forgeInstallProfile = await ZipFileHelper.GetObjectFromJsonEntryAsync <ForgeInstallProfileModel> (archive.Entries.First(x => x.Name.Equals("install_profile.json", StringComparison.OrdinalIgnoreCase))); var forgeVersion = forgeInstallProfile.Version.Replace("-forge-", "-"); forgeInstallProfile.Data["BINPATCH"].Client = $"[net.minecraftforge:forge:{forgeVersion}:clientdata@lzma]"; forgeInstallProfile.Data["BINPATCH"].Server = $"[net.minecraftforge:forge:{forgeVersion}:serverdata@lzma]"; OnProgressChanged(0.2, $"Installing Forge Loader - Initialized"); #endregion #region Get Lzma OnProgressChanged(0.3, $"Installing Forge Loader - Extracting Files"); var clientLzma = archive.Entries.FirstOrDefault(e => e.FullName.Equals("data/client.lzma", StringComparison.OrdinalIgnoreCase)); var serverLzma = archive.Entries.FirstOrDefault(e => e.FullName.Equals("data/server.lzma", StringComparison.OrdinalIgnoreCase)); var clientLzmaFile = new FileInfo(GetMavenFilePath(forgeInstallProfile.Data["BINPATCH"].Client)); var serverLzmaFile = new FileInfo(GetMavenFilePath(forgeInstallProfile.Data["BINPATCH"].Server)); await ZipFileHelper.WriteAsync(clientLzma, clientLzmaFile.Directory.FullName, clientLzmaFile.Name); await ZipFileHelper.WriteAsync(serverLzma, serverLzmaFile.Directory.FullName, serverLzmaFile.Name); #endregion #region Extract Forge Jar var forgeJar = archive.Entries.FirstOrDefault (e => e.FullName.Equals($"maven/net/minecraftforge/forge/{forgeVersion}/forge-{forgeVersion}.jar", StringComparison.OrdinalIgnoreCase)); var forgeUniversalJar = archive.Entries.FirstOrDefault (e => e.FullName.Equals($"maven/net/minecraftforge/forge/{forgeVersion}/forge-{forgeVersion}-universal.jar", StringComparison.OrdinalIgnoreCase)); if (forgeJar != default) { if (forgeUniversalJar != default) { var fileUniversalJar = new FileInfo($"{PathHelper.GetLibrariesFolder(this.CoreLocator.Root)}{PathHelper.X}{forgeUniversalJar.FullName.Replace("maven/", "").Replace("/", PathHelper.X)}"); if (!fileUniversalJar.Directory.Exists) { fileUniversalJar.Directory.Create(); } await ZipFileHelper.WriteAsync(forgeUniversalJar, fileUniversalJar.Directory.FullName); } var file = new FileInfo($"{PathHelper.GetLibrariesFolder(this.CoreLocator.Root)}{PathHelper.X}{forgeJar.FullName.Replace("maven/", "").Replace("/", PathHelper.X)}"); if (!file.Directory.Exists) { file.Directory.Create(); } await ZipFileHelper.WriteAsync(forgeJar, file.Directory.FullName); } OnProgressChanged(0.4, $"Installing Forge Loader - Extracted"); #endregion #region Parser Processor OnProgressChanged(0.4, $"Installing Forge Loader - Parsering Processor"); var replaceValues = new Dictionary <string, string> { { "{SIDE}", "client" }, { "{MINECRAFT_JAR}", $"{PathHelper.GetVersionFolder(this.CoreLocator.Root,this.McVersionId)}{PathHelper.X}{this.McVersionId}.jar" }, { "{MINECRAFT_VERSION}", this.McVersion }, { "{ROOT}", this.CoreLocator.Root }, { "{INSTALLER}", this.ForgeInstallerPackagePath }, { "{LIBRARY_DIR}", PathHelper.GetLibrariesFolder(this.CoreLocator.Root) }, { "/", PathHelper.X } }; var replaceArgs = forgeInstallProfile.Data.Select(x => ($"{{{x.Key}}}", x.Value.Client)).ToDictionary(k => k.Item1, v => { if (v.Client.Contains("[") && v.Client.Contains("]")) { return(GetMavenFilePath(v.Client)); } return(v.Client); }); for (int i = 0; i < forgeInstallProfile.Processors.Count; i++) { var processModel = forgeInstallProfile.Processors[i]; if (processModel.Sides != null && !processModel.Sides.Any(s => s.Equals("client", StringComparison.OrdinalIgnoreCase))) { forgeInstallProfile.Processors.RemoveAt(i); continue; } } for (int i = 0; i < forgeInstallProfile.Processors.Count; i++) { var processModel = forgeInstallProfile.Processors[i]; processModel.Args = StringHelper.Replace(processModel.Args, replaceValues).ToList(); processModel.Args = StringHelper.Replace(processModel.Args, replaceArgs).ToList(); processModel.Args = processModel.Args.Select(x => { if (x.Contains("[") && x.Contains("]")) { return($"{Path.Combine(PathHelper.GetLibrariesFolder(this.CoreLocator.Root), new Library { Name = x.TrimStart('[').TrimEnd(']') }.GetRelativePath())}"); } return(x); }).ToList(); if (processModel.Outputs != default) { processModel.Outputs = processModel.Outputs.Select (x => (StringHelper.Replace(x.Key, replaceArgs), StringHelper.Replace(x.Value, replaceArgs))).ToDictionary(k => k.Item1, v => v.Item2); } forgeInstallProfile.Processors[i] = processModel; } OnProgressChanged(0.5, $"Installing Forge Loader - Parsered Processor"); #endregion #region Download Libraries OnProgressChanged(0.5, $"Installing Forge Loader - Downloading Libraries"); for (int i = 0; i < versionModel.Libraries.Count; i++) { if (versionModel.Libraries[i].Name == forgeInstallProfile.Path) { versionModel.Libraries.Remove(versionModel.Libraries[i]); } } for (int i = 0; i < forgeInstallProfile.Libraries.Count; i++) { if (forgeInstallProfile.Libraries[i].Name == $"{forgeInstallProfile.Path}:universal") { forgeInstallProfile.Libraries.Remove(forgeInstallProfile.Libraries[i]); } } async Task Download(IEnumerable <HttpDownloadRequest> requests) { var manyBlock = new TransformManyBlock <IEnumerable <HttpDownloadRequest>, HttpDownloadRequest>(x => x); var blockOptions = new ExecutionDataflowBlockOptions { BoundedCapacity = DependencesCompleter.MaxThread, MaxDegreeOfParallelism = DependencesCompleter.MaxThread }; var actionBlock = new ActionBlock <HttpDownloadRequest>(async x => { try { if (!x.Directory.Exists) { x.Directory.Create(); } var res = await HttpHelper.HttpDownloadAsync(x, x.FileName); if (res.HttpStatusCode != HttpStatusCode.OK) { this.ErrorDownload.Add(x); } } catch { throw; } }, blockOptions); var linkOptions = new DataflowLinkOptions { PropagateCompletion = true }; _ = manyBlock.LinkTo(actionBlock, linkOptions); _ = manyBlock.Post(requests); manyBlock.Complete(); await actionBlock.Completion; GC.Collect(); } var downloadList = versionModel.Libraries.Union(forgeInstallProfile.Libraries).Select(x => { var result = x.GetDownloadRequest(this.CoreLocator.Root, true); if (SystemConfiguration.Api.Url != new Mojang().Url) { result.Url = result.Url.Replace("https://maven.minecraftforge.net", $"{SystemConfiguration.Api.Url}/maven"); } return(result); }); await Download(downloadList); //Try Again if (ErrorDownload.Count > 0) { await Download(ErrorDownload.Select(x => { x.Url = x.Url.Replace($"{SystemConfiguration.Api.Url}/maven", "https://maven.minecraftforge.net"); return(x); })); } OnProgressChanged(0.8, $"Installing Forge Loader - Downloaded Libraries"); #endregion #region Run Process OnProgressChanged(0.8, $"Installing Forge Loader - Processing"); foreach (var process in forgeInstallProfile.Processors) { string JarFile = $"{Path.Combine(PathHelper.GetLibrariesFolder(this.CoreLocator.Root), new Library { Name = process.Jar }.GetRelativePath())}"; using var JarFileArchive = ZipFile.OpenRead(JarFile); var libEntry = JarFileArchive.Entries.FirstOrDefault(e => e.FullName.Equals("META-INF/MANIFEST.MF", StringComparison.OrdinalIgnoreCase)); string[] lines = (await ZipFileHelper.GetStringFromJsonEntryAsync(libEntry)).Split("\r\n"); var mainClass = lines.ToList().FirstOrDefault(x => x.Contains("Main-Class: ")).Replace("Main-Class: ", ""); var libs = new List <string>() { process.Jar }.Concat(process.Classpath); var classpath = libs.Select(x => $"{Path.Combine(PathHelper.GetLibrariesFolder(this.CoreLocator.Root), new Library { Name = x }.GetRelativePath())}"); var parameter = new List <string> { "-cp", $"\"{string.Join(ArgumentsBuilder.Separator,classpath)}\"", mainClass }; parameter.AddRange(process.Args); var processContainer = new ProcessContainer(new ProcessStartInfo(JavaPath) { Arguments = string.Join(" ", parameter), WorkingDirectory = this.CoreLocator.Root }); processContainer.Start(); await processContainer.Process.WaitForExitAsync(); processOutputs.AddRange(processContainer.OutputData); processErrorOutputs.AddRange(processContainer.ErrorData); processContainer.Dispose(); } OnProgressChanged(0.9, $"Installing Forge Loader - Processed"); #endregion OnProgressChanged(1.0, $"Installing Forge Loader - Finished"); if (processErrorOutputs.Count > 0) { return new ForgeInstallerResultModel { IsSuccessful = false, Message = $"Failed Install Forge-{forgeVersion}!", ProcessOutput = processOutputs, ProcessErrorOutput = processErrorOutputs } } ; return(new ForgeInstallerResultModel { IsSuccessful = true, Message = $"Successfully Install Forge-{forgeVersion}!", ProcessOutput = processOutputs, ProcessErrorOutput = processErrorOutputs }); }
public void Transfer(ProcessContainer to, int numAtoms) { to.Fill(Drain(numAtoms)); }
/// <summary> /// Creates a thread-safe lifetime scope DI container to isolate unit of work in a separate database transaction. /// To commit changes to database, call <see cref="TransactionScopeContainer.CommitChanges"/> at the end of the 'using' block. /// </summary> public static TransactionScopeContainer CreateTransactionScopeContainer(Action <ContainerBuilder> registerCustomComponents = null) { return(ProcessContainer.CreateTransactionScopeContainer(registerCustomComponents)); }
public async Task RealTest() { var receivedException = (Exception?)null; using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15)); await using var container = new ProcessContainer(nameof(ProcessContainerTests)) { MethodsCancellationToken = cancellationTokenSource.Token, }; container.ExceptionOccurred += (_, exception) => { Console.WriteLine($"ExceptionOccurred: {exception}"); receivedException = exception; // ReSharper disable once AccessToDisposedClosure cancellationTokenSource.Cancel(); }; await container.InitializeAsync(cancellationTokenSource.Token); await container.StartAsync(cancellationTokenSource.Token); var directory = Path.Combine(Path.GetTempPath(), "H.Containers.Tests_WitAiConverter"); Directory.CreateDirectory(directory); var path = Path.Combine(directory, "WitAiConverter.zip"); var bytes = ResourcesUtilities.ReadFileAsBytes("WitAiConverter.zip"); File.WriteAllBytes(path, bytes); ZipFile.ExtractToDirectory(path, directory, true); await container.LoadAssemblyAsync(Path.Combine(directory, "WitAiConverter.dll"), cancellationTokenSource.Token); var instance = await container.CreateObjectAsync <IConverter>("H.NET.Converters.WitAiConverter", cancellationTokenSource.Token); Assert.IsNotNull(instance); Assert.AreEqual("WitAiConverter", instance.ShortName); var availableSettings = instance.GetAvailableSettings().ToArray(); Console.WriteLine("AvailableSettings:"); foreach (var setting in availableSettings) { Console.WriteLine($" - {setting}"); } CollectionAssert.AreEqual( new[] { "Token" }, availableSettings); instance.SetSetting("Token", "XZS4M3BUYV5LBMEWJKAGJ6HCPWZ5IDGY"); await BaseConvertersTests.ConvertTest(instance, "проверка_проверка_8000.wav", "проверка", cancellationTokenSource.Token); try { await Task.Delay(TimeSpan.FromSeconds(1), cancellationTokenSource.Token); } catch (OperationCanceledException) { } if (receivedException != null) { Assert.Fail(receivedException.ToString()); } }
public static ProcessContainer GetTarget_OwnerProcessContainer() { return(ProcessContainer.RetrieveFromOwnerContent(InformationContext.CurrentOwner, "default")); }
public static void ExecuteMethod_ObtainLockRemoveFromContainerAndDeleteProcess(string processID, Process process, ProcessContainer ownerProcessContainer) { if (process == null) { if (ownerProcessContainer != null && ownerProcessContainer.ProcessIDs != null) { ownerProcessContainer.ProcessIDs.Remove(processID); ownerProcessContainer.StoreInformation(); } } else { string lockEtag = process.ObtainLockOnObject(); if (lockEtag == null) { return; } try { if (ownerProcessContainer != null) { ownerProcessContainer.ProcessIDs.Remove(process.ID); ownerProcessContainer.StoreInformation(); } process.DeleteInformationObject(); } finally { process.ReleaseLockOnObject(lockEtag); } } }
private static void ServerFactory_OnServerAdded(ProcessContainer pc) { util.Log($"Server '{pc.ProcName}': {pc.Path} was added."); ServerFactory.Save(); }
/// <summary> /// Creates a thread-safe lifetime scope DI container to isolate unit of work in a separate database transaction. /// To commit changes to database, call <see cref="UnitOfWorkScope.CommitAndClose"/> at the end of the 'using' block. /// </summary> public static UnitOfWorkScope CreateScope(Action <ContainerBuilder> registerCustomComponents = null) { return(ProcessContainer.CreateScope(registerCustomComponents)); }
public async Task BaseModuleTest <T>( string name, string typeName, string shortName, Func <T, CancellationToken, Task> testFunc) where T : class, IModule { var receivedException = (Exception?)null; using var tempDirectory = new TempDirectory(); using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(15)); await using var container = new ProcessContainer(nameof(ProcessContainerTests)) { MethodsCancellationToken = cancellationTokenSource.Token, }; container.ExceptionOccurred += (_, exception) => { Console.WriteLine($"ExceptionOccurred: {exception}"); receivedException = exception; // ReSharper disable once AccessToDisposedClosure cancellationTokenSource.Cancel(); }; await container.InitializeAsync(cancellationTokenSource.Token); await container.StartAsync(cancellationTokenSource.Token); var path = tempDirectory.Extract(name); await container.LoadAssemblyAsync(path, cancellationTokenSource.Token); var types = await container.GetTypesAsync(cancellationTokenSource.Token); ShowList(types, "Available types"); using var instance = await container.CreateObjectAsync <T>(typeName, cancellationTokenSource.Token); Assert.IsNotNull(instance); instance.NewCommand += (_, command) => { Console.WriteLine($"{nameof(instance.NewCommand)}: {command}"); }; instance.ExceptionOccurred += (_, exception) => { Console.WriteLine($"{nameof(instance.ExceptionOccurred)}: {exception}"); }; instance.LogReceived += (_, log) => { Console.WriteLine($"{nameof(instance.LogReceived)}: {log}"); }; Assert.AreEqual(shortName, instance.ShortName); var availableSettings = instance.GetAvailableSettings().ToArray(); ShowList(availableSettings, "Available settings"); await testFunc(instance, cancellationTokenSource.Token); try { await Task.Delay(TimeSpan.FromSeconds(1), cancellationTokenSource.Token); } catch (OperationCanceledException) { } if (receivedException != null) { Assert.Fail(receivedException.ToString()); } }
static void Main(string[] args) { string applicationFolder = @"..\..\..\..\Bookstore.Service\obj\Rhetos"; var directory = System.IO.Directory.GetFiles(applicationFolder); ConsoleLogger.MinLevel = EventType.Info; // Use EventType.Trace for more detailed log. using (var container = ProcessContainer.CreateTransactionScopeContainer(applicationFolder)) { var context = container.Resolve <Common.ExecutionContext>(); var repository = context.Repository; /* //DAY2 * * //1 * foreach (var book in repository.Bookstore.Book.Load()) * { * List<Guid> ids = new List<Guid>(); * * string authorName = string.Empty; * if (book.AuthorID.HasValue) * { * ids.Add(book.AuthorID.Value); * * var author = repository.Bookstore.Person.Load(ids);//Obsolete? * authorName = author.FirstOrDefault()?.Name; * } * * Console.WriteLine(book.Title + "\t\t\t\t" + authorName); * } * * Console.WriteLine(); * Console.WriteLine("------------------------"); * Console.WriteLine(); * * //2 * var q = repository.Bookstore.Book.Query().Select(x => new { x.Title, x.NumberOfPages, x.Author.Name }); * ConsoleDump.Extensions.Dump(q); * * Console.WriteLine(); * Console.WriteLine("------------------------"); * Console.WriteLine(); * * //3 * Console.WriteLine(q.ToString()); * * * //4 * repository.Bookstore.GenerateBooks.Execute(new GenerateBooks() { NumberOfBooks = 2, Title = "Novele" }); * * //repository.Bookstore.Insert5Books.Execute(null); * //repository.Bookstore.CreatePrincipal.Execute(new CreatePrincipal() { Name = "Ivan Glas" });//ID ne radi jer u .rhe skripti tip podataka je Guid, pa ne radi konverzija u Guid? * * * //DAY 2 */ //DAY3 var filterParametar = new Bookstore.LongBooks(); var q = repository.Bookstore.Book.Query(filterParametar, typeof(Bookstore.LongBooks)); var newForeignBook = new ForeignBook() { ID = Guid.Parse("fb7237c7-aa8f-4c8c-8bee-589e32c8bee3"), OriginalLanguage = "HR" }; repository.Bookstore.ForeignBook.Save(new List <ForeignBook> { newForeignBook }, null, null); //repository.Bookstore.Book.Insert(newBook); ConsoleDump.Extensions.Dump(q); Console.WriteLine(q.ToString()); container.CommitChanges(); Console.ReadLine(); // <<<< Copy-paste the example code here >>>> } }