コード例 #1
0
        void SaveImage(string glyph, IFormFile file)
        {
            string ssDirPath = Path.Combine("wwwroot", "Screenshots", glyph);

            if (Directory.Exists(ssDirPath) == false)
            {
                Directory.CreateDirectory(ssDirPath);
            }

            string Id        = System.Guid.NewGuid().ToString("N");
            string filePath  = Path.Combine(ssDirPath, $"{Id}.png");
            string thumbPath = Path.Combine(ssDirPath, $"{Id}-thumb.png");

            using (var img = Image.Load <Rgba32>(file.OpenReadStream()))
            {
                // Main Image
                using (var output = FileIo.OpenWrite(filePath))
                {
                    if (img.Width > 1920 || img.Height > 1080)
                    {
                        img.Mutate(i => i.Resize(1920, 1080));
                    }

                    img.SaveAsPng(output);
                }

                // Thumbnail
                using (var output = FileIo.OpenWrite(thumbPath))
                {
                    img.Mutate(i => i.Resize(256, 128));
                    img.SaveAsPng(output);
                }
            }
        }
コード例 #2
0
    public void SaveSettings()
    {
        var settings = new Settings(MusicVolume, SfxVolume);

        FileIo.SaveSettings(settings);
        IsDirty = false;
    }
コード例 #3
0
 private void importToolStripMenuItem_Click(object sender, EventArgs e)
 {
     credentials = FileIo.Import(credentials, FileIo.openFile());
     clearFields();
     dgAccountList.Rows.Clear();
     credentials.fillInDataGrid(dgAccountList);
 }
コード例 #4
0
ファイル: MosaicForm.cs プロジェクト: jwalke24/mosaic-creator
 private void saveMenuItem_Click(object sender, EventArgs e)
 {
     if (this.mosaicImageBox.Image != null)
     {
         FileIo.SaveFile(this.mosaicImageBox.Image);
     }
 }
コード例 #5
0
    public void LoadSettings()
    {
        var loadedSettings = FileIo.LoadSettingsOrDefault();

        MusicVolume = loadedSettings.MusicVolume;
        SfxVolume   = loadedSettings.SfxVolume;
        IsDirty     = false;
    }
コード例 #6
0
 public InputFileName(string dataType)
 {
     InitializeComponent();
     this.DataType        = dataType;
     this.extension       = FileIo.GetDataTypeExtension(dataType);
     pict_extension.Image = FileIo.GetDataTypeImage(dataType);
     la_extension.Text    = string.Format(".{0}", this.extension);
 }
コード例 #7
0
        private void AddCourse_Load(object sender, EventArgs e)
        {
            FileIo.LoadFileFromTxt("sel_courses.list", out ProgramData.ReadyToSelectCoursesList);

            foreach (var item in ProgramData.ReadyToSelectCoursesList)
            {
                list_Course.Items.Add(item.ToString());
            }
        }
コード例 #8
0
        private void btnRegister_Click(object sender, EventArgs e)
        {
            // Has the form been completed correctly?

            if (string.IsNullOrEmpty(tbName.Text))
            {
                //TODO: Requires Localization
                ErrorMessage("You must Include your Name");
                return;
            }

            if (string.IsNullOrEmpty(tbEmail.Text))
            {
                //TODO: Requires Localization
                ErrorMessage("A Valid Email Address Is Required");
                return;
            }

            //TODO: Improve Password Security... No limit on length beyond the limit of a string length, and proper complexity.
            if (string.IsNullOrEmpty(tbPassword.Text))
            {
                //TODO: Requires Localization
                ErrorMessage("A Password is Required");
                return;
            }

            if (tbPassword.Text != tbPasswordConfirm.Text)
            {
                //TODO: Requires Localization
                ErrorMessage("Passwords do not Match");
                return;
            }


            // Ok everything is fine now.
            //TODO: Write Proper XMLSerialization / DeSerialization Class
            // Just save as a Text file for just now
            var um = new UserModel
            {
                Name     = tbName.Text,
                Email    = tbEmail.Text,
                Password = tbPassword.Text,
                Facebook = cbFacebookAccount.Checked,
                GitHub   = cbGithubAccount.Checked,
                Twitter  = cbTwitterAccount.Checked
            };

            var fi = new FileIo();

            fi.WriteUserTextFile();

            //TODO: Log into the Server so that the user's statistics are saved, answers to their questions are displayed, no information on their projects is shown, and so that they can download new or updated libraries that they are currently using. Enable Chat if they wish etc...


            DialogResult = DialogResult.OK;
            Close();
        }
コード例 #9
0
        private void btnRegister_Click(object sender, EventArgs e)
        {
            // Has the form been completed correctly?

            if (string.IsNullOrEmpty(tbName.Text))
            {
                //TODO: Requires Localization
                ErrorMessage("You must Include your Name");
                return;
            }

            if (string.IsNullOrEmpty(tbEmail.Text))
            {
                //TODO: Requires Localization
                ErrorMessage("A Valid Email Address Is Required");
                return;
            }

            //TODO: Improve Password Security... No limit on length beyond the limit of a string length, and proper complexity.
            if (string.IsNullOrEmpty(tbPassword.Text))
            {
                //TODO: Requires Localization
                ErrorMessage("A Password is Required");
                return;
            }

            if (tbPassword.Text != tbPasswordConfirm.Text)
            {
                //TODO: Requires Localization
                ErrorMessage("Passwords do not Match");
                return;
            }

            // Ok everything is fine now.
            //TODO: Write Proper XMLSerialization / DeSerialization Class
            // Just save as a Text file for just now
            var um = new UserModel
            {
                Name = tbName.Text,
                Email = tbEmail.Text,
                Password = tbPassword.Text,
                Facebook = cbFacebookAccount.Checked,
                GitHub = cbGithubAccount.Checked,
                Twitter = cbTwitterAccount.Checked
            };

            var fi = new FileIo();
            fi.WriteUserTextFile();

            //TODO: Log into the Server so that the user's statistics are saved, answers to their questions are displayed, no information on their projects is shown, and so that they can download new or updated libraries that they are currently using. Enable Chat if they wish etc...

            DialogResult = DialogResult.OK;
            Close();
        }
コード例 #10
0
ファイル: MosaicForm.cs プロジェクト: jwalke24/mosaic-creator
        private void openMenuItem_Click(object sender, EventArgs e)
        {
            this.originalImage = FileIo.OpenFile();

            if (this.originalImage != null)
            {
                this.originalImageBox.Image = (Image)this.originalImage.Clone();
                this.enableBlockMosaicControls();
                this.enablePictureMosaicControls();
                this.mosaicImageBox.Image = null;
            }
        }
コード例 #11
0
        private void btn_Submit_Click(object sender, EventArgs e)
        {
            ProgramData.ReadyToSelectCoursesList.Clear();
            for (var i = 0; i < list_Course.Items.Count; i++)
            {
                ProgramData.ReadyToSelectCoursesList.Add(list_Course.Items[i].Text);
            }

            FileIo.SaveListToTxt("sel_courses.list", ProgramData.ReadyToSelectCoursesList);

            Close();
        }
コード例 #12
0
ファイル: MosaicForm.cs プロジェクト: jwalke24/mosaic-creator
        private void openFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.imagePalette.Images.Clear();
            this.imagePalette.Images.AddRange(FileIo.ReadImagesFromFolder().ToArray());
            this.imagePaletteLabel.Text = this.imagePalette.Images.Count + @" images in palette";
            this.enablePictureMosaicControls();

            if (this.imagePalette.Images.Count > 0)
            {
                this.viewPaletteButton.Enabled = true;
            }
        }
コード例 #13
0
        private void ZipFilesInDateRange(ArchiveArgs args, string archiveZipSearchPattern)
        {
            var total =
                new List <string>(Directory.GetFiles(CurrentDirectory, archiveZipSearchPattern)).Count();
            var filePathsToZip = new List <string>(Directory.GetFiles(CurrentDirectory, archiveZipSearchPattern))
                                 .Select(f => new { FilePath = f, FileDateTime = DateTimeFromFile(f) })
                                 .OrderByDescending(f => f.FileDateTime)
                                 .Where(f => f.FileDateTime.Date >= args.Start.Date && f.FileDateTime.Date <= args.End)
                                 .Select(f => f.FilePath);

            var test = new List <string>(Directory.GetFiles(CurrentDirectory, archiveZipSearchPattern))
                       .Select(f => new { FilePath = f, FileDateTime = DateTimeFromFile(f) })
                       .OrderByDescending(f => f.FileDateTime)
                       .Where(f => f.FileDateTime.Date >= args.Start.Date && f.FileDateTime.Date <= args.End)
                       .Select(f => f).ToList();

            long bytesZipped = 0;
            int  count       = 0;

            foreach (var file in filePathsToZip)
            {
                count++;
                if (FileIo.IsFileLocked(new FileInfo(file)))
                {
                    continue;
                }

                ZipAFile(file, Path.GetFileName(file), ZippedFullFileName, true);

                if (ArchiveArgs.IgnoreFileSizeLimits >= args.MaxArchiveSizeBytes)
                {
                    continue;
                }

                var fileInfo = new FileInfo(file);

                bytesZipped += fileInfo.Length;

                if (bytesZipped <= args.MaxArchiveSizeBytes)
                {
                    continue;
                }

                CreateEmptyFileInZip("FileSizeLimitReached.txt", ZippedFullFileName);
                break;
            }

            if (!System.IO.File.Exists(ZippedFullFileName))
            {
                CreateEmptyFileInZip("noLogs.txt", ZippedFullFileName);
            }
        }
コード例 #14
0
        public IActionResult SubmitGlyphEdit(SubmitGlyphModel glp)
        {
            var sanitizer = new Ganss.XSS.HtmlSanitizer();

            glp.Submitter = HttpContext.User.Identity.Name;
            glp.Notes     = sanitizer.Sanitize(glp.Notes);

            string ssDirPath = Path.Combine("wwwroot", "Screenshots", glp.DungeonGlyph);

            if (glp.DeletedImages != null)
            {
                var ids = glp.DeletedImages.Split(';');
                foreach (var id in ids)
                {
                    var mainFile  = Path.Combine(ssDirPath, $"{id}.png");
                    var thumbFile = Path.Combine(ssDirPath, $"{id}-thumb.png");

                    if (FileIo.Exists(mainFile))
                    {
                        FileIo.Delete(mainFile);
                    }
                    if (FileIo.Exists(thumbFile))
                    {
                        FileIo.Delete(thumbFile);
                    }
                }
            }

            if (glp.Screenshots != null && glp.Screenshots.Count > 0)
            {
                string[] validFileTypes = { "image/jpeg", "image/gif", "image/png" };
                foreach (var file in glp.Screenshots)
                {
                    if (file.Length <= 0)
                    {
                        continue;
                    }
                    if (validFileTypes.Contains(file.ContentType) == false)
                    {
                        continue;                                                                         // Skip when file is not a supported imagetype
                    }
                    SaveImage(glp.DungeonGlyph, file);
                }
            }

            ChaliceDb.UpdateGlyphFromModel(glp);

            return(Redirect($"/dungeon/viewglyph/{glp.DungeonGlyph}"));
        }
コード例 #15
0
        private static void LoadConfigs()
        {
            // --- Friends ---

            if (FileIo.FriendsExist())
            {
                FileIo.StreamLoadFriends(out WaveMaker.Friends);

                if (WaveMaker.Friends == null)
                {
                    Logging.Log("Internal Error", "Unable to load friends file");
                    throw new UnableToLoadException("Unable to load friends file");
                }
            }
            else
            {
                FileIo.CreateFriends(out WaveMaker.Friends);

                if (WaveMaker.Friends == null)
                {
                    Logging.Log("Internal Error", "Unable to create friends file");
                    throw new UnableToLoadException("Unable to create friends file");
                }
            }
            // --- Settings ---

            if (FileIo.SettingsExist())
            {
                FileIo.StreamLoadSettings(out WaveMaker.Settings);

                if (WaveMaker.Settings == null)
                {
                    Logging.Log("Internal Error", "Unable to load settings file");
                    throw new UnableToLoadException("Unable to load settings file");
                }
            }
            else
            {
                FileIo.CreateSettings(out WaveMaker.Settings);

                if (WaveMaker.Settings == null)
                {
                    Logging.Log("Internal Error", "Unable to create settings file");
                    throw new UnableToLoadException("Unable to create settings file");
                }
            }
        }
コード例 #16
0
        private void logOutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            switch (MessageBox.Show(this, "Would you like to save before you quit?", "Closing", MessageBoxButtons.YesNo))
            {
            case DialogResult.Yes:
                FileIo.saveCredentialToEncryptedFile(credentials);
                break;

            default:
                break;
            }

            Hide();
            credentials = null;
            frm_LogIn frm_LogIn = new frm_LogIn();

            frm_LogIn.FormClosed += (s, args) => Close();
            frm_LogIn.Show();
        }
コード例 #17
0
ファイル: TestCaseController.cs プロジェクト: outase/taws
        public ActionResult Insert2(TestCaseProperty testCase)
        {
            var fileIo = new FileIo();

            //テストケース登録日時取得
            string testDateTime = DateTime.Now.ToString("yyyyMMdd_HHmmss");

            //テストケースファイル保存
            string uploadFileSavePath = fileIo.SaveTestCaseFiles(testCase.testCaseFile, testDateTime);

            //ファイルからテストケース取得
            testCase.testElemList = new FileIo().TestCaseFromUploadFile(uploadFileSavePath, testCase.testCaseFile);

            //DataBaseにInsertする
            var testCaseFac = new TestCaseFactory();

            testCase.resultMsg = testCaseFac.insertTestCase(testCase);

            return(View("complete", testCase));
        }
コード例 #18
0
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            if (e.CloseReason == CloseReason.WindowsShutDown)
            {
                return;
            }

            // Confirm user wants to close

            switch (MessageBox.Show(this, "Would you like to save before you quit?", "Closing", MessageBoxButtons.YesNo))
            {
            case DialogResult.Yes:
                FileIo.saveCredentialToEncryptedFile(credentials);
                break;

            default:
                break;
            }
        }
コード例 #19
0
        public virtual void ExeTest <T>(T driver, ITestPropertyModelBase prop) where T : RemoteWebDriver
        {
            //テストケースの取得
            //カスタムテストケースから
            List <Dictionary <string, string> > testElemList = null;

            if (prop.testCase == "801")
            {
                testElemList = new TestCase01().TestElement(prop);
            }
            //CSVファイルから
            else if (prop.testCase == "901")
            {
                testElemList = new FileIo().TestCaseFromUploadFile(prop.uploadFileSavePath, prop.testCaseFile);
            }
            // データベースから
            else if (prop.testCase == "902")
            {
                var dbIo = new DataBaseIo();
                testElemList = dbIo.TestCaseFromDB(prop.selectTestCaseNo);
                List <TestCaseModel> testCaseList = dbIo.ExeReader <TestCaseModel>($@"select * from test_case_t where test_case_no = '{ prop.selectTestCaseNo }'");
                prop.testURL = testCaseList[0].test_url;
            }

            //ブラウザを開く
            driver.Navigate().GoToUrl(prop.testURL);

            //画面サイズ設定
            var so = new ScreenOprations();

            so.ReSize(driver, prop.screenWidth, prop.screenHeight);

            //テストケースの実行
            this.ExeTestCase <T>(driver, prop, testElemList);

            if (prop.screenCloseFlg)
            {
                //ブラウザを閉じる
                driver.Close();
            }
        }
コード例 #20
0
        //TODO:Check what happens when offline


        public static void LoadAll()
        {
            try
            {
                FileIo.CheckDirectory();
                FileIo.CheckEmpty();

                FileIo.CheckIfAgreed();

                LoadDownloads();

                WaveMaker.FirstTime = FileIo.CheckIfFirstTime();

                LoadConfigs();
                LoadKeybinds();
            }
            catch (UnableToLoadException e)
            {
                Logging.Exception(e);
                WaveMaker.HackDisabled = true;
            }
        }
コード例 #21
0
        private static void LoadKeybinds()
        {
            if (FileIo.KeybindsExist())
            {
                FileIo.StreamLoadKeybinds(out WaveMaker.Keybinds);

                if (WaveMaker.Keybinds == null)
                {
                    Logging.Log("Internal Error", "Unable to load keybinds file");
                    throw new UnableToLoadException("Unable to load keybinds file");
                }
            }
            else
            {
                FileIo.CreateKeybinds(out WaveMaker.Keybinds);

                if (WaveMaker.Keybinds == null)
                {
                    Logging.Log("Internal Error", "Unable to create keybinds file");
                    throw new UnableToLoadException("Unable to create keybinds file");
                }
            }
        }
コード例 #22
0
        static void Main(string[] args)
        {
            Log.licenseHeader();

            string baseDirectory      = AppDomain.CurrentDomain.BaseDirectory;
            string logFile            = Path.Combine(baseDirectory, logID + DateTime.Now.ToString("yyyyMMdd") + logExt);
            string workingDirectory   = String.Empty;
            string processDirectory   = String.Empty;
            bool   logVerbose         = true;
            int    fileRententionDays = 31;

            string inbox         = String.Empty;
            string searchSubject = String.Empty;

            try
            {
                workingDirectory   = ConfigurationManager.AppSettings["WorkingDirectory"];
                processDirectory   = Path.Combine(workingDirectory, processedDir);
                logVerbose         = bool.Parse(ConfigurationManager.AppSettings["LogVerbose"]);
                fileRententionDays = int.Parse(ConfigurationManager.AppSettings["ProcessedFileRetentionDays"]);

                inbox         = ConfigurationManager.AppSettings["Inbox"];
                searchSubject = ConfigurationManager.AppSettings["SearchSubject"];

                if (!Directory.Exists(workingDirectory))
                {
                    Directory.CreateDirectory(workingDirectory);
                }

                if (!Directory.Exists(processDirectory))
                {
                    Directory.CreateDirectory(processDirectory);
                }
            }
            catch (Exception ex)
            {
                Log.message(LogEntryType.ERROR, "DBAidExtractor", ex.Message + " - " + ex.StackTrace, logFile);
                Log.message(LogEntryType.ERROR, "DBAidExtractor", "Settings in App.Config may be incorrect and/or missing." + " - " + ex.StackTrace, logFile);
                Console.Write("Settings in App.Config may be incorrect and/or missing.");
                return;
            }

            try
            {
                //Clean up old log files
                FileIo.delete(baseDirectory, "*" + logExt, DateTime.Now.AddDays(-7));

                if (fileRententionDays > 0)
                {
                    fileRententionDays = fileRententionDays * -1;
                }

                //Clean up old processed files
                FileIo.delete(processDirectory, "*" + processedExt, DateTime.Now.AddDays(fileRententionDays));
            }
            catch (Exception ex)
            {
                Log.message(LogEntryType.WARNING, "DBAidExtractor", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
            }

            Log.message(LogEntryType.INFO, "DBAidExtractor", "Starting DBAid Extractor", logFile);
            //download emails from exchange
            try
            {
                Exchange.DownloadAttachement(inbox, searchSubject, workingDirectory, logFile, logVerbose);
            }
            catch (Exception ex)
            {
                Log.message(LogEntryType.ERROR, "DBAidExtractor", ex.Message, logFile);
                Log.message(LogEntryType.ERROR, "DBAidExtractor", "Error Downloading attachment from exchange", logFile);
                throw;
            }

            ConnectionStringSettings   css = ConfigurationManager.ConnectionStrings[0];
            SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder(css.ConnectionString);

            csb.ApplicationName = logID + Guid.NewGuid().ToString();

            foreach (string fileToProcess in Directory.GetFiles(workingDirectory, "*" + ext))
            {
                Dictionary <string, object> parameters = new Dictionary <string, object>();
                string servername = Path.GetFileNameWithoutExtension(fileToProcess);
                //if the instance name has an underscore, convert back.
                if (servername.Substring(0, 1) == "[")
                {
                    servername = servername.Substring(1);
                    servername = servername.Split(']')[0];
                    parameters.Add("server_name", servername);
                }
                else
                {
                    servername = servername.Split('_')[0];
                    parameters.Add("server_name", servername);
                }

                try /* Read in and decrypt encrypted files */
                {
                    string privateKey = Query.Execute(csb.ConnectionString, privateKeyProc, parameters).Rows[0][0].ToString();

                    try
                    {
                        using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(fileToProcess)))
                        {
                            Crypto.decrypt(privateKey, ms, fileToProcess.Replace(ext, ".decrypted.xml"));
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.message(LogEntryType.WARNING, "DBAidExtractor", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                        Log.message(LogEntryType.WARNING, "DBAidExtractor", "Failed to decrypted " + fileToProcess, logFile);
                        continue;
                    }

                    try
                    {
                        FileIo.move(fileToProcess, Path.Combine(processDirectory, Path.GetFileName(fileToProcess) + ".processed"));
                    }
                    catch (Exception ex)
                    {
                        Log.message(LogEntryType.WARNING, "DBAidExtractor", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                        Log.message(LogEntryType.WARNING, "DBAidExtractor", "Failed to decrypted " + fileToProcess, logFile);
                        continue;
                    }

                    if (logVerbose)
                    {
                        Log.message(LogEntryType.INFO, "DBAidExtractor", "Processed file: " + fileToProcess, logFile);
                    }
                }
                catch (Exception ex)
                {
                    Log.message(LogEntryType.WARNING, "DBAidExtractor", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                    Log.message(LogEntryType.WARNING, "DBAidExtractor", "Could not decrypt file for " + servername + " Check if server exists in DailyCheck db server table and public private key is correct", logFile);
                    continue;
                }
            }

            Log.message(LogEntryType.INFO, "DBAidExtractor", "Finished processing encrypted files.", logFile);

            // try to move the files using the the setting in FileIo.Config
            try
            {
                string      moveConfig  = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "move.config");
                XmlDocument doc         = new XmlDocument();
                string      source      = String.Empty;
                string      filter      = String.Empty;
                string      destination = String.Empty;

                if (File.Exists(moveConfig))
                {
                    doc.Load(moveConfig);

                    foreach (XPathNavigator child in doc.CreateNavigator().Select("move/file"))
                    {
                        source      = child.SelectSingleNode("@source").Value;
                        filter      = child.SelectSingleNode("@filter").Value;
                        destination = child.SelectSingleNode("@destination").Value;

                        List <MoveList> movedFiles = FileIo.movelist(source, filter, destination);

                        foreach (MoveList i in movedFiles)
                        {
                            try
                            {
                                FileIo.move(i.sourcefile, i.destfile);
                                if (logVerbose)
                                {
                                    Log.message(LogEntryType.INFO, "DBAidExtractor", "Moved file: \"" + i.sourcefile + "\" > \"" + i.destfile + "\"", logFile);
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.message(LogEntryType.WARNING, "DBAidExtractor", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                                Log.message(LogEntryType.WARNING, "DBAidExtractor", "Error occured when moving file: " + i.sourcefile, logFile);
                            }
                        }
                    }
                }
                else
                {
                    Log.message(LogEntryType.INFO, "DBAidExtractor", "No \"move.config\" file found in executable directory, skipping. ", logFile);
                }
            }
            catch (Exception ex)
            {
                Log.message(LogEntryType.WARNING, "DBAidExtractor", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
            }

            Log.message(LogEntryType.INFO, "DBAidExtractor", "Completed DBAid Extractor", logFile);
        }
コード例 #23
0
ファイル: tawsController.cs プロジェクト: outase/taws
        public ActionResult TestAction(TestProperty prop)
        {
            //Validation
            new tawsValidate().Validate(prop);
            if (prop.validationMsg.Count != 0)
            {
                //データベースからテストケースを取得
                prop.testCaseList = new DataBaseIo().ExeReader <TestCase>("select * from test_case_t");

                return(View("Index", prop));
            }

            //var browerName = ConfigurationManager.AppSettings["BrowserName"];
            var browerName = prop.testBrowser;

            //テスト実施日時取得
            prop.testDateTime = DateTime.Now.ToString("yyyyMMdd_HHmmss");

            //エビデンス用ディレクトリ作成
            var fileIo = new FileIo();

            prop.evidenceSavePath = fileIo.CreateEvidencesDirectory(prop);
            //テストケースファイル保存
            prop.uploadFileSavePath = fileIo.SaveTestCaseFiles(prop.testCaseFile, prop.testDateTime);

            //URL設定(configから)
            //var prop.testURL = $"{ConfigurationManager.AppSettings["Url"]}member";

            //ウィンドウ表示位置設定
            prop.positionX = 0;
            prop.positionY = 0;

            //スクリーンサイズ取得
            if (prop.testDevice == "pc")
            {
                prop.screenWidth  = Convert.ToInt32(ConfigurationManager.AppSettings["BrowerWidth"]);
                prop.screenHeight = Convert.ToInt32(ConfigurationManager.AppSettings["BrowerHeight"]);
            }
            else if (prop.testDevice == "sp_iphone")
            {
                prop.screenWidth  = Convert.ToInt32(ConfigurationManager.AppSettings["BrowerWidthiPhone"]);
                prop.screenHeight = Convert.ToInt32(ConfigurationManager.AppSettings["BrowerHeightiPhone"]);
            }
            else if (prop.testDevice == "sp_android")
            {
                prop.screenWidth  = Convert.ToInt32(ConfigurationManager.AppSettings["BrowerWidthAndroid"]);
                prop.screenHeight = Convert.ToInt32(ConfigurationManager.AppSettings["BrowerHeightAndroid"]);
            }


            //テスト実施---------------------------------------

            var excuteTest = new TestExecute();

            //Google Chromeのテスト
            if (browerName == "chrome")
            {
                //Web Driverの設定
                var option = new ChromeOptions();
                if (prop.testDevice == "sp_iphone")
                {
                    option.AddArgument($"--user-agent=\"{ ConfigurationManager.AppSettings["UserAgentiPhone"] }\"");
                }
                else if (prop.testDevice == "sp_android")
                {
                    option.AddArgument($"--user-agent=\"{ ConfigurationManager.AppSettings["UserAgentAndroid"] }\"");
                }

                excuteTest.ExeTest <ChromeDriver>(new ChromeDriver(option), prop);
            }
            //FireFoxのテスト
            else if (browerName == "firefox")
            {
                //Web Driverの設定
                var option = new FirefoxOptions();
                if (prop.testDevice == "sp_iphone")
                {
                    option.SetPreference("general.useragent.override", ConfigurationManager.AppSettings["UserAgentiPhone"]);
                }
                else if (prop.testDevice == "sp_android")
                {
                    option.SetPreference("general.useragent.override", ConfigurationManager.AppSettings["UserAgentAndroid"]);
                }
                //Proxyの設定
                if (Convert.ToBoolean(ConfigurationManager.AppSettings["SetProxy"]))
                {
                    var fireComm = new FireFoxTestCommons();
                    option = fireComm.SetProxy(option, ConfigurationManager.AppSettings["NonProxyString"]);
                }

                excuteTest.ExeTest <FirefoxDriver>(new FirefoxDriver(option), prop);
            }
            //Edgeのテスト
            else if (browerName == "edge")
            {
                excuteTest.ExeTest <EdgeDriver>(new EdgeDriver(), prop);
            }

            prop.resultMsg = $@"{ prop.evidenceSavePath } にテスト結果が保存されました。";

            return(View("complete", prop));
        }
コード例 #24
0
 private void frm_main_Load(object sender, EventArgs e)
 {
     credentials = FileIo.readCredentialFromEncryptedFile(credentials.email, credentials.password);
     credentials.fillInDataGrid(dgAccountList);
 }
コード例 #25
0
 private void btnSuggest_Click(object sender, EventArgs e)
 {
     tbNewPassword.Text = FileIo.generateSuggestion();
 }
コード例 #26
0
        static void Main(string[] args)
        {
            Log.licenseHeader();

            if (Array.IndexOf(args, @"/?") >= 0)
            {
                Console.WriteLine("See https://github.com/dc-sql/DBAid for more details");

                return;
            }

            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string logFile       = Path.Combine(baseDirectory, logID + DateTime.Now.ToString("yyyyMMdd") + ".log");

            Log.message(LogEntryType.INFO, "DBaidAsBuilt", "Process Started", logFile);

            Arguments flag = new Arguments(args);

            string server     = flag.ContainsFlag("-server") ? flag.GetValue("-server") : String.Empty;
            string database   = flag.ContainsFlag("-db") ? flag.GetValue("-db") : "_dbaid";
            bool   disableWmi = flag.ContainsFlag("-disablewmi") ? bool.Parse(flag.GetValue("-disablewmi")) : false;
            bool   disableMd  = flag.ContainsFlag("-disablemd") ? bool.Parse(flag.GetValue("-disablemd")) : false;
            bool   logVerbose = flag.ContainsFlag("-logverbose") ? bool.Parse(flag.GetValue("-logverbose")) : false;
            string emailSmtp  = flag.ContainsFlag("-emailsmtp") ? flag.GetValue("-emailsmtp") : String.Empty;

            string[] emailTo                   = flag.ContainsFlag("-emailto") ? flag.GetValue("-emailto").Split(new char[] { ';' }) : new string[0];
            string   emailFrom                 = flag.ContainsFlag("-emailfrom") ? flag.GetValue("-emailfrom") : String.Empty;
            string   emailSubject              = flag.ContainsFlag("-emailsubject") ? flag.GetValue("-emailsubject") : String.Empty;
            long     emailAttachmentByteLimit  = flag.ContainsFlag("-emailbytelimit") ? long.Parse(flag.GetValue("-emailbytelimit")) : 10000000;
            int      emailAttachmentCountLimit = flag.ContainsFlag("-emailattlimit") ? int.Parse(flag.GetValue("-emailattlimit")) : 15;
            bool     emailEnableSsl            = flag.ContainsFlag("-emailssl") ? bool.Parse(flag.GetValue("-emailssl")) : false;
            bool     emailIgnoreSslError       = flag.ContainsFlag("-emailignoresslerror") ? bool.Parse(flag.GetValue("-emailignoresslerror")) : false;
            bool     emailAnonymous            = flag.ContainsFlag("-emailanonymous") ? bool.Parse(flag.GetValue("-emailanonymous")) : true;
            int      connectionTimeout         = flag.ContainsFlag("-connectionTimeout") ? int.Parse(flag.GetValue("-connectionTimeout")) : 60;
            int      timeOut                   = flag.ContainsFlag("-commandTimeout") ? int.Parse(flag.GetValue("-commandTimeout")) : 30;

            if (String.IsNullOrEmpty(server))
            {
                Log.message(LogEntryType.WARNING, "DBaidAsBuilt", "No -server specified. Exiting program...", logFile);
                return;
            }

            string host     = String.Empty;
            string instance = String.Empty;

            if (server.Contains("\\"))
            {
                host     = server.Split(new char[] { '\\' }, 2)[0];
                instance = server.Split(new char[] { '\\' }, 2)[1];
            }
            else
            {
                host = server;
            }

            string file = Path.Combine(baseDirectory, server.Replace(@"\", "@").ToLower() + "_asbuilt.md");
            var    csb  = new SqlConnectionStringBuilder();

            csb.ApplicationName    = logID + Guid.NewGuid().ToString();
            csb.DataSource         = server;
            csb.InitialCatalog     = database;
            csb.IntegratedSecurity = true;
            csb.ConnectTimeout     = connectionTimeout;

            try
            {
                //clean up log files older than 3 days
                FileIo.delete(Path.GetDirectoryName(logFile), "*.log", DateTime.Now.AddDays(-3));
            }
            catch (Exception ex)
            {
                Log.message(LogEntryType.WARNING, "DBaidAsBuilt", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
            }

            try
            {
                csb.ApplicationName = Query.Select(csb.ConnectionString, mssqlAppSelect, timeOut).Rows[0][0].ToString();
            }
            catch (ApplicationException ex)
            {
                Log.message(LogEntryType.ERROR, "DBaidAsBuilt", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                Console.Write(ex);
                return;
            }

            if (!disableWmi)
            {
                var parameters = new Dictionary <string, object>();

                foreach (Wmi.PropertyValue prop in Wmi.getHostInfo(host))
                {
                    parameters.Clear();

                    parameters.Add("hierarchy", prop.Path);
                    parameters.Add("property", prop.Property.Value);
                    parameters.Add("value", prop.Value);

                    Query.Execute(csb.ConnectionString, mssqlInsertService, parameters, timeOut);
                }

                Log.message(LogEntryType.INFO, "DBaidAsBuilt", "Loaded WMI HostInfo.", logFile);

                foreach (Wmi.PropertyValue prop in Wmi.getServiceInfo(host, instance))
                {
                    parameters.Clear();

                    parameters.Add("hierarchy", prop.Path);
                    parameters.Add("property", prop.Property.Value);
                    parameters.Add("value", prop.Value);

                    Query.Execute(csb.ConnectionString, mssqlInsertService, parameters, timeOut);
                }

                Log.message(LogEntryType.INFO, "DBaidAsBuilt", "Loaded WMI ServiceInfo.", logFile);

                foreach (Wmi.PropertyValue prop in Wmi.getDriveInfo(host))
                {
                    parameters.Clear();

                    parameters.Add("hierarchy", prop.Path);
                    parameters.Add("property", prop.Property.Value);
                    parameters.Add("value", prop.Value);

                    Query.Execute(csb.ConnectionString, mssqlInsertService, parameters, timeOut);
                }

                Log.message(LogEntryType.INFO, "DBaidAsBuilt", "Loaded WMI DriveInfo.", logFile);
            }

            if (!disableMd)
            {
                using (StreamWriter outfile = new StreamWriter(file))
                {
                    try
                    {
                        outfile.Write("# As-Built Document - " + csb.DataSource + Environment.NewLine + "---" + Environment.NewLine);
                        outfile.Write("## Contents" + Environment.NewLine);
                        outfile.Write(Markdown.getMarkdown(csb.ConnectionString, mssqlControlFact, timeOut));

                        Log.message(LogEntryType.INFO, "DBaidAsBuilt", "Generated AsBuilt for [" + csb.DataSource + "]", logFile);
                    }
                    catch (Exception ex)
                    {
                        Log.message(LogEntryType.ERROR, "DBaidAsBuilt", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                        throw ex;
                    }
                }

                if (!String.IsNullOrEmpty(emailSmtp))
                {
                    try
                    {
                        Smtp.send(emailSmtp, emailFrom, emailTo, emailSubject, "", new [] { file }, emailAttachmentByteLimit, emailAttachmentCountLimit, emailEnableSsl, emailIgnoreSslError, emailAnonymous);
                        Log.message(LogEntryType.INFO, "DBaidAsBuilt", "Email sent to \"" + String.Join("; ", emailTo) + "\"", logFile);
                    }
                    catch (Exception ex)
                    {
                        Log.message(LogEntryType.ERROR, "DBaidAsBuilt", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                        throw ex;
                    }
                }
                else
                {
                    Log.message(LogEntryType.INFO, "DBaidAsBuilt", "Emailing of config not enabled or configured.", logFile);
                }
            }

            Log.message(LogEntryType.INFO, "DBaidAsBuilt", "Process Completed", logFile);

            //System.Threading.Thread.Sleep(10000);
        }
コード例 #27
0
 public void SaveFriends()
 {
     FileIo.SaveFriends(this);
 }
コード例 #28
0
 private void frm_LogIn_Load(object sender, EventArgs e)
 {
     FileIo.initWordList();
     AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
 }
コード例 #29
0
 private static void InitializeCoursesList()
 {
     FileIo.LoadFileFromTxt("sel_courses.list", out ProgramData.ReadyToSelectCoursesList);
     FileIo.LoadFileFromTxt("del_courses.list", out ProgramData.ReadyToDeleteCoursesList);
 }
コード例 #30
0
 private void exportToolStripMenuItem_Click(object sender, EventArgs e)
 {
     FileIo.Export(credentials);
 }
コード例 #31
0
ファイル: Program.cs プロジェクト: yang-jiayi/DBAid
        static void Main(string[] args)
        {
            Log.licenseHeader();

            if (Array.IndexOf(args, @"/?") >= 0)
            {
                Console.WriteLine("See https://github.com/dc-sql/DBAid for more details");

                return;
            }

            Arguments flag = new Arguments(args);

            string server   = flag.ContainsFlag("-server") ? flag.GetValue("-server") : String.Empty;
            string database = flag.ContainsFlag("-db") ? flag.GetValue("-db") : "_dbaid";

            int errorCount   = 0;
            int warningCount = 0;

            string baseDirectory      = AppDomain.CurrentDomain.BaseDirectory;
            string logFile            = Path.Combine(baseDirectory, logID + DateTime.Now.ToString("yyyyMMdd") + logExt);
            string workingDirectory   = String.Empty;
            string processDirectory   = String.Empty;
            bool   logVerbose         = true;
            byte   fileRententionDays = 7;

            bool   emailEnable = true;
            string emailSmtp   = String.Empty;

            string[] emailTo                        = { String.Empty };
            string   emailFrom                      = String.Empty;
            string   emailSubject                   = String.Empty;
            long     emailAttachmentByteLimit       = 0;
            int      emailAttachmentCountLimit      = 0;
            bool     emailEnableSsl                 = true;
            bool     emailIgnoreSslError            = false;
            bool     emailAnonymous                 = true;
            int      defaultCmdTimout               = 0;
            ConnectionStringSettingsCollection cssc = new ConnectionStringSettingsCollection();

            try
            {
                if (String.IsNullOrEmpty(server) || String.IsNullOrEmpty(database))
                {
                    cssc = ConfigurationManager.ConnectionStrings;
                }
                else
                {
                    string cs = "Server=" + server + ";Database=" + database + ";Trusted_Connection=True;";
                    cssc.Add(new ConnectionStringSettings(server.Replace("\\", "@"), cs));
                }

                workingDirectory   = ConfigurationManager.AppSettings["WorkingDirectory"];
                processDirectory   = Path.Combine(workingDirectory, processedDir);
                logVerbose         = bool.Parse(ConfigurationManager.AppSettings["logVerbose"]);
                fileRententionDays = byte.Parse(ConfigurationManager.AppSettings["ProcessedFileRetentionDays"]);

                emailEnable               = bool.Parse(ConfigurationManager.AppSettings["emailEnable"]);
                emailSmtp                 = ConfigurationManager.AppSettings["EmailSmtp"];
                emailTo                   = ConfigurationManager.AppSettings["EmailTo"].Split(';');
                emailFrom                 = ConfigurationManager.AppSettings["EmailFrom"];
                emailSubject              = ConfigurationManager.AppSettings["EmailSubject"];
                emailAttachmentByteLimit  = long.Parse(ConfigurationManager.AppSettings["EmailAttachmentByteLimit"]);
                emailAttachmentCountLimit = int.Parse(ConfigurationManager.AppSettings["EmailAttachmentCountLimit"]);
                emailEnableSsl            = bool.Parse(ConfigurationManager.AppSettings["EmailEnableSsl"]);
                emailIgnoreSslError       = bool.Parse(ConfigurationManager.AppSettings["EmailIgnoreSslError"]);
                emailAnonymous            = bool.Parse(ConfigurationManager.AppSettings["EmailAnonymous"]);
                defaultCmdTimout          = int.Parse(ConfigurationManager.AppSettings["default_cmd_timeout_sec"]);

                if (!Directory.Exists(workingDirectory))
                {
                    Directory.CreateDirectory(workingDirectory);
                }

                if (!Directory.Exists(processDirectory))
                {
                    Directory.CreateDirectory(processDirectory);
                }

                Log.message(LogEntryType.INFO, "DBAidCollector", "Starting DBAid Collector", logFile);
            }
            catch (Exception ex)
            {
                Log.message(LogEntryType.ERROR, "DBAidCollector", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                errorCount++;
                if (emailEnable)
                {
                    Smtp.send(emailSmtp, emailFrom, emailTo, Environment.MachineName, "Failed to initialise DBAid collector", null, emailAttachmentByteLimit, emailAttachmentCountLimit, emailEnableSsl, emailIgnoreSslError, emailAnonymous);
                }
                Console.Write("Settings in App.Config may be incorrect and/or missing, or permissions to write log file is missing.");
                return;
            }

            try
            {
                //Clean up old files
                FileIo.delete(baseDirectory, "*" + logExt, DateTime.Now.AddDays(-7));

                FileIo.delete(processDirectory, "*" + processedExt, DateTime.Now.AddDays(fileRententionDays * -1));
            }
            catch (Exception ex)
            {
                Log.message(LogEntryType.WARNING, "DBAidCollector", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                warningCount++;
            }

            foreach (ConnectionStringSettings css in cssc)
            {
                DateTime runtime = DateTime.UtcNow;
                SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder(css.ConnectionString);
                DataRowCollection          procedures;
                List <string> attachments = new List <string>();
                string        publicKey   = String.Empty;
                string        instanceTag = String.Empty;

                csb.ApplicationName = logID + Guid.NewGuid().ToString();
                Log.message(LogEntryType.INFO, "DBAidCollector", "Starting Collection on [" + csb.DataSource + "]", logFile);

                try
                {
                    // query database for assigned application name.
                    csb.ApplicationName = Query.Select(csb.ConnectionString, mssqlAppSelect, defaultCmdTimout).Rows[0][0].ToString();
                    // query database for instance guid.
                    instanceTag = Query.Execute(csb.ConnectionString, mssqlInstanceTagProc, defaultCmdTimout).Rows[0][0].ToString();

                    if (String.IsNullOrEmpty(instanceTag))
                    {
                        instanceTag = css.Name.Replace("\\", "@").Replace("_", "~") + "_" + IPGlobalProperties.GetIPGlobalProperties().DomainName.Replace(".", "_");
                    }

                    // query database for public key.
                    publicKey = Query.Select(csb.ConnectionString, mssqlKeySelect, defaultCmdTimout).Rows[0][0].ToString();
                    // get procedure returned from control procedure.
                    procedures = Query.Select(csb.ConnectionString, mssqlControlProc, defaultCmdTimout).Rows;
                }
                catch (Exception ex)
                {
                    Log.message(LogEntryType.WARNING, "DBAidCollector", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                    warningCount++;
                    continue;
                }

                foreach (DataRow dr in procedures)
                {
                    string file     = instanceTag + "_" + dr[0].ToString().Replace("].[", "_").Replace(".", "_") + "_" + runtime.ToString("yyyyMMddHHmmss") + encryptedExt;
                    string filepath = Path.Combine(workingDirectory, file);
                    // execute procedure, compress, and encrypt stream. Write contents out to file.
                    using (MemoryStream msRaw = new MemoryStream())
                        using (StreamWriter swRaw = new StreamWriter(msRaw, Encoding.Unicode))
                        {
                            try
                            {
                                DataTable     dt = Query.Execute(csb.ConnectionString, dr[0].ToString(), defaultCmdTimout);
                                StringBuilder sb = new StringBuilder(dt.TableName.Length);

                                foreach (char c in dt.TableName) // remove special characters from table name as this causes issues with SSIS xml source.
                                {
                                    if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '-' || c == '_')
                                    {
                                        sb.Append(c);
                                    }
                                }

                                dt.TableName = sb.ToString();
                                dt.WriteXml(swRaw, XmlWriteMode.WriteSchema);
                                dt.Clear();
                            }
                            catch (Exception ex)
                            {
                                Log.message(LogEntryType.WARNING, "DBAidCollector", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                                warningCount++;
                                continue;
                            }

                            try
                            {
                                if (logVerbose)
                                {
                                    Log.message(LogEntryType.INFO, "DBAidCollector", "Writing Encrypted File: \"" + filepath + "\"", logFile);
                                }

                                Crypto.encrypt(publicKey, msRaw, filepath);
                            }
                            catch (Exception ex)
                            {
                                Log.message(LogEntryType.WARNING, "DBAidCollector", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                                warningCount++;
                                continue;
                            }
                        }
                }

                Log.message(LogEntryType.INFO, "DBAidCollector", "Completed Collection on [" + csb.DataSource + "]", logFile);

                try
                {
                    foreach (string file in Directory.GetFiles(workingDirectory, "*" + encryptedExt))
                    {
                        attachments.Add(file);
                    }

                    string body = "DBAid collector process logged: \n\t"
                                  + errorCount.ToString()
                                  + " error(s) \n\t"
                                  + warningCount.ToString()
                                  + " warning(s) \n";

                    if (emailEnable)
                    {
                        Smtp.send(emailSmtp, emailFrom, emailTo, emailSubject, body, attachments.ToArray(), emailAttachmentByteLimit, emailAttachmentCountLimit, emailEnableSsl, emailIgnoreSslError, emailAnonymous);

                        foreach (string file in attachments)
                        {
                            FileIo.move(file, Path.Combine(processDirectory, Path.GetFileName(file) + processedExt));
                        }

                        Log.message(LogEntryType.INFO, "DBAidCollector", "Email Sent to \"" + string.Join("; ", emailTo) + "\"", logFile);
                    }
                }
                catch (Exception ex)
                {
                    Log.message(LogEntryType.WARNING, "DBAidCollector", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                }
            }

            Log.message(LogEntryType.INFO, "DBAidCollector", "Completed DBAid Collection", logFile);

            //System.Threading.Thread.Sleep(10000);
        }