Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
        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();
        }
Exemplo n.º 3
0
        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; };
        }
Exemplo n.º 4
0
        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
        }
Exemplo n.º 5
0
        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;
            }
        }
Exemplo n.º 6
0
 public StorageService()
 {
     if (m_DBService == null)
     {
         Mef.Initialize(this);
     }
 }
Exemplo n.º 7
0
        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);
            };
        }
Exemplo n.º 8
0
        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);
        }
Exemplo n.º 9
0
        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);
                }
            }
        }
Exemplo n.º 11
0
 public MainService()
 {
     if (m_DBService == null)
     {
         Mef.Initialize(this, new List <Type> {
             GetType(), typeof(StorageRepo)
         });
     }
 }
Exemplo n.º 12
0
        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);
        }
Exemplo n.º 13
0
 private void RunRtlCss()
 {
     foreach (string file in files)
     {
         new NodeCompilerRunner(Mef.GetContentType("CSS"))
         .CompileAsync(file, GetTargetPath(file))
         .DoNotWait("generating RTL variant of " + file);
     }
 }
Exemplo n.º 14
0
        public MarkdownMenu(DTE2 dte, OleMenuCommandService mcs)
        {
            Mef.SatisfyImportsOnce(this);
            _contentType = ContentTypes.GetContentType("Markdown");
            _extensions  = FileExtensionRegistry.GetFileExtensionSet(_contentType);

            _dte = dte;
            _mcs = mcs;
        }
Exemplo n.º 15
0
 private void RunJson2Cson()
 {
     foreach (string file in jsonFiles)
     {
         new NodeCompilerRunner(Mef.GetContentType(CsonContentTypeDefinition.CsonContentType))
         .CompileAsync(file, GetTargetPath(file))
         .DoNotWait("generating CSON from " + file);
     }
 }
Exemplo n.º 16
0
 public StorageService()
 {
     if (m_DBService == null)
     {
         Mef.Initialize(this, new List <Type> {
             typeof(StorageRepo), typeof(MessageboxService)
         });
     }
 }
Exemplo n.º 17
0
        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);
            }
        }
Exemplo n.º 19
0
        public FormVolume()
        {
            InitializeComponent();

            if (m_DBService == null)
            {
                Mef.Initialize(this, new List <Type> {
                    GetType(), typeof(ModelsForViewing)
                });
            }
        }
Exemplo n.º 20
0
        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));
            }
        }
Exemplo n.º 21
0
        public FormAuthors()
        {
            if (m_DBService == null)
            {
                Mef.Compose(this);
            }

            InitializeComponent();

            LoadAuthors();
        }
Exemplo n.º 22
0
        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;
        }
Exemplo n.º 24
0
        public HandlebarsMenu(DTE2 dte, OleMenuCommandService mcs)
        {
            Mef.SatisfyImportsOnce(this);
            _contentType = ContentTypes.GetContentType("Handlebars");

            if (_contentType != null)
            {
                _extensions = FileExtensionRegistry.GetFileExtensionSet(_contentType);
            }

            _dte = dte;
            _mcs = mcs;
        }
Exemplo n.º 25
0
        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);
        }
Exemplo n.º 26
0
        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);
            }
        }
Exemplo n.º 27
0
        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);
        }
Exemplo n.º 28
0
        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);
        }
Exemplo n.º 29
0
        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);
        }
Exemplo n.º 30
0
        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);
            }
        }