//
        // The Run method is the entry point of a background task.
        //
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            if (lc == null)
            {
                lc = new LoggingChannel("Tile", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
            }

            lc.LogMessage("Run entry");
            Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");

            PlaySound();

            //
            // Associate a cancellation handler with the background task.
            //
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            //
            // Get the deferral object from the task instance, and take a reference to the taskInstance;
            //
            //_deferral = taskInstance.GetDeferral();
            _taskInstance = taskInstance;

            //_periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1));
        }
Ejemplo n.º 2
0
        private async void Picker_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            var folderPicker = new Windows.Storage.Pickers.FolderPicker();

            folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            folderPicker.FileTypeFilter.Add("*");

            Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            if (folder != null)
            {
                log.LogMessage("Folder Picked");

                // Application now has read/write access to all contents in the picked folder
                // (including other sub-folder contents)
                Windows.Storage.AccessCache.StorageApplicationPermissions.
                FutureAccessList.AddOrReplace("PickedFolderToken", folder);

                //Show the chosen path
                this.folderTextBox.Text = folder.Path;
            }
            else
            {
                this.folderTextBox.Text = "Operation cancelled.";
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Start of the Webpage. Load all the files required for webpage presentation
        /// Bind and listen to socket
        /// </summary>
        public async void Start()
        {
            await Task.Run(() => BackupLogFile());

            headerFile = File.ReadAllText("webpages\\header.html");
            cssFile    = File.ReadAllText("webpages\\theme.css");
            bodyFile   = File.ReadAllText("webpages\\body.html");

            StreamSocketListener listener = new StreamSocketListener();
            await listener.BindServiceNameAsync(Constants.SOCKET);

            listener.ConnectionReceived += Listener_ConnectionReceived;

            if (LOG)
            {
                lc.LogMessage("Webhost started successfully");
            }

            if (writeLog)
            {
                WriteDebugInfo("Webhost started successfully");
            }

            //UDP Listener for Temperature and Intruder sensors
            LSS.Initialise();

            //Actions for Automation
            PA.Initialise();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Logs a verbose message.
        /// </summary>
        /// <param name="message">The message string to log.</param>
        public static void Log(string message)
        {
#if !NETFX_CORE
            Trace.WriteLine(message, VerboseCategory);
#else
            _channel.LogMessage(message);
#endif
        }
Ejemplo n.º 5
0
        protected override async Task <bool> OnOpeningAsync()
        {
            try
            {
                InitializeTokens();

                var serialPortsSelector = SerialDevice.GetDeviceSelector();
                var devices             = await DeviceInformation.FindAllAsync(serialPortsSelector);

                if (!devices.Any())
                {
                    throw new Exception(ExceptionMessages.NoDeviceFound);
                }

                var deviceIds = devices
                                .Where(device => device.Name.StartsWith(StmDeviceName))
                                .Select(device => device.Id)
                                .ToList();

                if (deviceIds.Count > 1)
                {
                    throw new Exception(ExceptionMessages.MultipleDevicesFound);
                }

                var firstDeviceId = deviceIds.FirstOrDefault();

                if (firstDeviceId == null)
                {
                    throw new Exception(ExceptionMessages.NoSpecificDeviceFound);
                }

                _device = await SerialDevice.FromIdAsync(firstDeviceId);

                if (_device == null)
                {
                    throw new Exception(ExceptionMessages.CouldNotConnect);
                }

                _dataReaderObject = new DataReader(_device.InputStream);

                _readTask = Task.Run(TryReadAsync, _readCancellationToken);

                return(true);
            }
            catch (Exception ex)
            {
                // TODO POP TO UI - change how this method is invoked
                _loggingChannel.LogMessage($"{ex.Message}", LoggingLevel.Error);
                return(false);
            }
        }
Ejemplo n.º 6
0
    public static void Debug(
        object data = null,
        string tag  = null,
        [CallerMemberName] string memberName    = null,
        [CallerFilePath] string sourceFilePath  = null,
        [CallerLineNumber] int sourceLineNumber = -1)
    {
        string message = FormatLogString(data, tag, memberName, sourceFilePath, sourceLineNumber);

        System.Diagnostics.Debug.WriteLine(message);
#if WINDOWS_UWP
        loggingChannel?.LogMessage(message, LoggingLevel.Verbose); // For ETW logging through UWP Device Portal. Read more at https://blogs.windows.com/buildingapps/2016/06/10/using-device-portal-to-view-debug-logs-for-uwp/#1CvyvpPD4lUTtPzc.99
#endif
    }
Ejemplo n.º 7
0
 private async void OnUnhandledErrorDetected(object sender, UnhandledErrorDetectedEventArgs e)
 {
     try
     {
         if (sender != null)
         {
             logChannel.LogMessage(sender.ToString());
         }
         e.UnhandledError.Propagate();
     }
     catch (Exception exception)
     {
         await Log(exception);
     }
 }
Ejemplo n.º 8
0
        public static void Log(string message, LoggingLevel level)
        {
            loggingChannel.LogMessage(message, level);
#if DEBUG
            Debug.WriteLine(message);
#endif
        }
        public static async void LogMessageToFile(string message, LoggingLevel level)
        {
            // Initialization
            if (fileLoggingSession == null)
            {
                fileLoggingSession = new FileLoggingSession("NewTestamentLogSession");
            }
            using (var loggingChannel = new LoggingChannel(
                       "NewTestamentLogSession",
                       new LoggingChannelOptions(new Guid("2e0582f3-d1b6-516a-00e3-9fd79ef95200")))) // Join a provider group
            {
                // The Id is generated by hashing the string "SampleProvider".
                // channel.Id == eff1e128-4903-5093-096a-bdc29b38456f
                fileLoggingSession.AddLoggingChannel(loggingChannel);
                // Log messages
                loggingChannel.LogMessage(message, level);
            }
            var file = await fileLoggingSession.CloseAndSaveToFileAsync();

            StorageFolder sampleAppDefinedLogFolder =
                await ApplicationData.Current.LocalFolder.CreateFolderAsync("Logs", CreationCollisionOption.OpenIfExists);

            string newLogFileName = "Log1-" + TimeStamp.Now() + ".etl";
            await file.MoveAsync(sampleAppDefinedLogFolder, newLogFileName);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Logs to <see cref="Constants.ETWChannelName"/> and either to <see cref="Debug.WriteLine"/> or <see cref="CustomLog"/>
        /// </summary>
        public static void Log(string message, LoggingLevel level)
        {
            /*
             *  You can collect the events generated by this method with xperf or another
             *  ETL controller tool. To collect these events in an ETL file:
             *
             *  xperf -start MySession -f MyFile.etl -on Constants.ETWGuid
             *  (call LogError())
             *  xperf -stop MySession
             *
             *  After collecting the ETL file, you can decode the trace using xperf, wpa,
             *  or tracerpt. For example, to decode MyFile.etl with tracerpt:
             *
             *  tracerpt MyFile.etl
             *  (generates dumpfile.xml)
             */

            using (var channel = new LoggingChannel(Constants.ETWChannelName, null /*default options*/, new Guid(Constants.ETWGuid)))
            {
                channel.LogMessage(message, level);
            }

            if (CustomLog != null)
            {
                CustomLog(message, level);
            }
            else
            {
                Debug.WriteLine("[" + Constants.ETWChannelName + "]    [" + level.ToString() + "]    " + message);
            }
        }
Ejemplo n.º 11
0
        /*************************
        * OutputWebPages checks whether the data coming in is "Request=Feedback" if it is then
        * only the feedback variable is sent back prefixed with "Result: ". Thus the jquery
        * in HTML webpage can look for this keyword at the begining of the text to take any
        * action.
        * If Feedback info is not requested, a webpage is constructed and sent. Note that the
        * Header and body tags are added to the webpage while the contents are read from
        * respective files. A line for providing the log is added at the end with an ID of retVal for
        * calling theme benefit. The log line provides decoded input passed by webpage
        * ***********************/
        private async void OutputWebPage(StreamSocketListenerConnectionReceivedEventArgs args, string inputString)
        {
            bAction = inputString.Contains("Action");

            //Use the next two lines for event logging
            //lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
            //lc.LogMessage(inputString.ToString());

            string data = string.IsNullOrWhiteSpace(feedBack) ? "None" : feedBack;

            try
            {
                using (IOutputStream output = args.Socket.OutputStream)
                {
                    using (Stream response = output.AsStreamForWrite())
                    {
                        if (bAction)
                        {
                            //data = "Results: " + feedBack;
                            //data = DateTime.Now.TimeOfDay.ToString();
                            byte[] fbArray = Encoding.UTF8.GetBytes(data);
                            await response.WriteAsync(fbArray, 0, fbArray.Length);

                            await response.FlushAsync();

                            //Use the next two lines for event logging
                            //lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
                            //lc.LogMessage(feedBack);
                        }
                        else
                        {
                            byte[] bodyArray = Encoding.UTF8.GetBytes(
                                $"<!DOCTYPE html>\n<html>\n<head>{headerFile}<style>{cssFile}</style>\n</head>\n<body>{bodyFile}<p>Feedback Received: <span id=\"retVal\">{data}</span></p>\n</body>\n</html>");

                            var bodyStream = new MemoryStream(bodyArray);

                            var header = "HTTP/1.1 200 OK\r\n" +
                                         $"Content-Length: {bodyStream.Length}\r\n" +
                                         "Connection: close\r\n\r\n";

                            byte[] headerArray = Encoding.UTF8.GetBytes(header);
                            await response.WriteAsync(headerArray, 0, headerArray.Length);

                            await bodyStream.CopyToAsync(response);

                            await response.FlushAsync();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception Occured: {0}", ex);
                //Uncomment next two lines for logging the exception errors
                lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
                lc.LogMessage("Exception at Output Page: " + ex);
                bMsg = false;
            }
        }
Ejemplo n.º 12
0
        public MainPage()
        {
            InitializeComponent();

            LoggingChannel lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));

            lc.LogMessage("I made a message!");
        }
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     using (var loggingChannel = new LoggingChannel("my provider", null, new Guid(loggingChannelId)))
     {
         loggingChannel.LogMessage("Back ground task started");
         if (taskInstance == null)
         {
             return;
         }
         taskDeferral = taskInstance.GetDeferral();
         LocalDataStore.CreateLocalConfigurationSettings();
         // taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
         var processor = new Processor(loggingChannel);
         processor.Process();
         Thread.Sleep(28800000);//ToDo-Temporary provision to run this service for a specified period(8 hours)..Should add Scheduler logic.
         taskDeferral.Complete();
         loggingChannel.LogMessage("Task completed at " + DateTime.UtcNow.ToString());
     }
 }
        /// <summary>
        /// IBackgroundTask starting point. Initializes logging
        /// </summary>
        /// <param name="taskInstance">IBackgroundTaskInstance object</param>
        public async Task Run()
        {
            //Create services
            _logging            = new LoggingChannel(_loggingAppName, null, _loggingAppId);
            _azureIoTHubService = new AzureIoTHubService(_loggingAppId);
            _azureIoTHubService.SetDesiredPropertyCallback(ReceiveDesiredConfiguration);
            _gpioService = new GPIOService(_loggingAppId);

            //First time configuration (runs only once)
            _logging.LogMessage("Initializing Application", LoggingLevel.Verbose);
            if (!InitApplicationInternal())
            {
                return;
            }

            //Run application (loop indefinitely)
            _logging.LogMessage("Run Application", LoggingLevel.Verbose);
            await RunApplicationInternal();
        }
Ejemplo n.º 15
0
        public async Task DeleteOutdatedLogs()
        {
            try
            {
                var logFiles = await LoggingFolder.GetFilesAsync();

                var obsoleteFiles = logFiles
                                    .Where(logFile => (DateTime.Now - logFile.DateCreated).Days > DaysToDelete);

                foreach (var logFile in obsoleteFiles)
                {
                    await logFile.DeleteAsync();
                }
            }
            catch (Exception ex)
            {
                _loggingChannel.LogMessage(ex.Message, LoggingLevel.Error);
            }
        }
Ejemplo n.º 16
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            //
            // TODO: Insert code to perform background work
            //
            // If you start any asynchronous methods here, prevent the task
            // from closing prematurely by using BackgroundTaskDeferral as
            // described in http://aka.ms/backgroundtaskdeferral
            //

            _deferral = taskInstance.GetDeferral();

            // set the security for fms
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            // hook into FMS from settings in the config file
            fmserver = GetFMSinstance();
            token    = string.Empty;

            // log into the Events Tracing for Windows ETW
            // on the Device Portal, ETW tab, pick "Microsoft-Windows-Diagnostics-LoggingChannel" from the registered providers
            // pick level 5 and enable
            lc = new LoggingChannel("BillyBassMotorTest", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
            lc.LogMessage("Starting up.");

            // determine whether we are in testing  mode
            var  resources = new ResourceLoader("Config");
            bool testing   = Convert.ToBoolean(resources.GetString("testing"));
            int  polling_interval_testing = Convert.ToInt16(resources.GetString(" polling_interval_testing"));
            int  polling_interval         = Convert.ToInt16(resources.GetString(" polling_interval"));

            lc.LogMessage("Testing = " + testing.ToString());
            if (testing == false)
            {
                // start the timer
                ThreadPoolTimer timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(polling_interval));
            }
            else
            {
                // start the timer
                ThreadPoolTimer timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromSeconds(polling_interval_testing));
            }
        }
Ejemplo n.º 17
0
        /******************************************
        * This procedure listens for messages arriving to socket 8090. This information will be
        * built to string. It will then extract the data from the received string
        * by calling GetQuery method. The data is properly dispatched to the service connection
        * established / stored by this application.
        * Finally OutputWebpage is called to provide feedback to the webclient.
        * bMsg bool is added to ensure that when multiple messages are received, the messages are discarded.
        * This is required. Without this, the Webservice crashes after some time.
        ******************************************/
        private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            if (!bMsg)
            {
                bMsg = true;
                StringBuilder request = new StringBuilder();
                try
                {
                    using (IInputStream input = args.Socket.InputStream)
                    {
                        byte[]  data     = new byte[BUFFERSIZE];
                        IBuffer buffer   = data.AsBuffer();
                        uint    dataRead = BUFFERSIZE;
                        while (dataRead == BUFFERSIZE)
                        {
                            await input.ReadAsync(buffer, BUFFERSIZE, InputStreamOptions.Partial);

                            request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                            dataRead = buffer.Length;
                        }
                    }

                    string inputString = GetQuery(request);

                    //If you are running as a background webserver serviceConnection will be null
                    //Dispatch the message to the service connection.
                    if (serviceConnection != null)
                    {
                        await serviceConnection.SendMessageAsync(new ValueSet { new KeyValuePair <string, object>("Query", inputString) });
                    }

                    OutputWebPage(args, inputString);
                }
                catch (Exception Ex)
                {
                    Debug.WriteLine("Exception occurred: {0}", Ex);
                    //Uncomment next two lines for logging the exception errors
                    lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
                    lc.LogMessage("Exception at Input String: " + Ex);
                    bMsg = false;
                }
                bMsg = false;
            }
            //Uncomment the else statement if you want to use debugging

            /*
             * else
             * {
             *  lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
             *  lc.LogMessage("Multiple messages received");
             * }
             */
        }
Ejemplo n.º 18
0
 public void Start()
 {
     if (channel != null)
     {
         channel.LogMessage(String.Format("Message={0}: Client To Server Application Started!", 1), LoggingLevel.Information);
     }
 }
Ejemplo n.º 19
0
    public static void LogError(string message)
    {
#if !UNITY_EDITOR
        portalLogger.LogMessage(message, LoggingLevel.Error);
        Debug.LogError(message);

        if (logFile == null)
        {
            logFile = File.CreateText(logPath);
        }
        logFile.WriteLineAsync("{date:\"" + DateTime.Now.ToString() + "\", message: \"" + message + "\"}");
#endif
    }
Ejemplo n.º 20
0
 private void CoreApplication_UnhandledErrorDetected(object sender, UnhandledErrorDetectedEventArgs e)
 {
     try
     {
         _logChannel.LogMessage("Caught and unhandled exception");
         e.UnhandledError.Propagate();
     }
     catch (Exception ex)
     {
         _logChannel.LogMessage($"Exception Message: {ex.Message}");
     }
 }
Ejemplo n.º 21
0
        internal async Task Init(int cameraIndex, string cameraResolution)
        {
            if (IsInitialized)
            {
                return;
            }

            _logging.LogMessage("Initializing Camera Service.", LoggingLevel.Verbose);

            // Create MediaCapture and its settings
            _mediaCapture = new MediaCapture();

            // Register for a notification when something goes wrong
            _mediaCapture.Failed += MediaCapture_Failed;

            var cameraDevice = await GetCameraDeviceByIdAsync(cameraIndex);

            if (cameraDevice == null)
            {
                _logging.LogMessage("No camera device found!", LoggingLevel.Error);
                return;
            }

            // Initialize MediaCapture
            try
            {
                var settings = new MediaCaptureInitializationSettings {
                    VideoDeviceId = cameraDevice.Id
                };
                await _mediaCapture.InitializeAsync(settings);

                StreamPropertiesModel[] supportedResolutions = GetStreamProperties();

                StreamPropertiesModel configuredResolution = supportedResolutions.FirstOrDefault(p => p.Resolution == cameraResolution);
                if (configuredResolution == null)
                {
                    configuredResolution = supportedResolutions.FirstOrDefault(p => p.Resolution == "1920x1080");
                }
                if (configuredResolution == null)
                {
                    configuredResolution = supportedResolutions.FirstOrDefault(p => p.Resolution == "1280x720");
                }
                if (configuredResolution == null)
                {
                    configuredResolution = supportedResolutions.FirstOrDefault();
                }

                await _mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, configuredResolution.EncodingProperties);

                IsInitialized = true;
            }
            catch (UnauthorizedAccessException)
            {
                _logging.LogMessage("CameraService - Init: The app was denied access to the camera", LoggingLevel.Critical);
                return;
            }
            return;
        }
Ejemplo n.º 22
0
 internal void Init(string subscriptionKey)
 {
     _logging.LogMessage("Initializing Cognitive Vision Service.", LoggingLevel.Verbose);
     if (string.IsNullOrEmpty(subscriptionKey))
     {
         _logging.LogMessage("No subscription key for CognitiveVision service found.", LoggingLevel.Error);
     }
     _subscriptionKey = subscriptionKey;
 }
Ejemplo n.º 23
0
    void Start()
    {
        lc.LogMessage("I made a message!");

        // subscribing to the Hololens API gesture recognizer to track user gestures
        recognizer = new GestureRecognizer();
        recognizer.SetRecognizableGestures(GestureSettings.Tap);
        recognizer.Tapped += TapHandler;
        recognizer.StartCapturingGestures();
    }
Ejemplo n.º 24
0
        public bool InitGPIOInput(int pinIndex, TypedEventHandler <GpioPin, GpioPinValueChangedEventArgs> callback)
        {
            try
            {
                GpioPin pin = GetPin(pinIndex);
                pin.SetDriveMode(GpioPinDriveMode.Input);
                pin.ValueChanged += callback;

                return(true);
            }
            catch (Exception e)
            {
                _logging.LogMessage($"InitGPIOInput: Error while trying to init gpio '{pinIndex}': {e.Message}", LoggingLevel.Error);
                throw e;
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        ///     Handle a log message from Untiy Debug
        /// </summary>
        /// <param name="condition">The message</param>
        /// <param name="stackTrace"></param>
        /// <param name="type">The type of message (Warning,...)</param>
        private void ApplicationOnLogMessageReceived(string condition, string stackTrace, LogType type)
        {
            LoggingLevel level;

            switch (type)
            {
            case LogType.Error:
                level = LoggingLevel.Error;
                break;

            case LogType.Assert:
                level = LoggingLevel.Critical;
                break;

            case LogType.Warning:
                level = LoggingLevel.Warning;
                break;

            case LogType.Log:
                level = LoggingLevel.Information;
                break;

            case LogType.Exception:
                level = LoggingLevel.Critical;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }

            loggingChannel.LogMessage(condition, level);
            float timeStartup = Time.realtimeSinceStartup;

            queue.Enqueue(async() => {
                ss.Wait();
                await streamWriter.WriteLineAsync($"[{DateTime.Now.ToString("hh:mm:ss", CultureInfo.CurrentCulture)},{string.Format("{0:0.00000}", timeStartup)}] {level.ToString()}: {condition}");
                if (!string.IsNullOrEmpty(stackTrace))
                {
                    await streamWriter.WriteLineAsync($"Stacktrace: {stackTrace}");
                }
                await streamWriter.FlushAsync();
                ss.Release();
            });
        }
Ejemplo n.º 26
0
        private async Task Init(SwapChainPanel swapChainPanel)
        {
            LoggingChannel = Logger.AddLoggingChannel(Name);
            var instance = new Instance(new List <string>
            {
                "-I",
                "dummy",
                "--no-osd",
                "--verbose=3",
                "--no-stats",
                "--avcodec-fast",
                "--subsdec-encoding",
                "",
                "--aout=winstore",
                $"--keystore-file={Path.Combine(ApplicationData.Current.LocalFolder.Path, KeyStoreFilename)}"
            }, swapChainPanel);

            Instance = instance;
            instance.setDialogHandlers(OnError, OnShowLoginDialog, OnShowDialog,
                                       (dialog, title, text, intermediate, position, cancel) => { },
                                       OnCancelCurrentDialog,
                                       (dialog, position, text) => { });
            instance.logSet((param0, param1) =>
            {
                var logLevel = (LogLevel)param0;
                Debug.WriteLine($"[VLC {logLevel}] {param1}");
                LoggingChannel.LogMessage(param1, logLevel.ToLoggingLevel());
            });

            await UpdateScale();

            UpdateDeinterlaceMode();

            AudioDeviceId = MediaDevice.GetDefaultAudioRenderId(AudioDeviceRole.Default);
            MediaDevice.DefaultAudioRenderDeviceChanged += (sender, e) => { if (e.Role == AudioDeviceRole.Default)
                                                                            {
                                                                                AudioDeviceId = e.Id;
                                                                            }
            };

            OnSourceChanged();
        }
Ejemplo n.º 27
0
        int pixelCounter;   // zero-based



        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //
            // TODO: Insert code to perform background work
            //
            // If you start any asynchronous methods here, prevent the task
            // from closing prematurely by using BackgroundTaskDeferral as
            // described in http://aka.ms/backgroundtaskdeferral
            //

            _deferral = taskInstance.GetDeferral();

            // set the security for fms
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            // hook into FMS from settings in the config file
            fmserver = GetFMSinstance();
            token    = string.Empty;


            // hook into the sense hat
            senseHat = await SenseHatFactory.GetSenseHat();

            // clear the LEDs
            senseHat.Display.Clear();
            senseHat.Display.Update();
            pixelCounter = 0;

            // log into the Events Tracing for Windows ETW
            // on the Device Portal, ETW tab, pick "Microsoft-Windows-Diagnostics-LoggingChannel" from the registered providers
            // pick level 5 and enable

            lc = new LoggingChannel("SenseHatFms", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
            lc.LogMessage("Starting up.");

            // start the timer
            ThreadPoolTimer timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromSeconds(2));
        }
Ejemplo n.º 28
0
        private void LogError()
        {
/*
 *          You can collect the events generated by this method with xperf or another
 *          ETL controller tool. To collect these events in an ETL file:
 *
 *          xperf -start MySession -f MyFile.etl -on 8aac9209-1e2b-5166-31b6-7c4af4bf7d27
 *          (call LogError())
 *          xperf -stop MySession
 *
 *          After collecting the ETL file, you can decode the trace using xperf, wpa,
 *          or tracerpt. For example, to decode MyFile.etl with tracerpt:
 *
 *          tracerpt MyFile.etl
 *          (generates dumpfile.xml)
 */

            using (var channel = new LoggingChannel("IoTDMBackground", null)) // null means use default options.
            {
                // Use this Id in xperf parameter
                Debug.WriteLine(channel.Id);
                channel.LogMessage("Unable to start background app", LoggingLevel.Error);
            }
        }
        /// <summary>
        /// This method demonstrates the LoggingChannel and LoggingActivity APIs.
        /// </summary>
        /// <param name="channel">
        /// The channel to use for the demonstration. This channel may have been
        /// constructed using a Windows 8.1 constructor or a Windows 10 constructor.
        /// The same APIs are supported in both cases, but the ETL events will be
        /// formatted a bit differently depending on how the channel was constructed.
        /// </param>
        private void DemonstrateLogging(LoggingChannel channel)
        {
            // Whenever any ETW session changes the way it is listening to this
            // channel, the LoggingEnable event is fired. For example, this might
            // be called when a session begins listening, changes the level at
            // which it is listening, or stops listening.
            channel.LoggingEnabled += this.OnLoggingEnabled;

            // Log simple string events
            channel.LogMessage("Simple message"); // default level is Verbose
            channel.LogMessage("Simple error", LoggingLevel.Error);

            // Log simple string + integer events.
            channel.LogValuePair("Simple message", 123); // default level is Verbose
            channel.LogValuePair("Simple error", 456, LoggingLevel.Error);

            // The channel.Name property returns the name that was used when the
            // channel was constructed. When running in Windows 10 mode, the name
            // is already set as the provider name, so no LoggingChannelName is
            // automatically added to the event.
            channel.LogMessage(channel.Name);

            // The channel.Id property is new to Windows 10.
            channel.LogMessage(channel.Id.ToString());

            // If you want to avoid the overhead of collecting data when nobody is
            // listening to your channel, check the Enabled property before logging.
            if (channel.Enabled)
            {
                channel.LogMessage(this.CollectExpensiveData());
            }

            // The IsEnabled() method is exactly the same as the Enabled property,
            // except that it is a new Windows 10 API.
            if (channel.IsEnabled())
            {
                channel.LogMessage(this.CollectExpensiveData());
            }

            // If you want to only collect data if somebody is listening at a specific
            // level, you need to check both Enabled and Level. Note that the value of
            // the Level is unspecified when Enabled is false.
            if (channel.Enabled && channel.Level <= LoggingLevel.Warning)
            {
                channel.LogMessage(this.CollectExpensiveData(), LoggingLevel.Warning);
            }

            // The IsEnabled(LoggingLevel) method is a bit nicer than checking both
            // Enabled and Level, but it is only available on Windows 10 or later.
            if (channel.IsEnabled(LoggingLevel.Warning))
            {
                channel.LogMessage(this.CollectExpensiveData(), LoggingLevel.Warning);
            }

            // You can also use IsEnabled to check for keywords.
            if (channel.IsEnabled(LoggingLevel.Information, 0x10))
            {
                channel.LogMessage(this.CollectExpensiveData(), LoggingLevel.Information);
            }

            // Use LoggingFields with the LogEvent method to write complex events.
            var fields = new LoggingFields();
            fields.AddDouble("pi", 3.14159);
            channel.LogEvent(
                "ComplexEvent",
                fields,
                LoggingLevel.Verbose,
                new LoggingOptions(0x10)); // Keywords = 0x10

            // You can add any number of name-value pairs to a fields object, though
            // you may encounter ETW limitations if you add too many. For example,
            // ETW is limited to a maximum event size of 64KB, and the current
            // TraceLogging decoder can handle no more than 128 fields.

            // Performance optimization: You can reuse a LoggingFields object to
            // avoid unnecessary allocations. Don't forget to call Clear()
            // between uses, and don't try to share a LoggingFields object between
            // threads.
            fields.Clear();
            fields.AddDateTime("Date", DateTimeOffset.Now);
            channel.LogEvent("Now", fields);

            fields.Clear();

            // You can add a formatting hint to affect the way a value is decoded.
            // Not all combinations are useful, and the hint may be ignored.
            // For example, you can encode an MBCS string by writing a byte array
            // with a String hint.
            fields.AddUInt8Array(
                "AnsiString",
                new byte[] { 65, 66, 67, 49, 50, 51 }, // "ABC123"
                LoggingFieldFormat.String);

            // You can add "tag" bits to a field. These are user-defined bits that
            // can be used to communicate with an event processing tool. For example,
            // you might define a tag bit to indicate that a field contains private
            // data that should not be displayed on-screen.
            fields.AddString("Password", "12345", LoggingFieldFormat.Default, 0x10);

            // You can add a "structure" to an event. A structure is a name for a
            // group of fields. Structures can nest. Call BeginStruct to add a level
            // of nesting, and call EndStruct after the last field of the structure.
            fields.BeginStruct("Nested");
                fields.AddInt16("Nested-1", 1);
                fields.AddInt16("Nested-2", 2);
                fields.BeginStruct("Nested-Nested");
                    fields.AddInt16("Nested-Nested-3", 3);
                fields.EndStruct();
                fields.AddInt16("Nested-4", 4);
            fields.EndStruct();

            // Advanced scenarios: you can use a LoggingOptions object to control
            // detailed event settings such as keywords, opcodes, and activity Ids.
            // These have their normal ETW semantics. You can also set event tags,
            // which are bit values that can be used to communicate with the event
            // processor.
            channel.LogEvent(
                "VeryComplexEvent",
                fields,
                LoggingLevel.Information,
                new LoggingOptions { Keywords = 0x123, Tags = 0x10 });

            // Windows 10 introduces the ILoggingTarget interface. LoggingChannel
            // implements this interface. This interface allows components to accept
            // a logger as an parameter.
            this.DoSomething(channel);

            /*
            If a LoggingActivity is created using a LoggingActivity constructor,
            it will use Windows 8.1 semantics:

            - If an activity is destroyed (garbage-collected) without being closed
              and the associated LoggingChannel is still open, the activity will
              write a default Stop event.
            - The default Stop event (written by the destructor or by the Close()
              method) is encoded as a "simple" event.

            The 8.1 semantics are deprecated because the automatic generation of
            a Stop event at garbage-collection can be misleading. The Stop event
            is intended to mark the a precise point at which an activity is
            completed, while the garbage-collection of an abandoned activity is
            inherently imprecise and unpredictable.

            If a LoggingActivity is created using a StartActivity method, it will
            use Windows 10 semantics:

            - If an activity is destroyed (garbage-collected) without being closed,
              there will be no Stop event for the activity.
            - The default Stop event (written by the Close() method) is encoded as
              a TraceLogging event with name "ActivityClosed".
            */

            // This activity is created with Windows 8.1 semantics.
            using (var a1 = new LoggingActivity("Activity1", channel))
            {
                // The activity Start event is written by the LoggingActivity constructor.
                // You would do your activity's work here.
                // The activity Stop event is written when the activity is closed (disposed).

                // The Windows 10 LoggingActivity adds new methods for writing events
                // that are marked as associated with the activity.
                a1.LogEvent("Activity event");

                // LoggingActivity also implements the ILoggingTarget interface, so you can
                // use either a channel or an activity as a logging target.
                this.DoSomething(a1);

                // The Windows 10 LoggingActivity adds new methods for creating nested activities.
                // Note that nested activities are always created with Windows 10 semantics,
                // even when nested under an activity that is using Windows 8.1 semantics.
                using (var a2 = a1.StartActivity("Activity2"))
                {
                    // Nested task occurs here.

                    // The Windows 10 LoggingActivity allows you to customize the Stop event.
                    a2.StopActivity("Activity 2 stop");
                }

                // Because a1 is using Windows 8.1 semantics, if we did not call Dispose(),
                // it would attempt to write a Stop event when it is garbage collected.
                // Writing Stop events during garbage collection is not useful, so be sure
                // to properly stop, close, or dispose activities.
            }

            // The Windows 10 StartActivity method creates a new activity, optionally with
            // specified fields and characteristics.
            // This activity is created with Windows 10 semantics.
            using (var a3 = channel.StartActivity("Activity3"))
            {
                // Because a3 is using Windows 10 semantics, if we did not call Dispose(),
                // there would be no Stop event (not even when the activity is garbage
                // collected). To get a Stop event, be sure to stop, close, or dispose the
                // activity.
            }
        }
Ejemplo n.º 30
0
    public static void Log(string message)
    {
#if !UNITY_EDITOR
        portalLogger.LogMessage(message, LoggingLevel.Information);
#endif
    }
Ejemplo n.º 31
0
        /// <summary>
        /// This method demonstrates the LoggingChannel and LoggingActivity APIs.
        /// </summary>
        /// <param name="channel">
        /// The channel to use for the demonstration. This channel may have been
        /// constructed using a Windows 8.1 constructor or a Windows 10 constructor.
        /// The same APIs are supported in both cases, but the ETL events will be
        /// formatted a bit differently depending on how the channel was constructed.
        /// </param>
        private void DemonstrateLogging(LoggingChannel channel)
        {
            // Whenever any ETW session changes the way it is listening to this
            // channel, the LoggingEnable event is fired. For example, this might
            // be called when a session begins listening, changes the level at
            // which it is listening, or stops listening.
            channel.LoggingEnabled += this.OnLoggingEnabled;

            // Log simple string events
            channel.LogMessage("Simple message"); // default level is Verbose
            channel.LogMessage("Simple error", LoggingLevel.Error);

            // Log simple string + integer events.
            channel.LogValuePair("Simple message", 123); // default level is Verbose
            channel.LogValuePair("Simple error", 456, LoggingLevel.Error);

            // The channel.Name property returns the name that was used when the
            // channel was constructed. When running in Windows 10 mode, the name
            // is already set as the provider name, so no LoggingChannelName is
            // automatically added to the event.
            channel.LogMessage(channel.Name);

            // The channel.Id property is new to Windows 10.
            channel.LogMessage(channel.Id.ToString());

            // If you want to avoid the overhead of collecting data when nobody is
            // listening to your channel, check the Enabled property before logging.
            if (channel.Enabled)
            {
                channel.LogMessage(this.CollectExpensiveData());
            }

            // The IsEnabled() method is exactly the same as the Enabled property,
            // except that it is a new Windows 10 API.
            if (channel.IsEnabled())
            {
                channel.LogMessage(this.CollectExpensiveData());
            }

            // If you want to only collect data if somebody is listening at a specific
            // level, you need to check both Enabled and Level. Note that the value of
            // the Level is unspecified when Enabled is false.
            if (channel.Enabled && channel.Level <= LoggingLevel.Warning)
            {
                channel.LogMessage(this.CollectExpensiveData(), LoggingLevel.Warning);
            }

            // The IsEnabled(LoggingLevel) method is a bit nicer than checking both
            // Enabled and Level, but it is only available on Windows 10 or later.
            if (channel.IsEnabled(LoggingLevel.Warning))
            {
                channel.LogMessage(this.CollectExpensiveData(), LoggingLevel.Warning);
            }

            // You can also use IsEnabled to check for keywords.
            if (channel.IsEnabled(LoggingLevel.Information, 0x10))
            {
                channel.LogMessage(this.CollectExpensiveData(), LoggingLevel.Information);
            }

            // Use LoggingFields with the LogEvent method to write complex events.
            var fields = new LoggingFields();

            fields.AddDouble("pi", 3.14159);
            channel.LogEvent(
                "ComplexEvent",
                fields,
                LoggingLevel.Verbose,
                new LoggingOptions(0x10)); // Keywords = 0x10

            // You can add any number of name-value pairs to a fields object, though
            // you may encounter ETW limitations if you add too many. For example,
            // ETW is limited to a maximum event size of 64KB, and the current
            // TraceLogging decoder can handle no more than 128 fields.

            // Performance optimization: You can reuse a LoggingFields object to
            // avoid unnecessary allocations. Don't forget to call Clear()
            // between uses, and don't try to share a LoggingFields object between
            // threads.
            fields.Clear();
            fields.AddDateTime("Date", DateTimeOffset.Now);
            channel.LogEvent("Now", fields);

            fields.Clear();

            // You can add a formatting hint to affect the way a value is decoded.
            // Not all combinations are useful, and the hint may be ignored.
            // For example, you can encode an MBCS string by writing a byte array
            // with a String hint.
            fields.AddUInt8Array(
                "AnsiString",
                new byte[] { 65, 66, 67, 49, 50, 51 }, // "ABC123"
                LoggingFieldFormat.String);

            // You can add "tag" bits to a field. These are user-defined bits that
            // can be used to communicate with an event processing tool. For example,
            // you might define a tag bit to indicate that a field contains private
            // data that should not be displayed on-screen.
            fields.AddString("Password", "12345", LoggingFieldFormat.Default, 0x10);

            // You can add a "structure" to an event. A structure is a name for a
            // group of fields. Structures can nest. Call BeginStruct to add a level
            // of nesting, and call EndStruct after the last field of the structure.
            fields.BeginStruct("Nested");
            fields.AddInt16("Nested-1", 1);
            fields.AddInt16("Nested-2", 2);
            fields.BeginStruct("Nested-Nested");
            fields.AddInt16("Nested-Nested-3", 3);
            fields.EndStruct();
            fields.AddInt16("Nested-4", 4);
            fields.EndStruct();

            // Advanced scenarios: you can use a LoggingOptions object to control
            // detailed event settings such as keywords, opcodes, and activity Ids.
            // These have their normal ETW semantics. You can also set event tags,
            // which are bit values that can be used to communicate with the event
            // processor.
            channel.LogEvent(
                "VeryComplexEvent",
                fields,
                LoggingLevel.Information,
                new LoggingOptions {
                Keywords = 0x123, Tags = 0x10
            });

            // Windows 10 introduces the ILoggingTarget interface. LoggingChannel
            // implements this interface. This interface allows components to accept
            // a logger as an parameter.
            this.DoSomething(channel);

            /*
             * If a LoggingActivity is created using a LoggingActivity constructor,
             * it will use Windows 8.1 semantics:
             *
             * - If an activity is destroyed (garbage-collected) without being closed
             * and the associated LoggingChannel is still open, the activity will
             * write a default Stop event.
             * - The default Stop event (written by the destructor or by the Close()
             * method) is encoded as a "simple" event.
             *
             * The 8.1 semantics are deprecated because the automatic generation of
             * a Stop event at garbage-collection can be misleading. The Stop event
             * is intended to mark the a precise point at which an activity is
             * completed, while the garbage-collection of an abandoned activity is
             * inherently imprecise and unpredictable.
             *
             * If a LoggingActivity is created using a StartActivity method, it will
             * use Windows 10 semantics:
             *
             * - If an activity is destroyed (garbage-collected) without being closed,
             * there will be no Stop event for the activity.
             * - The default Stop event (written by the Close() method) is encoded as
             * a TraceLogging event with name "ActivityClosed".
             */

            // This activity is created with Windows 8.1 semantics.
            using (var a1 = new LoggingActivity("Activity1", channel))
            {
                // The activity Start event is written by the LoggingActivity constructor.
                // You would do your activity's work here.
                // The activity Stop event is written when the activity is closed (disposed).

                // The Windows 10 LoggingActivity adds new methods for writing events
                // that are marked as associated with the activity.
                a1.LogEvent("Activity event");

                // LoggingActivity also implements the ILoggingTarget interface, so you can
                // use either a channel or an activity as a logging target.
                this.DoSomething(a1);

                // The Windows 10 LoggingActivity adds new methods for creating nested activities.
                // Note that nested activities are always created with Windows 10 semantics,
                // even when nested under an activity that is using Windows 8.1 semantics.
                using (var a2 = a1.StartActivity("Activity2"))
                {
                    // Nested task occurs here.

                    // The Windows 10 LoggingActivity allows you to customize the Stop event.
                    a2.StopActivity("Activity 2 stop");
                }

                // Because a1 is using Windows 8.1 semantics, if we did not call Dispose(),
                // it would attempt to write a Stop event when it is garbage collected.
                // Writing Stop events during garbage collection is not useful, so be sure
                // to properly stop, close, or dispose activities.
            }

            // The Windows 10 StartActivity method creates a new activity, optionally with
            // specified fields and characteristics.
            // This activity is created with Windows 10 semantics.
            using (var a3 = channel.StartActivity("Activity3"))
            {
                // Because a3 is using Windows 10 semantics, if we did not call Dispose(),
                // there would be no Stop event (not even when the activity is garbage
                // collected). To get a Stop event, be sure to stop, close, or dispose the
                // activity.
            }
        }