public void LoadFromAppSettingsJsonSection2() { var assembliesPath = "bin/Debug/netcore3.0"; var csvSearchPatterns = "Shared.*"; var mefSettingsText = $@"""mef"": {{ ""assembliesPath"": ""{assembliesPath}"", ""csvSearchPatterns"": ""{csvSearchPatterns}"" }}"; var appSettingsJsonNewText = //create a new appsettings.json file that has mef settings as a section inside, to use for deserialization $@"{{ ""key1"": ""val1"", ""key2"": 200, ""key3"": true, {mefSettingsText}, ""key4"": {{ ""k41"": ""v41"", ""k42"": ""v42"" }} }}"; File.WriteAllText(settingsFile, appSettingsJsonNewText); //overwrite if exists File.Delete(Mef.MEF_ConfigFileName); //delete mef-dedicated json config file //Act new Mef(); //only for testing; not the usual way of using this; this is to force Init() and reading configuration settings from wherever provided try { Mef.Resolve <IComparable>(); } catch { } //Assert ValidateMefConfiguration(assembliesPath, csvSearchPatterns); }
static void Main(string[] args) { Mef mef = new Mef(); mef.Config(); mef.Cat.Run(); mef.Kitty.Value.Run(); foreach (var animal in mef.Animals) { animal.Run(); } Console.WriteLine($"The little pig a {mef.Age} years old."); Console.WriteLine($"Owner is {mef.Owner}"); mef.Run(); var info = mef.GetInfo("Alfred Xing"); Console.WriteLine(info); Console.Read(); }
public void VsTextViewCreated(IVsTextView textViewAdapter) { var textView = GetInitializedTextView(textViewAdapter); ITextDocument document; if (!TextDocumentFactoryService.TryGetTextDocument(textView.TextDataModel.DocumentBuffer, out document)) { return; } var saveListeners = Mef.GetAllImports <IFileSaveListener>(document.TextBuffer.ContentType); if (saveListeners.Count == 0) { return; } EventHandler <TextDocumentFileActionEventArgs> saveHandler = (s, e) => { if (e.FileActionType != FileActionTypes.ContentSavedToDisk) { return; } foreach (var listener in saveListeners) { listener.FileSaved(document.TextBuffer.ContentType, e.FilePath, false, false); } }; document.FileActionOccurred += saveHandler; textView.Closed += delegate { document.FileActionOccurred -= saveHandler; }; }
public void InitCacheWithMefAndJsonConfigAndTestExpirationOverrideInPutCall() { //Arrange var expiration = new TimeSpan(0, 0, 10); //2 seconds for cache to hold a value SetupAppSettingsJsonConfigFile(expiration); //delete any existing dedicated JSON config file (it would try to read from there first) if (File.Exists(CacheManager.CACHE_ConfigFileName)) { File.Delete(CacheManager.CACHE_ConfigFileName); } var valueToCache = 23; var key = "MyIntVal"; var expirationOverride = new TimeSpan(0, 0, 2); //Act: init cache and validate setting var cacheMgr = Mef.Resolve <ICache>(); Assert.IsNotNull(cacheMgr); ValidateNonPublicStaticFieldValue(typeof(CacheManager), "Expiration", expiration); //Act: store value cacheMgr.Put(valueToCache, key, expirationOverride); //Assert: value is immediately available, but not after 2 seconds var cachedValue = cacheMgr.Get <int>(key); Assert.AreEqual(valueToCache, cachedValue); //wait 2 seconds, value should be gone from cache Thread.Sleep(expirationOverride.Seconds * 1000); cachedValue = cacheMgr.Get <int>(key); Assert.AreEqual(0, cachedValue); //0 is default for int }
public Form_Outline(VolumeService volumeService, Id currentCitation, int left, int top, int width, int height) { InitializeComponent(); Left = left; Top = top; Width = width; Height = height; if (m_DBService == null) { Mef.Compose(this); } References = m_VolumeService.GetAllReferences(); CitationReferences = CreateCitationReferenceList(References, m_VolumeService.Citations); listBox1.DrawItem += ListBox1_DrawItem; listBox1.MeasureItem += ListBox1_MeasureItem; listBox1.DataSource = CitationReferencesFiltered; CitationReference sel = CitationReferences.SingleOrDefault(x => x.Citation?.Id == currentCitation); if (sel != null) { listBox1.SelectedItem = sel; } }
public StorageService() { if (m_DBService == null) { Mef.Initialize(this); } }
public void VsTextViewCreated(IVsTextView textViewAdapter) { var textView = EditorAdaptersFactoryService.GetWpfTextView(textViewAdapter); var contentType = textView.TextBuffer.ContentType; ITextDocument document; if (!TextDocumentFactoryService.TryGetTextDocument(textView.TextDataModel.DocumentBuffer, out document)) { return; } var settings = WESettings.Instance.ForContentType <IChainableCompilerSettings>(contentType); var notifierProvider = Mef.GetImport <ICompilationNotifierProvider>(contentType); if (notifierProvider == null) { return; } var notifier = notifierProvider.GetCompilationNotifier(document); var compilerProvider = Mef.GetImport <ICompilerRunnerProvider>(contentType); if (compilerProvider == null) { return; } var compilerRunner = compilerProvider.GetCompiler(contentType); var graph = GetGraph(contentType); notifier.CompilationReady += async(s, e) => { if (!e.CompilerResult.IsSuccess) { return; } if (!settings.CompileOnSave || !settings.EnableChainCompilation || (bool)s) { return; } var count = 0; foreach (var file in await graph.GetRecursiveDependentsAsync(e.CompilerResult.SourceFileName)) { if (File.Exists(compilerRunner.GetTargetPath(file))) { compilerRunner.CompileToDefaultOutputAsync(file).DoNotWait("compiling " + file); count++; } } WebEssentialsPackage.DTE.StatusBar.Text = "Compiling " + count + " dependent file" + (count == 1 ? "s" : "") + " for " + Path.GetFileName(e.CompilerResult.SourceFileName); }; }
private string FindFile(IEnumerable <string> extensions, out int position) { ICssParser parser = CssParserLocator.FindComponent(Mef.GetContentType(LessContentTypeDefinition.LessContentType)).CreateParser(); string root = ProjectHelpers.GetProjectFolder(TextView.TextBuffer.GetFileName()); position = -1; string result = null; foreach (string ext in extensions) { foreach (string file in Directory.GetFiles(root, "*" + ext, SearchOption.AllDirectories)) { if (file.EndsWith(".min" + ext, StringComparison.OrdinalIgnoreCase)) { continue; } string text = File.ReadAllText(file); int index = text.IndexOf("." + _className, StringComparison.Ordinal); if (index > -1) { var css = parser.Parse(text, true); var visitor = new CssItemCollector <ClassSelector>(false); css.Accept(visitor); var selectors = visitor.Items.Where(c => c.ClassName.Text == _className); var high = selectors.FirstOrDefault(c => c.FindType <AtDirective>() == null && (c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ",")); if (high != null) { position = high.Start; return(file); } var medium = selectors.FirstOrDefault(c => c.Parent.NextSibling == null || c.Parent.NextSibling.Text == ","); if (medium != null) { position = medium.Start; result = file; continue; } var low = selectors.FirstOrDefault(); if (low != null) { position = low.Start; result = file; continue; } } } } return(result); }
private void AddHtmlFiles() { var paths = ProjectHelpers.GetSelectedItemPaths(_dte); var contentType = ContentTypeManager.GetContentType("Markdown"); var compiler = Mef.GetImport <ICompilerRunnerProvider>(contentType).GetCompiler(contentType); Parallel.ForEach(paths, f => compiler.CompileToDefaultOutputAsync(f).DoNotWait("compiling " + f)); }
private void PopulateLanguageBuffer(IContentType contentType, IEnumerable <CodeLineArtifact> artifacts) { var pBuffer = ProjectionBufferManager.GetProjectionBuffer(contentType); var embedder = Mef.GetImport <ICodeLanguageEmbedder>(contentType); var fullSource = new StringBuilder(); if (embedder != null) { fullSource.AppendLine(embedder.GlobalPrefix); } var mappings = new List <ProjectionMapping>(); foreach (var block in artifacts.GroupBy(a => a.BlockInfo)) { IReadOnlyCollection <string> surround = null; if (embedder != null) { surround = embedder.GetBlockWrapper(block.Select(a => a.GetText(EditorTree.TextSnapshot))); } if (surround != null) { fullSource.AppendLine(surround.FirstOrDefault()); } foreach (var artifact in block) { if (artifact.Start >= EditorTree.TextSnapshot.Length || artifact.End > EditorTree.TextSnapshot.Length || artifact.TreatAs != ArtifactTreatAs.Code) { continue; } mappings.Add(new ProjectionMapping(artifact.InnerRange.Start, fullSource.Length, artifact.InnerRange.Length, AdditionalContentInclusion.All)); fullSource.AppendLine(artifact.GetText(EditorTree.TextSnapshot)); } if (surround != null) { fullSource.AppendLine(surround.LastOrDefault()); } } if (embedder != null) { fullSource.AppendLine(embedder.GlobalSuffix); } pBuffer.SetTextAndMappings(fullSource.ToString(), mappings.ToArray()); if (createdContentTypes.Add(contentType)) { if (embedder != null) { embedder.OnBlockCreated(EditorTree.TextBuffer, pBuffer); } } }
public MainService() { if (m_DBService == null) { Mef.Initialize(this, new List <Type> { GetType(), typeof(StorageRepo) }); } }
protected CompilerRunnerBase(IContentType contentType) { Mef.SatisfyImportsOnce(this); SourceContentType = contentType; TargetContentType = FileExtensionRegistry.GetContentTypeForExtension(TargetExtension.TrimEnd('.')); _listeners = Mef.GetAllImports <IFileSaveListener>(TargetContentType); Settings = WESettings.Instance.ForContentType <ICompilerInvocationSettings>(contentType); }
private void RunRtlCss() { foreach (string file in files) { new NodeCompilerRunner(Mef.GetContentType("CSS")) .CompileAsync(file, GetTargetPath(file)) .DoNotWait("generating RTL variant of " + file); } }
public MarkdownMenu(DTE2 dte, OleMenuCommandService mcs) { Mef.SatisfyImportsOnce(this); _contentType = ContentTypes.GetContentType("Markdown"); _extensions = FileExtensionRegistry.GetFileExtensionSet(_contentType); _dte = dte; _mcs = mcs; }
private void RunJson2Cson() { foreach (string file in jsonFiles) { new NodeCompilerRunner(Mef.GetContentType(CsonContentTypeDefinition.CsonContentType)) .CompileAsync(file, GetTargetPath(file)) .DoNotWait("generating CSON from " + file); } }
public StorageService() { if (m_DBService == null) { Mef.Initialize(this, new List <Type> { typeof(StorageRepo), typeof(MessageboxService) }); } }
private async static Task MinifyFile(IContentType contentType, string sourcePath, string minPath, IMinifierSettings settings, bool compilerNeedsSourceMap = true) { IFileMinifier minifier = Mef.GetImport <IFileMinifier>(contentType); bool changed = await minifier.MinifyFile(sourcePath, minPath, compilerNeedsSourceMap); if (settings.GzipMinifiedFiles && (changed || !File.Exists(minPath + ".gzip"))) { FileHelpers.GzipFile(minPath); } }
private static void MinifyFile(IContentType contentType, string sourcePath, string minPath, IMinifierSettings settings) { IFileMinifier minifier = Mef.GetImport <IFileMinifier>(contentType); bool changed = minifier.MinifyFile(sourcePath, minPath); if (settings.GzipMinifiedFiles && (changed || !File.Exists(minPath + ".gzip"))) { FileHelpers.GzipFile(minPath); } }
public FormVolume() { InitializeComponent(); if (m_DBService == null) { Mef.Initialize(this, new List <Type> { GetType(), typeof(ModelsForViewing) }); } }
public void SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection <ITextBuffer> subjectBuffers) { ITextDocument document; if (TextDocumentFactoryService.TryGetTextDocument(textView.TextDataModel.DocumentBuffer, out document)) { textView.Properties.GetOrCreateSingletonProperty("HandlebarsCompilationNotifier", () => Mef.GetImport <ICompilationNotifierProvider>(ContentTypeManager.GetContentType("Handlebars")) .GetCompilationNotifier(document)); } }
public FormAuthors() { if (m_DBService == null) { Mef.Compose(this); } InitializeComponent(); LoadAuthors(); }
public ReferenceService() { if (m_DBService == null) { Mef.Initialize(this, new List <Type> { GetType(), typeof(HistoryRepo) }); } LastHistory = m_HistoryRepo.GetLastOpened(); // Our currently open file in Sumatra }
public TypeScriptCompilationNotifier(ITextDocument doc) { Document = doc; Document.FileActionOccurred += Document_FileActionOccurred; _listeners = Mef.GetAllImports <IFileSaveListener>(ContentTypeManager.GetContentType("JavaScript")); _watcher = new FileSystemWatcher(Path.GetDirectoryName(TargetFilePath)); _watcher.Filter = Path.GetFileName(TargetFilePath); _watcher.EnableRaisingEvents = true; _watcher.Created += FileTouched; _watcher.Changed += FileTouched; }
public HandlebarsMenu(DTE2 dte, OleMenuCommandService mcs) { Mef.SatisfyImportsOnce(this); _contentType = ContentTypes.GetContentType("Handlebars"); if (_contentType != null) { _extensions = FileExtensionRegistry.GetFileExtensionSet(_contentType); } _dte = dte; _mcs = mcs; }
public void InitCacheWithMefAndJsonConfigFile() { //Arrange var expiration = new TimeSpan(0, 0, 5); //setup dedicated JSON configuration SetupJsonConfigFile(expiration); //Act: resolve ICache with configuration loading from dedicated JSON config file var cacheMgr = Mef.Resolve <ICache>(); //Assert Assert.IsNotNull(cacheMgr); ValidateNonPublicStaticFieldValue(typeof(CacheManager), "Expiration", expiration); }
public Form_ReportCategory(Id citationId, int X, int Y) { CitationId = citationId; InitializeComponent(); StartPosition = FormStartPosition.Manual; Top = Y; Left = X; categoryUserControl1.CurrentCitationId = citationId; if (m_CategoryService == null) { Mef.Compose(this); } }
public void InitMefWithInstanceCtorWithParametersAfterStaticCtorInitFromConfigFile() { //Arrange var assembliesPath = "/abc4"; var csvSearchPatterns = "pat4.*"; //Act - try resolve some contract, but only to invoke static CTOR to read from config file values other than what is above try { Mef.Resolve <IComparable>(); //will fail } catch { } new Mef(assembliesPath, csvSearchPatterns); //init with params that override what the static ctor set above //Assert ValidateMefConfiguration(assembliesPath, csvSearchPatterns); }
public FormSeries(Id volumeId) { if (m_SeriesService == null) { Mef.Compose(this); } InitializeComponent(); m_Series = m_SeriesService.GetAllSeries(); listBox1.DataSource = m_Series; Series series = m_SeriesService.GetSeriesForVolume(volumeId); SelectSeries(series); }
private DependencyGraph GetGraph(IContentType contentType) { var graph = (VsDependencyGraph)Mef.GetImport <DependencyGraph>(contentType); if (!registeredContentTypes.Add(contentType)) { return(graph); } // Add this event handler only once per ContentType var settings = WESettings.Instance.ForContentType <IChainableCompilerSettings>(contentType); graph.IsEnabled = settings.EnableChainCompilation; settings.EnableChainCompilationChanged += delegate { graph.IsEnabled = settings.EnableChainCompilation; }; return(graph); }
public void TestLogLevels3() { //Arrange (use the XML AppSettings to init the logging framework var header = "TestLogLevels3"; var logFilePath = $"{LogFolder}/Some.LogFile3.log"; var log4netConfigFile = "xyzLog4net.config"; var runOnSeparateThread = false; //to avoid delay in logging File.WriteAllText(log4netConfigFile, ExistingLog4NetConfigText.Replace(log4netConfiguredLogFilePath, logFilePath)); //will be restored in test cleanup SetupJsonConfigFile(header, log4netConfigFile, runOnSeparateThread); if (File.Exists(settingsFile)) //delete the JSON appsettings file as well, to force fallback on XML app.config { File.Delete(settingsFile); } string pattern(string txt) => $".*{txt.Replace(" ", "\\s")}"; //Act - 1 var logMgr = Mef.Resolve <ILogManager>(); //Assert - 1 ExecuteAssertions(header, runOnSeparateThread, log4netConfigFile, logFilePath); //as specified in app.config of this project //Act - 2 var logger = logMgr.GetLogger <MefConfigTests>(); logger.Info($"log file: {logFilePath}"); //Assert = 2 ValidateLogEntry(logFilePath, pattern(logFilePath), new[] { LogLevel.Info }); //Act - 3 logger = logMgr.GetLogger(typeof(GeneralConfigTests)); logger.Warn("abc"); //Assert - 3 ValidateLogEntry(logFilePath, pattern("abc"), new[] { LogLevel.Warn }); if (File.Exists(log4netConfigFile)) { File.Delete(log4netConfigFile); } }