public void MenuHandler(Converter<ThreadItem, object> selector, MenuItem menu, PopupTargetInfo pti) { using (ViewList vl = this.js.ViewList()) using (DisposableList<ViewItem> views = new DisposableList<ViewItem>(vl)) using (DisposableList<ThreadItem> threads = new DisposableList<ThreadItem>()) { //スレッドを抽出 foreach (ViewItem view in views) { ThreadItem t = view.Thread(); if (t != null) threads.Add(t); } //スレッドを全部閉じる foreach (ThreadItem t in threads) { this.js.Close(t); } //スレッドのソートキー取得 List<ThreadKeyPair> pairs = new List<ThreadKeyPair>(threads.Count); foreach (ThreadItem t in threads) { pairs.Add(new ThreadKeyPair() { Thread = t, SortKey = (IComparable)selector(t), }); } //スレッドソート if (this.ascending) { pairs.Sort(this.AscendingComparison); } else { pairs.Sort(this.DescendingComparison); } //全部開く foreach (var p in pairs) { this.js.Open(p.Thread, 0, OpenOperation.Local, true, false, true); } } }
internal static void Merge() { var samplePackagagePath = @"C:\Dev\ed\DacMergeExample\SampleSQLProj\bin\Debug\Sample.dacpac"; TSqlModel sampleModel = new TSqlModel(samplePackagagePath, DacSchemaModelStorageType.Memory); var targetPackagePath = @"merged.dacpac"; DisposableList disposables = new DisposableList(); var newModel = new TSqlModel(sampleModel.Version, sampleModel.CopyModelOptions()); foreach (var item in sampleModel.GetObjects(DacQueryScopes.UserDefined)) { string script; if (item.TryGetScript(out script)) { newModel.AddObjects(script); } } DacPackageExtensions.BuildPackage( targetPackagePath, newModel, new PackageMetadata(), // Describes the dacpac. new PackageOptions()); // Use this to specify the deployment contributors, refactor log to include in package //DacPackage package = disposables.Add(DacPackage.Load(targetPackagePath, DacSchemaModelStorageType.Memory, FileAccess.ReadWrite)); //package.UpdateModel(cilModel, new PackageMetadata()); }
public void TestAgentCodeSequence() { var agent1 = new CodeSequenceMacro {CodeMeaning = "Contrastinol", CodeValue = "123", CodingSchemeDesignator = "ABC"}; var agent2 = new CodeSequenceMacro {CodeMeaning = "Bolusinate", CodeValue = "456", CodingSchemeDesignator = "DEF"}; var dataset = TestDataSource.CreateImageSopDataSource(); dataset[DicomTags.ContrastBolusAgent].SetStringValue(@"Contrastinol and Bolusinate"); dataset[DicomTags.ContrastBolusAgentSequence].AddSequenceItem(agent1.DicomSequenceItem); using (var sop = (ImageSop) Sop.Create(dataset)) using (var images = new DisposableList<IPresentationImage>(PresentationImageFactory.Create(sop))) { Assert.AreEqual(@"Contrastinol", _annotationItems[_cbAgent].GetAnnotationText(images[0])); dataset[DicomTags.ContrastBolusAgentSequence].AddSequenceItem(agent2.DicomSequenceItem); Assert.AreEqual(@"Contrastinol\Bolusinate", _annotationItems[_cbAgent].GetAnnotationText(images[0])); agent1.CodeMeaning = string.Empty; Assert.AreEqual(@"123 (ABC)\Bolusinate", _annotationItems[_cbAgent].GetAnnotationText(images[0])); agent2.CodeMeaning = string.Empty; Assert.AreEqual(@"Contrastinol and Bolusinate", _annotationItems[_cbAgent].GetAnnotationText(images[0])); dataset[DicomTags.ContrastBolusAgent].SetNullValue(); Assert.AreEqual(@"123 (ABC)\456 (DEF)", _annotationItems[_cbAgent].GetAnnotationText(images[0])); } }
private void AddThreads(NtProcess entry) { using (DisposableList<NtThread> threads = new DisposableList<NtThread>(entry.GetThreads(ThreadAccessRights.QueryInformation))) { foreach (NtThread thread in threads) { try { using (NtToken token = thread.OpenToken()) { if (token != null) { ListViewItem item = new ListViewItem(String.Format("{0} - {1}", entry.ProcessId, entry.Name)); item.SubItems.Add(thread.ThreadId.ToString()); item.SubItems.Add(token.User.ToString()); item.SubItems.Add(token.ImpersonationLevel.ToString()); item.Tag = thread.Duplicate(); listViewThreads.Items.Add(item); } } } catch (NtException) { } } } }
public void MenuHandler(Predicate<ViewItem> pred, MenuItem menu, PopupTargetInfo pti) { JaneScript js = base.Host.JaneScript; using (ViewList vl = js.ViewList()){ List<TitleUriPair> pairs = new List<TitleUriPair>(); using (DisposableList<ViewItem> views = new DisposableList<ViewItem>(vl)) { foreach (ViewItem view in views) { if (pred(view)) { using (ThreadItem t = view.Thread()) { pairs.Add(new TitleUriPair() { Title = t.Title, Uri = t.URL, }); } } } } if (pairs.Count == 0) { js.Log("書き出す対象のスレッドが1つもありませんでした。"); return; } string titleShort = "開いているスレの書き出し"; string titleLong = string.Format("{0}: {1}", titleShort, menu.Caption); Util.WriteToNewView(js, titleShort, titleLong, titleLong, false, false, (datout) => { datout.WriteText(titleLong); datout.WriteBR(); datout.WriteText(string.Format("{0} スレッド", pairs.Count)); datout.WriteBR(); datout.WriteHTML("<hr><br>"); foreach (TitleUriPair pair in pairs) { datout.WriteHTML(string.Format("{0}<br><a href=\"{1}\">{1}</a><br>", HttpUtility.HtmlEncode(pair.Title), pair.Uri)); } }); } }
public void TestNil() { var dataset = TestDataSource.CreateImageSopDataSource(); using (var sop = (ImageSop) Sop.Create(dataset)) using (var images = new DisposableList<IPresentationImage>(PresentationImageFactory.Create(sop))) { Assert.IsEmpty(_annotationItems[_cbAgent].GetAnnotationText(images[0])); } }
public void Dispose() { var list = new DisposableList<MyDisposable>(); Assert.True(list.All(x => !x.IsDisposed)); list.Dispose(); Assert.True(list.All(x => x.IsDisposed)); }
public void TestAgentDescriptorOnly() { var dataset = TestDataSource.CreateImageSopDataSource(); dataset[DicomTags.ContrastBolusAgent].SetStringValue(@"Contrastinol and Bolusinate"); using (var sop = (ImageSop) Sop.Create(dataset)) using (var images = new DisposableList<IPresentationImage>(PresentationImageFactory.Create(sop))) { Assert.AreEqual(@"Contrastinol and Bolusinate", _annotationItems[_cbAgent].GetAnnotationText(images[0])); } }
public void Dispose_EmptyList_ShouldDoNothing() { //Setup var sut = new DisposableList<IDisposable>(); //Exercise sut.Dispose(); //Verify sut.Should().BeEmpty(); }
public void InitializeTest() { Directory.CreateDirectory(GetTestDir()); _trash = new DisposableList(); _dacpacPath = GetTestFilePath("myDatabase.dacpac"); using (TSqlModel model = new TSqlModel(SqlServerVersion.Sql110, null)) { model.AddObjects("CREATE TABLE [dbo].[t1] (c1 INT NOT NULL PRIMARY KEY)"); DacPackageExtensions.BuildPackage(_dacpacPath, model, new PackageMetadata()); } }
public void InitializeTest() { Directory.CreateDirectory(GetTestDir()); _trash = new DisposableList(); _dacpacPath = GetTestFilePath("myDatabase.dacpac"); using (TSqlModel model = new TSqlModel(SqlServerVersion.Sql110, null)) { model.AddObjects(CreateOneTable); DacPackageExtensions.BuildPackage(_dacpacPath, model, new PackageMetadata()); } }
public void Host(ObfuscationConfiguration obfuscationConfiguration, Action<long, bool, double> statusCallback) { IEnumerable<IDictionary<string, object>> sourceDataEnumerable; IEnumerable<Message> messages; if ((object)obfuscationConfiguration == null) throw new ArgumentNullException("obfuscationConfiguration"); messages = obfuscationConfiguration.Validate(); if (messages.Any()) throw new ApplicationException(string.Format("Obfuscation configuration validation failed:\r\n{0}", string.Join("\r\n", messages.Select(m => m.Description).ToArray()))); using (IOxymoronEngine oxymoronEngine = new OxymoronEngine(this, obfuscationConfiguration)) { using (DisposableList<IDictionaryAdapter> dictionaryAdapters = new DisposableList<IDictionaryAdapter>()) { foreach (DictionaryConfiguration dictionaryConfiguration in obfuscationConfiguration.DictionaryConfigurations) { IDictionaryAdapter dictionaryAdapter; dictionaryAdapter = dictionaryConfiguration.DictionaryAdapterConfiguration.GetAdapterInstance<IDictionaryAdapter>(); dictionaryAdapters.Add(dictionaryAdapter); dictionaryAdapter.Initialize(dictionaryConfiguration.DictionaryAdapterConfiguration); dictionaryAdapter.InitializePreloadCache(dictionaryConfiguration, oxymoronEngine.SubstitutionCacheRoot); this.DictionaryConfigurationToAdapterMappings.Add(dictionaryConfiguration, dictionaryAdapter); } using (ISourceAdapter sourceAdapter = obfuscationConfiguration.SourceAdapterConfiguration.GetAdapterInstance<ISourceAdapter>()) { sourceAdapter.Initialize(obfuscationConfiguration.SourceAdapterConfiguration); using (IDestinationAdapter destinationAdapter = obfuscationConfiguration.DestinationAdapterConfiguration.GetAdapterInstance<IDestinationAdapter>()) { destinationAdapter.Initialize(obfuscationConfiguration.DestinationAdapterConfiguration); destinationAdapter.UpstreamMetadata = sourceAdapter.UpstreamMetadata; sourceDataEnumerable = sourceAdapter.PullData(obfuscationConfiguration.TableConfiguration); sourceDataEnumerable = oxymoronEngine.GetObfuscatedValues(sourceDataEnumerable); if ((object)statusCallback != null) sourceDataEnumerable = WrapRecordCounter(sourceDataEnumerable, statusCallback); destinationAdapter.PushData(obfuscationConfiguration.TableConfiguration, sourceDataEnumerable); } } } } }
public void Dispose_ListWithManyItems_ShouldDisposeAllItems( IEnumerable<IDisposable> items) { //Setup var sut = new DisposableList<IDisposable>(); sut.AddRange(items); //Exercise sut.Dispose(); //Verify sut.Should().NotBeEmpty(); sut.ForEach(item => Mock.Get(item).Verify(x => x.Dispose())); }
public void MenuHandler(Predicate<ViewItem> pred, MenuItem menu, PopupTargetInfo pti) { JaneScript js = base.Host.JaneScript; using (ViewList vl = js.ViewList()) using (DisposableList<ViewItem> views = new DisposableList<ViewItem>(vl)) { List<ViewItem> closeTargets = new List<ViewItem>(); foreach (ViewItem view in views) { if (pred(view)) { closeTargets.Add(view); } } foreach (ViewItem view in closeTargets) { js.Close(view); } } }
internal static void Merge() { var samplePackagagePath = @"..\..\Temp\Sample.dacpac"; TSqlModel sampleModel = new TSqlModel(samplePackagagePath, DacSchemaModelStorageType.Memory); var targetPackagePath = @"merged.dacpac"; DisposableList disposables = new DisposableList(); DacPackageExtensions.BuildPackage( targetPackagePath, sampleModel, new PackageMetadata(), // Describes the dacpac. new PackageOptions()); // Use this to specify the deployment contributors, refactor log to include in package //DacPackage package = disposables.Add(DacPackage.Load(targetPackagePath, DacSchemaModelStorageType.Memory, FileAccess.ReadWrite)); //package.UpdateModel(cilModel, new PackageMetadata()); }
private void FindAndWriteDrafts(JaneScript js, DatOut datout, bool readDraftContents) { datout.WriteText("草稿を検索しています。"); datout.WriteBR(); datout.WriteHTML("<hr>"); using (CategoryList cl = js.CategoryList()) using (DisposableList<Category> categories = new DisposableList<Category>(cl)) { foreach (Category category in categories) { DirectoryInfo diCate = new DirectoryInfo(category.LogDir); if (!diCate.Exists) continue; using (DisposableList<Board> boards = new DisposableList<Board>(category)) { foreach(Board board in boards){ board.Load(); // カテゴリディレクトリの草稿を探す FileInfo fi = new FileInfo(Path.Combine(category.LogDir, board.Name + "NewThread.mns")); if (fi.Exists) this.OutDraft(datout, category, board, fi, readDraftContents); // 板ディレクトリ内を探す DirectoryInfo di = new DirectoryInfo(board.LogDir); if (!di.Exists) continue; foreach (FileInfo fi2 in di.GetFiles("*.mns")) { if (fi2.Name == "NewThread.mns") { this.OutDraft(datout, category, board, fi2, readDraftContents); } else { using (ThreadItem thread = board.FindThread(Path.GetFileNameWithoutExtension(fi2.Name))) { this.OutDraft(datout, category, board, thread, fi2, readDraftContents); } } } js.ProcessMessages(); } } js.ProcessMessages(); } } datout.WriteBR(); datout.WriteHTML("<hr>"); datout.WriteText("検索が終了しました。"); }
public static DisposableList GetDisposable() { return(DisposableList.Make()); }
public void Build(SpaceNode rootNode, DisposableList <HLODBuildInfo> infos, GameObject root, float cullDistance, float lodDistance, bool writeNoPrefab, bool extractMaterial, Action <float> onProgress) { dynamic options = m_streamingOptions; string path = options.OutputDirectory; HLODTreeNodeContainer container = new HLODTreeNodeContainer(); HLODTreeNode convertedRootNode = ConvertNode(container, rootNode); if (onProgress != null) { onProgress(0.0f); } HLODData.TextureCompressionData compressionData; compressionData.PCTextureFormat = options.PCCompression; compressionData.WebGLTextureFormat = options.WebGLCompression; compressionData.AndroidTextureFormat = options.AndroidCompression; compressionData.iOSTextureFormat = options.iOSCompression; compressionData.tvOSTextureFormat = options.tvOSCompression; string filename = $"{path}{root.name}.hlod"; if (Directory.Exists(path) == false) { Directory.CreateDirectory(path); } using (Stream stream = new FileStream(filename, FileMode.Create)) { HLODData data = new HLODData(); data.CompressionData = compressionData; for (int i = 0; i < infos.Count; ++i) { data.AddFromWokringObjects(infos[i].Name, infos[i].WorkingObjects); data.AddFromWorkingColliders(infos[i].Name, infos[i].Colliders); if (onProgress != null) { onProgress((float)i / (float)infos.Count); } } if (writeNoPrefab) { for (int ii = 0; ii < infos.Count; ++ii) { var spaceNode = infos[ii].Target; for (int oi = 0; oi < spaceNode.Objects.Count; ++oi) { if (PrefabUtility.IsAnyPrefabInstanceRoot(spaceNode.Objects[oi]) == false) { data.AddFromGameObject(spaceNode.Objects[oi]); } } } } if (extractMaterial == true) { ExtractMaterial(data, $"{path}{root.name}"); } HLODDataSerializer.Write(stream, data); } AssetDatabase.ImportAsset(filename, ImportAssetOptions.ForceUpdate); RootData rootData = AssetDatabase.LoadAssetAtPath <RootData>(filename); m_manager.AddGeneratedResource(rootData); var defaultController = root.AddComponent <DefaultHLODController>(); GameObject hlodRoot = new GameObject("HLODRoot"); hlodRoot.transform.SetParent(root.transform, false); m_manager.AddGeneratedResource(hlodRoot); for (int ii = 0; ii < infos.Count; ++ii) { var spaceNode = infos[ii].Target; var hlodTreeNode = convertedTable[infos[ii].Target]; for (int oi = 0; oi < spaceNode.Objects.Count; ++oi) { GameObject obj = spaceNode.Objects[oi]; GameObject rootGameObject = rootData.GetRootObject(obj.name); if (rootGameObject != null) { GameObject go = PrefabUtility.InstantiatePrefab(rootGameObject) as GameObject; go.transform.SetParent(obj.transform.parent); go.transform.localPosition = obj.transform.localPosition; go.transform.localRotation = obj.transform.localRotation; go.transform.localScale = obj.transform.localScale; int highId = defaultController.AddHighObject(go); hlodTreeNode.HighObjectIds.Add(highId); if (m_manager.IsGeneratedResource(obj)) { m_manager.AddGeneratedResource(go); } else { m_manager.AddConvertedPrefabResource(go); } Object.DestroyImmediate(obj); } else { int highId = defaultController.AddHighObject(obj); hlodTreeNode.HighObjectIds.Add(highId); } } if (infos[ii].WorkingObjects.Count > 0) { GameObject prefab = rootData.GetRootObject(infos[ii].Name); if (prefab == null) { Debug.LogError("Prefab not found: " + infos[ii].Name); } else { GameObject go = PrefabUtility.InstantiatePrefab(prefab) as GameObject; go.transform.SetParent(hlodRoot.transform, false); go.SetActive(false); int lowId = defaultController.AddLowObject(go); hlodTreeNode.LowObjectIds.Add(lowId); m_manager.AddGeneratedResource(go); } } } defaultController.Container = container; defaultController.Root = convertedRootNode; defaultController.CullDistance = cullDistance; defaultController.LODDistance = lodDistance; }
internal abstract SafeBuffer ToBuffer(DisposableList list, string package);
public object GetFDListVariant(DisposableList disposableList, bool throwError) { return(GetFDList(disposableList, throwError)); }
private static SECURITY_ATTRIBUTES CreateSecurityAttributes(SecurityDescriptor sd, bool inherit, DisposableList <IDisposable> resources) { if (sd == null && !inherit) { return(null); } var ret = new SECURITY_ATTRIBUTES() { bInheritHandle = inherit }; if (sd != null) { ret.lpSecurityDescriptor = resources.AddResource(sd.ToSafeBuffer()); } return(ret); }
static Texture CreateTextureFromImage(string path, string textureName, TextureSettings textureSettings, bool isDecalsWad) { // Load the main texture image, and any available mipmap images: using (var images = new DisposableList <Image <Rgba32> >(GetMipmapFilePaths(path).Prepend(path) .Select(imagePath => File.Exists(imagePath) ? ImageReading.ReadImage(imagePath) : null))) { // Verify image sizes: if (images[0].Width % 16 != 0 || images[0].Height % 16 != 0) { throw new InvalidDataException($"Texture '{path}' width or height is not a multiple of 16."); } for (int i = 1; i < images.Count; i++) { if (images[i] != null && (images[i].Width != images[0].Width >> i || images[i].Height != images[0].Height >> i)) { throw new InvalidDataException($"Mipmap {i} for texture '{path}' width or height does not match texture size."); } } if (isDecalsWad) { return(CreateDecalTexture(textureName, images.ToArray(), textureSettings)); } var filename = Path.GetFileName(path); var isTransparentTexture = filename.StartsWith("{"); var isAnimatedTexture = AnimatedTextureNameRegex.IsMatch(filename); var isWaterTexture = filename.StartsWith("!"); // Create a suitable palette, taking special texture types into account: var transparencyThreshold = isTransparentTexture ? Clamp(textureSettings.TransparencyThreshold ?? 128, 0, 255) : 0; Func <Rgba32, bool> isTransparentPredicate = null; if (textureSettings.TransparencyColor != null) { var transparencyColor = textureSettings.TransparencyColor.Value; isTransparentPredicate = color => color.A < transparencyThreshold || (color.R == transparencyColor.R && color.G == transparencyColor.G && color.B == transparencyColor.B); } else { isTransparentPredicate = color => color.A < transparencyThreshold; } var colorHistogram = ColorQuantization.GetColorHistogram(images.Where(image => image != null), isTransparentPredicate); var maxColors = 256 - (isTransparentTexture ? 1 : 0) - (isWaterTexture ? 2 : 0); var colorClusters = ColorQuantization.GetColorClusters(colorHistogram, maxColors); // Always make sure we've got a 256-color palette (some tools can't handle smaller palettes): if (colorClusters.Length < maxColors) { colorClusters = colorClusters .Concat(Enumerable .Range(0, maxColors - colorClusters.Length) .Select(i => (new Rgba32(), new[] { new Rgba32() }))) .ToArray(); } // Make palette adjustments for special textures: if (isWaterTexture) { var fogColor = textureSettings.WaterFogColor ?? ColorQuantization.GetAverageColor(colorHistogram); var fogIntensity = new Rgba32((byte)Clamp(textureSettings.WaterFogColor?.A ?? (int)((1f - GetBrightness(fogColor)) * 255), 0, 255), 0, 0); colorClusters = colorClusters.Take(3) .Append((fogColor, new[] { fogColor })) // Slot 3: water fog color .Append((fogIntensity, new[] { fogIntensity })) // Slot 4: fog intensity (stored in red channel) .Concat(colorClusters.Skip(3)) .ToArray(); } if (isTransparentTexture) { var colorKey = new Rgba32(0, 0, 255); colorClusters = colorClusters .Append((colorKey, new[] { colorKey })) // Slot 255: used for transparent pixels .ToArray(); } // Create the actual palette, and a color index lookup cache: var palette = colorClusters .Select(cluster => cluster.Item1) .ToArray(); var colorIndexMappingCache = new Dictionary <Rgba32, int>(); for (int i = 0; i < colorClusters.Length; i++) { (_, var colors) = colorClusters[i]; foreach (var color in colors) { colorIndexMappingCache[color] = i; } } // Create any missing mipmaps: for (int i = 1; i < images.Count; i++) { if (images[i] == null) { images[i] = images[0].Clone(context => context.Resize(images[0].Width >> i, images[0].Height >> i)); } } // Create texture data: var textureData = images .Select(image => CreateTextureData(image, palette, colorIndexMappingCache, textureSettings, isTransparentPredicate, disableDithering: isAnimatedTexture)) .ToArray(); return(Texture.CreateMipmapTexture( name: textureName, width: images[0].Width, height: images[0].Height, imageData: textureData[0], palette: palette, mipmap1Data: textureData[1], mipmap2Data: textureData[2], mipmap3Data: textureData[3])); } }
public override List<IDisplaySet> CreateDisplaySets(Series series) { List<IDisplaySet> displaySets = new List<IDisplaySet>(); if (IsValidPETFusionSeries(series)) { var fuseableBaseSeries = new List<Series>(FindFuseableBaseSeries(series)); if (fuseableBaseSeries.Count > 0) { string error; if (!CheckPETFusionSeries(series, out error)) { // if there is an error with the PET series, avoid trying to generate the volume entirely // instead, generate a placeholder series for each base series foreach (var baseSeries in fuseableBaseSeries) displaySets.Add(CreateFusionErrorDisplaySet(baseSeries, series, error)); return displaySets; } var overlayFrames = GetFrames(series.Sops); using (var fusionOverlayData = new FusionOverlayData(overlayFrames)) { foreach (var baseSeries in fuseableBaseSeries) { if (!CheckBaseSeries(baseSeries, out error)) { // if there is an error with a single base series, generate a placeholder series displaySets.Add(CreateFusionErrorDisplaySet(baseSeries, series, error)); continue; } var descriptor = new PETFusionDisplaySetDescriptor(baseSeries.GetIdentifier(), series.GetIdentifier(), IsAttenuationCorrected(series.Sops[0])); var displaySet = new DisplaySet(descriptor); using (var sops = new DisposableList<Sop>(baseSeries.Sops.OfType<ImageSop>().Select(s => new ImageSop(new FusionSopDataSource(s.DataSource, _fusionType, overlayFrames))))) { foreach (var baseFrame in GetFrames(sops)) { using (var fusionOverlaySlice = fusionOverlayData.CreateOverlaySlice(baseFrame)) { var fus = new FusionPresentationImage(baseFrame, fusionOverlaySlice); displaySet.PresentationImages.Add(fus); } } } displaySet.PresentationImages.Sort(); displaySets.Add(displaySet); } } } } return displaySets; }
protected async Task <ProcessExecutionResult> RunSimulatorApp( AppBundleInformation appInformation, MlaunchArguments mlaunchArguments, ICrashSnapshotReporter crashReporter, ISimulatorDevice simulator, ISimulatorDevice?companionSimulator, TimeSpan timeout, bool waitForExit, CancellationToken cancellationToken) { _mainLog.WriteLine("System log for the '{1}' simulator is: {0}", simulator.SystemLog, simulator.Name); var simulatorLog = _captureLogFactory.Create( path: Path.Combine(_logs.Directory, simulator.Name + ".log"), systemLogPath: simulator.SystemLog, entireFile: false, LogType.SystemLog); simulatorLog.StartCapture(); _logs.Add(simulatorLog); var simulatorScanToken = await CaptureSimulatorLog(simulator, appInformation, cancellationToken); using var systemLogs = new DisposableList <ICaptureLog> { simulatorLog }; if (companionSimulator != null) { _mainLog.WriteLine("System log for the '{1}' companion simulator is: {0}", companionSimulator.SystemLog, companionSimulator.Name); var companionLog = _captureLogFactory.Create( path: Path.Combine(_logs.Directory, companionSimulator.Name + ".log"), systemLogPath: companionSimulator.SystemLog, entireFile: false, LogType.CompanionSystemLog); companionLog.StartCapture(); _logs.Add(companionLog); systemLogs.Add(companionLog); var companionScanToken = await CaptureSimulatorLog(companionSimulator, appInformation, cancellationToken); if (companionScanToken != null) { simulatorScanToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, companionScanToken.Token); } } await crashReporter.StartCaptureAsync(); _mainLog.WriteLine("Launching the app"); if (waitForExit) { var result = await _processManager.ExecuteCommandAsync(mlaunchArguments, _mainLog, timeout, cancellationToken : cancellationToken); simulatorScanToken?.Cancel(); return(result); } TaskCompletionSource appLaunched = new(); var scanLog = new ScanLog($"Launched {appInformation.BundleIdentifier} with pid", () => { _mainLog.WriteLine("App launch detected"); appLaunched.SetResult(); }); _mainLog.WriteLine("Waiting for the app to launch.."); var runTask = _processManager.ExecuteCommandAsync(mlaunchArguments, Log.CreateAggregatedLog(_mainLog, scanLog), timeout, cancellationToken: cancellationToken); await Task.WhenAny(runTask, appLaunched.Task); if (!appLaunched.Task.IsCompleted) { // In case the other task completes first, it is because one of these scenarios happened: // - The app crashed and never launched // - We missed the launch signal somehow and the app timed out // - The app launched and quit immediately and race condition noticed that before the scan log did its job // In all cases, we should return the result of the run task, it will be most likely 137 + Timeout (killed by us) // If not, it will be a success because the app ran for a super short amount of time _mainLog.WriteLine("App launch was not detected in time"); return(runTask.Result); } _mainLog.WriteLine("Not waiting for the app to exit"); return(new ProcessExecutionResult { ExitCode = 0 }); }
public void TestLevelsAndPeaks() { bool tested = false; AtemMockServerWrapper.Each(_output, _pool, null, DeviceTestCases.ClassicAudioMain, helper => { using var items = new DisposableList(); IReadOnlyList <long> useIds = helper.Helper.BuildLibState().Audio.Inputs.Keys.ToList(); var callbacks = new Dictionary <AudioSource, LevelCallback>(useIds.Count); // Setup callbacks foreach (long id in useIds) { IBMDSwitcherAudioInput input = GetInput(helper, id); var cb = new LevelCallback(); cb.Reset(); items.Items.Add(new UseCallback <LevelCallback>(cb, input.AddCallback, input.RemoveCallback)); callbacks[(AudioSource)id] = cb; } // Now run the tests for (int i = 0; i < 5; i++) { tested = true; AtemState stateBefore = helper.Helper.BuildLibState(); stateBefore.Audio.ProgramOut.Levels = null; var inputsState = stateBefore.Audio.Inputs; var testCmd = new AudioMixerLevelsCommand(); foreach (long tmpId in useIds) { var levels = new AudioMixerLevelInput((AudioSource)tmpId) { LeftLevel = Randomiser.Range(-100, 0), RightLevel = Randomiser.Range(-100, 0), LeftPeak = Randomiser.Range(-100, 0), RightPeak = Randomiser.Range(-100, 0), }; testCmd.Inputs.Add(levels); inputsState[tmpId].Levels = new AudioState.LevelsState { Levels = new[] { levels.LeftLevel, levels.RightLevel }, Peaks = new[] { levels.LeftPeak, levels.RightPeak }, }; } helper.SendAndWaitForChange(stateBefore, () => { helper.Server.SendCommands(testCmd); }, -1, (sdkState, libState) => { libState.Audio.ProgramOut.Levels = null; foreach (KeyValuePair <AudioSource, LevelCallback> i in callbacks) { sdkState.Audio.Inputs[(long)i.Key].Levels = new AudioState.LevelsState { Levels = i.Value.Levels, Peaks = i.Value.Peaks, }; } }); } }); Assert.True(tested); }
/// <summary> /// Overridden ProcessRecord method. /// </summary> protected override void ProcessRecord() { if (ThreadId == -1 && ProcessId == -1) { IEnumerable<NtThread> threads = NtThread.GetThreads(Access); if (FilterScript == null) { WriteObject(threads); } else { using (var ths = new DisposableList<NtThread>(threads)) { WriteObject(ths.Where(t => ArbitraryFilter(t, FilterScript)).Select(t => t.Duplicate()).ToArray()); } } } else if (ProcessId != -1) { using (NtProcess process = NtProcess.Open(ProcessId, ProcessAccessRights.MaximumAllowed)) { WriteObject(process.GetThreads()); } } else { WriteObject(NtThread.Open(ThreadId, Access)); } }
public static void Main(string[] args) { Bus conn; if (args.Length == 0) { conn = Bus.Session; } else { if (args[0] == "--session") { conn = Bus.Session; } else if (args[0] == "--system") { conn = Bus.System; } else { conn = Bus.Open(args[0]); } } IBus bus = conn.GetObject <IBus> ("org.freedesktop.DBus", new ObjectPath("/org/freedesktop/DBus")); Console.WriteLine(bus.ListNames().Length); var obj = conn.GetObject <Interface> (Constants.BusName, Constants.ObjectPath); var obj2 = conn.GetObject <Interface2> (Constants.BusName, Constants.ObjectPath); var objIntr = conn.GetObject <Introspectable> (Constants.BusName, Constants.ObjectPath); obj.Ping(); Console.WriteLine(obj.GetBytes(3).Length); Console.WriteLine("conn.UnixFDSupported = " + conn.UnixFDSupported); if (!conn.UnixFDSupported) { return; } using (var disposableList = new DisposableList()) { var res = obj.GetFD(disposableList, false); Console.WriteLine("Got FD:"); Mono.Unix.Native.Stdlib.system("ls -l /proc/$PPID/fd/" + res.Handle); } using (var disposableList = new DisposableList()) { var res = obj.GetFDList(disposableList, false); Console.WriteLine("Got FDs:"); foreach (var fd in res) { Mono.Unix.Native.Stdlib.system("ls -l /proc/$PPID/fd/" + fd.Handle); } } using (var disposableList = new DisposableList()) { var res = (UnixFD[])obj.GetFDListVariant(disposableList, false); Console.WriteLine("Got FDs as variant:"); foreach (var fd in res) { Mono.Unix.Native.Stdlib.system("ls -l /proc/$PPID/fd/" + fd.Handle); } } using (var disposableList = new DisposableList()) { try { obj.GetFD(disposableList, true); throw new Exception("Expected an exception"); } catch (Exception e) { if (!e.Message.Contains("Throwing an exception after creating a UnixFD object")) { throw; } } } using (var disposableList = new DisposableList()) { try { obj.GetFDList(disposableList, true); throw new Exception("Expected an exception"); } catch (Exception e) { if (!e.Message.Contains("Throwing an exception after creating a UnixFD object")) { throw; } } } using (var disposableList = new DisposableList()) { try { obj.GetFDListVariant(disposableList, true); throw new Exception("Expected an exception"); } catch (Exception e) { if (!e.Message.Contains("Throwing an exception after creating a UnixFD object")) { throw; } } } // Check whether this leaks an FD obj.GetFD(null, false); obj.GetFDList(null, false); obj.GetFDListVariant(null, false); try { obj.GetFD(null, true); } catch {} try { obj.GetFDList(null, true); } catch {} try { obj.GetFDListVariant(null, true); } catch {} obj2.GetFD(false); obj2.GetFDList(false); obj2.GetFDListVariant(false); try { obj2.GetFD(true); } catch {} try { obj2.GetFDList(true); } catch {} try { obj2.GetFDListVariant(true); } catch {} var fd_ = Syscall.open("/dev/zero", OpenFlags.O_RDWR, 0); if (fd_ < 0) { UnixMarshal.ThrowExceptionForLastError(); } using (var fd = new UnixFD(fd_)) { obj.SendFD(fd); obj.SendFD(fd); obj.SendFDList(new UnixFD[] { fd, fd }); obj.SendFDListVariant(new UnixFD[] { fd, fd }); var impl = new SignalsImpl(); var spath = new ObjectPath("/mono_dbus_sharp_test/Signals"); conn.Register(spath, impl); obj.RegisterSignalInterface(conn.UniqueName, spath); impl.CallGotFD(fd); } Console.WriteLine(objIntr.Introspect().Length); obj.ListOpenFDs(); Console.WriteLine("Open FDs:"); Mono.Unix.Native.Stdlib.system("ls -l /proc/$PPID/fd/"); }
public TextureAtlasCreator(List <object> objs, List <Rect> uvs, List <Guid> guids, DisposableList <TextureCombiner> combiners) : base(objs, uvs, guids) { for (int i = 0; i < combiners.Count; ++i) { Textures.Add(combiners[i].GetTexture().Clone()); } }
private SafeHGlobalBuffer GetAttributes(DisposableList <IDisposable> resources) { int count = GetAttributeCount(); if (count == 0) { return(SafeHGlobalBuffer.Null); } var attr_list = resources.AddResource(new SafeProcThreadAttributeListBuffer(count)); if (ParentProcess != null) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeParentProcess, ParentProcess.Handle.DangerousGetHandle()); } if (MitigationOptions2 != ProcessMitigationOptions2.None) { MemoryStream stm = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stm); writer.Write((ulong)MitigationOptions); writer.Write((ulong)MitigationOptions2); attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeMitigationPolicy, stm.ToArray()); } else if (MitigationOptions != ProcessMitigationOptions.None) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeMitigationPolicy, (ulong)MitigationOptions); } if (Win32kFilterFlags != Win32kFilterFlags.None) { Win32kFilterAttribute filter = new Win32kFilterAttribute(); filter.Flags = Win32kFilterFlags; filter.FilterLevel = Win32kFilterLevel; attr_list.AddAttributeBuffer(ProcessAttributes.ProcThreadAttributeWin32kFilter, resources.AddResource(filter.ToBuffer())); } if ((CreationFlags & CreateProcessFlags.ProtectedProcess) != 0) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeProtectionLevel, (int)ProtectionLevel); } if (InheritHandleList.Count > 0) { int total_size = IntPtr.Size * InheritHandleList.Count; var handle_list = resources.AddResource(new SafeHGlobalBuffer(total_size)); handle_list.WriteArray(0, InheritHandleList.ToArray(), 0, InheritHandleList.Count); attr_list.AddAttributeBuffer(ProcessAttributes.ProcThreadAttributeHandleList, handle_list); } if (AppContainerSid != null) { SECURITY_CAPABILITIES caps = new SECURITY_CAPABILITIES(); caps.AppContainerSid = resources.AddResource(AppContainerSid.ToSafeBuffer()).DangerousGetHandle(); if (Capabilities.Count > 0) { SidAndAttributes[] cap_sids = new SidAndAttributes[Capabilities.Count]; for (int i = 0; i < Capabilities.Count; ++i) { cap_sids[i] = new SidAndAttributes() { Sid = resources.AddResource(Capabilities[i].ToSafeBuffer()).DangerousGetHandle(), Attributes = GroupAttributes.Enabled }; } SafeHGlobalBuffer cap_buffer = resources.AddResource(new SafeHGlobalBuffer(Marshal.SizeOf(typeof(SidAndAttributes)) * Capabilities.Count)); cap_buffer.WriteArray(0, cap_sids, 0, cap_sids.Length); caps.Capabilities = cap_buffer.DangerousGetHandle(); caps.CapabilityCount = cap_sids.Length; } attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeSecurityCapabilities, caps); } if (LowPrivilegeAppContainer) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeAllApplicationPackagesPolicy, 1); } return(attr_list); }
private SafeHGlobalBuffer GetAttributes(DisposableList <IDisposable> resources) { int count = GetAttributeCount(); if (count == 0) { return(SafeHGlobalBuffer.Null); } var attr_list = resources.AddResource(new SafeProcThreadAttributeListBuffer(count)); if (ParentProcess != null) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeParentProcess, ParentProcess.Handle.DangerousGetHandle()); } if (MitigationOptions2 != ProcessMitigationOptions2.None) { MemoryStream stm = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stm); writer.Write((ulong)MitigationOptions); writer.Write((ulong)MitigationOptions2); attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeMitigationPolicy, stm.ToArray()); } else if (MitigationOptions != ProcessMitigationOptions.None) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeMitigationPolicy, (ulong)MitigationOptions); } if (Win32kFilterFlags != Win32kFilterFlags.None) { Win32kFilterAttribute filter = new Win32kFilterAttribute(); filter.Flags = Win32kFilterFlags; filter.FilterLevel = Win32kFilterLevel; attr_list.AddAttributeBuffer(ProcessAttributes.ProcThreadAttributeWin32kFilter, resources.AddResource(filter.ToBuffer())); } if ((CreationFlags & CreateProcessFlags.ProtectedProcess) != 0 && ProtectionLevel != ProtectionLevel.None) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeProtectionLevel, (int)ProtectionLevel); } if (InheritHandleList.Count > 0) { int total_size = IntPtr.Size * InheritHandleList.Count; var handle_list = resources.AddResource(new SafeHGlobalBuffer(total_size)); handle_list.WriteArray(0, InheritHandleList.ToArray(), 0, InheritHandleList.Count); attr_list.AddAttributeBuffer(ProcessAttributes.ProcThreadAttributeHandleList, handle_list); } if (AppContainerSid != null) { SECURITY_CAPABILITIES caps = new SECURITY_CAPABILITIES { AppContainerSid = resources.AddResource(AppContainerSid.ToSafeBuffer()).DangerousGetHandle() }; if (Capabilities.Count > 0) { SidAndAttributes[] cap_sids = new SidAndAttributes[Capabilities.Count]; for (int i = 0; i < Capabilities.Count; ++i) { cap_sids[i] = new SidAndAttributes() { Sid = resources.AddResource(Capabilities[i].ToSafeBuffer()).DangerousGetHandle(), Attributes = GroupAttributes.Enabled }; } SafeHGlobalBuffer cap_buffer = resources.AddResource(new SafeHGlobalBuffer(Marshal.SizeOf(typeof(SidAndAttributes)) * Capabilities.Count)); cap_buffer.WriteArray(0, cap_sids, 0, cap_sids.Length); caps.Capabilities = cap_buffer.DangerousGetHandle(); caps.CapabilityCount = cap_sids.Length; } attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeSecurityCapabilities, caps); } if (LowPrivilegeAppContainer) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeAllApplicationPackagesPolicy, 1); } if (RestrictChildProcessCreation || OverrideChildProcessCreation) { int flags = RestrictChildProcessCreation ? 1 : 0; flags |= OverrideChildProcessCreation ? 2 : 0; attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeChildProcessPolicy, flags); } if (DesktopAppBreakaway != ProcessDesktopAppBreakawayFlags.None) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeDesktopAppPolicy, (int)DesktopAppBreakaway); } if (!string.IsNullOrWhiteSpace(PackageName)) { byte[] str_bytes = Encoding.Unicode.GetBytes(PackageName); var string_buffer = resources.AddResource(new SafeHGlobalBuffer(str_bytes)); attr_list.AddAttributeBuffer(ProcessAttributes.ProcThreadAttributePackageName, string_buffer); } if (PseudoConsole != IntPtr.Zero) { attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributePseudoConsole, PseudoConsole); } if (!string.IsNullOrEmpty(BnoIsolationPrefix)) { var prefix = new BnoIsolationAttribute() { IsolationEnabled = 1, IsolationPrefix = BnoIsolationPrefix }; attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeBnoIsolation, prefix); } if (SafeOpenPromptOriginClaim != null) { var bytes = (byte[])SafeOpenPromptOriginClaim.Clone(); Array.Resize(ref bytes, 524); attr_list.AddAttribute(ProcessAttributes.ProcThreadAttributeSafeOpenPromptOriginClaim, bytes); } return(attr_list); }
private void RefreshSessionList() { using (DisposableList<NtToken> tokens = new DisposableList<NtToken>(TokenUtils.GetSessionTokens())) { ClearList(listViewSessions); foreach (NtToken token in tokens) { ListViewItem item = new ListViewItem(token.SessionId.ToString()); item.SubItems.Add(token.User.ToString()); item.Tag = token.Duplicate(); listViewSessions.Items.Add(item); } } }
public static IEnumerator Create(HLOD hlod) { try { Stopwatch sw = new Stopwatch(); AssetDatabase.Refresh(); AssetDatabase.SaveAssets(); sw.Reset(); sw.Start(); hlod.ConvertedPrefabObjects.Clear(); hlod.GeneratedObjects.Clear(); Bounds bounds = hlod.GetBounds(); List <GameObject> hlodTargets = ObjectUtils.HLODTargets(hlod.gameObject); ISpaceSplitter spliter = new QuadTreeSpaceSplitter(5.0f); SpaceNode rootNode = spliter.CreateSpaceTree(bounds, hlod.ChunkSize, hlod.transform.position, hlodTargets, progress => { EditorUtility.DisplayProgressBar("Bake HLOD", "Splitting space", progress * 0.25f); }); if (hlodTargets.Count == 0) { EditorUtility.DisplayDialog("Empty HLOD sources.", "There are no objects to be included in the HLOD.", "Ok"); yield break; } using (DisposableList <HLODBuildInfo> buildInfos = CreateBuildInfo(rootNode, hlod.MinObjectSize)) { if (buildInfos.Count == 0 || buildInfos[0].WorkingObjects.Count == 0) { EditorUtility.DisplayDialog("Empty HLOD sources.", "There are no objects to be included in the HLOD.", "Ok"); yield break; } Debug.Log("[HLOD] Splite space: " + sw.Elapsed.ToString("g")); sw.Reset(); sw.Start(); ISimplifier simplifier = (ISimplifier)Activator.CreateInstance(hlod.SimplifierType, new object[] { hlod.SimplifierOptions }); for (int i = 0; i < buildInfos.Count; ++i) { yield return(new BranchCoroutine(simplifier.Simplify(buildInfos[i]))); } yield return(new WaitForBranches(progress => { EditorUtility.DisplayProgressBar("Bake HLOD", "Simplify meshes", 0.25f + progress * 0.25f); })); Debug.Log("[HLOD] Simplify: " + sw.Elapsed.ToString("g")); sw.Reset(); sw.Start(); using (IBatcher batcher = (IBatcher)Activator.CreateInstance(hlod.BatcherType, new object[] { hlod.BatcherOptions })) { batcher.Batch(hlod.transform.position, buildInfos, progress => { EditorUtility.DisplayProgressBar("Bake HLOD", "Generating combined static meshes.", 0.5f + progress * 0.25f); }); } Debug.Log("[HLOD] Batch: " + sw.Elapsed.ToString("g")); sw.Reset(); sw.Start(); IStreamingBuilder builder = (IStreamingBuilder)Activator.CreateInstance(hlod.StreamingType, new object[] { hlod, hlod.StreamingOptions }); builder.Build(rootNode, buildInfos, hlod.gameObject, hlod.CullDistance, hlod.LODDistance, false, true, progress => { EditorUtility.DisplayProgressBar("Bake HLOD", "Storing results.", 0.75f + progress * 0.25f); }); Debug.Log("[HLOD] Build: " + sw.Elapsed.ToString("g")); sw.Reset(); sw.Start(); EditorUtility.SetDirty(hlod.gameObject); } } finally { EditorUtility.ClearProgressBar(); } }
private void PackingTexture(TexturePacker packer, DisposableList <HLODBuildInfo> targets, dynamic options, Action <float> onProgress) { List <TextureInfo> textureInfoList = options.TextureInfoList; using (MaterialTextureCache cache = new MaterialTextureCache(options)) { for (int i = 0; i < targets.Count; ++i) { var workingObjects = targets[i].WorkingObjects; Dictionary <Guid, TexturePacker.MaterialTexture> textures = new Dictionary <Guid, TexturePacker.MaterialTexture>(); for (int oi = 0; oi < workingObjects.Count; ++oi) { var materials = workingObjects[oi].Materials; for (int m = 0; m < materials.Count; ++m) { var materialTextures = cache.GetMaterialTextures(materials[m]); if (materialTextures == null) { continue; } if (textures.ContainsKey(materialTextures[0].GetGUID()) == true) { continue; } textures.Add(materialTextures[0].GetGUID(), materialTextures); } } packer.AddTextureGroup(targets[i], textures.Values.ToList()); if (onProgress != null) { onProgress(((float)i / targets.Count) * 0.1f); } } } packer.Pack(TextureFormat.RGBA32, options.PackTextureSize, options.LimitTextureSize, false); if (onProgress != null) { onProgress(0.3f); } int index = 1; var atlases = packer.GetAllAtlases(); foreach (var atlas in atlases) { Dictionary <string, WorkingTexture> textures = new Dictionary <string, WorkingTexture>(); for (int i = 0; i < atlas.Textures.Count; ++i) { WorkingTexture wt = atlas.Textures[i]; wt.Name = "CombinedTexture " + index + "_" + i; if (textureInfoList[i].Type == PackingType.Normal) { wt.Linear = true; } textures.Add(textureInfoList[i].OutputName, wt); } WorkingMaterial mat = CreateMaterial(options.MaterialGUID, textures); mat.Name = "CombinedMaterial " + index; m_createdMaterials.Add(atlas, mat); index += 1; } }
private static DisposableList <HLODBuildInfo> CreateBuildInfo(SpaceNode root, float minObjectSize) { List <HLODBuildInfo> resultsCandidates = new List <HLODBuildInfo>(); Queue <SpaceNode> trevelQueue = new Queue <SpaceNode>(); Queue <int> parentQueue = new Queue <int>(); Queue <string> nameQueue = new Queue <string>(); Queue <int> levelQueue = new Queue <int>(); trevelQueue.Enqueue(root); parentQueue.Enqueue(-1); levelQueue.Enqueue(0); nameQueue.Enqueue(""); while (trevelQueue.Count > 0) { int currentNodeIndex = resultsCandidates.Count; string name = nameQueue.Dequeue(); SpaceNode node = trevelQueue.Dequeue(); HLODBuildInfo info = new HLODBuildInfo { Name = name, ParentIndex = parentQueue.Dequeue(), Target = node }; for (int i = 0; i < node.GetChildCount(); ++i) { trevelQueue.Enqueue(node.GetChild(i)); parentQueue.Enqueue(currentNodeIndex); nameQueue.Enqueue(name + "_" + (i + 1)); } resultsCandidates.Add(info); //it should add to every parent. List <MeshRenderer> meshRenderers = GetMeshRenderers(node.Objects, minObjectSize); List <Collider> colliders = GetColliders(node.Objects, minObjectSize); int distance = 0; while (currentNodeIndex >= 0) { var curInfo = resultsCandidates[currentNodeIndex]; for (int i = 0; i < meshRenderers.Count; ++i) { curInfo.WorkingObjects.Add(meshRenderers[i].ToWorkingObject(Allocator.Persistent)); curInfo.Distances.Add(distance); } for (int i = 0; i < colliders.Count; ++i) { curInfo.Colliders.Add(colliders[i].ToWorkingCollider()); } currentNodeIndex = curInfo.ParentIndex; distance += 1; } } DisposableList <HLODBuildInfo> results = new DisposableList <HLODBuildInfo>(); for (int i = 0; i < resultsCandidates.Count; ++i) { if (resultsCandidates[i].WorkingObjects.Count > 0) { results.Add(resultsCandidates[i]); } else { resultsCandidates[i].Dispose(); } } return(results); }
internal SECURITY_ATTRIBUTES ThreadSecurityAttributes(DisposableList <IDisposable> resources) { return(CreateSecurityAttributes(ThreadSecurityDescriptor, InheritThreadHandle, resources)); }
public IEnumerator CreateImpl() { try { using (m_queue = new JobQueue(8)) { Stopwatch sw = new Stopwatch(); AssetDatabase.Refresh(); AssetDatabase.SaveAssets(); sw.Reset(); sw.Start(); EditorUtility.DisplayProgressBar("Bake HLOD", "Initialize Bake", 0.0f); TerrainData data = m_hlod.TerrainData; m_size = data.size; m_heightmap = new Heightmap(data.heightmapResolution, data.heightmapResolution, data.size, data.GetHeights(0, 0, data.heightmapResolution, data.heightmapResolution)); string materialPath = AssetDatabase.GUIDToAssetPath(m_hlod.MaterialGUID); m_terrainMaterial = AssetDatabase.LoadAssetAtPath <Material>(materialPath); if (m_terrainMaterial == null) { m_terrainMaterial = new Material(Shader.Find("Lightweight Render Pipeline/Lit-Terrain-HLOD-High")); } m_terrainMaterialInstanceId = m_terrainMaterial.GetInstanceID(); m_terrainMaterialName = m_terrainMaterial.name; materialPath = AssetDatabase.GUIDToAssetPath(m_hlod.MaterialLowGUID); m_terrainMaterialLow = AssetDatabase.LoadAssetAtPath <Material>(materialPath); if (m_terrainMaterialLow == null) { m_terrainMaterialLow = new Material(Shader.Find("Lightweight Render Pipeline/Lit-Terrain-HLOD-Low")); } m_terrainMaterialLowInstanceId = m_terrainMaterialLow.GetInstanceID(); m_terrainMaterialLowName = m_terrainMaterialLow.name; using (m_alphamaps = new DisposableList <WorkingTexture>()) using (m_layers = new DisposableList <Layer>()) { for (int i = 0; i < data.alphamapTextures.Length; ++i) { m_alphamaps.Add(new WorkingTexture(Allocator.Persistent, data.alphamapTextures[i])); } for (int i = 0; i < data.terrainLayers.Length; ++i) { m_layers.Add(new Layer(data.terrainLayers[i], m_hlod.ChunkSize)); } QuadTreeSpaceSplitter splitter = new QuadTreeSpaceSplitter(0.0f); SpaceNode rootNode = splitter.CreateSpaceTree(m_hlod.GetBounds(), m_hlod.ChunkSize * 2.0f, m_hlod.transform.position, null, progress => { }); EditorUtility.DisplayProgressBar("Bake HLOD", "Create mesh", 0.0f); using (DisposableList <HLODBuildInfo> buildInfos = CreateBuildInfo(data, rootNode)) { yield return(m_queue.WaitFinish()); //Write material & textures for (int i = 0; i < buildInfos.Count; ++i) { int curIndex = i; m_queue.EnqueueJob(() => { ISimplifier simplifier = (ISimplifier)Activator.CreateInstance(m_hlod.SimplifierType, new object[] { m_hlod.SimplifierOptions }); simplifier.SimplifyImmidiate(buildInfos[curIndex]); }); } EditorUtility.DisplayProgressBar("Bake HLOD", "Simplify meshes", 0.0f); yield return(m_queue.WaitFinish()); Debug.Log("[TerrainHLOD] Simplify: " + sw.Elapsed.ToString("g")); sw.Reset(); sw.Start(); EditorUtility.DisplayProgressBar("Bake HLOD", "Make border", 0.0f); for (int i = 0; i < buildInfos.Count; ++i) { HLODBuildInfo info = buildInfos[i]; m_queue.EnqueueJob(() => { for (int oi = 0; oi < info.WorkingObjects.Count; ++oi) { WorkingObject o = info.WorkingObjects[oi]; int borderVertexCount = m_hlod.BorderVertexCount * Mathf.RoundToInt(Mathf.Pow(2.0f, (float)info.Distances[oi])); using (WorkingMesh m = MakeBorder(o.Mesh, info.Heightmap, borderVertexCount)) { ReampUV(m, info.Heightmap); o.SetMesh(MakeFillHoleMesh(m)); } } }); } yield return(m_queue.WaitFinish()); Debug.Log("[TerrainHLOD] Make Border: " + sw.Elapsed.ToString("g")); sw.Reset(); sw.Start(); for (int i = 0; i < buildInfos.Count; ++i) { SpaceNode node = buildInfos[i].Target; HLODBuildInfo info = buildInfos[i]; if (node.HasChild() == false) { SpaceNode parent = node.ParentNode; node.ParentNode = null; GameObject go = new GameObject(buildInfos[i].Name); for (int wi = 0; wi < info.WorkingObjects.Count; ++wi) { WorkingObject wo = info.WorkingObjects[wi]; GameObject targetGO = null; if (wi == 0) { targetGO = go; } else { targetGO = new GameObject(wi.ToString()); targetGO.transform.SetParent(go.transform, false); } List <Material> materials = new List <Material>(); for (int mi = 0; mi < wo.Materials.Count; ++mi) { WorkingMaterial wm = wo.Materials[mi]; if (wm.NeedWrite() == false) { materials.Add(wm.ToMaterial()); continue; } Material mat = new Material(wm.ToMaterial()); string[] textureNames = wm.GetTextureNames(); for (int ti = 0; ti < textureNames.Length; ++ti) { WorkingTexture wt = wm.GetTexture(textureNames[ti]); Texture2D tex = wt.ToTexture(); tex.wrapMode = wt.WrapMode; mat.name = targetGO.name + "_Mat"; mat.SetTexture(textureNames[ti], tex); } mat.EnableKeyword("_NORMALMAP"); materials.Add(mat); } targetGO.AddComponent <MeshFilter>().sharedMesh = wo.Mesh.ToMesh(); var mr = targetGO.AddComponent <MeshRenderer>(); mr.sharedMaterials = materials.ToArray(); mr.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off; } go.transform.SetParent(m_hlod.transform, false); m_hlod.AddGeneratedResource(go); parent.Objects.Add(go); buildInfos.RemoveAt(i); i -= 1; } } //controller IStreamingBuilder builder = (IStreamingBuilder)Activator.CreateInstance(m_hlod.StreamingType, new object[] { m_hlod, m_hlod.StreamingOptions }); builder.Build(rootNode, buildInfos, m_hlod.gameObject, m_hlod.CullDistance, m_hlod.LODDistance, true, false, progress => { EditorUtility.DisplayProgressBar("Bake HLOD", "Storing results.", 0.75f + progress * 0.25f); }); Debug.Log("[TerrainHLOD] Build: " + sw.Elapsed.ToString("g")); } } EditorUtility.SetDirty(m_hlod.gameObject); } } finally { EditorUtility.ClearProgressBar(); GC.Collect(); } }
internal override SecBuffer ToBuffer(DisposableList list) { return(new SecBuffer(_type)); }
/// <summary> /// Updates the model inside an existing dacpac. All other parts of the package (the refactor log, pre/post deployment scripts, /// contributors to use etc) stay the same. /// </summary> /// <param name="dacpacPath"></param> public void UpdateDacpacModelWithFilter(string dacpacPath) { DisposableList disposables = new DisposableList(); try { TSqlModel model = disposables.Add(new TSqlModel(dacpacPath, DacSchemaModelStorageType.Memory)); TSqlModel filteredModel = disposables.Add(CreateFilteredModel(model)); // Note that the package must be opened in ReadWrite mode - this will fail if this isn't specified DacPackage package = disposables.Add(DacPackage.Load(dacpacPath, DacSchemaModelStorageType.Memory, FileAccess.ReadWrite)); package.UpdateModel(filteredModel, new PackageMetadata()); } finally { disposables.Dispose(); } }
void MakeTexture(TerrainLayer layer, Texture2D texture, Vector4 min, Vector4 max, DisposableList <WorkingTexture> results) { bool linear = !GraphicsFormatUtility.IsSRGBFormat(texture.graphicsFormat); var offset = layer.tileOffset; var size = layer.tileSize; if (!linear) { min.x = Mathf.Pow(min.x, 0.45f); min.y = Mathf.Pow(min.y, 0.45f); min.z = Mathf.Pow(min.z, 0.45f); max.x = Mathf.Pow(max.x, 0.45f); max.y = Mathf.Pow(max.y, 0.45f); max.z = Mathf.Pow(max.z, 0.45f); } //make to texture readable. var assetImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)); var textureImporter = assetImporter as TextureImporter; TextureImporterType type = TextureImporterType.Default; if (textureImporter) { type = textureImporter.textureType; textureImporter.isReadable = true; textureImporter.textureType = TextureImporterType.Default; textureImporter.SaveAndReimport(); } try { for (int i = 0; i < texture.mipmapCount; ++i) { int width = texture.width >> i; int height = texture.height >> i; WorkingTexture workingTexture = new WorkingTexture(Allocator.Persistent, texture.format, width, height, linear); Color[] colors = texture.GetPixels(i); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { workingTexture.SetPixel(x, y, colors[y * width + x]); } } RemapTexture(workingTexture, min, max); results.Add(workingTexture); } } finally { if (textureImporter) { textureImporter.isReadable = false; textureImporter.textureType = type; textureImporter.SaveAndReimport(); } } }
public SecurityInformationImpl(string obj_name, NtObject handle, Dictionary<uint, string> names, GenericMapping generic_mapping) { _mapping = generic_mapping; _handle = handle; _obj_name = new SafeStringBuffer(obj_name); _access_map = new SafeHGlobalBuffer(Marshal.SizeOf(typeof(SiAccess)) * names.Count); SiAccess[] sis = new SiAccess[names.Count]; IntPtr current_ptr = _access_map.DangerousGetHandle(); _names = new DisposableList<SafeStringBuffer>(); int i = 0; foreach (KeyValuePair<uint, string> pair in names) { _names.Add(new SafeStringBuffer(pair.Value)); SiAccess si = new SiAccess(); si.dwFlags = SiAccessFlags.SI_ACCESS_SPECIFIC | SiAccessFlags.SI_ACCESS_GENERAL; si.mask = pair.Key; si.pszName = _names[i].DangerousGetHandle(); sis[i] = si; i++; } _access_map.WriteArray(0, sis, 0, names.Count); }
public void TestEnhancedAgentCodeSequence() { var agent1 = new CodeSequenceMacro {CodeMeaning = "Contrastinol", CodeValue = "123", CodingSchemeDesignator = "ABC"}; var agent2 = new CodeSequenceMacro {CodeMeaning = "Bolusinate", CodeValue = "456", CodingSchemeDesignator = "DEF"}; var agent3 = new CodeSequenceMacro {CodeMeaning = "Dilithium", CodeValue = "789", CodingSchemeDesignator = "GHI"}; var usageFrame1 = new ContrastBolusUsageFunctionalGroup { ContrastBolusUsageSequence = new[] { new ContrastBolusUsageSequenceItem {ContrastBolusAgentNumber = 1}, new ContrastBolusUsageSequenceItem {ContrastBolusAgentNumber = 3} } }; var usageFrame2 = new ContrastBolusUsageFunctionalGroup { ContrastBolusUsageSequence = new[] { new ContrastBolusUsageSequenceItem {ContrastBolusAgentNumber = 2} } }; var usageFrame3 = new ContrastBolusUsageFunctionalGroup(new DicomSequenceItem()) { ContrastBolusUsageSequence = new[] { new ContrastBolusUsageSequenceItem {ContrastBolusAgentNumber = 999}, new ContrastBolusUsageSequenceItem {ContrastBolusAgentNumber = 2} } }; var usageFrame4 = new ContrastBolusUsageFunctionalGroup(new DicomSequenceItem()); var dataset = TestDataSource.CreateImageSopDataSource(4); dataset[DicomTags.ContrastBolusAgent].SetStringValue(@"Contrastinol and Bolusinate"); dataset[DicomTags.ContrastBolusAgentSequence].AddSequenceItem(agent1.DicomSequenceItem); dataset[DicomTags.ContrastBolusAgentSequence].AddSequenceItem(agent2.DicomSequenceItem); dataset[DicomTags.ContrastBolusAgentSequence].AddSequenceItem(agent3.DicomSequenceItem); dataset[DicomTags.PerFrameFunctionalGroupsSequence].AddSequenceItem(usageFrame1.DicomSequenceItem); dataset[DicomTags.PerFrameFunctionalGroupsSequence].AddSequenceItem(usageFrame2.DicomSequenceItem); dataset[DicomTags.PerFrameFunctionalGroupsSequence].AddSequenceItem(usageFrame3.DicomSequenceItem); dataset[DicomTags.PerFrameFunctionalGroupsSequence].AddSequenceItem(usageFrame4.DicomSequenceItem); agent1.DicomSequenceItem[DicomTags.ContrastBolusAgentNumber].SetInt32(0, 1); agent2.DicomSequenceItem[DicomTags.ContrastBolusAgentNumber].SetInt32(0, 2); agent3.DicomSequenceItem[DicomTags.ContrastBolusAgentNumber].SetInt32(0, 3); using (var sop = (ImageSop) Sop.Create(dataset)) using (var images = new DisposableList<IPresentationImage>(PresentationImageFactory.Create(sop))) { Assert.AreEqual(@"Contrastinol\Dilithium", _annotationItems[_cbAgent].GetAnnotationText(images[0]), "Frame 1"); Assert.AreEqual(@"Bolusinate", _annotationItems[_cbAgent].GetAnnotationText(images[1]), "Frame 2"); Assert.AreEqual(@"Bolusinate", _annotationItems[_cbAgent].GetAnnotationText(images[2]), "Frame 3"); Assert.IsEmpty(_annotationItems[_cbAgent].GetAnnotationText(images[3]), "Frame 4"); agent1.CodeMeaning = string.Empty; agent2.CodeMeaning = string.Empty; Assert.AreEqual(@"123 (ABC)\Dilithium", _annotationItems[_cbAgent].GetAnnotationText(images[0]), "Frame 1"); Assert.AreEqual(@"456 (DEF)", _annotationItems[_cbAgent].GetAnnotationText(images[1]), "Frame 2"); Assert.AreEqual(@"456 (DEF)", _annotationItems[_cbAgent].GetAnnotationText(images[2]), "Frame 3"); Assert.IsEmpty(_annotationItems[_cbAgent].GetAnnotationText(images[3]), "Frame 4"); agent3.CodeMeaning = string.Empty; Assert.AreEqual(@"123 (ABC)\789 (GHI)", _annotationItems[_cbAgent].GetAnnotationText(images[0])); Assert.AreEqual(@"456 (DEF)", _annotationItems[_cbAgent].GetAnnotationText(images[1]), "Frame 2"); Assert.AreEqual(@"456 (DEF)", _annotationItems[_cbAgent].GetAnnotationText(images[2]), "Frame 3"); Assert.IsEmpty(_annotationItems[_cbAgent].GetAnnotationText(images[3]), "Frame 4"); } }
public bool tickUpdate(GameTime time) { Game1.player.CanMove = false; timer += time.ElapsedGameTime.Milliseconds; Game1.fadeToBlackAlpha = 1f; if (timer > 1500 && !playedSound && !getBabyName) { if (soundName != null && !soundName.Equals("")) { Game1.playSound(soundName); playedSound = true; } if (!playedSound && message != null && !Game1.dialogueUp && Game1.activeClickableMenu == null) { Game1.drawObjectDialogue(message); Game1.afterDialogues = afterMessage; } } else if (getBabyName) { if (!naming) { Game1.activeClickableMenu = new NamingMenu(returnBabyName, Game1.content.LoadString(isMale ? "Strings\\Events:BabyNamingTitle_Male" : "Strings\\Events:BabyNamingTitle_Female"), ""); naming = true; } if (babyName != null && babyName != "" && babyName.Length > 0) { double chance = (Game1.player.spouse.Equals("Maru") ? 0.5 : 0.0); chance += (Game1.player.hasDarkSkin() ? 0.5 : 0.0); bool isDarkSkinned = new Random((int)Game1.uniqueIDForThisGame + (int)Game1.stats.DaysPlayed).NextDouble() < chance; string newBabyName = babyName; Dictionary <string, string> dispositions = Game1.content.Load <Dictionary <string, string> >("Data\\NPCDispositions"); DisposableList <NPC> all_characters = Utility.getAllCharacters(); bool collision_found = false; do { collision_found = false; if (dispositions.ContainsKey(newBabyName)) { newBabyName += " "; collision_found = true; continue; } foreach (NPC item in all_characters) { if (item.name.Equals(newBabyName)) { newBabyName += " "; collision_found = true; } } }while (collision_found); Child baby = new Child(newBabyName, isMale, isDarkSkinned, Game1.player); baby.Age = 0; baby.Position = new Vector2(16f, 4f) * 64f + new Vector2(0f, -24f); Utility.getHomeOfFarmer(Game1.player).characters.Add(baby); Game1.playSound("smallSelect"); Game1.player.getSpouse().daysAfterLastBirth = 5; Game1.player.GetSpouseFriendship().NextBirthingDate = null; if (Game1.player.getChildrenCount() == 2) { Game1.player.getSpouse().shouldSayMarriageDialogue.Value = true; Game1.player.getSpouse().currentMarriageDialogue.Insert(0, new MarriageDialogueReference("Data\\ExtraDialogue", "NewChild_SecondChild" + Game1.random.Next(1, 3), true)); Game1.getSteamAchievement("Achievement_FullHouse"); } else if (Game1.player.getSpouse().isGaySpouse()) { Game1.player.getSpouse().currentMarriageDialogue.Insert(0, new MarriageDialogueReference("Data\\ExtraDialogue", "NewChild_Adoption", true, babyName)); } else { Game1.player.getSpouse().currentMarriageDialogue.Insert(0, new MarriageDialogueReference("Data\\ExtraDialogue", "NewChild_FirstChild", true, babyName)); } Game1.morningQueue.Enqueue(delegate { Game1.multiplayer.globalChatInfoMessage("Baby", Lexicon.capitalize(Game1.player.Name), Game1.player.spouse, Lexicon.getGenderedChildTerm(isMale), Lexicon.getPronoun(isMale), baby.displayName); }); if (Game1.keyboardDispatcher != null) { Game1.keyboardDispatcher.Subscriber = null; } Game1.player.Position = Utility.PointToVector2(Utility.getHomeOfFarmer(Game1.player).GetPlayerBedSpot()) * 64f; Game1.globalFadeToClear(); return(true); } } return(false); }
private void ClearListView() { _processes?.Dispose(); _processes = new DisposableList <NtProcess>(); listViewProcesses.Items.Clear(); }
private void DrawShadows() { if (shadowReceiverMode != ShadowReceiverMode.Exact) { return; } DisposableList <IShadowCaster> shadowCasters = ShadowCasterHelper.VisibleShadowCasters; for (int i = 0; i < shadowCasters.Count; i++) { IShadowCaster shadowCaster = shadowCasters[i]; Box shadowVolume = shadowCaster.GetShadowVolume(); Box? shadowBox = shadowVolume.GetIntersectionVolume(BackingBox.B); if (shadowBox == null || (!BackingBox.B.isRamp && shadowBox.Value.Top < BackingBox.Top)) { continue; } Texture2D shadowTexture = shadowCaster.GetShadowTexture(); int xIndex; int yIndex; int sourceWidth; int sourceHeight; if (shadowCaster.ShouldTile()) { xIndex = (int)(shadowBox.Value.Left - shadowVolume.Left); yIndex = (int)(shadowBox.Value.Back - shadowVolume.Back); sourceWidth = (int)shadowBox?.Width; sourceHeight = (int)shadowBox?.Depth; } else { xIndex = (int)Math.Round((shadowBox.Value.Left - shadowVolume.Left) / shadowVolume.Width * shadowTexture.Width); yIndex = (int)Math.Round((shadowBox.Value.Back - shadowVolume.Back) / shadowVolume.Depth * shadowTexture.Height); sourceWidth = (int)Math.Round(shadowBox.Value.Width / shadowVolume.Width * shadowTexture.Width); sourceHeight = (int)Math.Round(shadowBox.Value.Depth / shadowVolume.Depth * shadowTexture.Height); } float opacity = (1f - (shadowVolume.Top - BackingBox.B.Top) / shadowVolume.Height) * shadowCaster.GetShadowOpacity(); if (!BackingBox.B.isRamp) { GameService.GetService <IRenderService>().PushAlphaFragment( RenderService.AlphaStacks.Shadows, shadowTexture, new Rectangle((int)Math.Round(shadowBox.Value.Left), (int)Math.Round(shadowBox.Value.Back - shadowBox.Value.Top), (int)Math.Round(shadowBox.Value.Width), (int)Math.Round(shadowBox.Value.Depth)), new Rectangle(xIndex, yIndex, sourceWidth, sourceHeight), IsTiling: shadowCaster.ShouldTile(), Tint: Color.White * opacity ); if (shadowBox.Value.Front == BackingBox.B.Front) { GameService.GetService <IRenderService>().PushAlphaFragment( RenderService.AlphaStacks.Shadows, shadowTexture, new Rectangle((int)Math.Round(shadowBox.Value.Left), (int)Math.Round(shadowBox.Value.Front - shadowBox.Value.Top), (int)Math.Round(shadowBox.Value.Width), (int)Math.Round(shadowBox.Value.Height)), new Rectangle(xIndex, yIndex + sourceHeight - 1, sourceWidth, 1), IsTiling: shadowCaster.ShouldTile(), Tint: Color.White * opacity ); } } else { GameService.GetService <IRenderService>().PushAlphaFragment( RenderService.AlphaStacks.Shadows, shadowTexture, new Rectangle((int)Math.Round(shadowBox.Value.Left), ((int)shadowBox.Value.Back - (int)BackingBox.Back) / 2 + (int)Math.Round(shadowBox.Value.Back - BackingBox.B.Top), (int)Math.Round(shadowBox.Value.Width), (int)Math.Round(shadowBox.Value.Depth * 1.5f)), new Rectangle(xIndex, yIndex, sourceWidth, sourceHeight), IsTiling: shadowCaster.ShouldTile(), Tint: Color.White * opacity ); } } }
public SEC_WINNT_AUTH_IDENTITY_EX(string user, string domain, SecureString password, DisposableList list) { Version = SEC_WINNT_AUTH_IDENTITY_VERSION; Length = Marshal.SizeOf(this); User = user; UserLength = user?.Length ?? 0; Domain = domain; DomainLength = domain?.Length ?? 0; if (password != null) { Password = list.AddResource(new SecureStringMarshal(password)); PasswordLength = password.Length; } Flags = SecWinNtAuthIdentityFlags.Unicode; }
internal SEC_WINNT_AUTH_IDENTITY ToAuthIdentity(DisposableList list) { return(new SEC_WINNT_AUTH_IDENTITY(UserName, Domain, Password, list)); }
private void RefreshProcessList(string filter, bool hideUnrestricted) { using (var processes = new DisposableList<NtProcess>(NtProcess.GetProcesses(ProcessAccessRights.QueryInformation))) { processes.Sort((a, b) => a.ProcessId- b.ProcessId); IEnumerable<NtProcess> filtered = processes.Where(p => GetToken(p) != null); if (!String.IsNullOrWhiteSpace(filter)) { filter = filter.ToLower(); filtered = filtered.Where(p => p.FullPath.ToLower().Contains(filter)); } if (hideUnrestricted) { filtered = filtered.Where(p => IsRestrictedToken(p)); } ClearTree(treeViewProcesses); ClearList(listViewThreads); foreach (NtProcess entry in filtered) { AddProcessNode(entry); AddThreads(entry); } listViewThreads.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); listViewThreads.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } }
public async Task Timestamp_Verify_WithOfflineRevocation_ReturnsCorrectFlagsAndLogsAsync() { var nupkg = new SimpleTestPackageContext(); using (var testServer = await SigningTestServer.CreateAsync()) using (var responders = new DisposableList <IDisposable>()) using (var packageStream = await nupkg.CreateAsStreamAsync()) using (var testCertificate = new X509Certificate2(_trustedTestCert.Source.Cert)) { CertificateAuthority rootCa = CertificateAuthority.Create(testServer.Url); CertificateAuthority intermediateCa = rootCa.CreateIntermediateCertificateAuthority(); responders.Add(testServer.RegisterResponder(intermediateCa)); responders.Add(testServer.RegisterResponder(rootCa)); using (var trustedServerRoot = TrustedTestCert.Create( new X509Certificate2(rootCa.Certificate.GetEncoded()), StoreName.Root, StoreLocation.LocalMachine)) { var timestampService = TimestampService.Create(intermediateCa); responders.Add(testServer.RegisterResponder(timestampService)); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var signature = await SignedArchiveTestUtility.CreateAuthorSignatureForPackageAsync(testCertificate, packageStream, timestampProvider); var timestamp = signature.Timestamps.First(); var settings = new SignedPackageVerifierSettings( allowUnsigned: false, allowUntrusted: false, allowIllegal: false, allowIgnoreTimestamp: false, allowMultipleTimestamps: false, allowNoTimestamp: false, allowUnknownRevocation: false, reportUnknownRevocation: true, verificationTarget: VerificationTarget.All, signaturePlacement: SignaturePlacement.Any, repositoryCountersignatureVerificationBehavior: SignatureVerificationBehavior.Always, revocationMode: RevocationMode.Online); var logs = new List <SignatureLog>(); var result = timestamp.Verify(signature, settings, HashAlgorithmName.SHA256, logs); result.HasFlag(SignatureVerificationStatusFlags.UnknownRevocation).Should().BeTrue(); var errors = logs.Where(l => l.Level == LogLevel.Error); errors.Count().Should().Be(RuntimeEnvironmentHelper.IsWindows ? 2 : 1); if (RuntimeEnvironmentHelper.IsWindows) { errors.Should().Contain(w => w.Code == NuGetLogCode.NU3028 && w.Message.Contains("The revocation function was unable to check revocation because the revocation server could not be reached.")); errors.Should().Contain(w => w.Code == NuGetLogCode.NU3028 && w.Message.Contains("The revocation function was unable to check revocation for the certificate.")); } else { errors.Should().Contain(w => w.Code == NuGetLogCode.NU3028 && w.Message.Contains("unable to get certificate CRL")); } } } }
private DisposableList <ToolStripItem> createMenuItems(HostPwEntry hostPwEntry) { var menuItems = new DisposableList <ToolStripItem>(); if (hostPwEntry.ConnectionMethods.Contains(ConnectionMethodType.RemoteDesktop)) { var menuItem = new ToolStripMenuItem() { Text = OpenRemoteDesktopMenuItemText, Image = (System.Drawing.Image)QuickConnectPlugin.Properties.Resources.remote, Enabled = hostPwEntry.HasIPAddress }; menuItem.Click += new EventHandler( delegate(object obj, EventArgs ev) { try { ProcessUtils.Start(CmdKeyRegisterArgumentsFormatter.CmdKeyPath, new CmdKeyRegisterArgumentsFormatter().Format(hostPwEntry)); IArgumentsFormatter argsFormatter = new RemoteDesktopArgumentsFormatter() { FullScreen = true }; ProcessUtils.StartDetached(argsFormatter.Format(hostPwEntry)); ProcessUtils.StartDetached(new CmdKeyUnregisterArgumentsFormatter() { IncludePath = true }.Format(hostPwEntry), RemoveCredentialsDelay); } catch (Exception ex) { log(ex); } } ); menuItems.Add(menuItem); } ; if (hostPwEntry.ConnectionMethods.Contains(ConnectionMethodType.RemoteDesktopConsole)) { var menuItem = new ToolStripMenuItem() { Text = OpenRemoteDesktopConsoleMenuItemText, Image = (System.Drawing.Image)QuickConnectPlugin.Properties.Resources.mycomputer, Enabled = hostPwEntry.HasIPAddress }; menuItem.Click += new EventHandler( delegate(object obj, EventArgs ev) { try { ProcessUtils.Start(CmdKeyRegisterArgumentsFormatter.CmdKeyPath, new CmdKeyRegisterArgumentsFormatter() .Format(hostPwEntry)); IArgumentsFormatter argsFormatter = new RemoteDesktopArgumentsFormatter() { FullScreen = true, UseConsole = true, IsOlderVersion = RDCIsOlderVersion }; ProcessUtils.StartDetached(argsFormatter.Format(hostPwEntry)); ProcessUtils.StartDetached(new CmdKeyUnregisterArgumentsFormatter() { IncludePath = true }.Format(hostPwEntry), RemoveCredentialsDelay); } catch (Exception ex) { log(ex); } } ); menuItems.Add(menuItem); } ; if (hostPwEntry.ConnectionMethods.Contains(ConnectionMethodType.vSphereClient)) { var vSphereClientPath = QuickConnectUtils.GetVSphereClientPath(); var menuItem = new ToolStripMenuItem() { Text = OpenVSphereClientMenuItemText, Image = (System.Drawing.Image)QuickConnectPlugin.Properties.Resources.vmware, Enabled = hostPwEntry.HasIPAddress && !String.IsNullOrEmpty(vSphereClientPath) }; menuItem.Click += new EventHandler( delegate(object obj, EventArgs ev) { try { IArgumentsFormatter argsFormatter = new VSphereClientArgumentsFormatter(vSphereClientPath); ProcessUtils.StartDetached(argsFormatter.Format(hostPwEntry)); } catch (Exception ex) { log(ex); } } ); menuItems.Add(menuItem); } if (hostPwEntry.ConnectionMethods.Contains(ConnectionMethodType.PuttySSH) || hostPwEntry.ConnectionMethods.Contains(ConnectionMethodType.PuttyTelnet)) { var sshClientPath = !String.IsNullOrEmpty(this.Settings.SSHClientPath) ? this.Settings.SSHClientPath : QuickConnectUtils.GetPuttyPath(); var menuItem = new ToolStripMenuItem() { Text = OpenSSHConsoleMenuItemText, Image = (System.Drawing.Image)QuickConnectPlugin.Properties.Resources.konsole, Enabled = hostPwEntry.HasIPAddress && !String.IsNullOrEmpty(sshClientPath) }; menuItem.Click += new EventHandler( delegate(object obj, EventArgs ev) { try { var sessionFinder = new RegistryPuttySessionFinder(new WindowsRegistryService()); IArgumentsFormatter argsFormatter = new PuttyArgumentsFormatter(sshClientPath, sessionFinder); ProcessUtils.StartDetached(argsFormatter.Format(hostPwEntry)); } catch (Exception ex) { log(ex); }; } ); menuItems.Add(menuItem); } ; if (hostPwEntry.ConnectionMethods.Contains(ConnectionMethodType.WinSCP)) { var winScpPath = !String.IsNullOrEmpty(this.Settings.WinScpPath) ? this.Settings.WinScpPath : QuickConnectUtils.GetWinScpPath(); var winScpConsoleMenuItem = new ToolStripMenuItem() { Text = OpenWinScpMenuItemText, Image = (System.Drawing.Image)QuickConnectPlugin.Properties.Resources.winscp, Enabled = hostPwEntry.HasIPAddress && !String.IsNullOrEmpty(winScpPath) }; winScpConsoleMenuItem.Click += new EventHandler( delegate(object obj, EventArgs ev) { try { IArgumentsFormatter argsFormatter = new WinScpArgumentsFormatter(winScpPath); ProcessUtils.StartDetached(argsFormatter.Format(hostPwEntry)); } catch (Exception ex) { log(ex); }; } ); menuItems.Add(winScpConsoleMenuItem); } ; return(menuItems); }
public UnixFD[] GetFDList(DisposableList disposableList, bool throwError) { return(new UnixFD[] { GetFD(disposableList, false), GetFD(disposableList, throwError), GetFD(disposableList, false) }); }
internal static List <SecBuffer> ToBufferList(this IEnumerable <SecurityBuffer> buffers, DisposableList list) { return(buffers.Select(b => b.ToBuffer(list)).ToList()); }
Func <FirewallFilter, bool> IFirewallEnumTemplate <FirewallFilter> .GetFilterFunc(DisposableList list) { var user_conditions = Conditions.Where(c => FirewallConditionGuids.IsUserId(c.FieldKey)); if (!user_conditions.Any()) { return(_ => true); } var rm = list.AddResource(AuthZResourceManager.Create()); Dictionary <Guid, AuthZContext> contexts = new Dictionary <Guid, AuthZContext>(); foreach (var condition in user_conditions) { if (contexts.ContainsKey(condition.FieldKey)) { continue; } if (!(condition.Value.ContextValue is FirewallTokenInformation token) || token.UserSid == null) { continue; } contexts.Add(condition.FieldKey, token.CreateContext(rm, list)); } return(f => FilterFunc(contexts, f)); }
/// <summary> /// Creates a new dacpac based on the filtered model. This implementation loads from and saves to /// disk, but the API supports loading from and saving to a memory stream. This can be useful if you /// want to support a scenario where you load a dacpac, filter its model, then immediately deploy the filtered /// model to a database. /// </summary> public void CreateFilteredDacpac(string dacpacPath, string filteredDacpacPath) { DisposableList disposables = new DisposableList(); try { TSqlModel model = disposables.Add(new TSqlModel(dacpacPath, DacSchemaModelStorageType.Memory)); TSqlModel filteredModel = disposables.Add(CreateFilteredModel(model)); DacPackageExtensions.BuildPackage( filteredDacpacPath, filteredModel, new PackageMetadata(), // Describes the dacpac. new PackageOptions()); // Use this to specify the deployment contributors, refactor log to include in package } finally { // Models and DacPackage objects are disposable - either use a "using" statement or dispose of them in a finally block. // In these examples we'd end up with a large amount of indentation and to avoid that I'm using a try/finally block. disposables.Dispose(); } }
/// <summary> /// Overridden ProcessRecord method. /// </summary> protected override void ProcessRecord() { if (MapGeneric && Type == null) { WriteWarning("Must specify Type for MapGeneric to work correctly."); } SecurityDescriptor sd; switch (ParameterSetName) { case "FromToken": { Type = Type ?? Parent?.NtType ?? Creator?.NtType; if (Type == null) { WriteWarning("Security descriptor type not specified, defaulting to File."); Type = NtType.GetTypeByType <NtFile>(); } using (var list = new DisposableList()) { if (EffectiveToken) { Token = list.AddResource(NtToken.OpenEffectiveToken()); } sd = SecurityDescriptor.Create(Parent, Creator, ObjectType, Container, AutoInherit, Token, Type.GenericMapping); } } break; case "FromSddl": sd = new SecurityDescriptor(Sddl); break; case "FromBytes": sd = new SecurityDescriptor(Bytes); break; case "FromKey": sd = new SecurityDescriptor(Key.QueryValue(ValueName).Data); break; case "FromKeyValue": sd = new SecurityDescriptor(KeyValue.Data); break; case "FromBase64": sd = SecurityDescriptor.ParseBase64(Base64); break; default: sd = CreateNewSecurityDescriptor(); break; } sd.NtType = Type; sd.Container = Container; if (MapGeneric) { sd.MapGenericAccess(); } sd.Control |= Control; WriteObject(sd); }
public void InitializeTest() { _trash = new DisposableList(); }
private IEnumerable<NtObject> GetProcesses() { if (string.IsNullOrWhiteSpace(Name) && string.IsNullOrWhiteSpace(CommandLine) && FilterScript == null) { return NtProcess.GetProcesses(Access); } using (DisposableList<NtProcess> procs = new DisposableList<NtProcess>(NtProcess.GetProcesses(Access))) { IEnumerable<NtProcess> filtered_procs = procs; if (!string.IsNullOrWhiteSpace(Name)) { filtered_procs = filtered_procs.Where(p => FilterName(p, Name)); } if (!string.IsNullOrWhiteSpace(CommandLine)) { filtered_procs = filtered_procs.Where(p => FilterCommandLine(p, CommandLine)); } if (FilterScript != null) { filtered_procs = filtered_procs.Where(p => ArbitraryFilter(p, FilterScript)); } return filtered_procs.Select(p => p.Duplicate()).ToArray(); } }