Пример #1
0
        public static void Main(string[] args)
        {
            Logger?.Info("Starting wcf server...");

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            #region self hosting impl.
            string     selfHostUrls = System.Configuration.ConfigurationManager.AppSettings["SelfHostUrls"]?.ToString();
            string[]   urls         = selfHostUrls?.Trim()?.Split(';')?.Select(x => x?.Trim())?.ToArray();
            List <Uri> uris         = new List <Uri>();

            if (urls?.Count() > 0)
            {
                foreach (string url in urls)
                {
                    if (Uri.TryCreate(url, UriKind.Absolute, out var uri))
                    {
                        uris.Add(uri);
                    }
                }
            }

            if (uris.Count <= 0)
            {
                uris.Add(new Uri("http://0.0.0.0:5000"));
            }
            #endregion

            try
            {
                using (ServiceHost serviceHost = new ServiceHost(typeof(Service), uris.ToArray()))
                {
                    serviceHost.UnknownMessageReceived += ServiceHost_UnknownMessageReceived;
                    serviceHost.Opening += ServiceHost_ChannelEvent;
                    serviceHost.Opened  += ServiceHost_ChannelEvent;
                    serviceHost.Closing += ServiceHost_ChannelEvent;
                    serviceHost.Closed  += ServiceHost_ChannelEvent;
                    serviceHost.Faulted += ServiceHost_ChannelEvent;

                    serviceHost.Open();

                    Logger?.Info("The service is ready at: ");
                    foreach (var uri in uris)
                    {
                        Logger?.Info(uri.ToString());
                    }

                    Logger?.Info("Press <ENTER> to terminate service.");
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Logger?.Error(ex, ex.Message);

                //this is for autorestart the service after failure in bad state!
                Environment.Exit(-1);
            }
        }
Пример #2
0
        public async Task StartMonitoring(Task preTask)
        {
            _logger?.Info("{0} A ring is set up: {1}", m_host.FullName, DisplayName);

            await preTask.ConfigureAwait(false);

            _logger?.Info("{0} Ring pretask done. Starting check loop for {1}", m_host.FullName, DisplayName);


            while (true)
            {
                await Task.Delay(m_host.m_dataflowOptions.MonitorInterval).ConfigureAwait(false);

                bool empty = false;

                if (m_hb.NoHeartbeatDuring(() => { empty = this.IsRingEmpty(); }) && empty)
                {
                    _logger.Debug("{0} 1st level empty ring check passed for {1}", m_host.FullName, this.DisplayName);

                    bool noHeartbeat = await m_hb.NoHeartbeatDuring(
                        async() =>
                    {
                        //trigger batch
                        foreach (var batchedFlow in m_ringNodes.OfType <IBatchedDataflow>())
                        {
                            batchedFlow.TriggerBatch();
                        }

                        await Task.Delay(m_host.m_dataflowOptions.MonitorInterval).ConfigureAwait(false);

                        empty = this.IsRingEmpty();
                    }).ConfigureAwait(false);

                    if (noHeartbeat && empty)
                    {
                        _logger.Debug("{0} 2nd level empty ring check passed for {1}", m_host.FullName, this.DisplayName);

                        m_hb.Complete(); //start the completion domino :)
                        break;
                    }
                    else
                    {
                        //batched flow dumped some hidden elements to the flow, go back to the loop
                        _logger.Debug("{0} New elements entered the ring by batched flows ({1}). Will fall back to 1st level empty ring check.", m_host.FullName, this.DisplayName);
                    }
                }
            }

            _logger.Info("{0} Ring completion detected! Completion triggered on heartbeat node: {1}", m_host.FullName, DisplayName);
        }
        public void Initialize(bool useLogging = true, string folderPath = null, string fileNameFormat = null)
        {
            if (useLogging)
            {
                _logger = Logger.Create(nameof(DataCollector));

                Logger.UpdateFilePath(folderPath ?? $"{AppDomain.CurrentDomain.BaseDirectory}/{TextConstants.LogDefaultFolder}",
                                      fileNameFormat ?? TextConstants.LogFormatFileName);
                _isLogging = true;
            }

            _logger?.Info("Initialize timer...");
            _dataQueue.InitializeTimer();
        }
Пример #4
0
        static void Main(string[] args)
        {
            SetupLogger();
            FullConfig?config = GetConfig();

            if (config == null)
            {
                return;
            }

            CancellationTokenSource source = new();

            Classroom classroom = new Classroom(config, source.Token);
            Meet?     meet      = null;

            try
            {
                meet = classroom.InitMeetInstance(source.Token);
                logger?.Debug("Starting classroom");
                Task crTask = classroom.Start();
                logger?.Debug("Starting meet");
                Task meetTask = meet.Start();
                logger?.Debug("Started all");
                Console.ReadLine();
                source.Cancel();
                Task.WaitAll(crTask, meetTask);
            }
            catch (AggregateException ex)
            {
                if (ex.InnerException is TaskCanceledException)
                {
                    logger?.Info("Successfully canceled");
                }
                else
                {
                    logger?.Error(ex);
                }
            }
            catch (Exception ex)
            {
                logger?.Error(ex);
            }
            finally
            {
                source.Dispose();
                meet?.Dispose();
                classroom.Dispose();
            }
        }
Пример #5
0
        /// <summary>
        /// 恢复运行暂停的任务
        /// </summary>
        /// <param name="jobName">任务名称</param>
        /// <param name="jobGroup">任务分组</param>
        public async Task <ResultValue> ResumeJobAsync(string jobGroup, string jobName)
        {
            ResultValue result = new ResultValue();

            try
            {
                //检查任务是否存在
                var jobKey = new JobKey(jobName, jobGroup);
                if (await Scheduler.CheckExists(jobKey))
                {
                    //任务已经存在则暂停任务
                    await Scheduler.ResumeJob(jobKey);

                    result.Msg     = "恢复任务计划成功!";
                    result.MsgCode = 1;
                    log?.Info(string.Format("任务“{0}”恢复运行", jobName));
                }
                else
                {
                    result.Msg     = "任务不存在";
                    result.MsgCode = 2;
                }
            }
            catch (Exception ex)
            {
                result.Msg     = "恢复任务计划失败!";
                result.MsgCode = 2;
                log.Error(string.Format("恢复任务失败!{0}", ex));
            }
            return(result);
        }
Пример #6
0
        private void Capture_Load(object sender, EventArgs e)
        {
            /////////// Setup logger ///////////
            logger = NLog.LogManager.GetCurrentClassLogger();
            logger.Info("Starting application.");

            //target.Name = "display";
            //target.Layout = "${time} | ${Threadid} | ${level} | ${logger} | ${message}";
            //target.ControlName = "richTextBox1";
            //target.FormName = "Recorder";
            //target.UseDefaultRowColoringRules = true;
            //NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, NLog.LogLevel.Trace);
            //target.MaxLines = 1024;
            //target.AutoScroll = true;


            ///////////// Set new state to prevent the system from entering sleep mode /////////////
            // Source: David Anson @ Microsoft (2009) http://dlaa.me/blog/post/9901642
            m_previousExecutionState = NativeMethods.SetThreadExecutionState(NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED);
            if (0 == m_previousExecutionState)
            {
                MessageBox.Show("Failed to set system state for sleep mode.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // No way to recover; fail gracefully
                Close();
            }


            /////////// Set timer to first snapshot /////////// 
            //(Note: this must by setup on the UI thread)
            try
            {
                logger.Info("Configuring Timer");
                timer = new FixedStepDispatcherTimer(new TimeSpan(0, 0, 1));
                DateTime now = DateTime.Now;
                DateTime firstTick = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second + 1);
                timer.Restart(firstTick);
            }
            catch (Exception ex)
            {
                logger.Error("Error creating DispatcherTimer: " + ex.Message);
            }

            logger.Info("Configuring Recorder BackgroundWorker");
            bw = new BackgroundWorker();
            bw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            bw.RunWorkerAsync();
        }
Пример #7
0
        public MainWindow()
        {
            InitializeComponent();

            logger.Info("PhotoSensorMonApp Initialized...");
        }
Пример #8
0
        public static void Run(Options opts)
        {
            logger.Info("Starting...");

            var DetectedGame = opts.Game;
            var GameFolder   = opts.GamePath;
            var UseLocators  = true;

            if (GameFolder == null)
            {
                GameFolder = Environment.CurrentDirectory;
            }

            foreach (var gameDef in GameDefinition.All)
            {
                if (gameDef.Probe(GameFolder))
                {
                    DetectedGame = gameDef.Game;
                    UseLocators  = false;
                }
            }

            var definition = GameDefinition.FromGame(DetectedGame);
            GameInstallation installation;

            if (UseLocators)
            {
                installation = GameInstallation
                               .FindAll(new[] { definition })
                               .FirstOrDefault();
            }
            else
            {
                installation = new GameInstallation(definition, GameFolder);
            }

            if (installation == null)
            {
                Console.WriteLine($"OpenSAGE was unable to find any installations of {definition.DisplayName}.\n");

                Console.WriteLine("You can manually specify the installation path by setting the following environment variable:");
                Console.WriteLine($"\t{definition.Identifier.ToUpper()}_PATH=<installation path>\n");

                Console.WriteLine("OpenSAGE doesn't yet detect every released version of every game. Please report undetected versions to our GitHub page:");
                Console.WriteLine("\thttps://github.com/OpenSAGE/OpenSAGE/issues");

                Console.WriteLine("\n\n Press any key to exit.");

                Console.ReadLine();

                Environment.Exit(1);
            }

            logger.Debug($"Have installation of {definition.DisplayName}");

            Platform.Start();

            var traceEnabled = !string.IsNullOrEmpty(opts.TraceFile);

            if (traceEnabled)
            {
                GameTrace.Start(opts.TraceFile);
            }

            // TODO: Read game version from assembly metadata or .git folder
            // TODO: Set window icon.
            var config = new Configuration()
            {
                UseFullscreen  = opts.Fullscreen,
                UseRenderDoc   = opts.RenderDoc,
                LoadShellMap   = !opts.NoShellmap,
                UseUniquePorts = opts.UseUniquePorts
            };

            UPnP.InitializeAsync(TimeSpan.FromSeconds(10)).ContinueWith(_ => logger.Info($"UPnP status: {UPnP.Status}"));

            logger.Debug($"Have configuration");

            using (var game = new Game(installation, opts.Renderer, config))
            {
                game.GraphicsDevice.SyncToVerticalBlank = !opts.DisableVsync;

                game.DeveloperModeEnabled = opts.DeveloperMode;

                if (opts.DeveloperMode)
                {
                    game.Window.Maximized = true;
                }

                if (opts.ReplayFile != null)
                {
                    var replayFile = game.ContentManager.UserDataFileSystem?.GetFile(Path.Combine("Replays", opts.ReplayFile));
                    if (replayFile == null)
                    {
                        logger.Debug("Could not find entry for Replay " + opts.ReplayFile);
                        game.ShowMainMenu();
                    }

                    game.LoadReplayFile(replayFile);
                }
                else if (opts.Map != null)
                {
                    game.Restart = StartMap;
                    StartMap();

                    void StartMap()
                    {
                        var mapCache = game.AssetStore.MapCaches.GetByName(opts.Map);

                        if (mapCache == null)
                        {
                            logger.Debug("Could not find MapCache entry for map " + opts.Map);
                            game.ShowMainMenu();
                        }
                        else if (mapCache.IsMultiplayer)
                        {
                            var pSettings = new PlayerSetting?[]
                            {
                                new PlayerSetting(null, game.AssetStore.PlayerTemplates.GetByName("FactionAmerica"), new ColorRgb(255, 0, 0), 0, PlayerOwner.Player),
                                new PlayerSetting(null, game.AssetStore.PlayerTemplates.GetByName("FactionGLA"), new ColorRgb(0, 255, 0), 0, PlayerOwner.EasyAi),
                            };

                            logger.Debug("Starting multiplayer game");

                            game.StartMultiPlayerGame(opts.Map,
                                                      new EchoConnection(),
                                                      pSettings,
                                                      0,
                                                      Environment.TickCount);
                        }
                        else
                        {
                            logger.Debug("Starting singleplayer game");

                            game.StartSinglePlayerGame(opts.Map);
                        }
                    }
                }
                else
                {
                    logger.Debug("Showing main menu");
                    game.ShowMainMenu();
                }

                logger.Debug("Starting game");

                game.Run();
            }

            if (traceEnabled)
            {
                GameTrace.Stop();
            }

            Platform.Stop();
        }
Пример #9
0
        public override void Fire()
        {
            Task.Run(async() =>
            {
                DateTime sunriseMonitor = ConfigBuilder.Config.Sunrise;
                DateTime sunsetMonitor  = ConfigBuilder.Config.Sunset;
                if (ConfigBuilder.Config.Location.Enabled)
                {
                    LocationHandler.GetSunTimes(ConfigBuilder, out sunriseMonitor, out sunsetMonitor);
                }

                //the time between sunrise and sunset, aka "day"
                if (Extensions.NowIsBetweenTimes(sunriseMonitor.TimeOfDay, sunsetMonitor.TimeOfDay))
                {
                    if (SuntimeIsWithinSpan(sunsetMonitor))
                    {
                        if (!PostponeDark)
                        {
                            Logger.Info($"starting GPU usage monitoring, theme switch pending within {Math.Abs(ConfigBuilder.Config.GPUMonitoring.MonitorTimeSpanMin)} minute(s)");
                            State.PostponeSwitch = true;
                            PostponeDark         = true;
                        }
                    }
                    // if it's already light, check if the theme switch from dark to light should be delayed
                    else if (PostponeLight && DateTime.Now >= sunriseMonitor)
                    {
                        var result = await CheckForPostpone();
                        if (result != ThreshHigh)
                        {
                            PostponeLight = false;
                        }
                    }
                    else
                    {
                        if (PostponeDark || PostponeLight)
                        {
                            Logger.Info($"ending GPU usage monitoring");
                            PostponeDark         = false;
                            PostponeLight        = false;
                            State.PostponeSwitch = false;
                        }
                    }
                }
                // the time between sunset and sunrise, aka "night"
                else
                {
                    if (SuntimeIsWithinSpan(sunriseMonitor))
                    {
                        if (!PostponeLight)
                        {
                            Logger.Info($"starting GPU usage monitoring, theme switch pending within {Math.Abs(ConfigBuilder.Config.GPUMonitoring.MonitorTimeSpanMin)} minute(s)");
                            State.PostponeSwitch = true;
                            PostponeLight        = true;
                        }
                    }
                    // if it's already dark, check if the theme switch from light to dark should be delayed
                    else if (PostponeDark && DateTime.Now >= sunsetMonitor)
                    {
                        var result = await CheckForPostpone();
                        if (result != ThreshHigh)
                        {
                            PostponeDark = false;
                        }
                    }
                    else
                    {
                        if (PostponeDark || PostponeLight)
                        {
                            Logger.Info($"ending GPU usage monitoring");
                            PostponeDark         = false;
                            PostponeLight        = false;
                            State.PostponeSwitch = false;
                        }
                    }
                }
            });
        }
Пример #10
0
        /// <summary>
        /// Выполнение стадии
        /// </summary>
        /// <param name="stop"></param>
        /// <returns></returns>
        public StageResult DoStage(ManualResetEvent stop)
        {
            Log.Info("Stage {0} started in {1} cycle", Name, Battery.CurrentCycle);


            if (!Prepare())
            {
                return(StageResult.Failed);
            }


            string tfn = Path.GetTempFileName();

            temporaryStream = new StreamWriter(tfn);
            Log.Info("Stage temporary file : {0}", tfn);

            Start();


            StartTime = DateTime.Now;
            OnPropertyChanged("StartTime");

            StageResult sr = StageResult.Failed;

            while (true)
            {
                if (CheckForCompletion())
                {
                    sr = StageResult.Successful;
                    break;
                }

                if (stop.WaitOne(10))
                {
                    sr = StageResult.Breaked;
                    break;
                }

                if (CheckForTimeout())
                {
                    sr = StageResult.Timeout;
                    break;
                }


                if (CheckForFailure())
                {
                    sr = StageResult.Failed;
                    break;
                }

                Thread.Sleep(1000);
                Duration = DateTime.Now - StartTime;

                if (Tick != null)
                {
                    Tick(this, EventArgs.Empty);
                }

                OnPropertyChanged("Duration");
            }

            Stop();

            if (!Finalize())
            {
                return(StageResult.Failed);
            }

            return(sr);
        }
Пример #11
0
 public static void Main(string[] args)
 {
     Logger.Info("Start");
     CreateHostBuilder(args).Build().Run();
 }
Пример #12
0
 public static void Info(String className, String msg)
 {
     logger = NLog.LogManager.GetLogger(className);
     logger.Info(msg);
 }
Пример #13
0
 public static void LogInfo(string message)
 {
     logger.Info(message);
 }
Пример #14
0
        static void Main(string[] args)
        {
            logger.Info("Program started");

            try
            {
                string choice = "";
                do
                {
                    Console.WriteLine("  -MENU-  \n1. Display All Blogs\n2. Add New Blog\n3. Create Post\n4. Display Posts\nEnter 'done' to quit");
                    choice = Console.ReadLine();
                    logger.Info("User choice: " + choice);
                    if (choice == "1")
                    {
                        var db = new BloggingContext();
                        // Display all Blogs from the database
                        var query = db.Blogs.OrderBy(b => b.BlogId);

                        Console.WriteLine("All blogs in the database:");
                        var count = db.Blogs.Count();
                        Console.WriteLine(count + " blogs found.");
                        foreach (var item in query)
                        {
                            Console.WriteLine(item.BlogId + ") " + item.Name);
                        }
                    }
                    else if (choice == "2")
                    {
                        // Create and save a new Blog
                        Console.Write("Enter a name for a new Blog: ");
                        string input = Console.ReadLine();
                        if (string.IsNullOrEmpty(input))
                        {
                            logger.Error("Blog name cannot be null");
                        }
                        else
                        {
                            var name = input;
                            var blog = new Blog {
                                Name = name
                            };

                            var db = new BloggingContext();
                            db.AddBlog(blog);
                            logger.Info("Blog added - {name}", name);
                        }
                    }
                    else if (choice == "3")
                    {
                        var db = new BloggingContext();
                        Console.WriteLine("Please enter the blog you wish to post to: ");
                        var query = db.Blogs.OrderBy(b => b.BlogId);
                        foreach (var item in query)
                        {
                            Console.WriteLine(item.BlogId + ") " + item.Name);
                        }

                        string selectBlog = Console.ReadLine();
                        var    test       = db.Blogs.Select(b => b.BlogId);
                        string test2      = Convert.ToString(test);

                        if (test2.Contains(selectBlog))
                        {
                            try
                            {
                                int idNumber = Int32.Parse(selectBlog);
                                var titles   = db.Blogs.Where(b => b.BlogId.Equals(idNumber)).Select(b => b.BlogId);

                                Console.Write("Enter a post title: ");
                                string postInput = Console.ReadLine();
                                if (string.IsNullOrEmpty(postInput))
                                {
                                    logger.Error("Post title cannot be null");
                                }
                                else
                                {
                                    var title = postInput;
                                    Console.WriteLine("Write your post:");
                                    string postContent = Console.ReadLine();
                                    var    post        = new Post {
                                        Title = title, Content = postContent, BlogId = idNumber
                                    };

                                    var dp = new BloggingContext();
                                    db.AddPost(post);
                                    logger.Info("Post added - {title}", title);
                                }
                            }
                            catch (Exception exc)
                            {
                                logger.Error(exc.Message);
                            }
                        }
                        else
                        {
                            logger.Error("Blog does not exist.");
                        }
                    }
                    else if (choice == "4")
                    {
                        var db = new BloggingContext();
                        Console.WriteLine("Please enter the blog you wish to view posts from: ");
                        var query = db.Blogs.OrderBy(b => b.BlogId);
                        Console.WriteLine("0) Posts from all blogs");
                        foreach (var item in query)
                        {
                            Console.WriteLine(item.BlogId + ") Posts from " + item.Name);
                        }

                        string selectBlog      = Console.ReadLine();
                        var    convertBlogId   = db.Blogs.Select(b => b.BlogId);
                        string convertedBlogId = Convert.ToString(convertBlogId);
                        if (selectBlog == "0")
                        {
                            var postQuery = db.Posts.OrderBy(p => p.PostId);
                            Console.WriteLine("All posts in the database:");
                            var postCount = db.Posts.Count();
                            Console.WriteLine(postCount + " post(s) found.");
                            foreach (var postItem in postQuery)
                            {
                                Console.WriteLine("Blog: " + postItem.Blog.Name + "\nTitle: " + postItem.Title + "\nContent: " + postItem.Content + "\n");
                            }
                        }
                        else if (convertedBlogId.Contains(selectBlog))
                        {
                            //doesnt work
                            int idNumber  = Int32.Parse(selectBlog);
                            var postQuery = db.Posts.Where(b => b.BlogId.Equals(idNumber)).OrderBy(p => p.PostId);
                            Console.WriteLine("All posts in the select blog:");
                            var postCount = db.Posts.Where(b => b.BlogId.Equals(idNumber)).Count();
                            Console.WriteLine(postCount + " post(s) found.");
                            foreach (var postItem in postQuery)
                            {
                                Console.WriteLine("Blog: " + postItem.Blog.Name + "\nTitle: " + postItem.Title + "\nContent: " + postItem.Content + "\n");
                            }
                        }
                        else
                        {
                            logger.Error("Blog does not exist.");
                        }
                    }
                }while (choice != "done");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }

            logger.Info("Program ended");
        }
Пример #15
0
        public bool SendEmail(MailMessage message)
        {
            // Do not proceed further if mail relay is disabled.
            if (!_config.Enabled)
            {
                Logger.Warn("Mail Relay is disabled.");
                return(true);
            }

            // Configure the SMTP client and send the message
            var client = new SmtpClient
            {
                Host = _config.Address,
                Port = _config.Port,

                // Use whatever SSL mode is set.
                EnableSsl      = _config.EnableSsl,
                DeliveryMethod = SmtpDeliveryMethod.Network
            };

            if (_config.EnableSsl)
            {
                ServicePointManager.ServerCertificateValidationCallback = (s, certificate, chain, sslPolicyErrors) => true;
            }

            Logger.Debug($"Email configuration | Server: {_config.Address} Port: {_config.Port} SSL: {_config.EnableSsl}");

            message.From = new MailAddress(_config.MailFromAddress, "Profile Designer Portal");

            // If Mail Relay is in debug mode set all addresses to the configuration file.
            if (_config.Debug)
            {
                Logger.Debug($"Mail relay is in debug mode. Redirecting target email to: {string.Join("|", _config.DebugToAddresses)}");
                message.To.Clear();
                foreach (var address in _config.DebugToAddresses)
                {
                    message.To.Add(new MailAddress(address));
                }
            }

            // If the user has setup credentials, use them.
            if (!string.IsNullOrEmpty(_config.Username) && !string.IsNullOrEmpty(_config.Password))
            {
                client.Credentials = new NetworkCredential(_config.Username, _config.Password);
                Logger.Debug("Credentials are set in app settings, will leverage for SMTP connection.");
            }

            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {
                if (ex is SmtpException)
                {
                    Logger.Error("An SMTP exception occurred while attempting to relay mail.");
                }
                else
                {
                    Logger.Error("A general exception occured while attempting to relay mail.");
                }

                Logger.Error(ex.Message);
                return(false);
            }
            finally
            {
                message.Dispose();
            }

            Logger.Info("Message relay complete.");
            return(true);
        }
Пример #16
0
        /// <summary>
        /// Clean up the Inactive and expired items
        /// </summary>
        private void cleanUpItems(bool recoverReserveSpace)
        {
            if (_cacheStatus.Count == 0)
            {
                return;
            }

            lock (_syncObject)
            {
                //calculate the status score list
                //NOTE:: the lower score item remove first

                List <StatusItemScore> scoreList = new List <StatusItemScore>(_cacheStatus.Count);
                foreach (CacheItemStatus status in _cacheStatus.Values)
                {
                    if (status.HasStored)
                    {
                        if (status.ExpirationSecond > 0 &&
                            (_nowTime - status.LastAccessTime).TotalSeconds > status.ExpirationSecond)
                        {
                            scoreList.Add(new StatusItemScore(status.ItemKey, 0, status.Item.Content.Length));
                        }
                        else if (recoverReserveSpace)
                        {
                            int score = (int)(status.LastAccessTime - _baseTime).TotalSeconds;
                            scoreList.Add(new StatusItemScore(status.ItemKey, score, status.Item.Content.Length));
                        }
                    }
                }

                List <StatusItemScore> needRemoveItems = new List <StatusItemScore>();

                if (recoverReserveSpace)
                {
                    //calculate the clean up size this time
                    int needCleanUpSize = _poolReserveSize + _poolUsedSize - _poolMemorySize;
                    if (needCleanUpSize < 0)
                    {
                        needCleanUpSize = 0;
                    }
                    scoreList.Sort(_sortScore); //sort

                    //add the low score cache items to list
                    for (int idx = 0; idx < scoreList.Count; idx++)
                    {
                        StatusItemScore item = scoreList[idx];
                        if (item.Score == 0 || needCleanUpSize > 0)
                        {
                            needRemoveItems.Add(item);
                            needCleanUpSize -= item.ContentLength;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else
                {
                    needRemoveItems = scoreList;
                }

                if (needRemoveItems.Count > 0)
                {
                    foreach (StatusItemScore item in needRemoveItems)
                    {
                        _poolUsedSize -= item.ContentLength;
                        _cacheStatus.Remove(item.Key);
                    }

                    GC.Collect();

                    logger.Info("Found {0} items need to clean up, After clean up, used memory size: {1}",
                                needRemoveItems.Count, this.UsedMemorySize);
                }
            }
        }
Пример #17
0
        public static void Export <T>(
            this ICollectionView collectionView,
            Dictionary <string, Model.DataCellFormats> fieldsAndFormats,
            string reportTitle,
            string reportDescription,
            Func <T, string, string, object> getValueDelegate, Action <string> callBack = null)
        {
            if (getValueDelegate == null || fieldsAndFormats == null || reportTitle == null)
            {
                return;
            }

            const string commentFieldName = nameof(Model.Meter.Коментарий);
            bool         hasCommentColumn = fieldsAndFormats.ContainsKey(commentFieldName);

            IEnumerable <T> collection = null;

            Application.Current.Dispatcher.Invoke(() =>
            {
                collection = collectionView.Cast <T>();
            });
            int numberOfRows = collection.Count();

            // +1 т.к. первый столбец номер по порядку
            int numberOfColumns = fieldsAndFormats.Count + 1;

            callBack?.Invoke("чтение данных");
            object[,] output = BuildDataArray();
            object[,] outputWithTwoRowPerRecord = null;
            if (hasCommentColumn)
            {
                outputWithTwoRowPerRecord = BuildDataArrayWithTwoRowPerRecord();
            }

            callBack?.Invoke("поиск MS Excel");

            string fileName = System.IO.Path.GetTempFileName();

            fileName = System.IO.Path.ChangeExtension(fileName, "xlsx");

            System.Globalization.CultureInfo defaultCulture = System.Threading.Thread.CurrentThread.CurrentCulture;

            // HACK: Workaround for Excel bug on machines which are set up in the English language, but not an English region.
            System.Globalization.CultureInfo enusCultureInfo = System.Globalization.CultureInfo.GetCultureInfo("en-US");
            System.Threading.Thread.CurrentThread.CurrentCulture = enusCultureInfo;

            Excel.Application excelApplication = null;
            Excel.Workbook    xlWorkbook       = null;
            Excel.Worksheet   xlWorksheet      = null;
            Excel.Worksheet   xlWorksheet2     = null;

            NetOffice.OfficeApi.Tools.Contribution.CommonUtils utils = null;

            Exception exception = null;

            Process(output, outputWithTwoRowPerRecord);

            OpenCreatedWorkBook();

            // возвращает значение указанного поля записи
            object GetValueOfField(T item, string fieldName)
            {
                object value = string.Empty;

                if (string.IsNullOrWhiteSpace(fieldsAndFormats[fieldName].ExcelFormat) == false)
                {
                    value = getValueDelegate(item, string.Empty, fieldName);
                }
                else
                {
                    value = getValueDelegate(item, fieldsAndFormats[fieldName].ContentDisplayFormat, fieldName);
                }

                if (value is DateOnly dateOnlyValue)
                {
                    value = dateOnlyValue.ToDateTime(TimeOnly.MinValue);
                }

                return(value);
            }

            // создание массива данных
            object[,] BuildDataArray()
            {
                // +1 т.к. первый столбец номер по порядку
                int countOfColumns = fieldsAndFormats.Count + 1;

                // +1 т.к. первая строка шапка
                object[,] output = new object[numberOfRows + 1, countOfColumns];

                // for (int i = 0; i < numberOfRows + 1; i++)
                //    output[i] = new object[numberOfColumns];

                output[0, 0] = "№ п/п";
                int ind = 1;

                foreach (KeyValuePair <string, Model.DataCellFormats> field in fieldsAndFormats)
                {
                    output[0, ind++] = Utils.ConvertFromTitleCase(field.Key);
                }

                callBack?.Invoke("заполнение таблицы");

                int rowIndex = 1;

                foreach (T item in collection)
                {
                    output[rowIndex, 0] = rowIndex;
                    ind = 1; // т.к. первый столбец номер по порядку
                    foreach (string field in fieldsAndFormats.Keys)
                    {
                        output[rowIndex, ind++] = GetValueOfField(item, field);
                    }

                    rowIndex++;
                }

                return(output);
            }

            // создание массива данных со второй строкой в каждой записи где указан комментарий
            object[,] BuildDataArrayWithTwoRowPerRecord()
            {
                // -1 т.к. исключен столбец Комментарий
                // +1 т.к. первый столбец номер по порядку
                int countOfColumns = fieldsAndFormats.Count - 1 + 1;

                int numberOfRecords = collection.Count();

                // +1 т.к. первая строка шапка
                object[,] output = new object[(2 * numberOfRecords) + 1, countOfColumns];

                // for (int i = 0; i < numberOfRows + 1; i++)
                //    output[i] = new object[numberOfColumns];

                output[0, 0] = "№ п/п";
                int ind = 1;

                foreach (KeyValuePair <string, Model.DataCellFormats> field in fieldsAndFormats)
                {
                    if (field.Key == commentFieldName)
                    {
                        continue;
                    }
                    else
                    {
                        output[0, ind++] = Utils.ConvertFromTitleCase(field.Key);
                    }
                }

                callBack?.Invoke("заполнение таблицы");

                int rowIndex    = 1;
                int recordIndex = 1;

                foreach (T item in collection)
                {
                    output[rowIndex, 0] = recordIndex;
                    ind = 1; // т.к. первый столбец номер по порядку
                    foreach (string field in fieldsAndFormats.Keys)
                    {
                        if (field == commentFieldName)
                        {
                            continue;
                        }

                        output[rowIndex, ind++] = GetValueOfField(item, field);
                    }

                    string commentValue = GetValueOfField(item, commentFieldName).ToString().Trim().Replace('\n', '\t');
                    output[rowIndex + 1, 1] = commentValue;

                    rowIndex += 2;
                    recordIndex++;
                }

                return(output);
            }

            void ApplyDataFormatForSheet(Excel.Worksheet xlWorksheet, Excel.Range rangeToSetData, bool thisWorkSheetIsForPrint)
            {
                // -1 т.к. исключен столбец Комментарий
                // +1 т.к. первый столбец номер по порядку
                int countOfColumns = hasCommentColumn ? fieldsAndFormats.Count - 1 + 1 : fieldsAndFormats.Count + 1;

                callBack?.Invoke("установка формата данных");

                int rowIndex    = 2; // 1 - шапка таблицы
                int ind         = 1;
                int recordIndex = 1;

                foreach (T item in collection)
                {
                    rangeToSetData[rowIndex, 0 + 1].NumberFormat = "0";
                    ind = 1; // т.к. первый столбец номер по порядку
                    foreach (string field in fieldsAndFormats.Keys)
                    {
                        if (thisWorkSheetIsForPrint && field == commentFieldName)
                        {
                            continue;
                        }

                        try
                        {
                            object value = string.Empty;
                            if (string.IsNullOrWhiteSpace(fieldsAndFormats[field].ExcelFormat) == false)
                            {
                                string format = string.IsNullOrWhiteSpace(fieldsAndFormats[field].ExcelFormat) ? "General" : fieldsAndFormats[field].ExcelFormat;
                                rangeToSetData[rowIndex, 0 + 1 + ind].NumberFormat = format;
                            }
                            else if (string.IsNullOrWhiteSpace(fieldsAndFormats[field].ContentDisplayFormat) == false)
                            {
                                rangeToSetData[rowIndex, 0 + 1 + ind].NumberFormat = "General";
                            }
                        }
                        catch (Exception e)
                        {
#if DEBUG
                            App.ToDebug(e);
#endif
                        }
                        finally
                        {
                            ind++;
                        }
                    }

                    if (thisWorkSheetIsForPrint && hasCommentColumn)
                    {
                        // ячейка с номером по порядку
                        Excel.Range rng = rangeToSetData[rowIndex, 1];
                        rng = rng.Resize(2, 1);
                        rng.Merge();
                        rng.HorizontalAlignment = XlHAlign.xlHAlignLeft;
                        rng.VerticalAlignment   = XlVAlign.xlVAlignCenter;

                        // ячейка с комментарием
                        rng = rangeToSetData[rowIndex + 1, 2].Resize(1, countOfColumns - 1);
                        rng.Merge();
                        rng.WrapText     = true;
                        rng.NumberFormat = "@";

                        rng = rangeToSetData[rowIndex, 1].Resize(2, countOfColumns);
                        rng.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic);

                        rng.Borders[XlBordersIndex.xlInsideHorizontal].LineStyle = XlLineStyle.xlDot;
                        rng.Borders[XlBordersIndex.xlInsideHorizontal].Weight    = XlBorderWeight.xlThin;
                        rng.Borders[XlBordersIndex.xlInsideHorizontal].Color     = utils.Color.ToDouble(System.Drawing.Color.Gray);

                        rng.Borders[XlBordersIndex.xlInsideVertical].LineStyle = XlLineStyle.xlDot;
                        rng.Borders[XlBordersIndex.xlInsideVertical].Weight    = XlBorderWeight.xlThin;
                        rng.Borders[XlBordersIndex.xlInsideVertical].Color     = utils.Color.ToDouble(System.Drawing.Color.Gray);

                        if (recordIndex % 2 == 0)
                        {
                            rng = rangeToSetData[rowIndex, 1].Resize(2, countOfColumns);
                            rng.Interior.Color = utils.Color.ToDouble(System.Drawing.Color.WhiteSmoke);
                        }

                        rowIndex += 2;
                    }
                    else
                    {
                        rowIndex++;
                    }

                    recordIndex++;
                }
            }

            void Process(object[,] outputData1, object[,] outputData2)
            {
                try
                {
                    callBack?.Invoke("создание книги MS Excel");

                    excelApplication = new Excel.Application
                    {
                        DisplayAlerts  = false,
                        ScreenUpdating = false,
                    };

                    utils = new NetOffice.OfficeApi.Tools.Contribution.CommonUtils(excelApplication);

                    xlWorkbook  = excelApplication.Workbooks.Add();
                    xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets[1];

                    Excel.Range all = xlWorksheet.Range("A1");

                    Excel.Range header = xlWorksheet.Range("A1");
                    header.WrapText = true;
                    header.Resize(1, numberOfColumns).Merge();
                    using (Excel.Font font = header.Font)
                    {
                        font.Size = 14;
                        font.Bold = true;
                    }

                    header.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                    header.VerticalAlignment   = XlVAlign.xlVAlignCenter;

                    double oneRowHeight = (double)header.RowHeight;
                    int    rowsCount    = reportTitle.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Length;
                    header.RowHeight = oneRowHeight * rowsCount * 1.1;

                    header.Value2 = reportTitle;

                    Excel.Range description = xlWorksheet.Range("A2");
                    description.Resize(1, numberOfColumns).Merge();
                    description.WrapText = true;
                    using (Excel.Font font = description.Font)
                    {
                        font.Size   = 12;
                        font.Italic = true;
                    }

                    description.HorizontalAlignment = XlHAlign.xlHAlignLeft;
                    description.VerticalAlignment   = XlVAlign.xlVAlignCenter;

                    oneRowHeight          = (double)description.RowHeight;
                    rowsCount             = reportDescription.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Length;
                    description.RowHeight = oneRowHeight * rowsCount * 1.1;

                    description.Value2 = reportDescription;

                    callBack?.Invoke("настройка книги MS Excel");

                    if (hasCommentColumn)
                    {
                        // создание копии листа
                        xlWorksheet.Copy(xlWorksheet);
                        xlWorksheet       = (Excel.Worksheet)xlWorkbook.Sheets[1];
                        xlWorksheet2      = (Excel.Worksheet)xlWorkbook.Sheets[2];
                        xlWorksheet.Name  = "Данные";
                        xlWorksheet2.Name = "Для печати";

                        Excel.Range data2 = xlWorksheet2.Range("A3").Resize((2 * numberOfRows) + 1, numberOfColumns - 1);
                        data2.VerticalAlignment = VerticalAlignment.Center;
                        data2.NumberFormat      = "@";

                        data2.Value = outputData2;

                        ApplyDataFormatForSheet(xlWorksheet2, data2, true);

                        Excel.Range tableHeader = xlWorksheet2.Range("A3").Resize(1, numberOfColumns - 1);
                        tableHeader.WrapText = true;
                        using (Excel.Font font = tableHeader.Font)
                        {
                            font.Size = 12;
                            font.Bold = true;
                        }

                        header.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                        header.VerticalAlignment   = XlVAlign.xlVAlignCenter;

                        tableHeader.Interior.Color = utils.Color.ToDouble(System.Drawing.Color.LightGray);
                        tableHeader.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic);

                        tableHeader.Borders[XlBordersIndex.xlInsideHorizontal].LineStyle = XlLineStyle.xlDot;
                        tableHeader.Borders[XlBordersIndex.xlInsideHorizontal].Weight    = XlBorderWeight.xlThin;
                        tableHeader.Borders[XlBordersIndex.xlInsideHorizontal].Color     = utils.Color.ToDouble(System.Drawing.Color.Black);
                    }

                    Excel.Range data = xlWorksheet.Range("A3").Resize(numberOfRows + 1, numberOfColumns);
                    data.NumberFormat = "@";
                    data.Value        = outputData1;

                    ApplyDataFormatForSheet(xlWorksheet, data, false);

                    xlWorksheet.ListObjects.Add(XlListObjectSourceType.xlSrcRange, data,
                                                Type.Missing, XlYesNoGuess.xlYes, Type.Missing).Name = "DataTable";
                    xlWorksheet.ListObjects["DataTable"].TableStyle = "TableStyleMedium6";

                    SetupWorkSheet(xlWorksheet, numberOfColumns);

                    if (hasCommentColumn)
                    {
                        SetupWorkSheet(xlWorksheet2, numberOfColumns - 1);
                    }

                    callBack?.Invoke("сохранение книги MS Excel");
                    xlWorkbook.SaveAs(fileName);
                    xlWorkbook.Close(false);

                    callBack?.Invoke("завершение");

                    logger?.Info($"Export >> файл сформирован и сохранен: '{fileName}'");
                }
                catch (Exception e)
                {
                    exception = e;
#if DEBUG
                    App.ToDebug(e);
#endif
                    App.ShowError("Произошла ошибка:\n" + App.GetExceptionDetails(e));
                    return;
                }
                finally
                {
                    System.Threading.Thread.CurrentThread.CurrentCulture = defaultCulture;

                    excelApplication.Quit();
                    excelApplication.ScreenUpdating = true;
                    excelApplication.DisplayAlerts  = true;
                    if (exception != null)
                    {
                        if (excelApplication.Workbooks.Any())
                        {
                            foreach (Excel.Workbook workbook in excelApplication.Workbooks.Where(x => !x.IsDisposed))
                            {
                                workbook.Close(false, System.Reflection.Missing.Value, Missing.Value);
                                workbook.Dispose();
                            }
                        }

                        if (excelApplication.IsDisposed == false)
                        {
                            excelApplication.Quit();
                            excelApplication.Dispose();
                        }
                    }
                }
            }

            void SetupWorkSheet(Excel.Worksheet xlWorksheet, int numberOfColumns)
            {
                foreach (int i in Enumerable.Range(1, numberOfColumns))
                {
                    xlWorksheet.Columns[i].AutoFit();
                }

                Excel.PageSetup ps = xlWorksheet.PageSetup;
                ps.PaperSize      = XlPaperSize.xlPaperA4;
                ps.Orientation    = XlPageOrientation.xlLandscape;
                ps.Zoom           = false;
                ps.FitToPagesWide = 1;
                ps.FitToPagesTall = false;

                ps.PrintTitleRows = "$3:$3";

                ps.LeftMargin   = excelApplication.CentimetersToPoints(1.0);
                ps.RightMargin  = excelApplication.CentimetersToPoints(1.0);
                ps.TopMargin    = excelApplication.CentimetersToPoints(2.0);
                ps.BottomMargin = excelApplication.CentimetersToPoints(1.0);

                ps.HeaderMargin = excelApplication.CentimetersToPoints(0.6);
                ps.FooterMargin = excelApplication.CentimetersToPoints(0.6);

                ps.CenterHorizontally = true;
                ps.RightHeader        = DateTime.Now.ToString("D", defaultCulture);
                ps.CenterFooter       = "Страница &P / &N";
                ps.PrintArea          = xlWorksheet.Range("A1").Resize(numberOfRows + 3, numberOfColumns).Address;
            }

            void OpenCreatedWorkBook()
            {
                try
                {
                    callBack?.Invoke("открытие созданной книги MS Excel");

                    using System.Diagnostics.Process p = new System.Diagnostics.Process
                          {
                              StartInfo = new System.Diagnostics.ProcessStartInfo(fileName)
                              {
                                  UseShellExecute = true,
                              },
                          };
                    p.Start();

                    // System.Diagnostics.Process.Start(fileName);
                }
                catch (Exception e)
                {
#if DEBUG
                    App.ToDebug(e);
#endif
                    App.ShowError("Произошла ошибка при открытии файла:\n" + App.GetExceptionDetails(e));
                }
            }
        }
Пример #18
0
        protected override void CreateWindow_Internal()
        {
            Logger.Info("Starting Up Vulkan Renderer");
            Window = SDL.SDL_CreateWindow("Test", SDL.SDL_WINDOWPOS_UNDEFINED, SDL.SDL_WINDOWPOS_UNDEFINED, (int)ScreenSize.X, (int)ScreenSize.Y, SDL.SDL_WindowFlags.SDL_WINDOW_VULKAN | SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN);
            if (Window == IntPtr.Zero)
            {
                Logger.Error("Failed to create SDL window");
                IEngine.Instance.Shutdown();
            }

            SDL.SDL_SetWindowBordered(Window, SDL.SDL_bool.SDL_TRUE);

            uint ExtensionCount;

            SDL.SDL_Vulkan_GetInstanceExtensions(Window, out ExtensionCount, null);
            IntPtr[] ExtensionNames = new IntPtr[(int)ExtensionCount];
            SDL.SDL_Vulkan_GetInstanceExtensions(Window, out ExtensionCount, ExtensionNames);


            List <string> Extensions = new List <string>();

            for (int i = 0; i < ExtensionNames.Length; i++)
            {
                IntPtr Name = ExtensionNames[i];
                string?Ext  = Marshal.PtrToStringUTF8(Name);
                if (Ext != null)
                {
                    Extensions.Add(Ext);
                    Logger.Info("Enabling Vulkan Extension {0}", Ext);
                }
            }
            Extensions.Add("VK_EXT_debug_report");

            List <string> Layers = new List <string>
            {
                "VK_LAYER_KHRONOS_validation",

                /*
                 * "VK_LAYER_GOOGLE_threading",
                 * "VK_LAYER_LUNARG_parameter_validation",
                 * "VK_LAYER_LUNARG_device_limits",
                 * "VK_LAYER_LUNARG_object_tracker",
                 * "VK_LAYER_LUNARG_image",
                 * "VK_LAYER_LUNARG_core_validation",
                 * "VK_LAYER_LUNARG_swapchain",
                 * "VK_LAYER_GOOGLE_unique_objects"
                 */
            };

            Vulkan.ApplicationInfo applicationInfo = new Vulkan.ApplicationInfo
            {
                EngineName         = "Watertight",
                EngineVersion      = 1,
                ApplicationName    = IEngine.Instance.Name,
                ApplicationVersion = 1,
            };



            Vulkan.InstanceCreateInfo createInfo = new Vulkan.InstanceCreateInfo
            {
                ApplicationInfo       = applicationInfo,
                EnabledExtensionCount = (uint)Extensions.Count,
                EnabledExtensionNames = Extensions.ToArray(),
                EnabledLayerCount     = (uint)Layers.Count,
                EnabledLayerNames     = Layers.ToArray(),
            };

            vkInstance    = new Vulkan.Instance(createInfo);
            DebugCallback = DebugReportCallback;
            vkInstance.EnableDebug(DebugCallback);

            {
                //HACKHACK: SDL and Vulkan do not play nice together, so we have to manually set some internal data.

                //Get the Marshalled ptr from the Instance
                Vulkan.IMarshalling MarshalledInstace = vkInstance;
                ulong SurfaceId = 0;
                SDL.SDL_Vulkan_CreateSurface(Window, MarshalledInstace.Handle, out SurfaceId);

                //Two problems.  1) the constructor for SurfaceKhr is internal, so we need to construct it with Activator
                Vulkan.SurfaceKhr surfaceKhr = Activator.CreateInstance(typeof(Vulkan.SurfaceKhr), true) as Vulkan.SurfaceKhr;
                //The internal marshalled pointer here is a private field named "m".  We got a ulong from SDL above, so we need to set that by using Reflection
                var pointerField = typeof(Vulkan.SurfaceKhr).GetField("m", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                pointerField?.SetValue(surfaceKhr, SurfaceId);

                Surface = surfaceKhr;
            }


            InitializeVulkan(vkInstance.EnumeratePhysicalDevices()[0], Surface);
        }
Пример #19
0
        private void NetworkLoop(object ctxObject)
        {
            var ctx = (ConnectionContext)ctxObject;

            while (true)
            {
                lock (statusLock)
                {
                    if (ctx.WasExit)
                    {
                        break;
                    }
                }

                var packet = packetHandler.FetchPacket();
                if (packet == null)
                {
                    break;
                }

                lock (statusLock)
                {
                    if (ctx.WasExit)
                    {
                        break;
                    }

                    switch (packet.PacketType)
                    {
                    case PacketType.Command:
                    case PacketType.CommandLow:
                        string message = Util.Encoder.GetString(packet.Data, 0, packet.Data.Length);
                        LogCmd.Debug("[I] {0}", message);
                        var result = msgProc.PushMessage(message);
                        if (result.HasValue)
                        {
                            dispatcher.Invoke(result.Value);
                        }
                        break;

                    case PacketType.Voice:
                    case PacketType.VoiceWhisper:
                        OutStream?.Write(packet.Data, new Meta
                        {
                            In = new MetaIn
                            {
                                Whisper = packet.PacketType == PacketType.VoiceWhisper
                            }
                        });
                        break;

                    case PacketType.Init1:
                        // Init error
                        if (packet.Data.Length == 5 && packet.Data[0] == 1)
                        {
                            var errorNum = BinaryPrimitives.ReadUInt32LittleEndian(packet.Data.AsReadOnlySpan().Slice(1));
                            if (Enum.IsDefined(typeof(Ts3ErrorCode), errorNum))
                            {
                                Log.Info("Got init error: {0}", (Ts3ErrorCode)errorNum);
                            }
                            else
                            {
                                Log.Warn("Got undefined init error: {0}", errorNum);
                            }
                            DisconnectInternal(ctx, setStatus: Ts3ClientStatus.Disconnected);
                        }
                        break;
                    }
                }
            }

            lock (statusLock)
            {
                DisconnectInternal(ctx, setStatus: Ts3ClientStatus.Disconnected);
            }
        }
Пример #20
0
 public void Info(string msg, params object[] args)
 {
     logger.Info(msg, args);
 }
Пример #21
0
        private static void Main(string[] args)
        {
            // Need to reset the Working directory, since when we called via the Explorer Context menu, it'll be different
            Directory.SetCurrentDirectory(Application.StartupPath);

            // Add our Bin and Bin\Bass Directory to the Path
            SetPath(Path.Combine(Application.StartupPath, "Bin"));
            SetPath(Path.Combine(Application.StartupPath, @"Bin\Bass"));

            _portable      = 0;
            _startupFolder = "";
            // Process Command line Arguments
            foreach (string arg in args)
            {
                if (arg.ToLower().StartsWith("/folder="))
                {
                    _startupFolder = arg.Substring(8);
                }
                else if (arg.ToLower() == "/portable")
                {
                    _portable = 1;
                }
            }

            try
            {
                // Let's see, if we already have an instance of MPTagThat open
                using (var mmf = MemoryMappedFile.OpenExisting("MPTagThat"))
                {
                    if (_startupFolder == string.Empty)
                    {
                        // Don't allow a second instance of MPTagThat running
                        return;
                    }

                    byte[] buffer            = Encoding.Default.GetBytes(_startupFolder);
                    var    messageWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "MPTagThat_IPC");

                    // Create accessor to MMF
                    using (var accessor = mmf.CreateViewAccessor(0, buffer.Length))
                    {
                        // Write to MMF
                        accessor.WriteArray <byte>(0, buffer, 0, buffer.Length);
                        messageWaitHandle.Set();

                        // End exit this instance
                        return;
                    }
                }
            }
            catch (FileNotFoundException)
            {
                // The Memorymap does not exist, so MPTagThat is not yet running
            }

            // Read the Config file
            ReadConfig();

            // Register Bass
            BassRegistration.BassRegistration.Register();

            using (new ServiceScope(true))
            {
                ILogger logger = new FileLogger("MPTagThat.log", NLog.LogLevel.Debug, _portable);
                ServiceScope.Add(logger);

                NLog.Logger log = ServiceScope.Get <ILogger>().GetLogger;

                log.Info("MPTagThat is starting...");

                log.Info("Registering Services");
                log.Debug("Registering Settings Manager");
                ServiceScope.Add <ISettingsManager>(new SettingsManager());
                // Set the portable Indicator
                ServiceScope.Get <ISettingsManager>().SetPortable(_portable);
                // Set the Max Songs number
                ServiceScope.Get <ISettingsManager>().SetMaxSongs(_maxSongs);

                try
                {
                    logger.Level = NLog.LogLevel.FromString(Options.MainSettings.DebugLevel);
                }
                catch (ArgumentException)
                {
                    Options.MainSettings.DebugLevel = "Info";
                    logger.Level = NLog.LogLevel.FromString(Options.MainSettings.DebugLevel);
                }

                log.Debug("Registering Localisation Services");
                ServiceScope.Add <ILocalisation>(new StringManager());

                log.Debug("Registering Message Broker");
                ServiceScope.Add <IMessageBroker>(new MessageBroker());

                log.Debug("Registering Theme Manager");
                ServiceScope.Add <IThemeManager>(new ThemeManager());

                log.Debug("Registering Action Handler");
                ServiceScope.Add <IActionHandler>(new ActionHandler());

                // Move Init of Services, which we don't need immediately to a separate thread to increase startup performance
                Thread initService = new Thread(DoInitService);
                initService.IsBackground = true;
                initService.Name         = "InitService";
                initService.Start();

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                try
                {
                    _main = new Main();

                    // Set the Startup Folder we might have received via an argument, before invoking the form
                    _main.CurrentDirectory = _startupFolder;
                    Application.Run(_main);
                }
                catch (OutOfMemoryException)
                {
                    GC.Collect();
                    MessageBox.Show(ServiceScope.Get <ILocalisation>().ToString("message", "OutOfMemory"),
                                    ServiceScope.Get <ILocalisation>().ToString("message", "Error_Title"), MessageBoxButtons.OK);
                    log.Error("Running out of memory. Scanning aborted.");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ServiceScope.Get <ILocalisation>().ToString("message", "FatalError"),
                                    ServiceScope.Get <ILocalisation>().ToString("message", "Error_Title"), MessageBoxButtons.OK);
                    log.Error("Fatal Exception: {0}\r\n{1}", ex.Message, ex.StackTrace);
                }
            }
        }
Пример #22
0
        private void ProcessData()
        {
            SetProcessing(true);
            SqlConnection sql_connection;

            SqlCommand sql_command;
            int        iCount;
            int        iIndex = 0;
            DataTable  dt     = new DataTable();

            try
            {
                string szSQLConnectionInfo;
                string szTagQuery;
                szSQLConnectionInfo = "Data Source=localhost;Initial Catalog=Runtime;Trusted_Connection=true";
                sql_connection      = new SqlConnection(szSQLConnectionInfo);
                if (chkSystemTags.Checked)
                {
                    szTagQuery = "SELECT [TagName] FROM[dbo].[Tag] where TagType <> 5";
                }
                else
                {
                    szTagQuery = "SELECT [TagName] FROM[dbo].[Tag] where TagType <> 5 and [TagName] not like 'sys%'";
                }
                sql_command             = new SqlCommand(szTagQuery, sql_connection);
                sql_command.CommandType = CommandType.Text;
                SqlDataAdapter da = new SqlDataAdapter(sql_command);
                da.Fill(dt);
                iCount = dt.Rows.Count;
                sql_connection.Close();
            }
            catch (Exception exDb)
            {
                logger.Error(exDb, "Error retreiving tags");
            }


            List <string> szTagLists = new List <string>();
            string        szTagList  = "";

            logger.Info("test");

            try
            {
                foreach (DataRow row in dt.Rows)
                {
                    szTagList = szTagList + "[" + row[0].ToString() + "],";
                    iIndex    = iIndex + 1;
                    if (iIndex == nmBatchSize.Value)
                    {
                        szTagList = szTagList.TrimEnd(',');
                        szTagLists.Add(szTagList);

                        szTagList = "";
                        iIndex    = 0;
                    }
                }
            }
            catch (Exception exList)
            {
                logger.Error(exList, "Error retreiving tags");
            }

            if (szTagList != "")
            {
                szTagList = szTagList.TrimEnd(',');
                szTagLists.Add(szTagList);

                szTagList = "";
            }

            iIndex = 0;
            foreach (string szList in szTagLists)
            {
                iIndex = iIndex + 1;
                SetIndex(iIndex.ToString("D5"));

                SqlConnection sql_connection_results;
                string        szSQLConnectionInfo_results;
                szSQLConnectionInfo_results = "Data Source=localhost;Initial Catalog=Runtime;Trusted_Connection=true";
                sql_connection_results      = new SqlConnection(szSQLConnectionInfo_results);
                SqlCommand sql_command_results;

                DateTime dtNow = DateTime.Now;
                for (DateTime dtStart = dtpStart.Value.AddSeconds(dtpStart.Value.Second * -1).AddMinutes(dtpStart.Value.Minute * -1).
                                        AddHours(dtpStart.Value.Hour * -1).AddDays(dtpStart.Value.Day * -1 + 1); dtStart < dtpEnd.Value; dtStart = dtStart.AddMonths(1))
                {
                    SetDate(dtStart.ToString("yyyy-MM-dd HH:mm:ss"));

                    string    szQuery    = "";
                    DataTable dt_Results = new DataTable();
                    try
                    {
                        szQuery = "SET QUOTED_IDENTIFIER OFF SELECT DateTime," + szList;
                        szQuery = szQuery + " FROM OPENQUERY(INSQL, \"SELECT DateTime = convert(nvarchar, DateTime, 21), ";
                        szQuery = szQuery + szList + " FROM WideHistory WHERE wwRetrievalMode = 'Cyclic' AND wwResolution = 60000 AND wwQualityRule = 'Extended' AND wwVersion = 'Latest' AND DateTime >= ";


                        DateTime dtEnd;
                        dtEnd = dtStart.AddMonths(1).AddSeconds(-1);
                        if (dtEnd > dtpEnd.Value)
                        {
                            dtEnd = dtpEnd.Value;
                        }



                        szQuery = szQuery + "'" + dtStart.ToString() + "'";
                        szQuery = szQuery + " AND DateTime <= ";
                        szQuery = szQuery + "'" + dtEnd.ToString() + "'" + "\")";
                        Debug.Write(szQuery);
                        sql_command_results                = new SqlCommand(szQuery, sql_connection_results);
                        sql_command_results.CommandType    = CommandType.Text;
                        sql_command_results.CommandTimeout = 120;
                        SqlDataAdapter da_results = new SqlDataAdapter(sql_command_results);
                        logger.Info(szQuery);
                        da_results.Fill(dt_Results);


                        iCount = dt_Results.Rows.Count;
                        logger.Info("Completed query for taglist Number: {0} Month: {1} Year: {2}", iIndex, dtStart.Month, dtStart.Year);
                        logger.Info("{0} Rows Returned", iCount);
                    }
                    catch (Exception exHistory)
                    {
                        logger.Error(exHistory, "Error retreiving history");
                    }

                    StreamWriter csv;

                    try
                    {
                        csv = new StreamWriter(this.txtDirectory.Text + "\\" + iIndex.ToString("D5") + dtStart.Year.ToString() + dtStart.Month.ToString("D2") + ".csv", false);


                        csv.WriteLine("DateTime," + szList);
                        int iLineCount = 0;
                        foreach (DataRow ResultRow in dt_Results.Rows)
                        {
                            try
                            {
                                string szLine = "";
                                foreach (object cell in ResultRow.ItemArray)
                                {
                                    string szData = cell.ToString();
                                    if (szData == "")
                                    {
                                        szData = "NULL";
                                    }
                                    szLine = szLine + szData + ",";
                                }
                                szLine = szLine.TrimEnd(',');
                                csv.WriteLine(szLine);
                                iLineCount = iLineCount + 1;
                            }
                            catch (Exception exCSVWrite)
                            {
                                logger.Error(exCSVWrite, "Error writing CSV line");
                            }
                        }
                        logger.Info("Wrote {0} results for Taglist: {1} Year: {2} Month: {3}", iLineCount, iIndex, dtStart.Year, dtStart.Month);
                        csv.Close();
                    }
                    catch (Exception exCSV)
                    {
                        logger.Error(exCSV, "Error opening CSV");
                    }
                }
                sql_connection_results.Close();
            }
            SetProcessing(false);
        }
Пример #23
0
        void Log(LogItem item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (item.LogException != null)
            {
                switch (item.Level)
                {
                case LogLevel.Fatal:
                    _logger.FatalException(item.Text, item.LogException);
                    break;

                case LogLevel.Error:
                    _logger.ErrorException(item.Text, item.LogException);
                    break;

                case LogLevel.Warn:
                    _logger.WarnException(item.Text, item.LogException);
                    break;

                case LogLevel.Info:
                    _logger.InfoException(item.Text, item.LogException);
                    break;

                case LogLevel.Debug:
                    _logger.DebugException(item.Text, item.LogException);
                    break;

                default:
                    _logger.InfoException(item.Text, item.LogException);
                    break;
                }
            }
            else
            {
                switch (item.Level)
                {
                case LogLevel.Fatal:
                    _logger.Fatal(item.Text);
                    break;

                case LogLevel.Error:
                    _logger.Error(item.Text);
                    break;

                case LogLevel.Warn:
                    _logger.Warn(item.Text);
                    break;

                case LogLevel.Info:
                    _logger.Info(item.Text);
                    break;

                case LogLevel.Debug:
                    _logger.Debug(item.Text);
                    break;

                default:
                    _logger.Info(item.Text);
                    break;
                }
            }
        }
Пример #24
0
 public void Info(object message)
 {
     logger.Info(message);
 }
Пример #25
0
        private bool prepareStand(bool?chargeRelay, bool?dischargeRelay)
        {
            try
            {
                //РЕЛЕ ЗАРЯДА
                if (chargeRelay.HasValue)
                {
                    Log.Info("Turn {0} charge relay", (bool)chargeRelay ? "ON" : "OFF");
                    A02.SetDiscreteOutput(ChargeRelayChannelNo, (bool)chargeRelay);
                    Thread.Sleep(100);
                }

                //РЕЛЕ РАЗРЯДА
                if (dischargeRelay.HasValue)
                {
                    Log.Info("Turn {0} discharge relay", (bool)dischargeRelay ? "ON" : "OFF");
                    A02.SetDiscreteOutput(DischargeRelayChannelNo, (bool)dischargeRelay);
                    Thread.Sleep(100);
                }
            }
            catch (Exception e)
            {
                Log.Error(e, "{0} => preparation failure : {0}", TypeOfBattery, e.Message);
                return(false);
            }

            Log.Info("Stand preparation complete.");
            return(true);
        }
Пример #26
0
        public (bool finished, DirectoryInfo[] subDirs) CheckFolderForMovies([NotNull] DirectoryInfo di2, bool andGuess, bool fullLogging, bool showErrorMsgBox)
        {
            CurrentPhaseDirectory++;
            try
            {
                // ..and not already a folder for one of our shows
                string theFolder = di2.FullName.ToLower();
                foreach (var si in mDoc.FilmLibrary.Movies)
                {
                    if (RejectFolderIfIncludedInShow(fullLogging, si, theFolder))
                    {
                        return(true, null);
                    }
                } // for each showitem

                //We don't have it already
                DirectoryInfo[] subDirectories = GetValidDirectories(di2);

                //This is an indication that something is wrong
                if (subDirectories is null)
                {
                    return(false, null);
                }

                bool hasSubFolders = subDirectories.Length > 0;
                if (hasSubFolders)
                {
                    return(false, subDirectories);
                }

                if (TVSettings.Instance.BulkAddIgnoreRecycleBin && IsRecycleBin(di2))
                {
                    return(false, subDirectories);
                }

                List <FileInfo> films = FilmFiles(di2);
                if (TVSettings.Instance.BulkAddCompareNoVideoFolders && !films.Any())
                {
                    return(false, subDirectories);
                }
                if (!films.Any())
                {
                    Logger.Warn($"Checked {di2.FullName} and it had no movie files.");
                    if (!di2.GetFiles().Any() && !di2.GetDirectories().Any())
                    {
                        di2.Delete(false);
                    }
                }

                foreach (FileInfo newFilm in films)
                {
                    // ....its good!
                    Logger.Info("Adding {0} as a new folder", theFolder);
                    PossibleNewMovie ai = new PossibleNewMovie(newFilm, andGuess, showErrorMsgBox);
                    AddItems.AddIfNew(ai);
                }

                return(false, subDirectories);
            }
            catch (UnauthorizedAccessException)
            {
                Logger.Info("Can't access {0}, so ignoring it", di2.FullName);
                return(true, null);
            }
        }
Пример #27
0
        /// <summary>
        /// 执行dotnet Command命令
        /// </summary>
        /// <param name="projectPath"></param>
        /// <param name="fileName"></param>
        /// <param name="arguments"></param>
        /// <param name="logger"></param>
        /// <returns></returns>
        private static bool RunDotnetExternalExe(string projectPath, string fileName, string arguments, NLog.Logger logger)
        {
            Process process = null;

            try
            {
                try
                {
                    logger.Info(fileName + " " + arguments);
                }
                catch (Exception)
                {
                }
                if (string.IsNullOrEmpty(arguments))
                {
                    throw new ArgumentException(nameof(arguments));
                }

                //执行dotnet命令如果 projectdir路径含有空格 或者 outDir 路径含有空格 都是没有问题的

                process = new Process();

                process.StartInfo.WorkingDirectory       = projectPath;
                process.StartInfo.FileName               = fileName;
                process.StartInfo.Arguments              = arguments;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.Verb                   = "runas";
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.RedirectStandardOutput = true;



                process.Start();


                process.OutputDataReceived += (sender, args) =>
                {
                    if (!string.IsNullOrWhiteSpace(args.Data))
                    {
                        if (!args.Data.StartsWith(" ") && args.Data.Contains(": error"))
                        {
                            logger?.Warn(args.Data);
                        }
                        else if (args.Data.Contains(".csproj : error"))
                        {
                            logger?.Error(args.Data);
                        }
                        else
                        {
                            logger?.Info(args.Data);
                        }
                    }
                };
                process.BeginOutputReadLine();

                process.ErrorDataReceived += (sender, data) =>
                {
                    if (!string.IsNullOrWhiteSpace(data.Data))
                    {
                        logger?.Error(data.Data);
                    }
                };
                process.BeginErrorReadLine();

                process.WaitForExit();

                try
                {
                    process.Kill();
                }
                catch (Exception)
                {
                    //ignore
                }
                return(process.ExitCode == 0);
            }
            catch (Exception ex)
            {
                logger?.Error(ex.Message);
                return(false);
            }
            finally
            {
                process?.Dispose();
            }
        }
Пример #28
0
        public Recorder(RecorderView view)
        {
            this.view = view;
            view.recorder = this;

            /////////// Setup logger ///////////
            logger = NLog.LogManager.GetCurrentClassLogger();
            loggerWCF = NLog.LogManager.GetLogger("Capture.Recorder.WCF");

            /////////// Setup WCF notification to a BriefMaker ///////////
            briefMakerClient = new BriefMakerServiceReference.BriefMakerClient();

            /////////// Download Symbols ///////////
            try
            {
                logger.Debug("Downloading symbols");
                var dbSymbols = from s in dc.Symbols select s;

                foreach (var s in dbSymbols)
                {
                    if (String.IsNullOrWhiteSpace(s.Name))
                    {
                        logger.Error("SymbolID:" + s.SymbolID + " does not have a name(symbol). Item will be skipped.");
                        continue;
                    }
                    if (s.SymbolID > 255 || s.SymbolID < 0)
                    {
                        logger.Error("SymbolID:" + s.SymbolID + " range is not valid. Supported(0-255). Item will be skipped.");
                        continue;
                    }

                    SecurityType secType = s.Type.Trim() == "STK" ? SecurityType.Stock : SecurityType.Index;
                    string market = s.Market.Trim();

                    var new_symb = new MarketSymbol()
                    {
                        SymbolID = s.SymbolID,
                        Symbol = s.Name.Trim(),
                        securityType = s.Type.Trim() == "STK" ? SecurityType.Stock : SecurityType.Index,
                        Market = s.Market
                    };
                    symbols.Add(new_symb);
                }
            }
            catch (Exception ex)
            {
                logger.Error("Database Exception: " + ex.Message);
                logger.Error("Make sure that the connection string is set correctly in app.config.");
                Thread.Sleep(5000);
                ShutdownRecorder();
            }


            // Setup BinaryWriters
            logger.Debug("Downloading symbols");
            capturingWriter = new BinaryWriter(new MemoryStream(MemoryStreamReserveSpace));
            capturingWriter.Write((long)0);  // leave some space at the beginning for time later
            manufacturedWriterForFuture = new BinaryWriter(new MemoryStream(MemoryStreamReserveSpace));
            manufacturedWriterForFuture.Write((long)0);  // leave some space at the beginning for time later

            // Run this thread will a little higher priority since it is dealing with real-time information.
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
            // Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;

            view.timer.Tick += new EventHandler(timer1Sec_Tick);


            while (true)
            {
                TimeSpan timespan = new TimeSpan(DateTime.Now.Ticks - lastRecievedUpdate.Ticks);
                if (timespan.Seconds > 30)
                {
                    logger.Info("No Data received in over 30 seconds. Requesting Reconnect...");
                    lastRecievedUpdate = DateTime.Now;
                    ConnectToIB();
                }

                if (terminateRequested || (DateTime.Now.TimeOfDay > settings.ShutDownTime))
                {
                    logger.Info("Close requested or automatic end of day shutdown.");
                    ShutdownRecorder();
                    break;
                }

                view.BeginInvoke((MethodInvoker)delegate
                {
                    view.toolStripStatusLabelEventCt.Text = totalCaptureEventsForDisplay.ToString() + " (" + (totalCaptureEventsForDisplay - lastTotalCaptureEventsForDisplay).ToString() + "/sec)";  // runs on UI thread 
                    lastTotalCaptureEventsForDisplay = totalCaptureEventsForDisplay;
                    view.toolStripStatusLabelLastBrfID.Text = lastUpdateTime.ToString();
                });  // runs on UI thread 

                Thread.Sleep(1000);
            }
        }
Пример #29
0
        public void Configure(string ip = "127.0.0.1", string port = "8088")
        {
            _ip   = ip.Trim();
            _port = port.Trim();

            //_configured = true;
            _logger.Info("Configuring to {0}:{1}.", ip, port);
        }
Пример #30
0
 public void Info(string format, params object[] args)
 {
     _innerLogger.Info(format, args);
 }
Пример #31
0
 protected override void Initialize()
 {
     logger.Info("Server Network READY!!!");
 }
Пример #32
0
 public void StoreFastResume()
 {
     try
     {
         logger.Info("storing fast resume");
         BEncodedList list = new BEncodedList();
         foreach (Download t in Torrents)
         {
             list.Add(t.SaveFastResume().Encode());
         }
         File.WriteAllBytes(Defines.SerializedFastResume, list.Encode());
     }
     catch (Exception ex)
     {
         logger.Warn(string.Format("Couldn't store fast resume: {0}", ex));
     }
 }
Пример #33
0
        static void Main(string[] args)
        {
            logger.Info("Program started");

            try
            {
                Console.WriteLine("Would you like to view:");
                Console.WriteLine("1) Categories");
                Console.WriteLine("2) Products");
                Console.WriteLine("(Select 1 or 2)");
                string Selection = Console.ReadLine();

                if (Selection == "1")
                {
                    string choice;
                    do
                    {
                        Console.WriteLine("1) Display Categories");
                        Console.WriteLine("2) Add Category");
                        Console.WriteLine("3) Display Category and related products");
                        Console.WriteLine("4) Display all Categories and their related products");
                        Console.WriteLine("5) Edit a Category");
                        Console.WriteLine("6) Delete a Category");
                        Console.WriteLine("\"q\" to quit");
                        choice = Console.ReadLine();
                        Console.Clear();
                        logger.Info($"Selection {choice} selected");

                        if (choice == "1")
                        {
                            var db    = new NWConsole_96_EJBContext();
                            var query = db.Categories.OrderBy(p => p.CategoryName);

                            Console.ForegroundColor = ConsoleColor.Blue;
                            Console.WriteLine($"{query.Count()} records returned");
                            Console.ForegroundColor = ConsoleColor.Magenta;
                            foreach (var item in query)
                            {
                                Console.WriteLine($"{item.CategoryName} - {item.Description}");
                            }
                            Console.ForegroundColor = ConsoleColor.White;
                        }
                        else if (choice == "2")
                        {
                            logger.Info("User choice: 2 - Enter new Category");
                            try
                            {
                                var        db          = new NWConsole_96_EJBContext();
                                bool       nameChanged = true;
                                Categories category    = InputCategory(db);

                                Categories validCategory = ValidateCategoryName(db, category, nameChanged);
                                if (validCategory != null)
                                {
                                    db.AddCategory(validCategory);
                                    logger.Info("Category added - {name}", validCategory.CategoryName);
                                }
                            }
                            catch (Exception ex)
                            {
                                logger.Error(ex.Message);
                            }
                        }
                        else if (choice == "3")
                        {
                            logger.Info("User choice: 3 - Display category and related products");
                            var db    = new NWConsole_96_EJBContext();
                            var query = db.Categories.OrderBy(p => p.CategoryId);

                            Console.WriteLine("Select the category to display related products");
                            Console.ForegroundColor = ConsoleColor.DarkRed;
                            foreach (var item in query)
                            {
                                Console.WriteLine($"{item.CategoryId}) {item.CategoryName}");
                            }
                            Console.ForegroundColor = ConsoleColor.White;
                            int id = int.Parse(Console.ReadLine());
                            Console.Clear();
                            logger.Info($"CategoryId {id} selected");

                            Categories category = db.Categories.Include("Products").FirstOrDefault(c => c.CategoryId == id);
                            Console.WriteLine($"{category.CategoryName} - {category.Description}");

                            if (category.Products.Count() != 0)
                            {
                                foreach (Products p in category.Products.Where(p => !p.Discontinued))
                                {
                                    Console.WriteLine(p.ProductName);
                                }
                            }
                            else
                            {
                                Console.WriteLine("There are no products in this category.");
                            }
                        }
                        else if (choice == "4")
                        {
                            logger.Info("User choice: 4 - Display all categories and related active products.");
                            var db    = new NWConsole_96_EJBContext();
                            var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId);
                            foreach (var item in query)
                            {
                                Console.WriteLine($"{item.CategoryName}");
                                foreach (Products p in item.Products.Where(p => !p.Discontinued))
                                {
                                    Console.WriteLine($"\t{p.ProductName}");
                                }
                            }
                        }
                        else if (choice == "5")
                        {
                            logger.Info("User choice: 5 - Edit Category");
                            Console.WriteLine("Choose the category to edit:");
                            var db       = new NWConsole_96_EJBContext();
                            var category = GetCategory(db);
                            if (category != null)
                            {
                                Categories UpdatedCategory = InputCategory(db);
                                UpdatedCategory.CategoryId = category.CategoryId;
                                bool       editing = !category.CategoryName.Equals(UpdatedCategory.CategoryName);
                                Categories ValidUpdatedCategory = ValidateCategoryName(db, UpdatedCategory, editing);
                                if (ValidUpdatedCategory != null)
                                {
                                    db.EditCategory(ValidUpdatedCategory);
                                    logger.Info($"Category (id: {category.CategoryId}) updated.");
                                }
                            }
                        }
                        else if (choice == "6")
                        {
                            logger.Info("User choice: 6 - Delete Category");
                            Console.WriteLine("Select the category to delete");
                            var db       = new NWConsole_96_EJBContext();
                            var category = GetCategory(db);
                            if (category != null)
                            {
                                var products = db.Products.Where(p => p.CategoryId == category.CategoryId);

                                if (products.Count() == 0)
                                {
                                    db.DeleteCategory(category);
                                    logger.Info($"Category (id: {category.CategoryId}) deleted.");
                                }
                                else
                                {
                                    logger.Error("Cannot delete category with products in it. To delete the category, first remove any products.");
                                }
                            }
                        }
                        Console.WriteLine();
                    } while (choice.ToLower() != "q");
                }
                else if (Selection == "2")
                {
                    logger.Info("User choice: 2 - Products");

                    string choice;
                    do
                    {
                        Console.WriteLine("1) Display Products: ");
                        Console.WriteLine("2) Add Product: ");
                        Console.WriteLine("3) Edit Product: ");
                        Console.WriteLine("4) Delete Product: ");
                        Console.WriteLine("\"q\" to quit");
                        choice = Console.ReadLine();
                        Console.Clear();
                        logger.Info($"Selection {choice} selected");

                        if (choice == "1")
                        {
                            logger.Info("User choice: 1 - Display Products");
                            var db = new NWConsole_96_EJBContext();

                            Console.WriteLine("1) Display Active Products: ");
                            Console.WriteLine("2) Display Discontinued Products: ");
                            Console.WriteLine("3) Display All Products: ");
                            Console.WriteLine("4) Display Specific Product Information: ");
                            string input = Console.ReadLine();

                            if (input == "1")
                            {
                                logger.Info("User choice: 1 - Display active products");
                                var activeQuery = db.Products.OrderBy(p => p.ProductName).Where(p => !p.Discontinued);
                                Console.WriteLine($"Number of Active Products: {activeQuery.Count()}");

                                if (activeQuery.Count() != 0)
                                {
                                    foreach (var product in activeQuery)
                                    {
                                        Console.WriteLine(product.ProductName);
                                    }
                                    Console.WriteLine();
                                }
                                else
                                {
                                    logger.Info("No active products");
                                    Console.WriteLine("There are no active products");
                                }
                            }
                            else if (input == "2")
                            {
                                logger.Info("User choice: 2 - Display discontinued prodcuts");
                                var discontinuedQuery = db.Products.OrderBy(p => p.ProductName).Where(p => p.Discontinued);
                                Console.WriteLine($"Number of Discontinued Products: {discontinuedQuery.Count()}");

                                Console.ForegroundColor = ConsoleColor.Red;
                                if (discontinuedQuery.Count() != 0)
                                {
                                    foreach (var product in discontinuedQuery)
                                    {
                                        Console.WriteLine(product.ProductName);
                                    }
                                    Console.WriteLine();
                                    Console.ForegroundColor = ConsoleColor.White;
                                }
                                else
                                {
                                    logger.Info("No discontinued products");
                                }
                            }
                            else if (input == "3")
                            {
                                logger.Info("User choice: 3 - Display all products");
                                var activeQuery       = db.Products.OrderBy(p => p.ProductName).Where(p => !p.Discontinued);
                                var discontinuedQuery = db.Products.OrderBy(p => p.ProductName).Where(p => p.Discontinued);

                                Console.WriteLine("Active Products: ");
                                foreach (var product in activeQuery)
                                {
                                    Console.WriteLine($"\t{product.ProductName}");
                                }
                                Console.WriteLine($"Total Active Products: {activeQuery.Count()}");

                                Console.WriteLine("Discontinued Products:");
                                foreach (var product in discontinuedQuery)
                                {
                                    Console.WriteLine($"\t{product.ProductName}");
                                }
                                Console.WriteLine($"Total Discontinued Products: {discontinuedQuery.Count()}");
                            }
                            else if (input == "4")
                            {
                                logger.Info("User choice 4: Display specific product information");
                                Console.WriteLine("Select a product to display");
                                var product = GetProduct(db);

                                if (product != null)
                                {
                                    var    isActive = product.Discontinued;
                                    string status;
                                    if (isActive)
                                    {
                                        status = "true";
                                    }
                                    else
                                    {
                                        status = "false";
                                    }
                                    Console.WriteLine($"Product Id: {product.ProductId}\nProduct name: {product.ProductName}\nSupplier Id: {product.SupplierId}\nCategory Id: {product.CategoryId}\nQuantity Per Unit: {product.QuantityPerUnit}\nUnit Price: {product.UnitPrice:C2}\nUnits in Stock: {product.UnitsInStock}\nUnits on Order: {product.UnitsOnOrder}\nReorder Level: {product.ReorderLevel}\nDiscontinued: {status}\n");
                                }
                                else
                                {
                                    logger.Error("No product");
                                }
                            }
                            else
                            {
                                logger.Error("Invalid Choice");
                            }
                        }
                        else if (choice == "2")
                        {
                            logger.Info("User choice: 2 - Add product");
                            try
                            {
                                var      db           = new NWConsole_96_EJBContext();
                                Products product      = InputProduct(db);
                                bool     nameChanged  = true;
                                Products validProduct = ValidateProductName(db, product, nameChanged);
                                if (validProduct != null)
                                {
                                    db.AddProduct(validProduct);
                                    logger.Info("Product added - {name}", validProduct.ProductName);
                                }
                            }
                            catch (Exception ex)
                            {
                                logger.Error(ex.Message);
                            }
                        }
                        else if (choice == "3")
                        {
                            logger.Info("User choice: 3 - Edit product");
                            Console.WriteLine("Select a product to edit");
                            var db      = new NWConsole_96_EJBContext();
                            var product = GetProduct(db);
                            if (product != null)
                            {
                                Products UpdatedProduct = InputProduct(db);
                                UpdatedProduct.ProductId = product.ProductId;
                                bool     nameChanged         = !product.ProductName.Equals(UpdatedProduct.ProductName);
                                Products ValidUpdatedProduct = ValidateProductName(db, UpdatedProduct, nameChanged);
                                if (ValidUpdatedProduct != null)
                                {
                                    db.EditProduct(ValidUpdatedProduct);
                                    logger.Info($"Product (id: {product.ProductId}) updated.");
                                }
                            }
                        }
                        else if (choice == "4")
                        {
                            logger.Info("User choice: 4 - Delete product");
                            Console.WriteLine("Select a product to delete");
                            var db      = new NWConsole_96_EJBContext();
                            var product = GetProduct(db);

                            if (product != null)
                            {
                                var orderDetails = db.OrderDetails.Where(o => o.ProductId == product.ProductId);
                                if (orderDetails.Count() != 0)
                                {
                                    logger.Error("Cannot delete product where order exists.");
                                }
                                else
                                {
                                    db.DeleteProduct(product);
                                    logger.Info($"Product (id: {product.ProductId}) deleted.");
                                }
                            }
                        }
                    }while (choice.ToLower() != "q");
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }

            logger.Info("Program ended");
        }