public async Task Invoke(HttpContext context)
        {
            var requestBodyStream   = new MemoryStream();
            var originalRequestBody = context.Request.Body;

            await context.Request.Body.CopyToAsync(requestBodyStream);

            requestBodyStream.Seek(0, SeekOrigin.Begin);

            var url             = context.Request.GetDisplayUrl();
            var requestBodyText = await new StreamReader(requestBodyStream).ReadToEndAsync();
            var message         =
                $"REQUEST METHOD: {context.Request.Method}, REQUEST BODY: {requestBodyText}, REQUEST URL: {url}";
            var headers
                = context.Request.Headers.ToDictionary(a => a.Key, a => string.Join(";", a.Value));

            ApplicationLogger.TraceEvent(message, headers);

            requestBodyStream.Seek(0, SeekOrigin.Begin);
            context.Request.Body = requestBodyStream;

            await _next(context);

            context.Request.Body = originalRequestBody;
        }
Exemplo n.º 2
0
        public override IEnumerable <AudioCaptureDevice> ReadJson(JsonReader reader, Type objectType, [AllowNull] IEnumerable <AudioCaptureDevice> existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            var deviceCollection = new List <AudioCaptureDevice>();

            try
            {
                while (reader.TokenType != JsonToken.EndArray && reader.TokenType != JsonToken.None)
                {
                    if (reader.Value?.ToString() == "DeviceId")
                    {
                        reader.Read();

                        // DeviceId
                        var deviceId = Guid.Parse((string)reader.Value);
                        deviceCollection.Add(new AudioCaptureDevice(deviceId)
                        {
                            DeviceActive = true
                        });;
                    }
                    else
                    {
                        reader.Read();
                    }
                }

                existingValue = deviceCollection;
            }
            catch (Exception ex)
            {
                ApplicationLogger.Log(ex.Message, ex.StackTrace);
            }

            return(existingValue);
        }
Exemplo n.º 3
0
        /// <summary>
        /// this will set the highlighting rectangle upon automation element.
        /// </summary>
        /// <param name="selectedElement"></param>
        private void SetHighlightingElement(AutomationElement selectedElement)
        {
            if (selectedElement == null)
            {
                SetVisibility(false); //if we do net have selected element then hide hilightling rectangle
            }
            else
            {
                Rect rectangle = Rect.Empty;
                try
                {
                    //we will try to get bounding rectangle
                    rectangle = (Rect)selectedElement.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty, true);
                }
                catch (Exception ex)
                {
                    //if it failed then log exception
                    ApplicationLogger.LogException(ex);
                }

                if (rectangle != Rect.Empty)
                {
                    //if we have rectangle then set the highlighting rectangle
                    this.Location = new Drawing.Rectangle((int)rectangle.Left, (int)rectangle.Top, (int)rectangle.Width, (int)rectangle.Height);
                    SetToolTip(selectedElement);
                    SetVisibility(true);
                }
                else
                {
                    //if we don't then hide hilightting rectangle
                    SetVisibility(false);
                }
            }
        }
Exemplo n.º 4
0
        internal void saveCBResponse(string tranID, string msg, string code)
        {
            string save = "0";

            using (SqlConnection conn2 = new SqlConnection(DB_CONN_STRING))
            {
                try
                {
                    conn2.Open();

                    // ... Inserting the item into database
                    SqlCommand save_cb_response = new SqlCommand(DbSettingsUtilities.SAVE_CB_RESPONSE, conn2);
                    save_cb_response.Parameters.Add(new SqlParameter("respCode", code));
                    save_cb_response.Parameters.Add(new SqlParameter("respMsg", msg));
                    save_cb_response.Parameters.Add(new SqlParameter("respTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm.ss")));
                    save_cb_response.Parameters.Add(new SqlParameter("tranId", tranID));

                    if (save_cb_response.ExecuteNonQuery() == 1)
                    {
                        //transaction saved
                        save = "1";
                    }

                    conn2.Close();
                }
                catch (Exception mm)
                {
                    // ... logging application failures
                    string request_message = "Saving core banking response With Transaction ID: " + tranID + ", ERROR MESSAGE: " + mm.Message + ")";
                    ApplicationLogger.WriteToFile("{0} SYSTEM FAILURE: " + request_message);
                } // ... end of try catch
            }     // ... end of connection
        }
Exemplo n.º 5
0
        private void LaunchMainWindow()
        {
            var logger = new ApplicationLogger("YlImgV");

            logger.WriteLine("initialize");
            var container = new Container();

            container.RegisterSingleton <ILogger>(() => logger);
            container.RegisterSingleton <ConfigLoader>();
            container.RegisterSingleton <Config>(() => container.GetInstance <ConfigLoader>().LoadOrCreateConfig());
            container.RegisterSingleton <ConfigService>();
            container.RegisterSingleton <Project>();
            container.RegisterSingleton <RenbanDownLoader>();
            container.RegisterSingleton <ThumbnailService>();
            container.RegisterSingleton <IWindowService, WindowService>();
            container.RegisterSingleton <DocumentOperator>();
            container.RegisterSingleton <MainWindowVm>();

        #if DEBUG
            container.Verify();
        #endif

            var window = new MainWindow
            {
                DataContext = container.GetInstance <MainWindowVm>()
            };
            window.Show();
            window.Closed += (_, __) =>
            {
                container.Dispose();
            };
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            LoadLoggers();

            //VS needs to be opened as Administrator for EventViewer.
            var logger = new ApplicationLogger(loggers["EventViewer"]);

            logger.WriteLog("Started", LogLevel.INFO);

            try
            {
                // Cause an Exception intentionally
                int age = Int32.Parse("NotNumeric");
            }
            catch (Exception ex)
            {
                logger.WriteLog(ex.Message, LogLevel.ERROR);
                logger.WriteLog("Error was thrown previously", LogLevel.WARNING);
            }


            //Now change the log mechanism to FileLogger
            logger.Logger = loggers["File"];
            logger.WriteLog("Finished", LogLevel.INFO);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes the settings from the settings file on disk.
        /// </summary>
        /// <typeparam name="T">The data type of a simple Data Transfer Object to use during deserialization of the data contract.</typeparam>
        /// <remarks>The provided DTO type <typeparamref name="T"/> is inspected for correctness. The following are reported to the
        /// application log, and, if running a debug build, via a dialog:
        /// <list type="bullet">
        /// <item><description>This type and <typeparamref name="T"/> must have matching Data Contracts (name, namespace)</description></item>
        /// <item><description>All public properties that can be get and set, and that are not application properties, must also be marked as Data Members</description></item>
        /// <item><description>All properties in the data contract of this type must match those on <typeparamref name="T"/></description></item>
        /// <item><description>Data types of all properties in the data contracts must match</description></item>
        /// </list></remarks>
        protected void InitializeFromSettingsFile <T>() where T : new()
        {
            var dtoProperties = ValidateDataTransferObjectType <T>();

            if (File.Exists(ComponentSettingsFilePath))
            {
                try
                {
                    using (var xmlDictionaryReader = XmlDictionaryReader.CreateTextReader(FileUtilities.OpenFileStream(ComponentSettingsFilePath), new XmlDictionaryReaderQuotas()))
                    {
                        var dataContractSerializer = new DataContractSerializer(typeof(T));
                        var dtoSettingsData        = dataContractSerializer.ReadObject(xmlDictionaryReader);
                        foreach (var dtoProperty in dtoProperties)
                        {
                            var settingValue = dtoProperty.GetValue(dtoSettingsData);
                            this[dtoProperty.Name] = settingValue;
                        }
                    }
                }
                catch (Exception e)
                {
                    var errorMessage = $"Error initializing from preferences file:\n  {ComponentSettingsFilePath}\n\n{e}";
                    ApplicationLogger.RecordDebugTraceMessage(errorMessage);
                }
            }
            InitializeFromApplicationSettings();
        }
Exemplo n.º 8
0
        private static async Task <ClaimsIdentity> GetClaimsIdentityByAudience(ClaimsPrincipal principal)
        {
            var section = (ConfigurationSection)ConfigurationHelper.GetConfiguration().GetSection("Audience");

            var audience = section.Value;

            if (audience == null)
            {
                throw new ArgumentNullException("audience");
            }

            // Verify this is the intended audience of the token
            var claimsIdentity = principal.Identities.FirstOrDefault(
                i => i.Claims.Any(c => c.Type == "aud" && c.Value == audience)
                );

            if (claimsIdentity == null)
            {
                await ApplicationLogger
                .LogSecurity(
                    message : $"No OAuth claims found for user: {principal.Identity?.Name ?? "Unknown"} and audience : {audience}"
                    );
            }

            return(claimsIdentity);
        }
Exemplo n.º 9
0
 public void should_trace_without_or_without_properties()
 {
     ApplicationLogger.TraceWithProperties("Category", "Title", "User", null);
     ApplicationLogger.TraceWithProperties("Category", "Title", "User", new Dictionary <string, string> {
         { "property", "value" }
     });
 }
Exemplo n.º 10
0
        private async Task GetGoogleCalendarInternal()
        {
            try
            {
                if (SelectedGoogleAccount == null || SelectedGoogleAccount.Name == null)
                {
                    return;
                }
                var calendars =
                    await GoogleCalendarService.GetAvailableCalendars(SelectedGoogleAccount.Name);

                if (calendars.Any())
                {
                    if (SelectedCalendar != null)
                    {
                        SelectedCalendar = calendars.FirstOrDefault(t => t.Id.Equals(SelectedCalendar.Id));
                    }

                    if (SelectedCalendar == null)
                    {
                        SelectedCalendar = calendars.First();
                    }
                }
                GoogleCalendars = calendars;
            }
            catch (Exception exception)
            {
                MessageService.ShowMessageAsync("Unable to get Google calendars.");
                ApplicationLogger.Error(exception);
            }
        }
Exemplo n.º 11
0
 protected void gridRoles_RowCommand(object sender, GridViewCommandEventArgs e)
 {
     if (e.CommandName.Equals("DeleteRow"))
     {
         string roleName = e.CommandArgument.ToString();
         try
         {
             if (Roles.GetUsersInRole(roleName).Length > 0)
             {
                 lblStatus.Text = String.Format("Cannot delete role name {0} since it already has users associated with it", roleName);
             }
             else
             {
                 try
                 {
                     UserManagement.DeleteRole(roleName);
                 }
                 catch (Exception ex)
                 {
                     ApplicationLogger.Write(ex);
                     DynamicControlBinding.SetLabelTextWithCssClass(lblStatus, ex.Message, LabelStyleNames.ErrorMessage);
                 }
             }
         }
         catch (Exception ex)
         {
             ApplicationLogger.Write(ex);
             DynamicControlBinding.SetLabelTextWithCssClass(lblStatus, ex.Message, LabelStyleNames.ErrorMessage);
         }
     }
     BindToGrid(null);
 }
Exemplo n.º 12
0
        private async Task GetOutlookMailBoxesInternal()
        {
            try
            {
                var mailBoxes = await Task <List <OutlookMailBox> > .Factory.StartNew(GetOutlookMailBox);

                if (mailBoxes == null)
                {
                    MessageService.ShowMessageAsync("Failed to fetch outlook mailboxes. Please try again." +
                                                    Environment.NewLine + "If the problem persists, Please restart Outlook application.");
                    return;
                }

                if (SelectedOutlookMailBox != null && mailBoxes.Any())
                {
                    var mailbox = mailBoxes.FirstOrDefault(
                        t => t.EntryId.Equals(SelectedOutlookMailBox.EntryId)) ?? mailBoxes.First();

                    if (SelectedOutlookCalendar != null)
                    {
                        SelectedOutlookCalendar =
                            mailbox.Calendars.FirstOrDefault(
                                t => t.EntryId.Equals(SelectedOutlookCalendar.EntryId)) ??
                            mailbox.Calendars.First();
                    }
                    SelectedOutlookMailBox = mailbox;
                }
                OutlookMailBoxes = mailBoxes;
            }
            catch (Exception aggregateException)
            {
                ApplicationLogger.Error(aggregateException);
            }
        }
Exemplo n.º 13
0
        private async Task <bool> CacheHistoryData(DateTime indianTime, bool isDevelopment)
        {
            //Delete Previous data
            //Directory.Delete(GlobalConfigurations.CachedDataPath , recursive: true);

            var job = await _jobService.GetJob(_jobId);

            var strategy = await _strategyService.Get(job.StrategyId);

            var symbols = await _watchlistService.GetSymbols(strategy.WatchlistId);

            var userSession = await _userSessionService.GetCurrentSession();

            if (userSession != null)
            {
                _zeropdhaService = new ZerodhaBroker(AutoMapper.Mapper.Map <UserSessionModel>(userSession));
                await symbols.ParallelForEachAsync(async symbol =>
                {
                    var candles = await _zeropdhaService.GetCachedDataAsync(symbol, _HistoricalDataTimeframe,
                                                                            indianTime.AddDays(_HistoricalDataInDays),
                                                                            indianTime,
                                                                            isDevelopment: isDevelopment);
                    if (candles != null && candles.Count() > 0)
                    {
                        ApplicationLogger.LogJob(_jobId, "Trading Data Cached :" + symbol.TradingSymbol);
                    }
                    else
                    {
                        ApplicationLogger.LogJob(_jobId, "Trading Data Not Cached :" + symbol.TradingSymbol);
                    }
                });
            }
            return(true);
        }
        public async Task <IActionResult> GetCurrentParticipant()
        {
            var participants = await _participantService.GetParticipantsByUsernameAsync(User.Identity.Name);

            Participant firstParticipant;

            try
            {
                firstParticipant = participants.First();
            }
            catch (Exception ex)
            {
                ApplicationLogger.TraceException
                (
                    TraceCategories.MissingResource,
                    $"Failed to find GetParticipantsByUsername()",
                    ex,
                    User
                );

                return(NotFound());
            }

            return(Ok(new ParticipantResponse {
                Id = firstParticipant.Id, Username = firstParticipant.Username
            }));
        }
Exemplo n.º 15
0
        public void SetSelectedAudioDevices(AudioDeviceType audioDeviceType)
        {
            try
            {
                switch (audioDeviceType)
                {
                case AudioDeviceType.Capture:
                    using (AudioCaptureDeviceDialog audioCaptureDeviceDialog = new AudioCaptureDeviceDialog(SelectedCaptureDevicesCollection))
                    {
                        if (audioCaptureDeviceDialog.ShowDialog().Value)
                        {
                            SelectedCaptureDevicesCollection = new ObservableCollection <AudioCaptureDevice>(audioCaptureDeviceDialog.SelectedAudioCaptureDevices);
                        }
                    }
                    break;

                case AudioDeviceType.Render:
                    using (AudioOutputDeviceDialog audioOutputDeviceDialog = new AudioOutputDeviceDialog(SelectedOutputDevicesCollection))
                    {
                        if (audioOutputDeviceDialog.ShowDialog().Value)
                        {
                            SelectedOutputDevicesCollection = new ObservableCollection <AudioOutputDevice>(audioOutputDeviceDialog.SelectedAudioOutputDevices);
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                ApplicationLogger.Log(ex.Message, ex.StackTrace);
            }
        }
Exemplo n.º 16
0
 private static void ProcessBook(Guid bookID, int iterator)
 {
     try
     {
         using (Entities context = new Entities())
         {
             Book book = context.Books.FirstOrDefault(x => x.BookId == bookID);
             if (book.BookContents.Count > 0)
             {
                 ApplicationLogger.WriteStringToLog("Process book: " + book.BookId.ToString());
                 Flag flag = context.Flags.FirstOrDefault(x => x.Name.ToLower().Equals("sources uploaded") && x.BookId == bookID);
                 UploadBookSources(book, flag);
                 context.SaveChanges();
             }
         }
     }
     catch (Exception e)
     {
         if (iterator <= 10)
         {
             ApplicationLogger.WriteStringToError(e.Message);
             Thread.Sleep(2000);
             iterator = iterator++;
             ProcessBook(bookID, iterator);
         }
         else
         {
             ApplicationLogger.WriteStringToLog("Application can't commit cahnges to the database because:\r\n");
             throw e;
         }
     }
 }
Exemplo n.º 17
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request,
                                                                      CancellationToken cancellationToken)
        {
            var properties = new Dictionary <string, string>();

            var token = _memoryCache.Get <string>(TokenCacheKey);

            if (string.IsNullOrEmpty(token))
            {
                var authenticationResult = await _tokenProvider.GetAuthorisationResult(_securitySettings.UserApiClientId,
                                                                                       _securitySettings.UserApiClientSecret, ClientResource);

                token = authenticationResult.AccessToken;
                var tokenExpireDateTime = authenticationResult.ExpiresOn.DateTime.AddMinutes(-1);
                _memoryCache.Set(TokenCacheKey, token, tokenExpireDateTime);
            }

            request.Headers.Add("Authorization", $"Bearer {token}");
            try
            {
                return(await base.SendAsync(request, cancellationToken));
            }
            catch (Exception e)
            {
                ApplicationLogger.TraceException(TraceCategories.Authorization, "BookHearing Client Exception", e, null,
                                                 properties);
                throw;
            }
        }
Exemplo n.º 18
0
        private void OnHovering()
        {
            if (Control.ModifierKeys == Keys.Control)
            {
                using (new WaitCursor())
                {
                    AutomationElement element = null;
                    try
                    {
                        element = AutomationElement.FromPoint(new Point((double)Cursor.Position.X, (double)Cursor.Position.Y));
                    }
                    catch (Exception ex)
                    {
                        ApplicationLogger.LogException(ex);
                    }

                    if (element != null)
                    {
                        if (this._treeControl.IsMember(element))
                        {
                            SelectNode(this._treeControl.BuildTreeFromRootToElement(element));
                        }
                    }
                }
            }
        }
Exemplo n.º 19
0
        static void Main()
        {
            //global exception logger
#if DEBUG
            var applicationLogger = new ApplicationLogger(LogLevel.Info);
#else
            var applicationLogger = new ApplicationLogger(LogLevel.Error);
#endif

            var hierarchy = new Element("Add")
            {
                Children = new List <Element> {
                    new Element("Product"),
                    new Element("Product")
                }
            };

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
                Application.Run(new MainForm(applicationLogger));
            }
            catch (Exception ex)
            {
                applicationLogger.Log(ex.ToString(), LogLevel.Error);
#if DEBUG
                throw;
#endif
            }
        }
        public static string siiign0(string text)
        {
            // retrieve private key
            try
            {
                string           certificate = @"path to pfx file";
                X509Certificate2 cert        = new X509Certificate2(certificate, "password", X509KeyStorageFlags.UserKeySet);
                //X509Certificate2 cert = get_certificate();
                RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;

                // Hash the data
                SHA1Managed   sha1     = new SHA1Managed();
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[]        data     = encoding.GetBytes(text);
                byte[]        hash     = sha1.ComputeHash(data);

                // Sign the hash
                byte[] digitalCert = rsa.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
                string s           = hash.ToString();
                string strDigCert  = Convert.ToBase64String(digitalCert);
                return(strDigCert);
            }
            catch (CryptographicException e)
            {
                ApplicationLogger.WriteToFile("{0} DEBUG: " + e.Message);
                return(null);
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// GTK-specific implementation to saves the settings to disk using <see cref="DataContractSerializer"/>.
 /// </summary>
 partial void OSSave()
 {
     // If no settings are specific to the type, and all are shunted to application settings,
     // don't bother creating the settings file!
     if (_values.Keys.Except(_applicationSettingsKeys).Any())
     {
         try
         {
             var xmlWriter = XmlWriter.Create(ComponentSettingsFilePath, new XmlWriterSettings()
             {
                 Indent = true
             });
             using (var xmlDictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(xmlWriter))
             {
                 var dataContractSerializer = new DataContractSerializer(this.GetType());
                 dataContractSerializer.WriteObject(xmlDictionaryWriter, this);
                 xmlDictionaryWriter.Flush();
             }
         }
         catch (Exception e)
         {
             var errorMessage = $"Error saving preferences file:\n  {ComponentSettingsFilePath}\n\n{e}";
             ApplicationLogger.RecordDebugTraceMessage(errorMessage);
         }
     }
 }
Exemplo n.º 22
0
        public async Task DeleteSampleAsync(SoundboardSample soundboardSample)
        {
            try
            {
                // Recursively try to acquire file lock. This can sometimes take a few seconds to release after
                // an audio playback event has ended
                bool success = false;
                while (!success)
                {
                    try
                    {
                        AudioAgent.StopAudioPlayback(SelectedOutputDevicesCollection.ToList());
                        File.Delete(soundboardSample.FilePath);
                        SoundboardSampleCollection.Remove(soundboardSample);

                        success = true;
                    }
                    catch
                    {
                        await Task.Delay(500);
                    }
                }
            }
            catch (Exception ex)
            {
                ApplicationLogger.Log(ex.Message, ex.StackTrace);
            }
        }
Exemplo n.º 23
0
 public ShellViewModel(IShellView view, IShellService shellService,
                       ISyncService syncStartService,
                       IGuiInteractionService guiInteractionService,
                       Settings settings,
                       SyncSummary syncSummary,
                       IMessageService messageService,
                       ApplicationLogger applicationLogger, IApplicationUpdateService applicationUpdateService,
                       SystemTrayNotifierViewModel systemTrayNotifierViewModel, ChildContentViewFactory childContentViewFactory)
     : base(view)
 {
     _statusBuilder              = new StringBuilder();
     MessageService              = messageService;
     ApplicationLogger           = applicationLogger;
     Logger                      = applicationLogger.GetLogger(GetType());
     ApplicationUpdateService    = applicationUpdateService;
     ShellService                = shellService;
     SyncStartService            = syncStartService;
     GuiInteractionService       = guiInteractionService;
     Settings                    = settings;
     SyncSummary                 = syncSummary;
     SystemTrayNotifierViewModel = systemTrayNotifierViewModel;
     ChildContentViewFactory     = childContentViewFactory;
     view.Closing               += ViewClosing;
     view.Closed                += ViewClosed;
 }
Exemplo n.º 24
0
        public void LoadAudioSamples()
        {
            try
            {
                if (Directory.Exists(ApplicationConfiguration.Instance.SoundboardSampleDirectory))
                {
                    foreach (string audioSamplePath in Directory.GetFiles(ApplicationConfiguration.Instance.SoundboardSampleDirectory, "*", SearchOption.AllDirectories))
                    {
                        string   relativePath   = Path.GetRelativePath(ApplicationConfiguration.Instance.SoundboardSampleDirectory, audioSamplePath);
                        string[] directorySplit = relativePath.Split('\\');
                        double   totalSeconds   = AudioAgent.GetFileAudioDuration(audioSamplePath).TotalSeconds;

                        string groupName = "Ungrouped";
                        if (directorySplit.Length > 1)
                        {
                            groupName = directorySplit[0];
                        }

                        _soundboardSampleCollection.Add(new SoundboardSample(audioSamplePath)
                        {
                            GroupName          = groupName,
                            FileTimeMax        = totalSeconds,
                            FileTimeMin        = 0,
                            FileTimeUpperValue = totalSeconds,
                            FileTimeLowerValue = 0,
                            HotkeyId           = _soundboardSampleCollection.Count
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                ApplicationLogger.Log(ex.Message, ex.StackTrace);
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// The overrided on exception method.
        /// </summary>
        /// <param name="actionExecutedContext">The action executed context.</param>
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            ApplicationLogger.LogError(actionExecutedContext.Exception);

            if (actionExecutedContext.Exception is NotImplementedException)
            {
                actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
                return;
            }
            else if (actionExecutedContext.Exception is ArgumentNullException)
            {
                actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            }
            else if (actionExecutedContext.Exception is ArgumentException)
            {
                actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            }
            else if (actionExecutedContext.Exception is NullReferenceException)
            {
                actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }
            else if (actionExecutedContext.Exception is IndexOutOfRangeException)
            {
                actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }

            // Another types of an exception.
            else
            {
                base.OnException(actionExecutedContext);
            }
        }
Exemplo n.º 26
0
        public void RegisterHotKeysAndHooks()
        {
            try
            {
                if (RegisterRecordHotKey(ApplicationConfiguration.Instance.RecordHotkey))
                {
                    RecordHotkey = ApplicationConfiguration.Instance.RecordHotkey;
                }

                SoundboardSampleCollection.ToList().ForEach(soundboardSample =>
                {
                    if (soundboardSample.Hotkey != Key.None)
                    {
                        RegisterSoundboardSampleHotKey(soundboardSample.Hotkey, soundboardSample.HotkeyId);
                    }
                });

                // Hooks
                _hwndSource = HwndSource.FromHwnd(WindowHandle);
                _hwndSource.AddHook(HwndHook);
            }
            catch (Exception ex)
            {
                ApplicationLogger.Log(ex.Message, ex.StackTrace);
            }
        }
Exemplo n.º 27
0
        private void ProcessFile(string filename)
        {
            string extension = Path.GetExtension(filename);

            if (String.Compare(extension, ".fb2", true) == 0)
            {
                using (FileStream fileStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    try
                    {
                        DateTime now         = DateTime.Now;
                        TimeSpan localOffset = now - now.ToUniversalTime();

                        ProcessDocument(fileStream, Path.GetFileNameWithoutExtension(filename), File.GetLastWriteTimeUtc(filename) + localOffset);
                    }
                    catch (Exception exp)
                    {
                        ApplicationLogger.WriteStringToError(exp.Message);
                        try
                        {
                            string outputFilename = GetOutputFileName(this.outputDirectoryBad, Path.GetFileNameWithoutExtension(filename), ".fb2");
                            File.Copy(filename, outputFilename);
                        }
                        catch (Exception e)
                        {
                            ApplicationLogger.WriteStringToError(e.Message);
                        }
                    }
                }
            }
        }
Exemplo n.º 28
0
        public void SaveSample(SoundboardSample soundboardSample)
        {
            try
            {
                // Trimming
                if (soundboardSample.FileTimeUpperValue != soundboardSample.FileTimeMax || soundboardSample.FileTimeLowerValue != soundboardSample.FileTimeMin)
                {
                    AudioAgent.TrimFile(soundboardSample.FilePath, soundboardSample.FileTimeLowerValue * 1000, soundboardSample.FileTimeUpperValue * 1000);

                    soundboardSample.FileTimeMin        = 0;
                    soundboardSample.FileTimeMax        = AudioAgent.GetFileAudioDuration(soundboardSample.FilePath).TotalSeconds;
                    soundboardSample.FileTimeLowerValue = 0;
                    soundboardSample.FileTimeUpperValue = soundboardSample.FileTimeMax;
                }

                // File name
                if (Path.GetFileNameWithoutExtension(soundboardSample.FilePath) != soundboardSample.Name)
                {
                    string targetDirectory = Path.Combine(ApplicationConfiguration.Instance.SoundboardSampleDirectory, soundboardSample.GroupName == "Ungrouped" ? string.Empty : soundboardSample.GroupName);
                    string newFilePath     = soundboardSample.GetVirtualFilePath();

                    Directory.CreateDirectory(targetDirectory);
                    File.Move(soundboardSample.FilePath, newFilePath);

                    soundboardSample.FilePath = newFilePath;
                }

                soundboardSample.SaveMetadataProperties();
            }
            catch (Exception ex)
            {
                ApplicationLogger.Log(ex.Message, ex.StackTrace);
            }
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            const string AUTHORIZATION = "Authorization";
            const string BEARER        = "Bearer";
            const string ERR_MSG       = "Client Exception";
            const int    MINUTES       = -1;

            var properties = new Dictionary <string, string>();

            var token = _memoryCache.Get <string>(TokenCacheKey);

            if (string.IsNullOrEmpty(token))
            {
                var authenticationResult = await _tokenProvider.GetAuthorisationResult(_azureAdConfiguration.ClientId, _azureAdConfiguration.ClientSecret, ClientResource);

                token = authenticationResult.AccessToken;
                var tokenExpireDateTime = authenticationResult.ExpiresOn.DateTime.AddMinutes(MINUTES);
                _memoryCache.Set(TokenCacheKey, token, tokenExpireDateTime);
            }

            request.Headers.Add(AUTHORIZATION, $"{BEARER} {token}");
            try
            {
                return(await base.SendAsync(request, cancellationToken));
            }
            catch (Exception e)
            {
                ApplicationLogger.TraceException(TraceCategory.ServiceAuthentication.ToString(), ERR_MSG, e, null, properties);

                throw;
            }
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            try
            {
                ApplicationLogger.ClearLogFile();
                ApplicationLogger.ClearErrorFile();
                ApplicationLogger.WriteStringToLog("Application started.");

                string orderByClause = string.Empty;
                if (args.Length > 0 && args[0].ToLower().StartsWith("order by "))
                {
                    orderByClause = args[0];
                }

                new ProcessBooks(orderByClause);

                ApplicationLogger.WriteStringToLog("Application finished.");
            }
            catch (ApplicationException ex)
            {
                Console.WriteLine("Application finished work with error. Please see error file.");
                ApplicationLogger.WriteStringToError(ex.Message);
                ApplicationLogger.WriteStringToLog("Application finished work with error. Please see error file.");
            }
        }