Best Vstest code snippet using Microsoft.TestPlatform.Extensions.EventLogCollector.EventLogDataCollector.ConfigureEventSources
EventLogDataCollector.cs
Source:EventLogDataCollector.cs  
...185            // Load the configuration186            CollectorNameValueConfigurationManager nameValueSettings =187                new CollectorNameValueConfigurationManager(configurationElement);188            // Apply the configuration189            this.ConfigureEventSources(nameValueSettings);190            this.ConfigureEntryTypes(nameValueSettings);191            this.ConfigureMaxEntries(nameValueSettings);192            this.ConfigureEventLogNames(nameValueSettings);193            // Register for events194            events.SessionStart += this.sessionStartEventHandler;195            events.SessionEnd += this.sessionEndEventHandler;196            events.TestCaseStart += this.testCaseStartEventHandler;197            events.TestCaseEnd += this.testCaseEndEventHandler;198        }199        #endregion200        #region Internal201        /// <summary>202        /// The write event logs.203        /// </summary>204        /// <param name="eventLogEntries">205        /// The event log entries.206        /// </param>207        /// <param name="maxLogEntries">208        /// Max Log Entries.209        /// </param>210        /// <param name="dataCollectionContext">211        /// The data collection context.212        /// </param>213        /// <param name="requestedDuration">214        /// The requested duration.215        /// </param>216        /// <param name="timeRequestReceived">217        /// The time request received.218        /// </param>219        /// <returns>220        /// The <see cref="string"/>.221        /// </returns>222        internal string WriteEventLogs(List<EventLogEntry> eventLogEntries, int maxLogEntries, DataCollectionContext dataCollectionContext, TimeSpan requestedDuration, DateTime timeRequestReceived)223        {224            // Generate a unique but friendly Directory name in the temp directory225            string eventLogDirName = string.Format(226                CultureInfo.InvariantCulture,227                "{0}-{1}-{2:yyyy}{2:MM}{2:dd}-{2:HH}{2:mm}{2:ss}.{2:fff}",228                "Event Log",229                Environment.MachineName,230                DateTime.Now);231            string eventLogDirPath = Path.Combine(Path.GetTempPath(), eventLogDirName);232            // Create the directory233            this.fileHelper.CreateDirectory(eventLogDirPath);234            string eventLogBasePath = Path.Combine(eventLogDirPath, EventLogFileName);235            bool unusedFilenameFound = false;236            string eventLogPath = eventLogBasePath + ".xml";237            if (this.fileHelper.Exists(eventLogPath))238            {239                for (int i = 1; !unusedFilenameFound; i++)240                {241                    eventLogPath = eventLogBasePath + "-" + i.ToString(CultureInfo.InvariantCulture) + ".xml";242                    if (!this.fileHelper.Exists(eventLogPath))243                    {244                        unusedFilenameFound = true;245                    }246                }247            }248            DateTime minDate = DateTime.MinValue;249            // Limit entries to a certain time range if requested250            if (requestedDuration < TimeSpan.MaxValue)251            {252                try253                {254                    minDate = timeRequestReceived - requestedDuration;255                }256                catch (ArgumentOutOfRangeException)257                {258                    minDate = DateTime.MinValue;259                }260            }261            Stopwatch stopwatch = new Stopwatch();262            stopwatch.Start();263            EventLogXmlWriter.WriteEventLogEntriesToXmlFile(264                eventLogPath,265                eventLogEntries.Where(266                    entry => entry.TimeGenerated > minDate && entry.TimeGenerated < DateTime.MaxValue).OrderBy(x => x.TimeGenerated).ToList().Take(maxLogEntries).ToList(),267                this.fileHelper);268            stopwatch.Stop();269            if (EqtTrace.IsVerboseEnabled)270            {271                EqtTrace.Verbose(272                    string.Format(273                        CultureInfo.InvariantCulture,274                        "EventLogDataContainer: Wrote {0} event log entries to file '{1}' in {2} seconds",275                        eventLogEntries.Count,276                        eventLogPath,277                        stopwatch.Elapsed.TotalSeconds.ToString(CultureInfo.InvariantCulture)));278            }279            // Write the event log file280            FileTransferInformation fileTransferInformation =281                new FileTransferInformation(dataCollectionContext, eventLogPath, true, this.fileHelper);282            this.dataSink.SendFileAsync(fileTransferInformation);283            if (EqtTrace.IsVerboseEnabled)284            {285                EqtTrace.Verbose(286                    "EventLogDataContainer: Event log successfully sent for data collection context '{0}'.",287                    dataCollectionContext.ToString());288            }289            return eventLogPath;290        }291        #endregion292        #region IDisposable Members293        /// <summary>294        /// Cleans up resources allocated by the data collector295        /// </summary>296        /// <param name="disposing">Not used since this class does not have a finaliser.</param>297        protected override void Dispose(bool disposing)298        {299            // Unregister events300            this.events.SessionStart -= this.sessionStartEventHandler;301            this.events.SessionEnd -= this.sessionEndEventHandler;302            this.events.TestCaseStart -= this.testCaseStartEventHandler;303            this.events.TestCaseEnd -= this.testCaseEndEventHandler;304            // Unregister EventLogEntry Written.305            foreach (var eventLogContainer in this.eventLogContainerMap.Values)306            {307                eventLogContainer.Dispose();308            }309            // Delete all the temp event log directories310            this.RemoveTempEventLogDirs(this.eventLogDirectories);311            GC.SuppressFinalize(this);312        }313        #endregion314        private static ISet<string> ParseCommaSeparatedList(string commaSeparatedList)315        {316            ISet<string> strings = new HashSet<string>();317            string[] items = commaSeparatedList.Split(new char[] { ',' });318            foreach (string item in items)319            {320                strings.Add(item.Trim());321            }322            return strings;323        }324        #region Event Handlers325        private void OnSessionStart(object sender, SessionStartEventArgs e)326        {327            ValidateArg.NotNull(e, "SessionStartEventArgs");328            ValidateArg.NotNull(e.Context, "SessionStartEventArgs.Context");329            if (EqtTrace.IsVerboseEnabled)330            {331                EqtTrace.Verbose("EventLogDataCollector: SessionStart received");332            }333            this.StartCollectionForContext(e.Context, true);334        }335        private void OnSessionEnd(object sender, SessionEndEventArgs e)336        {337            ValidateArg.NotNull(e, "SessionEndEventArgs");338            ValidateArg.NotNull(e.Context, "SessionEndEventArgs.Context");339            if (EqtTrace.IsVerboseEnabled)340            {341                EqtTrace.Verbose("EventLogDataCollector: SessionEnd received");342            }343            this.WriteCollectedEventLogEntries(e.Context, true, TimeSpan.MaxValue, DateTime.Now);344        }345        private void OnTestCaseStart(object sender, TestCaseStartEventArgs e)346        {347            ValidateArg.NotNull(e, "TestCaseStartEventArgs");348            ValidateArg.NotNull(e.Context, "TestCaseStartEventArgs.Context");349            if (!e.Context.HasTestCase)350            {351                Debug.Fail("Context is not for a test case");352                throw new ArgumentNullException("TestCaseStartEventArgs.Context.HasTestCase");353            }354            if (EqtTrace.IsVerboseEnabled)355            {356                EqtTrace.Verbose("EventLogDataCollector: TestCaseStart received for test '{0}'.", e.TestCaseName);357            }358            this.StartCollectionForContext(e.Context, false);359        }360        private void OnTestCaseEnd(object sender, TestCaseEndEventArgs e)361        {362            ValidateArg.NotNull(e, "TestCaseEndEventArgs");363            Debug.Assert(e.Context != null, "Context is null");364            Debug.Assert(e.Context.HasTestCase, "Context is not for a test case");365            if (EqtTrace.IsVerboseEnabled)366            {367                EqtTrace.Verbose(368                    "EventLogDataCollector: TestCaseEnd received for test '{0}' with Test Outcome: {1}.",369                    e.TestCaseName,370                    e.TestOutcome);371            }372            this.WriteCollectedEventLogEntries(e.Context, false, TimeSpan.MaxValue, DateTime.Now);373        }374        #endregion375        #region Private methods376        private void RemoveTempEventLogDirs(List<string> tempDirs)377        {378            if (tempDirs != null)379            {380                foreach (string dir in tempDirs)381                {382                    // Delete only if the directory is empty383                    this.fileHelper.DeleteEmptyDirectroy(dir);384                }385            }386        }387        private void StartCollectionForContext(DataCollectionContext dataCollectionContext, bool isSessionContext)388        {389            EventLogSessionContext eventLogSessionContext = null;390            lock (this.ContextMap)391            {392                eventLogSessionContext =393                    new EventLogSessionContext(this.eventLogContainerMap);394                this.ContextMap.Add(dataCollectionContext, eventLogSessionContext);395            }396        }397        private void WriteCollectedEventLogEntries(398            DataCollectionContext dataCollectionContext,399            bool isSessionEnd,400            TimeSpan requestedDuration,401            DateTime timeRequestReceived)402        {403            var context = this.GetEventLogSessionContext(dataCollectionContext);404            context.CreateEventLogContainerEndIndexMap();405            List<EventLogEntry> eventLogEntries = new List<EventLogEntry>();406            foreach (KeyValuePair<string, IEventLogContainer> kvp in this.eventLogContainerMap)407            {408                try409                {410                    if (isSessionEnd)411                    {412                        kvp.Value.EventLog.EnableRaisingEvents = false;413                    }414                    for (int i = context.EventLogContainerStartIndexMap[kvp.Key]; i <= context.EventLogContainerEndIndexMap[kvp.Key]; i++)415                    {416                        eventLogEntries.Add(kvp.Value.EventLogEntries[i]);417                    }418                }419                catch (Exception e)420                {421                    this.logger.LogWarning(422                        dataCollectionContext,423                        string.Format(424                            CultureInfo.InvariantCulture,425                            Resource.CleanupException,426                            kvp.Value.EventLog,427                            e.ToString()));428                }429            }430            var fileName = this.WriteEventLogs(eventLogEntries, isSessionEnd ? int.MaxValue : this.maxEntries, dataCollectionContext, requestedDuration, timeRequestReceived);431            // Add the directory to the list432            this.eventLogDirectories.Add(Path.GetDirectoryName(fileName));433            lock (this.ContextMap)434            {435                this.ContextMap.Remove(dataCollectionContext);436            }437        }438        private void ConfigureEventLogNames(CollectorNameValueConfigurationManager collectorNameValueConfigurationManager)439        {440            this.eventLogNames = new HashSet<string>();441            string eventLogs = collectorNameValueConfigurationManager[EventLogConstants.SettingEventLogs];442            if (eventLogs != null)443            {444                this.eventLogNames = ParseCommaSeparatedList(eventLogs);445                if (EqtTrace.IsVerboseEnabled)446                {447                    EqtTrace.Verbose(448                        "EventLogDataCollector configuration: " + EventLogConstants.SettingEventLogs + "=" + eventLogs);449                }450            }451            else452            {453                // Default to collecting these standard logs454                this.eventLogNames.Add("System");455                this.eventLogNames.Add("Security");456                this.eventLogNames.Add("Application");457            }458            foreach (string eventLogName in this.eventLogNames)459            {460                try461                {462                    // Create an EventLog object and add it to the eventLogContext if one does not already exist463                    if (!this.eventLogContainerMap.ContainsKey(eventLogName))464                    {465                        IEventLogContainer eventLogContainer = new EventLogContainer(466                            eventLogName,467                            this.eventSources,468                            this.entryTypes,469                            int.MaxValue,470                            this.logger,471                            this.dataCollectorContext);472                        this.eventLogContainerMap.Add(eventLogName, eventLogContainer);473                    }474                    if (EqtTrace.IsVerboseEnabled)475                    {476                        EqtTrace.Verbose(string.Format(477                            CultureInfo.InvariantCulture,478                            "EventLogDataCollector: Created EventSource '{0}'",479                            eventLogName));480                    }481                }482                catch (Exception ex)483                {484                    this.logger.LogError(485                        null,486                        new EventLogCollectorException(string.Format(CultureInfo.InvariantCulture, Resource.ReadError, eventLogName, Environment.MachineName), ex));487                }488            }489        }490        private void ConfigureEventSources(CollectorNameValueConfigurationManager collectorNameValueConfigurationManager)491        {492            string eventSourcesStr = collectorNameValueConfigurationManager[EventLogConstants.SettingEventSources];493            if (!string.IsNullOrEmpty(eventSourcesStr))494            {495                this.eventSources = ParseCommaSeparatedList(eventSourcesStr);496                if (EqtTrace.IsVerboseEnabled)497                {498                    EqtTrace.Verbose(499                        "EventLogDataCollector configuration: " + EventLogConstants.SettingEventSources + "="500                        + this.eventSources);501                }502            }503        }504        private void ConfigureEntryTypes(CollectorNameValueConfigurationManager collectorNameValueConfigurationManager)...ConfigureEventSources
Using AI Code Generation
1using Microsoft.TestPlatform.Extensions.EventLogCollector;2using System;3using System.Collections.Generic;4using System.Linq;5using System.Text;6using System.Threading.Tasks;7{8    {9        static void Main(string[] args)10        {11            EventLogDataCollector eventLogDataCollector = new EventLogDataCollector();12            Dictionary<string, string> parameters = new Dictionary<string, string>();13            parameters.Add("EventLogName", "Application");14            parameters.Add("EventLogLevel", "Error");15            parameters.Add("EventLogProviderName", "Microsoft-Windows-AppLocker/EXE and DLL");16            eventLogDataCollector.ConfigureEventSources(parameters);17        }18    }19}20using Microsoft.TestPlatform.Extensions.EventLogCollector;21using System;22using System.Collections.Generic;23using System.Linq;24using System.Text;25using System.Threading.Tasks;26{27    {28        static void Main(string[] args)29        {30            EventLogDataCollector eventLogDataCollector = new EventLogDataCollector();31            Dictionary<string, string> parameters = new Dictionary<string, string>();32            parameters.Add("EventLogName", "Application");33            parameters.Add("EventLogLevel", "Error");34            parameters.Add("EventLogProviderName", "Microsoft-Windows-AppLocker/EXE and DLL");35            eventLogDataCollector.ConfigureEventSources(parameters);36        }37    }38}ConfigureEventSources
Using AI Code Generation
1using Microsoft.TestPlatform.Extensions.EventLogCollector;2using System;3using System.Collections.Generic;4using System.Diagnostics;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8{9    {10        static void Main(string[] args)11        {12            var dataCollector = new EventLogDataCollector();13            var dict = new Dictionary<string, string>();14            dict.Add("EventLogName", "Application");15            dict.Add("EventLogSource", "Application");16            dict.Add("EventLogLevel", "Error");17            dataCollector.ConfigureEventSources(dict);18        }19    }20}21using Microsoft.TestPlatform.Extensions.EventLogCollector;22using System;23using System.Collections.Generic;24using System.Diagnostics;25using System.Linq;26using System.Threading.Tasks;27{28    {29        static void Main(string[] args)30        {31            var dataCollector = new EventLogDataCollector();32            var dict = new Dictionary<string, string>();33            dict.Add("EventLogName", "Application");34            dict.Add("EventLogSource", "Application");35            dict.Add("EventLogLevel", "Error");36            dataCollector.ConfigureEventSources(dict);37            dataCollector.EnableCollection();38            dataCollector.DisableCollection();39        }40    }41}42using Microsoft.TestPlatform.Extensions.EventLogCollector;43using System;44using System.Collections.Generic;45using System.Diagnostics;46using System.Linq;47using System.Threading.Tasks;48{49    {50        static void Main(string[] args)51        {52            var dataCollector = new EventLogDataCollector();53            var dict = new Dictionary<string, string>();54            dict.Add("EventLogName", "Application");55            dict.Add("EventLogSource", "Application");56            dict.Add("EventLogLevel", "Error");57            dataCollector.ConfigureEventSources(dict);58            dataCollector.EnableCollection();59            dataCollector.DisableCollection();60            dataCollector.GetParameters();61        }62    }63}64using Microsoft.TestPlatform.Extensions.EventLogCollector;65using System;ConfigureEventSources
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Microsoft.TestPlatform.Extensions.EventLogCollector;7using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection;8{9    [DataCollectorFriendlyName("EventLogCollector")]10    {11        public void Initialize(TestPlatformDataCollectionEvents events, Dictionary<string, string> environmentVariables)12        {13            var config = new EventLogCollectorConfiguration();14            config.ConfigureEventSources(new List<EventLogCollectorConfiguration.EventLogConfiguration>15            {16                {17                }18            });19            events.SessionStart += (sender, args) =>20            {21            };22        }23    }24}25using System;26using System.Collections.Generic;27using System.Linq;28using System.Text;29using System.Threading.Tasks;30using Microsoft.TestPlatform.Extensions.EventLogCollector;31using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection;32{33    [DataCollectorFriendlyName("EventLogCollector")]34    {35        public void Initialize(TestPlatformDataCollectionEvents events, Dictionary<string, string> environmentVariables)36        {37            var config = new EventLogCollectorConfiguration();38            config.ConfigureEventSources(new List<EventLogCollectorConfiguration.EventLogConfiguration>39            {40                {41                }42            });43            events.SessionStart += (sender, args) =>44            {45            };46        }47    }48}49using System;50using System.Collections.Generic;51using System.Linq;52using System.Text;ConfigureEventSources
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Microsoft.TestPlatform.Extensions.EventLogCollector;7{8    {9        static void Main(string[] args)10        {11            EventLogDataCollector eventLogDataCollector = new EventLogDataCollector();12            Dictionary<string, string> eventSources = new Dictionary<string, string>();13            eventSources.Add("Application", "Application");14            eventSources.Add("System", "System");15            eventLogDataCollector.ConfigureEventSources(eventSources);16        }17    }18}19using System;20using System.Collections.Generic;21using System.Linq;22using System.Text;23using System.Threading.Tasks;24using Microsoft.TestPlatform.Extensions.EventLogCollector;25{26    {27        static void Main(string[] args)28        {29            EventLogDataCollector eventLogDataCollector = new EventLogDataCollector();30            Dictionary<string, string> eventSources = new Dictionary<string, string>();31            eventSources.Add("Application", "Application");32            eventSources.Add("System", "System");33            eventLogDataCollector.ConfigureEventSources(eventSources);34        }35    }36}37using System;38using System.Collections.Generic;39using System.Linq;40using System.Text;41using System.Threading.Tasks;42using Microsoft.TestPlatform.Extensions.EventLogCollector;43{44    {45        static void Main(string[] args)46        {47            EventLogDataCollector eventLogDataCollector = new EventLogDataCollector();48            Dictionary<string, string> eventSources = new Dictionary<string, string>();49            eventSources.Add("Application", "Application");50            eventSources.Add("System", "System");51            eventLogDataCollector.ConfigureEventSources(eventSources);52        }53    }54}ConfigureEventSources
Using AI Code Generation
1using Microsoft.TestPlatform.Extensions.EventLogCollector;2using System;3using System.Collections.Generic;4using System.Linq;5using System.Text;6using System.Threading.Tasks;7{8    {9        public void ConfigureEventSources()10        {            11            EventLogDataCollector eventLogDataCollector = new EventLogDataCollector();12            eventLogDataCollector.ConfigureEventSources("Application", "System", "Security");13        }14    }15}16using Microsoft.TestPlatform.Extensions.EventLogCollector;17using System;18using System.Collections.Generic;19using System.Linq;20using System.Text;21using System.Threading.Tasks;22{23    {24        public void ConfigureEventSources()25        {26            EventLogDataCollector eventLogDataCollector = new EventLogDataCollector();27            eventLogDataCollector.ConfigureEventSources("Application", "System", "Security");28        }29    }30}31using Microsoft.TestPlatform.Extensions.EventLogCollector;32using System;33using System.Collections.Generic;34using System.Linq;35using System.Text;36using System.Threading.Tasks;37{38    {39        public void ConfigureEventSources()40        {41            EventLogDataCollector eventLogDataCollector = new EventLogDataCollector();42            eventLogDataCollector.ConfigureEventSources("Application", "System", "Security");43        }44    }45}46using Microsoft.TestPlatform.Extensions.EventLogCollector;47using System;48using System.Collections.Generic;49using System.Linq;50using System.Text;51using System.Threading.Tasks;52{53    {54        public void ConfigureEventSources()55        {56            EventLogDataCollector eventLogDataCollector = new EventLogDataCollector();57            eventLogDataCollector.ConfigureEventSources("ConfigureEventSources
Using AI Code Generation
1            EventLogDataCollector eventLogDataCollector = new EventLogDataCollector();2            Dictionary<string, string> eventSources = new Dictionary<string, string>();3            eventSources.Add("Application", "Application");4            eventSources.Add("System", "System");5            eventLogDataCollector.ConfigureEventSources(eventSources);6        }7    }8}9using System;10using System.Collections.Generic;11using System.Linq;12using System.Text;13using System.Threading.Tasks;14using Microsoft.TestPlatform.Extensions.EventLogCollector;15{16    {17        static void Main(string[] args)18        {19            EventLogDataCollector eventLogDataCollector = new EventLogDataCollector();20            Dictionary<string, string> eventSources = new Dictionary<string, string>();21            eventSources.Add("Application", "Application");22            eventSources.Add("System", "System");23            eventLogDataCollector.ConfigureEventSources(eventSources);24        }25    }26}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
