コード例 #1
0
        public async Task Invoke(HttpContext context, LogDatabase db)
        {
            //First, get the incoming request
            var request = await FormatRequest(context.Request);

            //Copy a pointer to the original response body stream
            var originalBodyStream = context.Response.Body;

            //Create a new memory stream...
            using (var responseBody = new MemoryStream())
            {
                //...and use that for the temporary response body
                context.Response.Body = responseBody;

                //Continue down the Middleware pipeline, eventually returning to this class
                await _next(context);

                //Format the response from the server
                var response = await FormatResponse(context.Response);

                //TODO: Save log to chosen datastore
                request.Response = response;

                /*db.LogRegs.Add(request);
                 * await db.SaveChangesAsync();*/

                //Copy the contents of the new memory stream (which contains the response) to the original stream, which is then returned to the client
                await responseBody.CopyToAsync(originalBodyStream);
            }
        }
コード例 #2
0
ファイル: LogExporter.cs プロジェクト: mirsys/pebakery
 public LogExporter(LogDatabase db, LogExportType type, TextWriter writer)
 {
     // The responsibility of closing _db and _w goes to the caller of LogExporter
     _db         = db ?? throw new ArgumentNullException(nameof(db));
     _w          = writer ?? throw new ArgumentNullException(nameof(writer));
     _exportType = type;
 }
コード例 #3
0
ファイル: Form1.cs プロジェクト: ArcamEBM/LogStudio
        private void OpenLogFile(string filename)
        {
            CloseFile();


            if (CheckIfNetworkFile(filename))
            {
                if (MessageBox.Show(this, "It seems like the log file is uncompressed and lives on a network device.\r\nThis might degrade your Log Studio experience.\r\nAre you sure you want to continue?", "Performance issue...", MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    return;
                }
            }

            m_ModuleTabControl.Enabled = false;

            m_Database = new LogDatabase(filename, true, m_AdminMode ? null : m_AllowedItemSettings.AllowedItems);
            m_Database.OnParserReadError     += OnParserReadErrorCallback;
            m_Database.MultipleLogFilesQuery += OnMultipleLogFileQuery;


            m_ItemTree.ItemDatabase = m_Database;
            foreach (IModule module in m_ModuleManager.Modules)
            {
                module.Database = m_Database;
            }

            m_Database.OnInitialReadDone += OnDatabaseOnInitialReadDone;
            m_Database.Start();

            UpdateTitle();
            m_MruMenu.AddFile(filename);
            UpdateControlsState();
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: asveredyuk/LogExplorer
        static int CheckCacheJob(string jobPath)
        {
            try
            {
                string json = File.ReadAllText(jobPath);
                var    job  = JsonConvert.DeserializeObject <Job>(json);
                if (job.Type == JobType.CacheLabel)
                {
                    var cachejob = JsonConvert.DeserializeObject <CacheLabelJob>(json);
                    if (!DatabaseClient.Self.GetLogNames().Contains(cachejob.LogName))
                    {
                        //no such log
                        string msg = $"No such log \"{cachejob.LogName}\"";
                        Console.WriteLine(msg);
                        JobResult.WriteForJob(jobPath, cachejob, 3, msg);
                        return(3);
                    }

                    Database = DatabaseClient.Self.GetLogDatabase(cachejob.LogName);

                    var label = GetLabels(new [] { cachejob.LabelId }).FirstOrDefault();
                    if (label == null)
                    {
                        Console.WriteLine("Label not found");
                        JobResult.WriteForJob(jobPath, cachejob, 4, $"label {cachejob.LabelId} not found");
                    }

                    if (Database.LabelHasCache(label._id))
                    {
                        Console.WriteLine("Already done");
                        return(0);
                    }

                    Console.WriteLine("Baking label " + label._id);
                    var sw = Stopwatch.StartNew();
                    BakeLabel(label);
                    sw.Stop();
                    Console.WriteLine("done in " + sw.ElapsedMilliseconds + "ms");
                    return(0);
                }
                else
                {
                    return(-1);
                }
            }
            catch (JobParseException e)
            {
                Console.WriteLine("Failed to initialize the job");
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to load the job");
                return(2);
            }

            return(0);
        }
コード例 #5
0
        public void GetAllDPTestsOneExists()
        {
            using (LogDatabase db = new LogDatabase(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Testfiles\\TestLog4.plg"), false, null))
            {
                db.Read();

                NamedLogRow[] data;
                Assert.Catch <KeyNotFoundException>(() => data = db.GetAllDP(new[] { new KeyValuePair <string, LogRowType>("Gamma", LogRowType.Point), new KeyValuePair <string, LogRowType>("Delta", LogRowType.Raw) }).ToArray());
            }
        }
コード例 #6
0
 private void MainForm_Load(object sender, EventArgs e)
 {
     _db = new LogDatabase();
     // Попытка проинициализировать базу данных (если нет, то падаем с сообщением)
     try {
         InitUsers();
     } catch (System.Data.Entity.Core.EntityException) {
         MessageBox.Show("Cannot access database! [Maybe, you should run me as admin? :) ]");
         Close();
         return;
     }
 }
コード例 #7
0
 void Awake()
 {
     if (inst == null)
     {
         inst = this;
     }
     else
     {
         Debug.Log("LogDatabase destroyed on '" + gameObject.name + "'. Are there duplicates in the scene?");
         DestroyImmediate(this);
     }
 }
コード例 #8
0
        public void GetCycleStateTest()
        {
            using (LogDatabase db = new LogDatabase(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Testfiles\\TestLog4.plg"), false, null))
            {
                db.Read();

                var data = db.GetCycleState(1805).ToArray();

                Assert.AreEqual(3, data.Length);
                Assert.NotNull(Array.Find(data, rowData => rowData.ItemID == "Alpha" && rowData.CycleIndex == 1669 && rowData.Value == "False"));
                Assert.NotNull(Array.Find(data, rowData => rowData.ItemID == "Beta" && rowData.CycleIndex == 1803 && rowData.Value == "24"));
                Assert.NotNull(Array.Find(data, rowData => rowData.ItemID == "Delta" && rowData.CycleIndex == 1669 && rowData.Value == "0.7"));
            }
        }
コード例 #9
0
    void OnTriggerEnter2D(Collider2D other)
    {
        if (!NutrientSpawner.inst.m_active)
        {
            return;
        }

        NutrientLife _nutrientLife = other.GetComponent <NutrientLife>();

        if (_nutrientLife == null)
        {
            return;
        }

        FOODTYPE _foodType  = other.GetComponent <NutrientLife>().m_foodType;
        int      _foodIndex = other.GetComponent <NutrientLife>().m_foodTypeIndex;

        switch (_foodType)
        {
        case FOODTYPE.LOGFOOD:
            if (_foodIndex == ND_RobotHandler.inst.m_wantedFoods[ND_RobotHandler.inst.m_wantedFoodIndex])
            {
                //Add wanted food to items collected
                LogDatabase.AddItemToCollection(other.GetComponent <Image>());

                //The wanted food was eaten.
                ND_RobotHandler.inst.NextFood();

                //Apply a robot eating animation.

                //Destroy incoming food.
                Destroy(other.gameObject);
            }
            break;

        case FOODTYPE.NOTFOOD:
            //Apply stun effect if the food acquired is not actually a food item.
            robotStunEffect.ApplyStun();
            ND_RobotHandler.inst.EatBadFood();

            Destroy(other.gameObject);
            break;

        case FOODTYPE.OTHERFOOD:
            break;

        default:
            break;
        }
    }
コード例 #10
0
    public void StartLevel(LevelInput _levelInput)
    {
        //Call this immediately after loading the scene. Pass the LevelInput, and the level will start with those values.
        m_levelInput = _levelInput;
        NutrientBucket.inst.Pause();
        NutrientSpawner.inst.Pause();
        NutrientSpawner.inst.SetSpawnerInfo(m_levelInput.m_foodDropLevelInput.m_spawnerInfo);
        ND_RobotHandler.inst.SetWantedFoods();
        ND_LevelTimer.inst.SetupTimer();
        m_pauseMenu.RequestPause();

        //Tell the food database which tab it should open to.
        switch (m_levelInput.m_levelName)
        {
        case "Grains":
            LogManager.activeTab = LogManager.TabType.Grain;
            break;

        case "Drinks":
            LogManager.activeTab = LogManager.TabType.Drink;
            break;

        case "MeatAlternatives":
            LogManager.activeTab = LogManager.TabType.MeatAlts;
            break;

        default:
            LogManager.activeTab = LogManager.TabType.Grain;
            break;
        }
        LogDatabase.ClearItemsCollected();

        //Start the intro dialogue if it exists and isn't set to be skipped, else start the drop game.
        if ((FindSceneInfo() == null) || (!FindSceneInfo()[0].GetComponent <SceneInfo>().m_skipIntro))
        {
            if (FindDialogue(DIALOGUETYPE.FD_INTRO, false) != null)
            {
                DialogueManager.inst.StartConversation(FindDialogue(DIALOGUETYPE.FD_INTRO), SpeechBubble.SPEECHBUBBLETYPE.ASSISTANT);
                m_animDialogue.SetTrigger("Go_BottomIn");
            }
            else
            {
                StartDropGame();
            }
        }
        else
        {
            StartDropGame();
        }
    }
コード例 #11
0
    private void startFtpThread(object obj)
    {
        Complete = false;
        string objString = obj.ToString();

        string[] split    = objString.Split(';');
        string   download = split[0];
        string   file     = split[1];

        do
        {
            try {
                string uri       = String.Format("ftp://{0}/{1}/{2}", SERVER, download, file);
                Uri    serverUri = new Uri(uri);
                if (serverUri.Scheme != Uri.UriSchemeFtp)
                {
                    Cancel = true;
                    return;
                }
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.Credentials      = new NetworkCredential(USERNAME, PASSWORD);
                reqFTP.KeepAlive        = true;
                reqFTP.Method           = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.EnableSsl        = false;
                reqFTP.Proxy            = null;
                reqFTP.UsePassive       = true;
                reqFTP.Timeout          = Timeout;
                reqFTP.ReadWriteTimeout = ReadWriteTimeout;
                using (FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse()) {
                    using (Stream responseStream = response.GetResponseStream()) {
                        using (FileStream writeStream = new FileStream(path + file, FileMode.Create)) {
                            Byte[] buffer    = new Byte[BUF_SIZE];
                            int    bytesRead = responseStream.Read(buffer, 0, BUF_SIZE);
                            while (0 < bytesRead)
                            {
                                writeStream.Write(buffer, 0, bytesRead);
                                bytesRead = responseStream.Read(buffer, 0, BUF_SIZE);
                            }
                        }
                        responseStream.Close();
                    }
                    response.Close();
                    Complete = true;
                }
            } catch (WebException wEx) {
                LogDatabase.WriteLog("Download File", wEx.ToString(), "Download File");
            }
        } while (!Cancel && !Complete);
    }
コード例 #12
0
        public static LogDatabase GetDataBaseFromFile(string filename)
        {
            filename = Path.GetFullPath(filename);
            Assert.That(File.Exists(filename));

            LogDatabase db = new LogDatabase(filename, false, null);

            db.Start();
            while (db.State != ProgressStateEnum.Done)
            {
                Thread.Sleep(10);
            }

            return(db);
        }
コード例 #13
0
        private void QueryLog(bool includeInfo, bool includeWarn, bool includeError)
        {
            String filter = " ";

            if (!includeInfo)
            {
                filter += "AND level!='INFO' ";
            }
            if (!includeWarn)
            {
                filter += "AND level!='WARN' ";
            }
            if (!includeError)
            {
                filter += "AND level!='ERROR' ";
            }

            LogDatabase.Clear();
            MySqlDataReader reader = null;

            try
            {
                String       sql = "SELECT date,millisecond,level,message,location FROM loginfo WHERE id='" + crawlId + "'" + filter + " ORDER BY date DESC LIMIT 1024;";
                MySqlCommand cmd = new MySqlCommand(sql, database);
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Log log = new Log();
                    log.Date        = reader.GetDateTime(0);
                    log.Millisecond = reader.GetInt16(1);
                    log.Level       = reader.GetString(2);
                    log.Message     = reader.GetString(3);
                    log.Location    = reader.GetString(4);
                    LogDatabase.Add(log);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
コード例 #14
0
        public static void RunTestcase(int executionNO, int iteration, int clientId, HttpRequestMessage request, string db, string testcase, string api)
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            HttpResponseMessage response = SendToAPI(request);

            stopWatch.Stop();



            LogDatabase.InsertToLogDb(clientId, stopWatch.ElapsedMilliseconds,
                                      request.Content == null ? 0 : request.Content.Headers.ContentLength,
                                      response.Content.Headers.ContentLength == null ? 0 : response.Content.Headers.ContentLength,
                                      executionNO, iteration, db, testcase, api);
        }
コード例 #15
0
ファイル: LogDatabaseService.cs プロジェクト: okusnadi/Dalyan
 public ServiceResult <LogDatabase> Edit(LogDatabase obj)
 {
     try
     {
         IMediator    service     = _container.GetInstance <IMediator>();
         IUserContext currentUser = _container.GetInstance <IUserContext>();
         var          query       = new LogDatabaseEditQuery();
         query.LogDatabase = obj;
         return(new ServiceResult <LogDatabase>(service.Proccess(query), message: ClientErrorMessage.Success(), state: ServiceResultStates.SUCCESS));
     }
     catch (ExceptionLog ex)
     {
         LoggerService.Logger.Log(_container, ex);
         return(new ServiceResult <LogDatabase>(result: null, message: ClientErrorMessage.Error(), state: ServiceResultStates.ERROR));
     }
 }
コード例 #16
0
ファイル: Form1.cs プロジェクト: ArcamEBM/LogStudio
        private void CloseFile()
        {
            if (m_Database != null)
            {
                m_ItemTree.ItemDatabase = null;

                foreach (IModule module in m_ModuleManager.Modules)
                {
                    module.Database = null;
                }

                m_Database.MultipleLogFilesQuery -= OnMultipleLogFileQuery;
                m_Database.OnParserReadError     -= OnParserReadErrorCallback;
                m_Database.Dispose();
                m_Database = null;
            }
        }
コード例 #17
0
        public void TestSimpleExport()
        {
            string      filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Testfiles/TestLog2.plg");
            LogDatabase db       = GetDataBaseFromFile(filename);

            DataTable table = db.ExportStateOnItemChangeToDataTable("Alpha");

            Assert.AreEqual(table.Rows.Count, 2);
            Assert.AreEqual(table.Columns.Count, 3);

            Assert.AreEqual(table.Rows[0][0].ToString(), "False");
            Assert.AreEqual(table.Rows[1][0].ToString(), "True");

            Assert.AreEqual(table.Rows[0][1].ToString(), "20");
            Assert.AreEqual(table.Rows[1][1].ToString(), "22");

            Assert.AreEqual(table.Rows[0][2].ToString(), "0.7");
            Assert.AreEqual(table.Rows[1][2].ToString(), "0.7");
        }
コード例 #18
0
        public void GetAllDPTests()
        {
            using (LogDatabase db = new LogDatabase(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Testfiles\\TestLog4.plg"), false, null))
            {
                db.Read();

                var data = db.GetAllDP(new KeyValuePair <string, LogRowType>[] { new KeyValuePair <string, LogRowType>("Alpha", LogRowType.Raw), new KeyValuePair <string, LogRowType>("Delta", LogRowType.Point) }).ToArray();

                Assert.AreEqual("Alpha", data[0].Fullname);
                Assert.AreEqual("False", data[0].GetAsDataRow.Value);

                Assert.AreEqual("Delta", data[1].Fullname);
                Assert.AreEqual(0.7, data[1].GetAsDataPoint.Value, 0.1);

                Assert.AreEqual("Alpha", data[2].Fullname);
                Assert.AreEqual("True", data[2].GetAsDataRow.Value);

                Assert.AreEqual("Delta", data[3].Fullname);
                Assert.AreEqual(0.9, data[3].GetAsDataPoint.Value, 0.1);
            }
        }
コード例 #19
0
 public BranchOfficeController(LogDatabase db)
 {
     context = db;
 }
コード例 #20
0
 public ComprasController(LogDatabase db)
 {
     context = db;
 }
コード例 #21
0
ファイル: LogDataBaseTest.cs プロジェクト: berczeck/.Net
 public void TestInitialize()
 {
     log     = new LogDatabase();
     message = new Message("Hello");
 }
コード例 #22
0
 public RolesController(LogDatabase db)
 {
     context = db;
 }
コード例 #23
0
 public ClientsController(LogDatabase db)
 {
     context = db;
 }
コード例 #24
0
 public WorkersController(LogDatabase db)
 {
     context = db;
 }
コード例 #25
0
 public PackagesController(LogDatabase db)
 {
     context = db;
 }
コード例 #26
0
ファイル: Main.cs プロジェクト: hansonw/LoLGears
        private void LoadLogFiles()
        {
            var logDirectory = FindLogDirectory();
              if (logDirectory == null) {
            Environment.Exit(1);
              }

              database = new LogDatabase();

              var pd = new ProgressDialog(this.Handle);
              pd.Title = "Loading logs...";
              pd.CancelMessage = "Please wait while the operation is cancelled...";
              pd.Maximum = 100;
              pd.Value = 0;
              pd.Line1 = "Loading LoLGears...";
              pd.Line2 = "Loading new logs...";
              pd.Line3 = "This may take a while. Please be patient..";

              pd.ShowDialog(ProgressDialog.PROGDLG.Modal, ProgressDialog.PROGDLG.AutoTime, ProgressDialog.PROGDLG.NoMinimize);

              var bg = new BackgroundWorker();
              bg.WorkerReportsProgress = true;
              bg.WorkerSupportsCancellation = true;
              bg.DoWork += (sender, e) => {
            database.Load(logDirectory, sender as BackgroundWorker);
            Invoke(new Action(() => pd.Line2 = "Loading statistics..."));
            LoadData();
              };
              bg.ProgressChanged += (sender, e) => {
            if (pd.HasUserCancelled) {
              bg.CancelAsync();
            }
            var status = e.UserState as int[];
            int tick = status[1]/100;
            if (tick == 0) tick = 1;
            if (status[0]%tick == 0) {
              pd.Value = (uint) e.ProgressPercentage;
            }
            pd.Line2 = String.Format("Loading new logs... ({0}/{1})", status[0], status[1]);
              };
              bg.RunWorkerCompleted += (sender, e) => {
            if (e.Error != null) {
              Logger.LogException(e.Error);
            }

            pd.CloseDialog();
            // Bring to front; closing the dialog seems to send the window to the back.
            TopMost = true;
            TopMost = false;
              };
              bg.RunWorkerAsync();
        }
コード例 #27
0
        public ServiceResult <LogDatabase> Edit(LogDatabase obj)
        {
            LogDatabaseService service = new LogDatabaseService(_container);

            return(service.Edit(obj));
        }
コード例 #28
0
 public LogData(LogDatabase pDB) : base(pDB)
 {
 }
コード例 #29
0
 public ProductsController(LogDatabase db)
 {
     context = db;
 }
コード例 #30
0
ファイル: Program.cs プロジェクト: asveredyuk/LogExplorer
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("No job specified");
                return(2);
            }

            if (!File.Exists(args[0]))
            {
                Console.WriteLine("Job file not found");
                return(2);
            }

            string jobPath          = args[0];
            var    checkCacheJobRes = CheckCacheJob(jobPath);

            if (checkCacheJobRes >= 0)
            {
                return(checkCacheJobRes);
            }
            //load the job
            try
            {
                string json = File.ReadAllText(jobPath);
                Job = JsonConvert.DeserializeObject <ProcessMapJob>(json);
            }
            catch (JobParseException e)
            {
                Console.WriteLine("Failed to initialize the job");
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to load the job");
                return(2);
            }

            //init database
            if (!DatabaseClient.Self.GetLogNames().Contains(Job.LogName))
            {
                //no such log
                string msg = $"No such log \"{Job.LogName}\"";
                Console.WriteLine(msg);
                JobResult.WriteForJob(jobPath, Job, 3, msg);
                return(3);
            }

            Database = DatabaseClient.Self.GetLogDatabase(Job.LogName);

            if (Job.Labels.Length < 2)
            {
                string msg = "Number of labels is lower then 2";
                Console.WriteLine(msg);
                JobResult.WriteForJob(jobPath, Job, 4, msg);
                return(4);
            }


            var labels = GetLabels(Job.Labels).ToList();

            if (labels.Count != Job.Labels.Length)
            {
                string msg = $"Not all labels were found!";
                Console.WriteLine(msg);
                JobResult.WriteForJob(jobPath, Job, 4, msg);
                return(4);
            }
            //check if need to bake the labels
            var db = Database.Db;

            foreach (var logLabel in labels)
            {
                if (!Database.LabelHasCache(logLabel._id))
                {
                    var sw = Stopwatch.StartNew();
                    Console.WriteLine($"Baking {logLabel._id} label");
                    BakeLabel(logLabel);
                    sw.Stop();
                    Console.WriteLine($"Done in {sw.ElapsedMilliseconds}ms");
                }
            }

            (var crtMapCode, var map) = CreateMap(labels);
            if (crtMapCode != 0)
            {
                return(crtMapCode);
            }

            foreach (var kv in map.OrderByDescending(t => t.Value))
            {
                Console.WriteLine($"{kv.Key} - {kv.Value}");
            }

            Console.WriteLine("Saving map");
            var saveMapCode = SaveMap(map, labels);

            Console.WriteLine("OK");
            //Console.ReadLine();
            return(saveMapCode);
            //return 0;
        }
コード例 #31
0
 public RepartidorController(LogDatabase db)
 {
     context = db;
 }