Exemplo n.º 1
0
        public async Task <int> Create(PostCreateViewModel viewModel)
        {
            StringBuilder permalinkBuilder = new StringBuilder();

            Post post = new Post();

            permalinkBuilder.Append(PermalinkHelper.GenerateSlug(viewModel.Title));

            int countPermalinks = _postRepository.GetPermalinks(permalinkBuilder.ToString());

            if (countPermalinks > 0)
            {
                permalinkBuilder.Append($"-{countPermalinks}");
            }

            post.Permalink     = permalinkBuilder.ToString();
            post.Title         = viewModel.Title;
            post.Text          = viewModel.Text;
            post.Summary       = SummaryHelper.GetWords(viewModel.Text, numberOfWords);
            post.DatePublished = viewModel.DatePublished;
            post.DateUpdated   = DateTime.Now;
            post.ImageBase64   = viewModel.ImageBase64;
            await _postRepository.Save(post);

            return(post.Id);
        }
Exemplo n.º 2
0
        private CancellationTokenSource m_cancellationTokenSource; // For cancelling thread awaiting rider start



        public MainForm(IServiceProvider serviceProvider, IConfiguration configuration, ZPMonitorService zpMonitorService, ILoggerFactory loggerFactory)
        {
            m_logger           = loggerFactory.CreateLogger <MainForm>();;
            m_serviceProvider  = serviceProvider;
            m_zpMonitorService = zpMonitorService;
            m_loggerFactory    = loggerFactory;

            m_maCollection  = new Dictionary <DurationType, MovingAverageWrapper>();
            m_summaryHelper = new SummaryHelper(new SummaryListViewItem(new SummaryItem()));
            //m_labelUnits = new Dictionary<string, string>();

            //m_labelHelpers = new List<LabelHelper>();

            m_normalizedPower = new NormalizedPower(zpMonitorService, loggerFactory);
            m_normalizedPower.NormalizedPowerChangedEvent += NormalizedPowerChangedEventHandler;
            m_normalizedPower.MetricsChangedEvent         += MetricsChangedEventHandler;

            InitializeComponent();

            // This rounds the edges of the borderless window
            this.Region = System.Drawing.Region.FromHrgn(ZAMsettings.CreateRoundRectRgn(0, 0, Width, Height, 15, 15));
            btnClose.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); //transparent

            //MainForm.colorListViewHeader(ref lvViewer, lvViewer.BackColor, Color.White); // transparent ListView headers
            //MainForm.colorListViewHeader(ref lvOverall, lvOverall.BackColor, Color.White); // transparent ListView headers
            SetListViewHeaderColor(ref lvViewer, Color.FromArgb(255, 243, 108, 61), Color.White);  // Orange ListView headers
            SetListViewHeaderColor(ref lvOverall, Color.FromArgb(255, 243, 108, 61), Color.White); // Orange ListView headers
        }
Exemplo n.º 3
0
        public MainViewControl()
        {
            InitializeComponent();

            this.refreshTimer.Interval = 1000;
            this.refreshTimer.Tick    += new System.EventHandler(this.refreshTimer_Tick);

            m_summaryHelper = new SummaryHelper(new SummaryListViewItem(new SummaryItem()));
            m_maCollection  = new Dictionary <DurationType, MovingAverageWrapper>();

            UserControlBase.SetListViewHeaderColor(ref this.lvViewer, Color.FromArgb(255, 243, 108, 61), Color.White);  // Orange ListView headers
            UserControlBase.SetListViewHeaderColor(ref this.lvOverall, Color.FromArgb(255, 243, 108, 61), Color.White); // Orange ListView headers
        }
Exemplo n.º 4
0
        private static async Task <ContentObject> LoadPageScript(SiteObject site, Stream stream, FileEntry file)
        {
            // Read the stream
            var reader  = new StreamReader(stream);
            var content = await reader.ReadToEndAsync();

            // Early dispose the stream
            stream.Dispose();

            ContentObject page = null;

            // Parse the page, using front-matter mode
            var scriptInstance = site.Scripts.ParseScript(content, file.FullName, ScriptMode.FrontMatterAndContent);

            if (!scriptInstance.HasErrors)
            {
                page = new ContentObject(site, file, scriptInstance);

                var evalClock = Stopwatch.StartNew();
                if (site.Content.TryPreparePage(page))
                {
                    evalClock.Stop();

                    // Update statistics
                    var contentStat = site.Statistics.GetContentStat(page);

                    contentStat.EvaluateTime += evalClock.Elapsed;

                    // Update the summary of the page
                    evalClock.Restart();
                    SummaryHelper.UpdateSummary(page);
                    evalClock.Stop();

                    // Update statistics
                    contentStat.SummaryTime += evalClock.Elapsed;
                }
            }

            return(page);
        }
Exemplo n.º 5
0
        private static async Task LoadLogicAsync(Config config, State state)
        {
            var backlog = new BlockingCollection <Request>();
            var tasks   = GenerateTasks(backlog, config.System.MinTasks.Value).ToList();

            while (!state.Shutdown)
            {
                var data      = GenerateTimedData(config.Load.Requests.Value, state.NumTicks, state.Noise);
                var startTime = DateTime.Now;

                for (int tickIndex = 0; tickIndex < data.Count; tickIndex++)
                {
                    var timeBetweenRequests = 1 / ((float)data[tickIndex] / config.Noise.Resolution.Value);

                    var currentIterationTime = startTime.AddSeconds(tickIndex * config.Noise.Resolution.Value);
                    var nextIterationTime    = startTime.AddSeconds((tickIndex + 1) * config.Noise.Resolution.Value);

                    int taskDelta = ManageTasks(data[tickIndex], config.System.MinTasks.Value, config.System.MaxTasks.Value, backlog, tasks);

                    SummaryHelper.WriteTickSummary(
                        data[tickIndex], backlog, tasks, currentIterationTime,
                        nextIterationTime, taskDelta, DateTime.Now, config.System.NoStats.Value);

                    for (int i = 0; i < data[tickIndex]; i++)
                    {
                        backlog.Add(new Request(currentIterationTime.AddSeconds(timeBetweenRequests * i), state.Plugins));
                    }

                    // Task.Delay will wait for X amount of milliseconds but its constraint by the systems clock resolution,
                    // which according to the MSDN documentation is about 15 milliseconds. Having the call be 15ms late is a
                    // good tradeoff since we don't need to actively way and we have cancellationtoken capabilities.
                    int delay = (int)(nextIterationTime - DateTime.Now).TotalMilliseconds;

                    if (delay > 0)
                    {
                        try
                        {
                            await Task.Delay(delay, state.CancelSource.Token);
                        }
                        catch (OperationCanceledException)
                        {
                            break;
                        }
                    }

                    if (state.Shutdown)
                    {
                        break;
                    }
                }

                if (!config.Load.Infinite.Value)
                {
                    break;
                }
            }

            // Cleanup and wait for cancellation
            {
                backlog.CompleteAdding();

                foreach (var task in tasks)
                {
                    task.Token.Cancel();
                }

                Task.WaitAll(tasks.Select(t => t.Task).ToArray());
            }
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            string configFile = "config.json";

            // Initial config file environment / argument check
            {
                configFile = ConfigHelper.GetEnvironmentStr("XLOAD_CONFIG", configFile);
                configFile = ConfigHelper.GetStrFromArgs(args, "-config", configFile);

                if (!File.Exists(configFile))
                {
                    Console.WriteLine("[ERROR] Config file not found! Aborting...");
                    return;
                }
            }

            var configuration = new ConfigurationBuilder()
                                .AddJsonFile(configFile)
                                .Build();

            var config = configuration
                         .GetSection("XLoad")
                         .Get <Config>();

            // Improve this for plugins (issues with references on IConfiguration)
            var jsonconfig = JsonConvert.DeserializeObject <JToken>(File.ReadAllText(configFile));

            // Environment variables argument parsing
            {
                config.Noise.Scale      = ConfigHelper.GetEnvironmentFloat("XLOAD_SCALE", config.Noise.Scale);
                config.Noise.Seed       = ConfigHelper.GetEnvironmentInt("XLOAD_SEED", config.Noise.Seed);
                config.Noise.Resolution = ConfigHelper.GetEnvironmentInt("XLOAD_RESOLUTION", config.Noise.Resolution);
                config.Load.Time        = ConfigHelper.GetEnvironmentInt("XLOAD_TIME", config.Load.Time);
                config.Load.Requests    = ConfigHelper.GetEnvironmentInt("XLOAD_REQUESTS", config.Load.Requests);
                config.Load.Infinite    = ConfigHelper.GetEnvironmentBool("XLOAD_INFINITE", config.Load.Infinite);
                config.System.MaxTasks  = ConfigHelper.GetEnvironmentInt("XLOAD_MAXTASKS", config.System.MaxTasks);
                config.System.MinTasks  = ConfigHelper.GetEnvironmentInt("XLOAD_MINTASKS", config.System.MinTasks);
                config.System.DryRun    = ConfigHelper.GetEnvironmentBool("XLOAD_DRYRUN", config.System.DryRun);
                config.System.NoStats   = ConfigHelper.GetEnvironmentBool("XLOAD_NOSTATS", config.System.NoStats);
                config.Diagnostic.Image = ConfigHelper.GetEnvironmentStr("XLOAD_IMAGE", config.Diagnostic.Image);
            }

            // Command line argument parsing
            {
                config.Noise.Scale      = ConfigHelper.GetFloatFromArgs(args, "-scale", config.Noise.Scale);
                config.Noise.Seed       = ConfigHelper.GetIntFromArgs(args, "-seed", config.Noise.Seed);
                config.Noise.Resolution = ConfigHelper.GetIntFromArgs(args, "-resolution", config.Noise.Resolution);
                config.Load.Time        = ConfigHelper.GetIntFromArgs(args, "-time", config.Load.Time);
                config.Load.Requests    = ConfigHelper.GetIntFromArgs(args, "-requests", config.Load.Requests);
                config.Load.Infinite    = ConfigHelper.GetBoolFromArgs(args, "-infinite", config.Load.Infinite);
                config.System.MaxTasks  = ConfigHelper.GetIntFromArgs(args, "-maxTasks", config.System.MaxTasks);
                config.System.MinTasks  = ConfigHelper.GetIntFromArgs(args, "-minTasks", config.System.MinTasks);
                config.System.DryRun    = ConfigHelper.GetBoolFromArgs(args, "-dryrun", config.System.DryRun);
                config.System.NoStats   = ConfigHelper.GetBoolFromArgs(args, "-nostats", config.System.NoStats);
                config.Diagnostic.Image = ConfigHelper.GetStrFromArgs(args, "-image", config.Diagnostic.Image);
            }

            // Validate configs & apply defaults
            {
                if (config.Noise.Scale == null)
                {
                    Console.WriteLine("[ERROR] Scale configuration not found! Aborting..."); return;
                }
                if (config.Noise.Seed == null)
                {
                    Console.WriteLine("[ERROR] Seed configuration not found! Aborting..."); return;
                }
                if (config.Noise.Resolution == null)
                {
                    Console.WriteLine("[ERROR] Resolution configuration not found! Aborting..."); return;
                }
                if (config.Load.Time == null)
                {
                    Console.WriteLine("[ERROR] Time configuration not found! Aborting..."); return;
                }
                if (config.Load.Requests == null)
                {
                    Console.WriteLine("[ERROR] Requests configuration not found! Aborting..."); return;
                }

                if (config.System.MaxTasks == null)
                {
                    config.System.MaxTasks = int.MaxValue;
                }
                if (config.System.MaxTasks < 1)
                {
                    config.System.MaxTasks = int.MaxValue;
                }
                if (config.System.MinTasks == null)
                {
                    config.System.MinTasks = 1;
                }
                if (config.System.MinTasks < 1)
                {
                    config.System.MinTasks = 1;
                }

                if (config.System.DryRun == null)
                {
                    config.System.DryRun = false;
                }
                if (config.System.NoStats == null)
                {
                    config.System.NoStats = false;
                }
                if (config.Load.Infinite == null)
                {
                    config.Load.Infinite = false;
                }

                if (config.Noise.Resolution > config.Load.Time)
                {
                    Console.WriteLine("[ERROR] Resolution needs to be smaller than Time! Aborting...");
                    return;
                }

                if (config.System.MaxTasks < config.System.MinTasks)
                {
                    Console.WriteLine("[ERROR] MinTasks must be smaller than MaxTasks! Aborting...");
                    return;
                }
            }

            var state = new State()
            {
                Noise        = new Noise(config.Noise.Seed.Value, config.Noise.Scale.Value),
                NumTicks     = config.Load.Time.Value / config.Noise.Resolution.Value,
                Shutdown     = false,
                CancelSource = new CancellationTokenSource(),
                Plugins      = new List <IPlugin>()
            };

            // Check plugins
            {
                foreach (var item in config.System.Plugins)
                {
                    var pluginFile = Directory
                                     .EnumerateFiles(Directory.GetCurrentDirectory(), item.Name + ".dll", SearchOption.AllDirectories)
                                     .FirstOrDefault();

                    var configJson = jsonconfig
                                     .Children()
                                     .Select(c => (JProperty)c)
                                     .FirstOrDefault(c => c.Name == item.Config)
                                     .Value;

                    var pluginConfig   = configuration.GetSection(item.Config);
                    var pluginAssembly = PluginLoader.LoadPlugin(pluginFile);
                    var pluginObject   = PluginLoader.GetPluginFromAssembly(pluginAssembly);

                    pluginObject.Initialize(JsonConvert.SerializeObject(configJson));

                    state.Plugins.Add(pluginObject);
                }
            }

            // Diagnostic Data
            {
                var sample = GenerateTimedData(config.Load.Requests.Value, state.NumTicks, state.Noise);

                ImageHelper.WriteImage(config, sample);
                SummaryHelper.WriteSummary(args, config, state.NumTicks, sample);

                state.Noise.Reset();

                if (config.System.DryRun.Value)
                {
                    return;
                }
            }

            // Setup graceful shutdown https://github.com/aspnet/Hosting/issues/870#issuecomment-257435212
            {
                Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) =>
                {
                    Console.WriteLine();

                    if (!state.Shutdown)
                    {
                        Console.WriteLine($"[{DateTime.Now}] Attempting graceful shutdown");

                        e.Cancel       = true;
                        state.Shutdown = true;
                        state.CancelSource.Cancel();
                    }
                    else
                    {
                        Console.WriteLine($"[{DateTime.Now}] Forcing shutdown");
                    }
                };
            }

            Console.WriteLine($"{Environment.NewLine}[{DateTime.Now}] Starting up");

            // Start running
            {
                Task.Factory
                .StartNew(
                    () => LoadLogicAsync(config, state).Wait(),
                    TaskCreationOptions.LongRunning)
                .Wait();
            }

            Console.WriteLine($"[{DateTime.Now}] Shutdown complete");
        }
        public List <SummaryCategoryViewModel> GetSummaryCategories(string summaryType)
        {
            List <SummaryCategoryViewModel> result = new List <SummaryCategoryViewModel>();

            List <string> categoryNames = null;
            Dictionary <string, List <string> > summaryLabelMap = null;

            using (var summaryMappingManager = new SummaryMappingManager())
            {
                categoryNames   = summaryMappingManager.GetAllCategoryNamesBySummaryType(summaryType);
                summaryLabelMap = summaryMappingManager.GetSummaryLabelMapBySummaryType(summaryType);
            }

            if (categoryNames == null)
            {
                return(result);
            }

            foreach (var summaryCategoryName in categoryNames)
            {
                SummaryCategoryViewModel sumCategoryViewModel = new SummaryCategoryViewModel(summaryCategoryName);

                if (summaryCategoryName.Contains("Gastrointestinal Health"))
                {
                    sumCategoryViewModel.Highlight = true;
                }

                foreach (var summary in Participant.Summaries)
                {
                    if (summary != null && summary.PHSEventID.Equals(Event.PHSEventID))
                    {
                        if (SummaryHelper.IsFieldNameAndCategoryFoundInSummaryMap(summaryLabelMap, summaryCategoryName, summary.Label))
                        {
                            if (summary.SummaryValue == null || summary.SummaryValue.Count() <= 0)
                            {
                                continue;
                            }

                            SummaryViewModel sumview = new SummaryViewModel(summary);

                            if (sumCategoryViewModel.Highlight != true)
                            {
                                // summary.TemplateFieldID;
                                if (SummaryHelper.IsHighlightCategoryRequired(summaryCategoryName, summary.TemplateField.SummaryFieldName, summary.SummaryValue))
                                {
                                    sumCategoryViewModel.Highlight = true;
                                }
                            }


                            if (summary.StandardReferenceID != null && summary.StandardReferenceID > 0 &&
                                summary.SummaryValue != null)
                            {
                                if (SummaryHelper.IsJson(summary.SummaryValue))
                                {
                                    //if (summary.StandardReferenceID == 1) //Systolic Blood Pressure
                                    //{
                                    //    sumview.SummaryValue = summary.SummaryValue;
                                    //    sumview.SummaryInnerValue = summary.SummaryValue;
                                    //}else if (summary.StandardReferenceID == 2) //Diastolic Blood Pressure
                                    //{
                                    //        sumview.SummaryValue = summary.SummaryValue;
                                    //        sumview.SummaryInnerValue = summary.SummaryValue;
                                    //}else if (summary.StandardReferenceID == 3) //Sugar
                                    //{
                                    //    sumview.SummaryValue = summary.SummaryValue;
                                    //    sumview.SummaryInnerValue = summary.SummaryValue;
                                    //}else

                                    if (summary.StandardReferenceID == 4) //BMI
                                    {
                                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                                        BMIViewModel         bmi        = serializer.Deserialize <BMIViewModel>(summary.SummaryValue as string);
                                        if (bmi.BodyMassIndex != null)
                                        {
                                            //Weight: 50, Height: 180, BodyMassIndex: 15.43  (UNDERWEIGHT)
                                            sumview.SummaryValue      = "Weight: " + bmi.Weight + ", Height: " + bmi.Height + ", BodyMassIndex: " + bmi.BodyMassIndex;
                                            sumview.SummaryInnerValue = bmi.BodyMassIndex;
                                        }
                                    }
                                }
                                else
                                {
                                    sumview.SummaryInnerValue = summary.SummaryValue;
                                }

                                ReferenceRange referenceRange = null;

                                using (var StandardReferenceManager = new StandardReferenceManager())
                                {
                                    string message = string.Empty;
                                    referenceRange = StandardReferenceManager.GetReferenceRange(summary.StandardReferenceID.GetValueOrDefault(),
                                                                                                sumview.SummaryInnerValue, out message);
                                }

                                if (referenceRange != null)
                                {
                                    sumview.Result    = referenceRange.Result;
                                    sumview.Highlight = referenceRange.Highlight;
                                }
                            }

                            if (sumview != null)
                            {
                                sumCategoryViewModel.AddSummary(sumview);
                            }
                        }
                    }
                }

                result.Add(sumCategoryViewModel);
            }

            return(result);
        }