public TResult ExecuteQuery <TSearch, TResult>(
     IQuery <TSearch, TResult> query,
     TSearch search)
 {
     _logger.Log(query.Name, search);
     return(query.Execute(search));
 }
        private async void OnScanDrives()
        {
            try
            {
                IsScanning = true;

                // Give time to show indicator to user
                await Task.Delay(2000);

                await _driveDetector.ScanAttachedDrivesAsync();
            }
            catch (Exception ex)
            {
                _logger.Log(ex.Message, Category.Exception, Priority.High);
            }
        }
Beispiel #3
0
        public override void ExtractAsWav(IApplicationLogger logger, MaterialSection.MaterialEntry entry, byte[] fullFileBytes, string wavPath)
        {
            var rawContentBytes = fullFileBytes.SubArray(entry.InnerStreamStartPosition, entry.InnerStreamSize);
            var vorbis          = Vorbis.FromMemory(rawContentBytes);


            WavWriterLoopPoint[] loopPoints = null;
            if (entry.IsLooping)
            {
                loopPoints = new[] { new WavWriterLoopPoint {
                                         StartSample = entry.LoopStart, EndSample = entry.LoopEnd
                                     } }
            }
            ;

            var wavWriter = new CustomWavWriter();

            wavWriter.WriteWav(new CustomWavWriterRequest()
            {
                WavPath         = wavPath,
                Channels        = vorbis.Channels,
                SampleRate      = vorbis.SampleRate,
                WavSampleWriter = new OggVorbisToWavSampleWriter(vorbis),
                LoopPoints      = loopPoints,
            });

            logger.Log($"Created wav audio track at: {wavPath}");
        }
        public Task <IEnumerable <string> > EnumerateDirectoriesAsync()
        {
            var directories = new List <string>();

            try
            {
                var setting = CloudConfigurationManager.GetSetting(AppSettings.StorageConnectionString);

                var account = CreateStorageAccountFromConnectionString(setting);

                var client = account.CreateCloudFileClient();

                var share = client.GetShareReference("library");

                if (share == null)
                {
                    throw new InvalidOperationException("Share not found");
                }

                var root = share.GetRootDirectoryReference();

                var library = root.GetDirectoryReference("Library");

                directories.AddRange(library.ListFilesAndDirectories().Select(item => item.Uri.LocalPath.Substring(9)));
            }
            catch (Exception ex)
            {
                _logger.Log(ex);
            }

            return(Task.FromResult(directories.AsEnumerable()));
        }
Beispiel #5
0
        public override void ExtractOriginal(IApplicationLogger logger, MaterialSection.MaterialEntry entry, byte[] fullFileBytes, string outputPath)
        {
            var rawBytes = fullFileBytes.SubArray(entry.InnerStreamStartPosition, entry.InnerStreamSize);

            var rawPath = ExtensionMethods.ChangeExtension(outputPath, FileFormat);

            File.WriteAllBytes(rawPath, rawBytes);
            logger.Log($"Created ogg audio track at: {rawPath}");
        }
Beispiel #6
0
        public bool TryGetVariableValue <TValue>(string key, out TValue value)
        {
            value = default(TValue);

            try
            {
                var result = GetVariableValue(key);
                value = ConverterHelper.Convert <TValue>(result);
            }
            catch (Exception ex)
            {
                _logger.Log(ex);

                // Use default value
                return(false);
            }

            return(true);
        }
        private async void AffirmNewConfigurationDialog(object sender, ExecutedRoutedEventArgs e)
        {
            try
            {
                var dialog = sender as CustomDialog;
                Debug.Assert(dialog != null);

                var configuration = dialog.DataContext as NewConfiguration;
                Debug.Assert(configuration != null);

                await NewConfigurationAsync(configuration);

                await _mainWindow.HideMetroDialogAsync(dialog);
            }
            catch (Exception ex)
            {
                _logger.Log(ex);
                await _messageService.ShowMessageAsync("New Product Configuration",
                                                       "Error occured creating new configuration");
            }
        }
Beispiel #8
0
        public override void ExtractOriginal(IApplicationLogger logger, MaterialSection.MaterialEntry entry, byte[] fullFileBytes, string outputPath)
        {
            var          rawContentBytes  = fullFileBytes.SubArray(entry.InnerStreamStartPosition, entry.InnerStreamSize);
            BinaryReader fullBinaryReader = new BinaryReader(new MemoryStream(fullFileBytes));
            var          encryption       = fullBinaryReader.ReadByteAt(entry.ExtraDataOffset + 0x0d);

            if (encryption == 1)
            {
                DecryptHCA(entry, rawContentBytes, fullBinaryReader);
            }
            var rawPath = ExtensionMethods.ChangeExtension(outputPath, FileFormat);

            File.WriteAllBytes(rawPath, rawContentBytes);
            logger.Log($"Created hca audio track at: {rawPath}");
        }
Beispiel #9
0
        public override void ExtractAsWav(IApplicationLogger logger, MaterialSection.MaterialEntry entry, byte[] fullFileBytes, string wavPath)
        {
            var rawContentBytes = fullFileBytes.SubArray(entry.InnerStreamStartPosition, entry.InnerStreamSize);

            AudioData    audioData        = null;
            HcaReader    reader           = new HcaReader();
            BinaryReader fullBinaryReader = new BinaryReader(new MemoryStream(fullFileBytes));
            var          encryption       = fullBinaryReader.ReadByteAt(entry.ExtraDataOffset + 0x0d);

            if (encryption == 1)
            {
                DecryptHCA(entry, rawContentBytes, fullBinaryReader);
            }
            audioData = reader.Read(rawContentBytes);
            WaveWriter writer   = new WaveWriter();
            var        wavBytes = writer.GetFile(audioData);

            File.WriteAllBytes(wavPath, wavBytes);
            logger.Log($"Created wav audio track at: {wavPath}");
        }
        //------------------------------------------------------------------------------
        //
        // Method: AttemptConnect
        //
        //------------------------------------------------------------------------------
        /// <summary>
        /// Attempts to connect to the specified IP address and port, and retries for the specified number of times if the attempt is unsuccessful.
        /// </summary>
        private void AttemptConnect()
        {
            int connectAttempt = 0;

            while (connectAttempt <= connectRetryCount)
            {
                try
                {
                    client.Connect(ipAddress, port);
                    logger.Log(this, LogLevel.Information, "Connected to " + ipAddress.ToString() + ":" + port + ".");
                    break;
                }
                catch (System.Net.Sockets.SocketException socketException)
                {
                    logger.Log(this, LogLevel.Error, "SocketException with error code " + socketException.ErrorCode + " occurred whilst trying to connect to " + ipAddress.ToString() + ":" + port + ".", socketException);
                    if (connectRetryInterval > 0)
                    {
                        Thread.Sleep(connectRetryInterval);
                    }
                }
                catch (System.Security.SecurityException securityException)
                {
                    logger.Log(this, LogLevel.Error, "SecurityException occurred whilst trying to connect to " + ipAddress.ToString() + ":" + port + ".", securityException);
                    if (connectRetryInterval > 0)
                    {
                        Thread.Sleep(connectRetryInterval);
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("Error connecting to " + ipAddress.ToString() + ":" + port + ".", e);
                }

                connectAttempt = connectAttempt + 1;
            }

            if (client.Connected == false)
            {
                throw new Exception("Failed to connect to " + ipAddress.ToString() + ":" + port + " after " + connectAttempt + " attempts.");
            }
        }
        /// <summary>
        /// Add exception, format string and additional arguments to log
        /// </summary>
        /// <param name="logger">The application logger</param>
        /// <param name="exception">The thrown exception</param>
        /// <param name="format">The format string</param>
        /// <param name="args">Additional arguments</param>
        public static void DebugFormat(this IApplicationLogger logger, Exception exception, string format, params object[] args)
        {
            Argument.NotNull(logger, nameof(logger));

            logger.Log(LogEntry(LogLevel.Debug, exception, format, args));
        }
        /// <summary>
        /// Add message and exception to the log
        /// </summary>
        /// <param name="logger">The application logger</param>
        /// <param name="exception">The thrown exception</param>
        /// <param name="message">The message string</param>
        public static void Debug(this IApplicationLogger logger, Exception exception, string message)
        {
            Argument.NotNull(logger, nameof(logger));

            logger.Log(LogEntry(LogLevel.Debug, exception, message));
        }
Beispiel #13
0
        private async Task BuildVariablesAsync()
        {
            try
            {
                ConfiguratorVariables.Clear();

                ConfiguratorVariables.Add("libraryPath");
                ConfiguratorVariables.Add("tempPath");
                ConfiguratorVariables.Add("installPath");

                var template = await _templateManager.GetTemplateAsync(_templateManager.CurrentKey);

                foreach (var option in template.Pages
                         .SelectMany(page => page.Sections)
                         .SelectMany(section => section.Options)
                         .Concat(template.Pages.SelectMany(page => page.Options)))
                {
                    if (!ConfiguratorVariables.Contains(option.Key))
                    {
                        ConfiguratorVariables.Add(option.Key);
                    }

                    if (option.Control is CheckControl)
                    {
                        var check = option.Control as CheckControl;

                        foreach (var key in check.Checked.Options
                                 .Concat(check.Unchecked.Options)
                                 .Select(opt => opt.Key))
                        {
                            if (!ConfiguratorVariables.Contains(key))
                            {
                                ConfiguratorVariables.Add(key);
                            }
                        }

                        foreach (var key in check.Checked.Tasks
                                 .Concat(check.Unchecked.Tasks)
                                 .OfType <SetVariableTask>()
                                 .Select(task => task.Key))
                        {
                            if (!ConfiguratorVariables.Contains(key))
                            {
                                ConfiguratorVariables.Add(key);
                            }
                        }
                    }
                    else if (option.Control is ComboControl)
                    {
                        var combo = option.Control as ComboControl;

                        foreach (var key in combo.Items
                                 .SelectMany(item => item.Tasks)
                                 .OfType <SetVariableTask>()
                                 .Select(task => task.Key))
                        {
                            if (!ConfiguratorVariables.Contains(key))
                            {
                                ConfiguratorVariables.Add(key);
                            }
                        }
                    }
                    else if (option.Control is ListControl)
                    {
                        var list = option.Control as ListControl;

                        foreach (var key in list.Items
                                 .SelectMany(item => item.Tasks)
                                 .OfType <SetVariableTask>()
                                 .Select(task => task.Key))
                        {
                            if (!ConfiguratorVariables.Contains(key))
                            {
                                ConfiguratorVariables.Add(key);
                            }
                        }
                    }
                    else if (option.Control is RadioControl)
                    {
                        var radio = option.Control as RadioControl;

                        foreach (var key in radio.Choices
                                 .SelectMany(choice => choice.Tasks)
                                 .OfType <SetVariableTask>()
                                 .Select(task => task.Key))
                        {
                            if (!ConfiguratorVariables.Contains(key))
                            {
                                ConfiguratorVariables.Add(key);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Log(ex);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Add format string and additional arguments to log
        /// </summary>
        /// <param name="logger">The application logger</param>
        /// <param name="format">The format string</param>
        /// <param name="args">Additional arguments</param>
        public static void InfoFormat(this IApplicationLogger logger, string format, params object[] args)
        {
            Argument.NotNull(logger, nameof(logger));

            logger.Log(LogEntry(LogLevel.Info, format, args));
        }
Beispiel #15
0
        /// <summary>
        /// Add message to the log
        /// </summary>
        /// <param name="logger">The application logger</param>
        /// <param name="message">The message string</param>
        public static void Info(this IApplicationLogger logger, string message)
        {
            Argument.NotNull(logger, nameof(logger));

            logger.Log(LogEntry(LogLevel.Info, message));
        }
Beispiel #16
0
        /// <summary>
        /// Add message and exception to the log
        /// </summary>
        /// <param name="logger">The application logger</param>
        /// <param name="level">The log level</param>
        /// <param name="exception">The thrown exception</param>
        /// <param name="message">The message string</param>
        public static void Log(this IApplicationLogger logger, LogLevel level, Exception exception, string message)
        {
            Argument.NotNull(logger, nameof(logger));

            logger.Log(LogEntry(level, exception, message, null));
        }
        /// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:MethodInvocationRemoting.IRemoteReceiver.Receive"]/*'/>
        public string Receive()
        {
            cancelRequest = false;
            CheckNotDisposed();
            CheckConnected();
            int    messageSequenceNumber = -1;
            string returnMessage         = "";

            while (cancelRequest == false)
            {
                // Check if there are any pending connections which would indicate the TcpRemoteSender has encountered an error and reconnected
                if (listener.Pending() == true)
                {
                    logger.Log(this, LogLevel.Warning, "New connection detected.  Attempting reconnect.");
                    AttemptConnect();
                    metricsUtilities.Increment(new TcpRemoteReceiverReconnected());
                }

                // Check if any data has been received from the TcpRemoteSender, and handle and retry if an exception occurs
                int availableData = 0;
                try
                {
                    availableData = client.Available;
                }
                catch (Exception e)
                {
                    availableData = HandleExceptionAndCheckAvailableData(e);
                }

                // If data has been received, attempt to read and parse it, and handle and retry if an exception occurs
                if (availableData != 0)
                {
                    metricsUtilities.Begin(new MessageReceiveTime());

                    MessageParseState parseState   = MessageParseState.StartOfMessage;
                    Queue <byte>      messageBytes = null; // Holds the bytes which form the body of the message received

                    try
                    {
                        messageBytes = SetupAndReadMessage(ref parseState, ref messageSequenceNumber);
                    }
                    catch (Exception e)
                    {
                        messageBytes = HandleExceptionAndRereadMessage(e, ref parseState, ref messageSequenceNumber);
                    }

                    // If the complete message has been read, break out of the current while loop
                    //   If the complete message was not read it would have been caused by a cancel request, or by a pending connection which is handled outside this block
                    if ((cancelRequest == false) && (parseState == MessageParseState.ReadCompleteMessage))
                    {
                        // If the sequence number of the message is the same as the last received message, then discard the message
                        //   This situation can be caused by the connection breaking before the sender received the last acknowledgment
                        if (messageSequenceNumber != lastMessageSequenceNumber)
                        {
                            lastMessageSequenceNumber = messageSequenceNumber;
                            returnMessage             = stringEncoding.GetString(messageBytes.ToArray());

                            metricsUtilities.End(new MessageReceiveTime());
                            metricsUtilities.Increment(new MessageReceived());
                            metricsUtilities.Add(new ReceivedMessageSize(returnMessage.Length));
                            loggingUtilities.LogMessageReceived(this, returnMessage);
                            break;
                        }
                        else
                        {
                            metricsUtilities.Increment(new TcpRemoteReceiverDuplicateSequenceNumber());
                            logger.Log(this, LogLevel.Warning, "Duplicate message with sequence number " + messageSequenceNumber + " received.  Message discarded.");
                            // Reset variables
                            messageSequenceNumber = -1;
                            returnMessage         = "";
                        }
                    }

                    metricsUtilities.End(new MessageReceiveTime());
                }

                waitingForRetry = true;
                if (receiveRetryInterval > 0)
                {
                    Thread.Sleep(receiveRetryInterval);
                }
                waitingForRetry = false;
            }

            return(returnMessage);
        }
 public void Log(object source, LogLevel level, string text)
 {
     logger.Log(source, level, text);
 }