Example #1
0
        public async Task <IActionResult> Post([FromBody] Website data)
        {
            MonitorAPI.Data.Website Website = new Data.Website();
            var website = new Website();

            website.Link      = data.Link;
            website.Word      = data.Word;
            website.TimeStamp = DateTime.Now.ToString("dd-MM-yyyyTHH:mm:sszzz");

            if (Website.GetStatus(website.Link, website.Word))
            {
                website.Status = true;
            }
            else
            {
                website.Status = false;
            }

            using (var db = new MonitorContext())
            {
                db.Websites.Add(website);
                await db.SaveChangesAsync();
            }

            return(CreatedAtAction("GetWebsite", new { id = website.Id }, website));
        }
 public MonitorController(ILogger <MonitorController> logger, IMonitorPingService monitorPingService, INetStatsService netStatsService, MonitorContext monitorContext)
 {
     _logger             = logger;
     _monitorPingService = monitorPingService;
     _netStatsService    = netStatsService;
     _monitorContext     = monitorContext;
 }
Example #3
0
 /// <summary>
 /// Gets the services from the database.
 /// </summary>
 /// <returns>The services out of the database.</returns>
 private static List <Service> GetServices()
 {
     using (var context = new MonitorContext())
     {
         return(context.Services.ToList());
     }
 }
Example #4
0
        /// <summary>
        /// Method called when a new message is in.
        /// </summary>
        /// <param name="sender">The object which sent the message.</param>
        /// <param name="e">The arguments containing the message.</param>
        private static void IsAuthenticatedOnReceived(object sender, BasicDeliverEventArgs e)
        {
            var body  = e.Body;
            var token = Encoding.UTF8.GetString(body);


            Log.Information("Checking authentication for token \"{Token}\"", token);

            Service service;

            // Check if it exists in the database.
            using (var context = new MonitorContext())
            {
                service = context.Services.FirstOrDefault(x => x.Token == token);
            }

            var isAuthenticatedMessage = new IsAuthenticatedMessage
            {
                CorrelationId = e.BasicProperties.MessageId, IsAuthenticated = service != null, Service = service
            };

            // Send back a JSON message with the authentication status.
            var json = JsonConvert.SerializeObject(isAuthenticatedMessage);

            _authProducer.SendMessage(json);
        }
Example #5
0
        public async Task <IActionResult> Post([FromBody] Service data)
        {
            MonitorAPI.Data.Service Service = new Data.Service();
            var service = new Service();

            service.Link      = data.Link;
            service.TimeStamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz");

            if (Service.GetStatus(service.Link))
            {
                service.Status = true;
            }
            else
            {
                service.Status = false;
            }

            using (var db = new MonitorContext())
            {
                db.Services.Add(service);
                await db.SaveChangesAsync();
            }

            return(CreatedAtAction("GetService", new { id = service.Id }, service));
        }
Example #6
0
        public static void Main(string[] args)
        {
            string[] newArgs = new string[args.Length + 1];

            IConfigurationRoot config = new ConfigurationBuilder()
                                        .AddJsonFile("appsettings.json", optional: false)
                                        .Build();
            string urlString = config.GetSection("APIUrl").Value;

            newArgs[0] = urlString;                                // set the prepended value
            Array.Copy(args, 0, newArgs, 1, args.Length);
            IWebHost host = CreateWebHostBuilder(newArgs).Build();

            using (IServiceScope scope = host.Services.CreateScope())
            {
                IServiceProvider services = scope.ServiceProvider;
                try
                {
                    MonitorContext context = services.GetRequiredService <MonitorContext>();
                    DbInitializer.Initialize(context);
                }
                catch (Exception ex)
                {
                    ILogger <Program> logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred while seeding the database.");
                }
            }
            host.Run();
        }
Example #7
0
        public MarketViewModel(MonitorContext context)
        {
            Context = context;
            Context.Products.Load();
            Context.Product.Load();
            Context.Markets.Load();
            if (Context.Markets.Count() == 0)
            {
                this.Fill();
            }

            DispatcherTimer timer = new DispatcherTimer();

            timer          = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 20, 0);
            timer.Tick    += new EventHandler(this.DBUpdate);
            User           = new User
            {
                LastUpdate = Properties.Settings.Default.LastUpdate
            };
            Notify = new Notification();
            // Start the timer.
            timer.Start();
            try
            {
                GoogleApi api = new GoogleApi(Properties.Settings.Default.Token);
                User.Email = api.GetEmailPlus();
            }
            catch
            {
            }
        }
Example #8
0
        public async Task <IActionResult> Put(int id, Service data)
        {
            using (var db = new MonitorContext())
            {
                var service = db.Services.SingleOrDefault(s => s.Id == id);

                if (service == null)
                {
                    return(NotFound());
                }

                service.TimeStamp = DateTime.Now.ToString("dd-MM-yyyyTHH:mm:sszzz");
                service.Link      = data.Link;

                MonitorAPI.Data.Service tester = new Data.Service();
                if (tester.GetStatus(service.Link))
                {
                    service.Status = true;
                }
                else
                {
                    service.Status = false;
                }

                db.Services.Update(service);
                await db.SaveChangesAsync();

                return(Ok(service));
            }
        }
Example #9
0
        public async Task <IActionResult> Put(int id, Website data)
        {
            using (var db = new MonitorContext())
            {
                var website = db.Websites.SingleOrDefault(s => s.Id == id);

                if (website == null)
                {
                    return(NotFound());
                }

                website.Word      = data.Word;
                website.TimeStamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz");

                MonitorAPI.Data.Website tester = new Data.Website();
                if (tester.GetStatus(website.Link, website.Word))
                {
                    website.Status = true;
                }
                else
                {
                    website.Status = false;
                }

                db.Websites.Update(website);
                await db.SaveChangesAsync();

                return(Ok(website));
            }
        }
Example #10
0
        public MarshallCPU(TextWriter outputChan, TextReader inputChan)
        {
            this.outputChan = outputChan;
            this.inputChan  = inputChan;

            if (this.outputChan != null)
            {
                this.outputChan.NewLine = CRLF;
            }

            core = new UserModeCore(false);

            cpu = new SimhPDP10CPU(core, OSTypes.Tops10)
            {
                ProcessorType = ProcessorTypes.KL10
            };

            tops10 = new MonitorContext(cpu);

            tops10.TTCALL.ConsoleOutput += TTCALL_ConsoleOutput;
            tops10.TTCALL.AttachToConsole();

            cpu.ProcFlags = 0;
            cpu.SetUserMode();

            parser = new SimpleParser {
                CPU = cpu
            };
        }
Example #11
0
 /// <summary>
 /// Saves the service to the database.
 /// </summary>
 /// <param name="service">The service object wanting to be saved.</param>
 private static void SaveService(Service service)
 {
     Log.Information("Creating new service for {applicationId}", service.ApplicationId);
     using (var context = new MonitorContext())
     {
         context.Services.Add(service);
         context.SaveChanges();
     }
 }
Example #12
0
        public MonController(MonitorContext context)
        {
            _context = context;

            if (_context.MonitorItems.Count() == 0)
            {
                _context.MonitorItems.Add(new MonitorItem {
                    ClientID = "INIT ENTRY"
                });
                _context.SaveChanges();
            }
        }
Example #13
0
        public void Intercept(IInvocation invocation)
        {
            var  methodName = invocation.Method.Name;
            bool skip       = methodName == "OpenSession" || methodName == "GetShardParams" || methodName == "CreateSpecification";

            if (!skip && (methodName == "GetList" || methodName == "Get"))
            {
                var arguments = invocation.Method.GetParameters();
                skip = arguments.Length != 2 || arguments[0].ParameterType != typeof(ShardParams);
            }
            if (!skip)
            {
                ProfilerContext.BeginWatch(invocation.TargetType.FullName + "." + invocation.Method.Name);
            }

            try
            {
                var entityType = ReflectionHelper.GetEntityTypeFromRepositoryType(invocation.TargetType);
                var metadata   = RepositoryFramework.GetDefineMetadata(entityType);

                if (metadata != null)
                {
                    var mi = invocations.FirstOrDefault(o => o.IsMatch(invocation));
                    if (mi != null)
                    {
                        mi.Process(invocation, metadata);
                        ProxyEntity(invocation);
                        return;
                    }
                }
                if (skip)
                {
                    invocation.Proceed();
                }
                else
                {
                    using (MonitorContext.Repository(invocation.Method))
                        invocation.Proceed();
                }

                ProxyEntity(invocation);
            }
            finally
            {
                if (!skip)
                {
                    ProfilerContext.EndWatch();
                }
            }
        }
Example #14
0
        public MainWindow()
        {
            InitializeComponent();
            main = this;
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges <MonitorContext>());

            Context = new MonitorContext();
            if (Context == null)
            {
                Database.SetInitializer(new DropCreateDatabaseAlways <MonitorContext>()); //  to recreate database
            }

            ProductsTab.DataContext = new MarketViewModel(Context);
        }
Example #15
0
        public static void Main(string[] args)
        {
            //MonitorContext _context;
            Settings settings = null;

            settings = ConfigHelper.GetSettings();                         //получаю настройки из конфигурации
            string connection       = ConfigHelper.GetDefaultConnection(); //получаю строку подключения из конфигурации
            var    dbContextOptions = new DbContextOptionsBuilder <MonitorContext>()
                                      .UseSqlite(connection).Options;
            var _context = new MonitorContext(dbContextOptions);

            UpkServices.ServiceProvider.RegisterService(typeof(MonitorContext), typeof(MonitorContext), dbContextOptions);
            //UpkServices.ServiceProvider.RegisterService< MonitorContext>(_context);
            var context = UpkServices.ServiceProvider.GetService <MonitorContext>();

            //var address  = context.Hosts.First().IpAddress;

            //for (int i = 0; i < 10000; i++) {

            //    Parallel.For(0, 4, l=> {

            //        var logs = Enumerable.Range(0, 2500).Select(j => new Log { Delay = 1, Generation = 1, IpAddress = address, TimeStamp = DateTime.Now });
            //        ResultToDataBase(null, new PingerEventArgs() { PingResults = logs });
            //    });
            //    //context.AddRange(logs);
            //    Console.WriteLine(i);
            //    //Thread.Sleep(100);
            //}

            MessageParams.MailTo     = settings.MailTo;
            MessageParams.ReplyTo    = settings.ReplyTo;
            MessageParams.SenderName = settings.SenderName;
            MessageParams.TextFormat = MimeKit.Text.TextFormat.Text;

            /*
             *    emailSendAdapter = new MailSendAdapter(
             *        SmtpServer: settings.SmtpServer,
             *        SmtpPort: settings.SmtpPort,                              РАСКОМЕНТИТЬ КОГДА ГУГЛ ОДУМАЕТСЯ
             *        Login: settings.Email, Password: settings.Password);*/

            List <Models.Host> hosts       = _context.Hosts.ToList();
            HostMonitor        hostMonitor = new HostMonitor(settings, hosts);

            hostMonitor.OnPingCompleted += ResultToDataBase;
            hostMonitor.OnPingCompleted += CheckChanges;
            hostMonitor.OnPingCompleted += CheckGeneration; //проверка generation на 10. Если 10 отправить письмо.
            hostMonitor.Start();

            CreateWebHostBuilder(args).Build().Run();
        }
        public void cpuSetup()
        {
            Core = new UserModeCore(true);

            CPU = new SimhPDP10CPU(Core, OSTypes.Tops10)
            {
                ProcessorType = ProcessorTypes.KA10
            };

            CPU.PCChanged                  += CPU_PCChanged;
            CPU.LightsChanged              += CPU_LightsChanged;
            CPU.ProcFlagChanged            += CPU_ProcFlagChanged;
            CPU.EffectiveAddressCalculated += CPU_EffectiveAddressCalculated;

            TOPS10 = new MonitorContext(CPU);

            TOPS10.TTCALL.ConsoleOutput += TTCALL_ConsoleOutput;
            TOPS10.TTCALL.AttachToConsole();

            loader = new Tops10SAVLoader(Core, KLADEXE);

            addACs();
            addSymbols <int>(typeof(JOBDAT));

            MapCore();

            MapProperties();

            foreach (var seg in Core)
            {
                seg.MemberPageChanged += seg_MemberPageChanged;
            }

            CoreBrowser.Rows[0].Expanded = true;
            var gr = FindGridRow(loader.Transaddr.UL);

            SelectGridRow(gr);
            DecorateRow(gr, Color.Red, "Transfer Address: " + loader.Transaddr);

            CPU.PC = loader.Transaddr.UI;

            CoreBrowser.AfterRowUpdate += CoreBrowser_AfterRowUpdate;

            setUpYet = true;

            CPU.ProcFlags = 0;
            CPU.SetUserMode();
        }
        public void Intercept(IInvocation invocation)
        {
            var entityType = ReflectionHelper.GetEntityTypeFromRepositoryType(invocation.TargetType);
            var metadata   = RepositoryFramework.GetDefineMetadata(entityType);

            if (metadata == null)
            {
                throw new NotSupportedException(String.Format("类型 {0} 未进行定义,因此无法实现仓储扩展。", entityType.FullName));
            }

            foreach (var type in providers)
            {
                AbstractCacheableRepositoryProvider <T> provider = (AbstractCacheableRepositoryProvider <T>)Projects.Tool.Reflection.FastActivator.Create(type);
                provider.Invocation = invocation;
                if (provider.IsMatch())
                {
                    provider.CacheKey = cacheKey;
                    var regionStr = String.Join(",", regions.Select(o => o.CacheKey));

                    var cacheData = provider.GetCacheData();
                    if (cacheData != null && IsCacheValid(metadata, cacheData))
                    {
                        log.DebugFormat("{0}.{1} query cache hit. #{2}", invocation.Method.DeclaringType.ToPrettyString(), invocation.Method.Name, provider.CacheKey);
                        if (ProfilerContext.Current.Enabled)
                        {
                            ProfilerContext.Current.Trace("platform", String.Format("hit  {1}\r\n{0}", ProfilerUtil.JsonFormat(provider.CacheKey), regionStr));
                        }

                        //处理缓存
                        using (MonitorContext.Repository(invocation.Method, true))
                            provider.ProcessCache(cacheData);
                        return;
                    }

                    //处理原始
                    var hasSource = provider.ProcessSource();

                    log.DebugFormat("{0}.{1} query cache missing. #{2}", invocation.Method.DeclaringType.ToPrettyString(), invocation.Method.Name, provider.CacheKey);
                    if (ProfilerContext.Current.Enabled)
                    {
                        ProfilerContext.Current.Trace("platform", String.Format("missing  {1}{2}\r\n{0}", ProfilerUtil.JsonFormat(provider.CacheKey), regionStr, hasSource ? "" : " for null"));
                    }
                    return;
                }
            }

            invocation.Proceed();
        }
Example #18
0
        public async Task <IActionResult> GetWebsite([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var db   = new MonitorContext();
            var site = await db.Websites.FindAsync(id);

            if (site == null)
            {
                return(NotFound());
            }

            return(Ok(site));
        }
Example #19
0
        public void Process(IInvocation invocation, ClassDefineMetadata metadata)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException("metadata");
            }

            var entity = invocation.Arguments[0];

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

            var interceptors = RepositoryFramework.GetInterceptors(metadata.EntityType);

            //invoke pre event
            var preUr  = new UniqueRaise(GetRaiseType(invocation, true), metadata, entity, false);
            var postUr = new UniqueRaise(GetRaiseType(invocation, false), metadata, entity, false);

            //invoke cascade delete or update
            var preRaiseType = GetRaiseType(invocation, true);

            if (preRaiseType == RaiseType.PreDelete || preRaiseType == RaiseType.PreUpdate)
            {
                Cascade(invocation, entity);
            }

            RepositoryFramework.Raise(entity, preRaiseType, preUr);

            using (MonitorContext.Repository(invocation.Method))
                invocation.Proceed();

            //invoke post event
            var postRaiseType = GetRaiseType(invocation, false);

            RepositoryFramework.Raise(entity, postRaiseType, postUr);

            //invoke cascade create
            if (postRaiseType == RaiseType.PostCreate)
            {
                Cascade(invocation, entity);
            }

            preUr.Dispose();
            postUr.Dispose();
        }
        public void Process(IInvocation invocation, ClassDefineMetadata metadata)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException("metadata");
            }

            if (metadata.IsCacheable)
            {
                var    cacheKey = metadata.GetCacheKeyById(invocation.Arguments[1]);
                ICache cache    = RepositoryFramework.GetCacher(metadata);
                //CacheData value = cache.Get(cacheKey);
                var value = cache.Get(metadata.EntityType, cacheKey);
                if (value == null)
                {
                    // 调用源接口,并将结果写入缓存
                    using (MonitorContext.Repository(invocation.Method))
                        invocation.Proceed();

                    var entity = invocation.ReturnValue;
                    if (entity != null)
                    {
                        cache.Set(cacheKey, metadata.CloneEntity(entity));
                    }

                    if (ProfilerContext.Current.Enabled)
                    {
                        ProfilerContext.Current.Trace("platform", String.Format("missing get{1}\r\n{0}", cacheKey, entity == null ? " for null" : ""));
                    }
                }
                else
                {
                    //if (ProfilerContext.Current.Enabled)
                    //    ProfilerContext.Current.Trace("platform", String.Format("hit get\r\n{0}", cacheKey));
                    //invocation.ReturnValue = value.Convert(metadata.EntityType);
                    using (MonitorContext.Repository(invocation.Method, true))
                    {
                    }
                    invocation.ReturnValue = value;
                }
            }
            else
            {
                using (MonitorContext.Repository(invocation.Method))
                    invocation.Proceed();
            }
        }
Example #21
0
        public async Task <IActionResult> Delete(int id)
        {
            using (var db = new MonitorContext())
            {
                var website = db.Websites.SingleOrDefault(s => s.Id == id);

                if (website == null || id <= 0)
                {
                    return(NotFound());
                }

                db.Websites.Remove(website);
                await db.SaveChangesAsync();

                return(Ok(website));
            }
        }
        public XDocument DownloadXML(MonitorContext db)
        {
            var temperatureList = db.Temperatures.ToList();

            XDocument xmldoc = new XDocument(new XElement("Temperatures"));

            foreach (Temperature temperature in temperatureList)
            {
                xmldoc.Root.Add(
                    new XElement("Measurement", new XAttribute("id", temperature.TemperatureId),
                                 new XElement("Celcius", temperature.Celcius),
                                 new XElement("Time", temperature.Time.ToString()),
                                 new XElement("Location", temperature.Location)
                                 )
                    );
            }
            return(xmldoc);
        }
Example #23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // получаем строку подключения из файла конфигурации
            string connection = Configuration.GetConnectionString("DefaultConnection");

            // добавляем контекст MobileContext в качестве сервиса в приложение
            services.AddDbContext <MonitorContext>(options => options.UseSqlite(connection));
            services.AddMvc();
            DbContextOptionsBuilder dbContextBuilder = new DbContextOptionsBuilder();

            dbContextBuilder.UseSqlite(connection);

            var            o  = new DbContextOptionsBuilder <MonitorContext>();
            var            c  = o.UseSqlite(connection).Options;
            MonitorContext mc = new MonitorContext(c);
            var            serviceCollection = new ServiceCollection();
        }
Example #24
0
 public override Task ProcessInScope(IServiceProvider serviceProvider)
 {
     Console.WriteLine("Saving data processing starts here");
     try
     {
         // Update schedule with string from appsettings.json
         _monitorPingService = serviceProvider.GetService <IMonitorPingService>();
         MonitorContext monitorContext = serviceProvider.GetService <MonitorContext>();
         updateSchedule(_monitorPingService.PingParams.SaveSchedule);
         ResultObj result = _monitorPingService.SaveData(monitorContext);
         Console.WriteLine(result.Message);
     }
     catch (Exception e)
     {
         Console.WriteLine("Error occured in SaveScheduleTask.ProcesInScope() : " + e.Message + "\n");
     }
     Console.WriteLine("Saving data processing ends here");
     return(Task.CompletedTask);
 }
Example #25
0
        public static InstructionExit Execute(MonitorContext monitor, SimhPDP10CPU processor, ulong instruction,
                                              OpCodes opcode, int ac, ulong ea)
        {
            var pageSize = processor.CORE.PageSize;

            // Ignore PHY for now - no physical mode anyway (we may want an emulator assert here though)

            var acV   = processor.CORE[ac];
            var hiseg = acV.LHW;
            var loseg = acV.RHW;

            // Error states

            // High and low are zero
            if (hiseg.Z && loseg.Z)
            {
                return(InstructionExit.Normal);
            }

            // Hiseg specified but not in high seg (clears - high segment, but can only be done from loseg)
            if (processor.PC >= 400000.OctU() &&
                hiseg.NZ &&
                hiseg < 400001.Oct18())
            {
                return(InstructionExit.Normal);
            }

            // Lowseg is running over the hiseg
            if (loseg.NZ &&
                loseg > 399999.Oct18())
            {
                return(InstructionExit.Normal);
            }



            processor.CORE.Tops10Core(hiseg, loseg);

            processor.PC++; // Success Exit
            return(InstructionExit.Normal);
        }
Example #26
0
        public static async void ResultToDataBase(object sender, PingerEventArgs args)
        {
            lock (lockObject)
            {
                if (count % 100 == 0)
                {
                    if (MonitorContext != null)
                    {
                        MonitorContext.Dispose();
                    }
                    count++;
                    GC.Collect();
                    MonitorContext = UpkServices.ServiceProvider.GetService <MonitorContext>();
                    MonitorContext.ChangeTracker.AutoDetectChangesEnabled = false;
                    MonitorContext.ChangeTracker.QueryTrackingBehavior    = QueryTrackingBehavior.NoTracking;
                    MonitorContext.ChangeTracker.LazyLoadingEnabled       = false;
                }
            }
            await MonitorContext.Logs.AddRangeAsync(args.PingResults);

            MonitorContext.SaveChanges();
        }
Example #27
0
 public static InstructionExit Execute(MonitorContext monitor, SimhPDP10CPU processor, ulong instruction, OpCodes opcode, int ac, ulong ea)
 {
     throw new NotImplementedException();
 }
Example #28
0
 public MonitorsController()
 {
     _dbContext = new MonitorContext();
 }
Example #29
0
 public void Setup(MonitorContext ctx)
 {
     Monitor = ctx;
 }
Example #30
0
        public IEnumerable <Website> Get()
        {
            var db = new MonitorContext();

            return(db.Websites);
        }