예제 #1
0
 public PlayerView(FileHandler fileHandler)
 {
     playerView = new ModalPlayerView();
     buttonAction = ButtonAction.NONE;
     this.fileHandler = fileHandler;
     WireHandlers();
 }
예제 #2
0
 public TeamSelectDelete(FileHandler fileHandler)
     : base(fileHandler)
 {
     deletedTeams = new List<int>();
     modalSelect.SetTeamDelete();
     WireHandlers();
 }
예제 #3
0
파일: TIL.cs 프로젝트: osROSE/UnityRose
        /// <summary>
        /// Loads the specified file.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        public void Load(string filePath)
        {
            FileHandler fh = new FileHandler(FilePath = filePath, FileHandler.FileOpenMode.Reading, null);

            int width = fh.Read<int>();
            int height = fh.Read<int>();

            Tiles = new Tile[height, width];

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    Tiles[y, x] = new Tile()
                    {
                        BrushID = fh.Read<byte>(),
                        TileIndex = fh.Read<byte>(),
                        TileSetNumber = fh.Read<byte>(),
                        TileID = fh.Read<int>()
                    };
                }
            }

            fh.Close();
        }
예제 #4
0
파일: LTB.cs 프로젝트: osROSE/UnityRose
        /// <summary>
        /// Loads the specified file.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        public void Load(string filePath)
        {
            FileHandler fh = new FileHandler(filePath, FileHandler.FileOpenMode.Reading, Encoding.GetEncoding("Unicode"));

            int columnCount = fh.Read<int>();
            int rowCount = fh.Read<int>();

            int[,] offsets = new int[rowCount, columnCount];
            short[,] lengths = new short[rowCount, columnCount];

            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < columnCount; j++)
                {
                    offsets[i, j] = fh.Read<int>();
                    lengths[i, j] = fh.Read<short>();
                }
            }

            Cells = new List<List<string>>(rowCount);

            for (int i = 0; i < rowCount; i++)
            {
                Cells.Add(new List<string>(columnCount));

                for (int j = 0; j < columnCount; j++)
                {
                    fh.Seek(offsets[i, j], SeekOrigin.Begin);

                    Cells[i].Add(fh.Read<string>(lengths[i, j] * 2));
                }
            }

            fh.Close();
        }
        public SalesManagerService()
        {
            InitializeComponent();

            log4net.Config.XmlConfigurator.Configure();
            _logger = LogManager.GetLogger("Windows Service");

            ApplicationConfigValidator validator = new ApplicationConfigValidator();
            try
            {
                validator.Validate();

                _serverFolderPath = ConfigurationManager.AppSettings["ServerFolder"];
                _wrongFilesFolderPath = ConfigurationManager.AppSettings["NotAppropriateFilesFolder"];
                _processedFiles = ConfigurationManager.AppSettings["ProcessedFilesFolder"];

                _cancelationTokenSource = new CancellationTokenSource();

                var taskScheduler =
                    new LimitedTaskScheduler(Int32.Parse(ConfigurationManager.AppSettings["MaxDatabaseConnections"]));
                _taskFactory = new TaskFactory(taskScheduler);
                _fileHandler = new FileHandler();
            }
            catch (ConfigurationErrorsException ex)
            {
                _logger.Fatal("Eroor occurs with configuration. " + ex.Message);
                return;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                _logger.Fatal("Erorr occurs with max number of connections to database. " + ex.Message);
                return;
            }
        }
예제 #6
0
        public W3CFieldCache(FileHandler ioHandler)
        {
            if (ioHandler == null)
                throw new ArgumentNullException("ioHandler");

            this.ioHandler = ioHandler;
        }
예제 #7
0
 public void SetFileManager(List<Imagen> imagenes, FileHandler fh, AddElemento ae)
 {
     F_H = fh;
     A_E = ae;
     foreach  (Imagen a in imagenes)
     {
         SelectImage.Items.Add(a.Nombre);
     }
 }
예제 #8
0
 public TeamSuper(FileHandler fileHandler)
 {
     players = new Dictionary<int, Player>();
     deletedPlayers = new List<int>();
     this.fileHandler = fileHandler;
     modalTeam = new ModalTeam();
     buttonAction = ButtonAction.NONE;
     WireHandlers();
 }
예제 #9
0
 public TeamSelect(FileHandler fileHandler)
 {
     this.fileHandler = fileHandler;
     teams = fileHandler.GetTeams();
     editedTeamsID = new List<int>();
     modalSelect = new ModalSelect();
     buttonAction = ButtonAction.NONE;
     WireCommonHandlers();
     modalSelect.DisplayTeams(teams);
 }
예제 #10
0
 public MainModel()
 {
     LogText = "No files selected...\r\n";
     CharConversion = false;
     FileExport = false;
     LeftFileHandler = new FileHandler();
     RightFileHandler = new FileHandler();
     RightFileName = "";
     LeftFileName = "";
 }
예제 #11
0
 public PlayerSelect(FileHandler fileHandler)
 {
     this.fileHandler = fileHandler;
     this.players = fileHandler.GetPlayers();
     playersIDSelected = new List<int>();
     modalSelect = new ModalSelect();
     buttonAction = ButtonAction.NONE;
     WireCommonHandlers();
     modalSelect.DisplayPlayers(players);
 }
예제 #12
0
 public ViewData(string name)
     : base(name)
 {
     FileHandler file = new FileHandler();
     foreach (string s in file.GetDirectorySubfolders(file.Files))
     {
         GameViewModel game = new GameViewModel(Path.GetFileName(s), s);
         Games.Add(game);
     }
 }
예제 #13
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var fileHandler = new FileHandler();
            var mainForm = new MainForm();
            var presenter = new MainPresenter(mainForm, new ContactRepository(fileHandler));

            Application.Run(mainForm);
        }
예제 #14
0
        public void SetUp()
        {
            testDir = @"./testFiles/";
            Directory.CreateDirectory(testDir);
            FileInfo tp = new FileInfo(testDir + "satisfaction.txt");
            //System.IO.File.WriteAllLines(tp.FullName, _satisfactionLyrics);
            string test = "Push me" + System.Environment.NewLine + "And then just touch me" + System.Environment.NewLine + "Till I can get my satisfaction" + System.Environment.NewLine + "Satisfaction, satisfaction, satisfaction,satifaction";
            System.IO.File.WriteAllText(tp.FullName, test);

            _handler = new FileHandler(".txt");
            _info = new FileInfo(testDir + "satisfaction.txt");
            _fileNonExistent = new FileInfo(testDir + "ThisFileDoesNotExist");
        }
예제 #15
0
        public frmError()
        {
            InitializeComponent();

            // Force grip style shown
            this.SizeGripStyle = SizeGripStyle.Show;

            // Set icon
            this.Icon = Values.icoAppIcon;

            MarketScanner.Common.FileHandler filehandler = new FileHandler();
            string messageForUser = string.Format("An unhandled error has occurred. The error is shown in the text box below and also written to the error log at \"{0}\"", filehandler.ErrorLogPath);
            label1.Text = messageForUser;
        }
예제 #16
0
        public void TestFileHasBeenModified()
        {
            // FileInfo tp = new FileInfo(testDir + "satisfaction.txt");
            // System.IO.File.WriteAllLines(tp.FullName, _satisfactionLyrics);
            // System.Windows.Forms.MessageBox.Show(File.Exists(tp.FullName).ToString());
            Assert.IsTrue(File.Exists(_info.FullName));
            Assert.IsFalse(_handler.HasFileBeenModified(_info));
            _handler.LoadFile(_info);
            Assert.IsFalse(_handler.HasFileBeenModified(_info));

            var temp = new FileHandler(".txt");
            temp.UpdateFileContentInMemory(_info, new[] { "Hello World", "This is a test" });
            temp.SaveFile(_info);
            Assert.IsTrue(_handler.HasFileBeenModified(_info));
        }
예제 #17
0
      private TXTextControl.FrameBase _objSel;                      // Currently selected object

      #endregion

      #region " Form Properties "

      public RichTextForm(IList<string> args)
      {
         InitializeComponent();
         _textControl.ButtonBar = buttonBar1;
         _textControl.RulerBar = rulerBar1;
         _textControl.VerticalRulerBar = rulerBar2;
         _textControl.StatusBar = statusBar1;

         _fileHandler = new FileHandler(this, _textControl);
         _fileDragDrop = new FileDragDropHandler();

         if (args != null && args.Count != 0)
         {
            _fileHandler.DocumentFileName = args[0];
            _bLoadFileOnCreate = true;
         }
      }
예제 #18
0
        // Global exeption handlers
        private static void ThreadExceptionHandler( object sender, ThreadExceptionEventArgs args )
        {
            try
            {
                // Write to error log
                MarketScanner.Common.FileHandler filehandler = new FileHandler();
                filehandler.WriteErrorLog( args.Exception );

                frmError errWindow = new frmError();
                errWindow.StartPosition = FormStartPosition.CenterParent;
                errWindow.ErrorMessage = args.Exception.ToString();
                errWindow.Show();
            }
            catch
            {
            }
        }
예제 #19
0
파일: MOV.cs 프로젝트: osROSE/UnityRose
        /// <summary>
        /// Loads the specified file.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        public void Load(string filePath)
        {
            FileHandler fh = new FileHandler(FilePath = filePath, FileHandler.FileOpenMode.Reading, Encoding.UTF8);

            int height = fh.Read<int>();
            int width = fh.Read<int>();

            IsWalkable = new byte[height, width];

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                    IsWalkable[y, x] = fh.Read<byte>();
            }

            fh.Close();
        }
예제 #20
0
        private static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            _logger = LogManager.GetLogger("Console application");

            try
            {

                _fileHandler = new FileHandler(new ManagerSalesParser(), new CsvReader());

                _maxNummberOfConnections = int.Parse(ConfigurationManager.AppSettings["MaxDatabaseConnections"]);
                _serverFolderPath = ConfigurationManager.AppSettings["ServerFolder"];
                _wrongFilesFolderPath = ConfigurationManager.AppSettings["NotAppropriateFilesFolder"];
                _processedFiles = ConfigurationManager.AppSettings["ProcessedFilesFolder"];

                SettingUpEnvironment.SettingUpFolders(new List<string>
                {
                    _serverFolderPath,
                    _wrongFilesFolderPath,
                    _processedFiles
                });

                _taskFactory = new TaskFactory(new ManagerTasksScheduler(_maxNummberOfConnections));

            }
            catch (ArgumentNullException ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                return;
            }

            ScanFolder();

            var watcher = new FileSystemWatcher
            {
                Path = _serverFolderPath,
                Filter = "*csv"
            };

            watcher.Created += WatcherOnCreated;
            watcher.EnableRaisingEvents = true;

            Console.Read();
        }
예제 #21
0
        public Indstillinger()
        {
            this.StartPosition = FormStartPosition.CenterParent;
            InitializeComponent();
            fileHandler = FileHandler.Instance;
            FillListViewBaner();
            FillListViewBarn();

            if(ListViewBaner.Items.Count > 0)
            {
                ListViewBaner.SelectedIndex = 0;
            }
            var screens = Screen.AllScreens;
            foreach(Screen s in screens)
                listBoxSkærme.Items.Add(s.DeviceName);

            loadSettings();
        }
예제 #22
0
파일: PageSetup.cs 프로젝트: gipasoft/Sfera
      public static void pageSetup_Click(
         object                     sender, 
         System.EventArgs           e, 
         TXTextControl.TextControl  tc,
         FileHandler                fh
      )
      {
         PageSetupDialog psd = new PageSetupDialog();
         psd.Document = new PrintDocument();

         tc.PageUnit = TXTextControl.MeasuringUnit.CentiInch;

         psd.EnableMetric = true;
         psd.PageSettings.PaperSize 
            = GetTxPaperSize(
                  tc.Selection.SectionFormat.PageSize, 
                  tc.Selection.SectionFormat.Landscape
              );

         Margins mrgDlg = psd.PageSettings.Margins;
         TXTextControl.PageMargins mrgTX = tc.Selection.SectionFormat.PageMargins;
         mrgDlg.Top = (int)mrgTX.Top; mrgDlg.Right = (int)mrgTX.Right;
         mrgDlg.Bottom = (int)mrgTX.Bottom; mrgDlg.Left = (int)mrgTX.Left;

         psd.PageSettings.Landscape = tc.Selection.SectionFormat.Landscape;

         if (psd.ShowDialog() == DialogResult.OK)
         {
            mrgDlg = psd.PageSettings.Margins;

            mrgTX.Top = mrgDlg.Top; mrgTX.Right = mrgDlg.Right; 
            mrgTX.Bottom = mrgDlg.Bottom; mrgTX.Left = mrgDlg.Left;

            // Temporarily set page orientation to portrait so the 
            // page size is set correctly
            tc.Selection.SectionFormat.Landscape = false;

            tc.Selection.SectionFormat.PageSize.Height = psd.PageSettings.PaperSize.Height;
            tc.Selection.SectionFormat.PageSize.Width = psd.PageSettings.PaperSize.Width;
            tc.Selection.SectionFormat.Landscape = psd.PageSettings.Landscape;

            fh.DocumentDirty = true;
         }
      }
예제 #23
0
        public VentanaJuego()
        {
            InitializeComponent();
            //this.Width = w;
            //this.Height = h;
            //pictureBox1.Width = w ;
            //pictureBox1.Height = h;
            //----------Manager--------------------//
            F_M = new FileManager();
            R_M = new RenderManager();
            S_M = new SceneManager();
            PM = new PhisicManager();

            //--------Delegados-------------------//
            S_H = new SceneHandler(S_M.PlayScene);
            R_H = new RenderHandler(R_M.AddData);
            F_H = new FileHandler(F_M.GetImg);

            //---------Inicializacion------------//
            R_M.AddHandlers(S_H, F_H);
            //mapa1.SetFileManager(F_H);
            mapa1 = F_M.CargarMapa("../../Mapas/mapa3.xml", this.Width, this.Height, 32);
            mapa1.IM.left = Keys.A;
            mapa1.IM.right = Keys.D;
            mapa1.IM.up = Keys.W;
            mapa1.IM.down = Keys.S;
            mapa1.Draw(R_H);
            R_M.Sorting();
            //--------Timer--------------------//
            //Thread mov = new Thread(Caminar);
            //Thread col = new Thread(Colicion);
            //mov.Start();
            timer1.Start();
            //col.Start();
            mapa1.FraccPantalla(pictureBox1.Width, pictureBox1.Height);
            mapa1.CentrarJugador();
            //----------Sonido------------------//
            //mp = new MP3Player();
            //mp.Open(F_M.GetAud_Path("Correr"));
            //mp.Play();

            pictureBox1.Refresh();
        }
예제 #24
0
 //, AddElemento ae)
 public MakeMap(FileHandler fh, List<Elemento> herr, CreateMap cm)
 {
     InitializeComponent();
     //
     Matriz = new List<Elemento>();
     temMap = new Map("", 0, 0, (int)width.Value, (int)height.Value, trackBar1.Maximum);
     S_M = new SceneManager();
     R_M = new RenderManager();
     R_M.AddHandlers(new SceneHandler(S_M.PlayScene), fh);
     F_H = fh;
     temMap.SetFileManager(fh);
     CrearMatriz((int)height.Value,(int)width.Value,trackBar1.Value,1);
     temMap.Draw(new RenderHandler(R_M.AddData));
     R_M.Fondo = Color.White;
     temp = new List<Elemento>();
     Herramienta = herr;
     pm = new PhisicManager();
     C_M = cm;
 }
예제 #25
0
        static void Main(string[] args)
        {
            ApplicationConfigValidator validator = new ApplicationConfigValidator();

            log4net.Config.XmlConfigurator.Configure();
            _logger = LogManager.GetLogger("Console application");

            try
            {
                validator.Validate();

                _serverFolderPath = ConfigurationManager.AppSettings["ServerFolder"];
                _wrongFilesFolderPath = ConfigurationManager.AppSettings["NotAppropriateFilesFolder"];
                _processedFiles = ConfigurationManager.AppSettings["ProcessedFilesFolder"];

                var taskScheduler =
                    new LimitedTaskScheduler(Int32.Parse(ConfigurationManager.AppSettings["MaxDatabaseConnections"]));
                _taskFactory = new TaskFactory(taskScheduler);
                _fileHandler = new FileHandler();
            }
            catch (ConfigurationErrorsException ex)
            {
                _logger.Fatal("Eroor occurs with configuration. " + ex.Message);
                return;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                _logger.Fatal("Erorr occurs with max number of connections to database. " + ex.Message);
                return;
            }

            ScanServerFolder();

            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = _serverFolderPath;
            watcher.Filter = "*.csv";
            watcher.Created += new FileSystemEventHandler(OnChanged);

            watcher.EnableRaisingEvents = true;

            Console.Read();
        }
        protected override void OnStart(string[] args)
        {
            try
            {
                _fileHandler = new FileHandler(new ManagerSalesParser(), new CsvReader());

                _maxNummberOfConnections = int.Parse(ConfigurationManager.AppSettings["MaxDatabaseConnections"]);
                _serverFolderPath = ConfigurationManager.AppSettings["ServerFolder"];
                _wrongFilesFolderPath = ConfigurationManager.AppSettings["NotAppropriateFilesFolder"];
                _processedFiles = ConfigurationManager.AppSettings["ProcessedFilesFolder"];

                SettingUpEnvironment.SettingUpFolders(new List<string>
                {
                    _serverFolderPath,
                    _wrongFilesFolderPath,
                    _processedFiles
                });

                _taskFactory = new TaskFactory(new ManagerTasksScheduler(_maxNummberOfConnections));
            }
            catch (ArgumentNullException ex)
            {
                _logger.Warn(ex.Message);
                return;
            }

            ScanFolder();

            var watcher = new FileSystemWatcher
            {
                Path = _serverFolderPath,
                Filter = "*csv"
            };

            watcher.Created += WatcherOnCreated;
            watcher.EnableRaisingEvents = true;
        }
예제 #27
0
 public Data_Tests()
 {
     _fileHandler = new FileHandler();
 }
예제 #28
0
 public static string LoadJson()
 {
     return(FileHandler.ReadFromFile("Database.json"));
 }
예제 #29
0
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtUserID.Text == string.Empty)
                {
                    //MessageHandler.ShowMessageBox(string.Format("用户ID不能为空。"), "用户登录", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    MessageHandler.ShowMessageBox("用户ID不能为空。");
                    txtUserID.Focus();
                    return;
                }

                if (txtPassword.Text == string.Empty)
                {
                    //MessageHandler.ShowMessageBox(string.Format("密码不能为空。"), "用户登录", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    MessageHandler.ShowMessageBox("密码不能为空。");
                    txtPassword.Focus();
                    return;
                }

                FileHandler fileHandler = new FileHandler();
                string      iniPath     = System.Windows.Forms.Application.StartupPath + "\\Config.ini";

                try
                {
                    //Data Source=192.168.0.3;Initial Catalog=PSAP;Persist Security Info=True;User ID=sa;Password=1qaz2wsx

                    string dataSourceStr = fileHandler.IniReadValue(iniPath, "System", "DataSource");
                    string userIDStr     = fileHandler.IniReadValue(iniPath, "System", "UserID");
                    string passwordStr   = fileHandler.IniReadValue(iniPath, "System", "Password");

                    BaseSQL.connectionString = BaseSQL.GetConnectionString(dataSourceStr, "PSAP", userIDStr, passwordStr);

                    string tempStr      = BaseSQL.connectionString.Replace("Data Source=", "");
                    string ipAddressStr = tempStr.Substring(0, tempStr.IndexOf(";"));

                    if (!new SystemHandler().TestIPAddress(ipAddressStr, 1000))
                    {
                        MessageHandler.ShowMessageBox(string.Format("IP地址【{0}】连接不通,请确认客户端和服务端的网络是否正常。", ipAddressStr));
                        btnSet.Visible = true;
                        return;
                    }
                    if (!BaseSQL.TestSqlConnection())
                    {
                        MessageHandler.ShowMessageBox("服务端的数据库不能正常访问,请确认数据库是否正常");
                        btnSet.Visible = true;
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageHandler.ShowMessageBox(ex.Message);
                    return;
                }

                EncryptMD5 en = new EncryptMD5(txtPassword.Text);                //实例化EncryptMD5, 加密后值引用en.str2
                if (FrmLoginBLL.CheckUser(txtUserID.Text, en.str2, cboLanguage)) // en.str2为加密后密码
                {
                    if (SystemInfo.user.IsDisable == 1)
                    {
                        MessageHandler.ShowMessageBox("当前用户已经停用,不可以登陆系统。");
                        txtUserID.Focus();
                        return;
                    }

                    new SystemHandler().InitializationSystemInfo(txtPassword.Text);

                    if (SystemInfo.IsCheckServer)//启动服务端检测
                    {
                        SocketHandler socket     = new SocketHandler();
                        string        messageStr = "";
                        if (!socket.ConnectServer(ref messageStr))
                        {
                            MessageHandler.ShowMessageBox(messageStr);
                            return;
                        }
                    }

                    fileHandler.IniWriteValue(iniPath, "System", "LastLanguage", cboLanguage.SelectedValue.ToString());

                    //Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    // cfa.AppSettings.Settings["last"].Value = "111";
                    //            cfa.Save();


                    Thread formThread = new Thread(ThreadInitializeForm);
                    formThread.Start();

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    txtPassword.Focus();
                }
            }
            catch (Exception ex)
            {
                //ExceptionHandler.HandleException(this.Text + "--用户登录错误。", ex);
                ExceptionHandler.HandleException(this.Text + "--" + tsmiYhdlcw.Text, ex);
            }
        }
예제 #30
0
 public void SaveStaticGame(object sender, RoutedEventArgs e)
 {
     FileHandler.SaveStaticMap();
     MessageBox.Show("Game Saved!");
 }
예제 #31
0
 /**********************SAVE Button**********************/
 private void BtSave_Click(object sender, EventArgs e)
 {
     FileHandler.writeToBinFile(this.listOfShapes);
 }
예제 #32
0
파일: ZON.cs 프로젝트: x3sphiorx/UnityRose
        /// <summary>
        /// Saves the specified file.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        public void Save(string filePath)
        {
            FileHandler fh = new FileHandler(FilePath = filePath, FileHandler.FileOpenMode.Writing, Encoding.UTF8);

            fh.Write <int>(Blocks.Count);

            for (int i = 0; i < Blocks.Count; i++)
            {
                fh.Write <int>(0);
                fh.Write <int>(0);
            }

            for (int i = 0; i < Blocks.Count; i++)
            {
                Blocks[i].Offset = fh.Tell();

                switch (Blocks[i].Type)
                {
                case BlockType.Block0:
                {
                    fh.Write <int>(ZoneInfo.ZoneType);
                    fh.Write <int>(ZoneInfo.ZoneWidth);
                    fh.Write <int>(ZoneInfo.ZoneHeight);
                    fh.Write <int>(ZoneInfo.GridCount);
                    fh.Write <float>(ZoneInfo.GridSize);

                    fh.Write <int>(ZoneInfo.XCount);
                    fh.Write <int>(ZoneInfo.YCount);

                    for (int x = 0; x < ZoneInfo.ZoneWidth; x++)
                    {
                        for (int y = 0; y < ZoneInfo.ZoneHeight; y++)
                        {
                            fh.Write <byte>(ZoneInfo.ZoneParts[x, y].UseMap);
                            fh.Write <Vector2>(ZoneInfo.ZoneParts[x, y].Position);
                        }
                    }
                }
                break;

                case BlockType.SpawnPoints:
                {
                    fh.Write <int>(SpawnPoints.Count);

                    for (int j = 0; j < SpawnPoints.Count; j++)
                    {
                        fh.Write <float>(-520000.0f + (SpawnPoints[j].Position.x * 100.0f));
                        fh.Write <float>(SpawnPoints[j].Position.z * 100.0f);
                        fh.Write <float>(-520000.0f + (SpawnPoints[j].Position.y * 100.0f));

                        fh.Write <BString>(SpawnPoints[j].Name);
                    }
                }
                break;

                case BlockType.Textures:
                {
                    fh.Write <int>(Textures.Count);

                    for (int j = 0; j < Textures.Count; j++)
                    {
                        fh.Write <BString>(Textures[j].TexPath);
                    }
                }
                break;

                case BlockType.Tiles:
                {
                    fh.Write <int>(Tiles.Count);

                    for (int j = 0; j < Tiles.Count; j++)
                    {
                        fh.Write <int>(Tiles[j].BaseID1);
                        fh.Write <int>(Tiles[j].BaseID2);
                        fh.Write <int>(Tiles[j].Offset1);
                        fh.Write <int>(Tiles[j].Offset2);
                        fh.Write <int>(Tiles[j].IsBlending ? 1 : 0);
                        fh.Write <int>((int)Tiles[j].Rotation);
                        fh.Write <int>(Tiles[j].TileType);
                    }
                }
                break;

                case BlockType.Economy:
                {
                    fh.Write <BString>(EconomyInfo.AreaName);
                    fh.Write <int>(EconomyInfo.IsUnderground);
                    fh.Write <BString>(EconomyInfo.ButtonBGM);
                    fh.Write <BString>(EconomyInfo.ButtonBack);
                    fh.Write <int>(EconomyInfo.CheckCount);
                    fh.Write <int>(EconomyInfo.StandardPopulation);
                    fh.Write <int>(EconomyInfo.StandardGrowthRate);
                    fh.Write <int>(EconomyInfo.MetalConsumption);
                    fh.Write <int>(EconomyInfo.StoneConsumption);
                    fh.Write <int>(EconomyInfo.WoodConsumption);
                    fh.Write <int>(EconomyInfo.LeatherConsumption);
                    fh.Write <int>(EconomyInfo.ClothConsumption);
                    fh.Write <int>(EconomyInfo.AlchemyConsumption);
                    fh.Write <int>(EconomyInfo.ChemicalConsumption);
                    fh.Write <int>(EconomyInfo.IndustrialConsumption);
                    fh.Write <int>(EconomyInfo.MedicineConsumption);
                    fh.Write <int>(EconomyInfo.FoodConsumption);
                }
                break;
                }
            }

            fh.Seek(4, SeekOrigin.Begin);

            for (int i = 0; i < Blocks.Count; i++)
            {
                fh.Write <int>((int)Blocks[i].Type);
                fh.Write <int>(Blocks[i].Offset);
            }

            fh.Close();
        }
예제 #33
0
파일: CHR.cs 프로젝트: x3sphiorx/UnityRose
        public void Load(string filePath)
        {
            var fh = new FileHandler(filePath, FileHandler.FileOpenMode.Reading, Encoding.UTF8);

            short skeletonFileCount = fh.Read <short>();

            for (int i = 0; i < skeletonFileCount; i++)
            {
                string skeletonFile = fh.Read <ZString>();
                SkeletonFiles.Add(skeletonFile);
            }

            short motionFileCount = fh.Read <short>();

            for (int i = 0; i < motionFileCount; i++)
            {
                string motionFile = fh.Read <ZString>();

                MotionFiles.Add(motionFile);
            }

            short effectFileCount = fh.Read <short>();

            for (int i = 0; i < effectFileCount; i++)
            {
                string effectFile = fh.Read <ZString>();

                EffectFiles.Add(effectFile);
            }

            short characterCount = fh.Read <short>();

            for (int i = 0; i < characterCount; i++)
            {
                Character character = new Character();
                character.IsEnabled = fh.Read <char>() != 0;

                if (character.IsEnabled)
                {
                    character.ID   = fh.Read <short>();
                    character.Name = fh.Read <ZString>();

                    short objectCount = fh.Read <short>();

                    for (int j = 0; j < objectCount; j++)
                    {
                        CharacterObject @object = new CharacterObject();
                        @object.Object = fh.Read <short>();

                        character.Objects.Add(@object);
                    }

                    short animationCount = fh.Read <short>();

                    for (int j = 0; j < animationCount; j++)
                    {
                        CharacterAnimation animation = new CharacterAnimation();
                        animation.Type      = (AnimationType)fh.Read <short>();
                        animation.Animation = fh.Read <short>();

                        character.Animations.Add(animation);
                    }

                    short effectCount = fh.Read <short>();

                    for (int j = 0; j < effectCount; j++)
                    {
                        CharacterEffect effect = new CharacterEffect();
                        effect.Bone   = fh.Read <short>();
                        effect.Effect = fh.Read <short>();

                        character.Effects.Add(effect);
                    }
                }

                Characters.Add(character);
            }
        }
예제 #34
0
 public void OpenCacheFolder()
 {
     #if UNITY_EDITOR
     EditorUtility.RevealInFinder(FileHandler.GoCachePath());
     #endif
 }
예제 #35
0
 private void tsbDGViewExportToCSV_Click(object sender, EventArgs e)
 {
     FileHandler.DataGridViewExportToCSV(bS_UserInfoDataGridView, psapCommon.GetDateNumber("用户信息"));
 }
예제 #36
0
        public ActionResult Upload(PhotoType type, long?id)
        {
            if (!sessionid.HasValue)
            {
                return(SendJsonSessionExpired());
            }
            long ownerid = sessionid.Value;

            if (Request.Files.Count < 1)
            {
                throw new Exception();
            }

            var    imageUpload = Request.Files[0];
            var    extIndex    = imageUpload.FileName.LastIndexOf('.');
            var    ext         = imageUpload.FileName.Substring(extIndex);
            string filename    = ImgHelper.BuildFilename(sessionid.Value, ext);

            var handler = new FileHandler(filename, UploadFileType.IMAGE, MASTERdomain.uniqueid);

            var url = handler.Save(imageUpload.InputStream);

            if (string.IsNullOrEmpty(url))
            {
                return(Content("," + GeneralConstants.PHOTO_UPLOAD_ERROR_PATH));
            }

            image         image  = null;
            product_image pimage = null;
            long          imageid;

            switch (type)
            {
            case PhotoType.BACKGROUND:
            case PhotoType.PROFILE:
            case PhotoType.COMPANY:
                image = new image
                {
                    imageType = type.ToString(),
                    url       = url,
                    subdomain = subdomainid.Value
                };
                imageid = repository.AddImage(image);
                break;

            case PhotoType.PRODUCT:
                pimage = new product_image
                {
                    url         = url,
                    subdomainid = subdomainid.Value
                };
                repository.AddProductImage(pimage);
                imageid = pimage.id;
                break;

            default:
                throw new NotImplementedException();
            }

            // depending on image type....
            user   usr;
            string retVal = "";
            long   profileID;
            string thumbnailUrl;

            switch (type)
            {
            case PhotoType.BACKGROUND:
                thumbnailUrl = Img.by_size(url, Imgsize.COMPACT);
                retVal       = string.Concat(imageid, ",#background_image,", thumbnailUrl);
                break;

            case PhotoType.COMPANY:
                thumbnailUrl           = Img.by_size(url, Imgsize.MEDIUM);
                profileID              = id.HasValue ? id.Value : ownerid;
                usr                    = repository.GetUserById(profileID, subdomainid.Value);
                usr.organisation1.logo = imageid;
                image.contextID        = usr.organisation.Value;
                repository.Save();
                retVal = string.Concat(imageid, ",#company_image,", thumbnailUrl);
                CacheHelper.Instance.invalidate_dependency(DependencyType.organisation, subdomainid.Value.ToString());
                break;

            case PhotoType.PROFILE:
                thumbnailUrl     = Img.by_size(url, Imgsize.MEDIUM);
                profileID        = id.HasValue ? id.Value : ownerid;
                usr              = repository.GetUserById(profileID, subdomainid.Value);
                usr.profilePhoto = imageid;
                image.contextID  = usr.id;
                repository.Save();
                retVal = string.Concat(imageid, ",#profile_image,", thumbnailUrl);
                break;

            case PhotoType.PRODUCT:
                thumbnailUrl = Img.by_size(url, Imgsize.MEDIUM);
                retVal       = string.Concat(imageid, ",#product_images,", thumbnailUrl);
                // for when editing products
                // when creating new product entry, contextid is only updated when product is saved, it  will be 0 if images
                // uploaded and then product is not saved
                if (id.HasValue)
                {
                    var productid = id.Value;
                    pimage.productid = productid;
                    repository.Save();
                    repository.UpdateProductMainThumbnail(productid, subdomainid.Value, imageid.ToString());
                }
                break;
            }

            return(Content(retVal));
        }
예제 #37
0
 public void ClearCache()
 {
     FileHandler.ClearEverythingInFolder(FileHandler.GoCachePath());
 }
예제 #38
0
파일: FrmRight.cs 프로젝트: comborep/PSAP
 private void tsbDGViewExportToCSV_Click(object sender, EventArgs e)
 {
     FileHandler.DataGridViewExportToCSV(dgvRoleList, psapCommon.GetDateNumber("角色"));
 }
예제 #39
0
파일: STB.cs 프로젝트: osROSE/UnityRose
        /// <summary>
        /// Loads the specified file.  If resource is found, it is loaded as a Text asset.  Otherwise, the function
        /// assumes this is an editor load and reads from disk
        /// </summary>
        /// <param name="filePath">The file path of the Text Asset resource (without extension) or file (with extension) to load</param>
        public void Load(string filePath)
        {
            asset = Resources.Load(filePath) as TextAsset;
            if (asset != null)
                fh = new FileHandler(asset, Encoding.UTF8);
            else
                fh = new FileHandler(filePath, FileHandler.FileOpenMode.Reading, Encoding.UTF8);

            Load();
        }
예제 #40
0
파일: CHR.cs 프로젝트: osROSE/UnityRose
        public void Load(string filePath)
        {
            var fh = new FileHandler(filePath, FileHandler.FileOpenMode.Reading, Encoding.UTF8);

            short skeletonFileCount = fh.Read<short>();

            for (int i = 0; i < skeletonFileCount; i++)
            {
                string skeletonFile = fh.Read<ZString>();
                SkeletonFiles.Add(skeletonFile);
            }

            short motionFileCount = fh.Read<short>();

            for (int i = 0; i < motionFileCount; i++)
            {
                string motionFile = fh.Read<ZString>();

                MotionFiles.Add(motionFile);
            }

            short effectFileCount = fh.Read<short>();

            for (int i = 0; i < effectFileCount; i++)
            {
                string effectFile = fh.Read<ZString>();

                EffectFiles.Add(effectFile);
            }

            short characterCount = fh.Read<short>();

            for (int i = 0; i < characterCount; i++)
            {
                Character character = new Character();
                character.IsEnabled = fh.Read<char>() != 0;

                if (character.IsEnabled)
                {
                    character.ID = fh.Read<short>();
                    character.Name = fh.Read<ZString>();

                    short objectCount = fh.Read<short>();

                    for (int j = 0; j < objectCount; j++)
                    {
                        CharacterObject @object = new CharacterObject();
                        @object.Object = fh.Read<short>();

                        character.Objects.Add(@object);
                    }

                    short animationCount = fh.Read<short>();

                    for (int j = 0; j < animationCount; j++)
                    {
                        CharacterAnimation animation = new CharacterAnimation();
                        animation.Type = (AnimationType)fh.Read<short>();
                        animation.Animation = fh.Read<short>();

                        character.Animations.Add(animation);
                    }

                    short effectCount = fh.Read<short>();

                    for (int j = 0; j < effectCount; j++)
                    {
                        CharacterEffect effect = new CharacterEffect();
                        effect.Bone = fh.Read<short>();
                        effect.Effect = fh.Read<short>();

                        character.Effects.Add(effect);
                    }
                }

                Characters.Add(character);
            }
        }
        public static string CreateNewFilename(string newFilenameVariable, string oldFilename, Metadata metadata)
        {
            #region List of vaiables - that can be used in Rename tool
            //%Trim%%MediaFileNow_DateTime% %FileNameWithoutDateTime%%Extension%
            //%Trim%
            //%FileName%
            //%FileNameWithoutDateTime%
            //%Extension%
            //%MediaFileNow_DateTime%
            //%Media_DateTime%
            //%Media_yyyy%
            //%Media_MM%
            //%Media_dd%
            //%Media_HH%
            //%Media_mm%
            //%Media_ss%
            //%File_DateTime%
            //%File_yyyy%
            //%File_MM%
            //%File_dd%
            //%File_HH%
            //%File_mm%
            //%File_ss%
            //%Now_DateTime%
            //%Now_yyyy%
            //%Now_MM%
            //%Now_dd%
            //%Now_HH%
            //%Now_mm%
            //%Now_ss%
            //%GPS_DateTimeUTC%
            //%MediaAlbum%
            //%MediaTitle%
            //%MediaDescription%
            //%MediaAuthor%
            //%LocationName%
            //%LocationCountry%
            //%LocationRegion%
            #endregion

            #region Filename
            string newFilename = newFilenameVariable;
            newFilename = newFilename.Replace("%FileName%", Path.GetFileNameWithoutExtension(oldFilename));
            newFilename = newFilename.Replace("%FileNameWithoutDateTime%", FileDateTimeFormats.RemoveAllDateTimes(Path.GetFileNameWithoutExtension(oldFilename)));
            newFilename = newFilename.Replace("%Extension%", Path.GetExtension(oldFilename));
            #endregion

            #region DataTime
            DateTime dateTime;
            if ((metadata != null && metadata.MediaDateTaken != null))
            {
                dateTime = (DateTime)metadata.MediaDateTaken;
            }
            else if (metadata != null && metadata.FileDateCreated != null)
            {
                dateTime = (DateTime)metadata.FileDateCreated;
            }
            else
            {
                dateTime = DateTime.Now;
            }
            newFilename = newFilename.Replace("%MediaFileNow_DateTime%", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));

            newFilename = newFilename.Replace("%Media_DateTime%", (metadata == null || metadata.MediaDateTaken == null) ? "" : ((DateTime)metadata.MediaDateTaken).ToString("yyyy-MM-dd HH-mm-ss"));
            newFilename = newFilename.Replace("%Media_yyyy%", (metadata == null || metadata.MediaDateTaken == null) ? "" : ((DateTime)metadata.MediaDateTaken).ToString("yyyy"));
            newFilename = newFilename.Replace("%Media_MM%", (metadata == null || metadata.MediaDateTaken == null) ? "" : ((DateTime)metadata.MediaDateTaken).ToString("MM"));
            newFilename = newFilename.Replace("%Media_dd%", (metadata == null || metadata.MediaDateTaken == null) ? "" : ((DateTime)metadata.MediaDateTaken).ToString("dd"));
            newFilename = newFilename.Replace("%Media_HH%", (metadata == null || metadata.MediaDateTaken == null) ? "" : ((DateTime)metadata.MediaDateTaken).ToString("HH"));
            newFilename = newFilename.Replace("%Media_mm%", (metadata == null || metadata.MediaDateTaken == null) ? "" : ((DateTime)metadata.MediaDateTaken).ToString("mm"));
            newFilename = newFilename.Replace("%Media_ss%", (metadata == null || metadata.MediaDateTaken == null) ? "" : ((DateTime)metadata.MediaDateTaken).ToString("ss"));

            newFilename = newFilename.Replace("%File_DateTime%", (metadata == null || metadata.FileDate == null) ? "" : ((DateTime)metadata.FileDate).ToString("yyyy-MM-dd HH-mm-ss"));
            newFilename = newFilename.Replace("%File_yyyy%", (metadata == null || metadata.FileDate == null) ? "" : ((DateTime)metadata.FileDate).ToString("yyyy"));
            newFilename = newFilename.Replace("%File_MM%", (metadata == null || metadata.FileDate == null) ? "" : ((DateTime)metadata.FileDate).ToString("MM"));
            newFilename = newFilename.Replace("%File_dd%", (metadata == null || metadata.FileDate == null) ? "" : ((DateTime)metadata.FileDate).ToString("dd"));
            newFilename = newFilename.Replace("%File_HH%", (metadata == null || metadata.FileDate == null) ? "" : ((DateTime)metadata.FileDate).ToString("HH"));
            newFilename = newFilename.Replace("%File_mm%", (metadata == null || metadata.FileDate == null) ? "" : ((DateTime)metadata.FileDate).ToString("mm"));
            newFilename = newFilename.Replace("%File_ss%", (metadata == null || metadata.FileDate == null) ? "" : ((DateTime)metadata.FileDate).ToString("ss"));

            newFilename = newFilename.Replace("%Now_DateTime%", DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"));
            newFilename = newFilename.Replace("%Now_yyyy%", DateTime.Now.ToString("yyyy"));
            newFilename = newFilename.Replace("%Now_MM%", DateTime.Now.ToString("MM"));
            newFilename = newFilename.Replace("%Now_dd%", DateTime.Now.ToString("dd"));
            newFilename = newFilename.Replace("%Now_HH%", DateTime.Now.ToString("HH"));
            newFilename = newFilename.Replace("%Now_mm%", DateTime.Now.ToString("mm"));
            newFilename = newFilename.Replace("%Now_ss%", DateTime.Now.ToString("ss"));

            newFilename = newFilename.Replace("%GPS_DateTimeUTC%", (metadata == null || metadata.LocationDateTime == null) ? "" : ((DateTime)metadata.LocationDateTime).ToString("u").Replace(":", "-"));
            #endregion

            #region Media Text
            newFilename = newFilename.Replace("%MediaAlbum%", (metadata == null || metadata.PersonalAlbum == null) ? "" : metadata.PersonalAlbum);
            newFilename = newFilename.Replace("%MediaTitle%", (metadata == null || metadata.PersonalTitle == null) ? "" : metadata.PersonalTitle);
            newFilename = newFilename.Replace("%MediaDescription%", (metadata == null || metadata.PersonalDescription == null) ? "" : metadata.PersonalDescription);
            newFilename = newFilename.Replace("%MediaAuthor%", (metadata == null || metadata.PersonalAuthor == null) ? "" : metadata.PersonalAuthor);
            #endregion

            #region Location
            newFilename = newFilename.Replace("%LocationName%", (metadata == null || metadata.LocationName == null) ? "" : metadata.LocationName);
            newFilename = newFilename.Replace("%LocationCountry%", (metadata == null || metadata.LocationCountry == null) ? "" : metadata.LocationCountry);
            newFilename = newFilename.Replace("%LocationRegion%", (metadata == null || metadata.LocationState == null) ? "" : metadata.LocationState);
            newFilename = newFilename.Replace("%LocationCity%", (metadata == null || metadata.LocationCity == null) ? "" : metadata.LocationCity);
            #endregion

            #region Trim WhiteSpace
            if (newFilename.Contains("%Trim%"))
            {
                int    indexOfSplit = newFilename.IndexOf("%Trim%");
                string beforeSplit  = newFilename.Substring(0, indexOfSplit);
                string afterSplit   = newFilename.Substring(indexOfSplit + ("%Trim%").Length);
                afterSplit  = FileHandler.TrimFolderName(afterSplit, "  ", " ");
                afterSplit  = FileHandler.TrimFolderName(afterSplit, "_ ", "_");
                afterSplit  = FileHandler.TrimFolderName(afterSplit, " -", "-");
                afterSplit  = FileHandler.TrimFolderName(afterSplit, "- ", "-");
                afterSplit  = FileHandler.TrimFolderName(afterSplit, " .", ".");
                afterSplit  = FileHandler.TrimFolderName(afterSplit, ". ", ".");
                afterSplit  = FileHandler.TrimFolderName(afterSplit, "\\ ", "\\");
                afterSplit  = FileHandler.TrimFolderName(afterSplit, " \\", "\\");
                newFilename = (beforeSplit + afterSplit).Replace("%Trim%", "").Trim(); //If contains more %Trim%, just remove them
            }
            #endregion

            #region Trim Leading space Folder Names
            newFilename = FileHandler.TrimFolderName(newFilename); //https://docs.microsoft.com/en-us/dotnet/api/system.io.directory.createdirectory?view=net-5.0
            #endregion

            #region Remove Not allowed Chars
            newFilename = newFilename
                          .Replace("\u0000", "")
                          .Replace("\u0001", "")
                          .Replace("\u0002", "")
                          .Replace("\u0003", "")
                          .Replace("\u0004", "")
                          .Replace("\u0005", "")
                          .Replace("\u0006", "")
                          .Replace("\u0007", "")
                          .Replace("\u0008", "")
                          .Replace("\u0009", "")
                          .Replace("\u000A", "")
                          .Replace("\u000B", "")
                          .Replace("\u000C", "")
                          .Replace("\u000D", "")
                          .Replace("\u000E", "")
                          .Replace("\u000F", "")
                          .Replace("\u0010", "")
                          .Replace("\u0011", "")
                          .Replace("\u0012", "")
                          .Replace("\u0013", "")
                          .Replace("\u0014", "")
                          .Replace("\u0015", "")
                          .Replace("\u0016", "")
                          .Replace("\u0017", "")
                          .Replace("\u0018", "")
                          .Replace("\u0019", "")
                          .Replace("\u001A", "")
                          .Replace("\u001B", "")
                          .Replace("\u001C", "")
                          .Replace("\u001D", "")
                          .Replace("\u001E", "")
                          .Replace("\u001F", "")
                          .Replace("<", "")
                          .Replace(">", "")
                          .Replace("|", "")
                          .Replace("?", "")
                          .Replace("*", "")
                          .Replace("/", "")
                          .Replace("\"", "");
            #endregion

            #region Handle Drive letters A:\a:\B:\b:\C:\and remove other :
            if (newFilename.Length >= 3 && Char.IsLetter(newFilename[0]) && newFilename[2] == '\\') //x:\
            {
                newFilename = newFilename.Substring(0, 3) + newFilename.Substring(3).Replace(":", "");
            }
            else
            {
                newFilename = newFilename.Replace(":", "");
            }
            #endregion

            return(newFilename);
        }
예제 #42
0
        public AdmissionStatus Process(Gender child_sex, int enrol_year, int school, int year, string child_name,
                                       string child_race, string child_dialect, string child_address,
                                       int child_dob_day, int child_dob_month, int child_dob_year, string child_pob,
                                       string child_citizenship, string child_birthcertno, string child_passportnric, bool child_bumi,
                                       string child_religion, HttpPostedFileBase child_photo, string child_previous_school,
                                       HttpPostedFileBase child_report, string child_previous_class, string child_leaving_reason, bool?child_handicap,
                                       bool?child_learning_problems, string child_disability_details,
                                       // parents fields
                                       string parent1_designation, string parent1_name, string parent1_passportnric,
                                       string parent1_occupation, string parent1_employer, string parent1_race,
                                       string parent1_dialect, bool?parent1_bumi, string parent1_marital, string parent1_citizenship,
                                       string parent1_religion, string parent1_officephone, string parent1_homephone, string parent1_handphone,
                                       string parent1_email, string parent1_address,
                                       string parent2_designation, string parent2_name, string parent2_passportnric,
                                       string parent2_occupation, string parent2_employer, string parent2_race,
                                       string parent2_dialect, bool?parent2_bumi, string parent2_marital, string parent2_citizenship,
                                       string parent2_religion, string parent2_officephone, string parent2_homephone, string parent2_handphone,
                                       string parent2_email, string parent2_address,
                                       // guardian fields
                                       string guardian_designation, string guardian_name, Gender?guardian_sex,
                                       string guardian_passportnric, string guardian_occupation, string guardian_employer, string guardian_race,
                                       string guardian_dialect, bool?guardian_bumi, string guardian_marital, string guardian_citizenship,
                                       string guardian_religion, string guardian_officephone, string guardian_homephone, string guardian_handphone,
                                       string guardian_email, string guardian_address,
                                       // other siblings
                                       string[] sibling_name, string[] sibling_nric,
                                       GuardianType?applicant_relationship, bool internalsubmission)
        {
            var noemail = true;   // to ensure at least parent/guardian has email
            var emails  = new List <string>();

            // sanitize inputs
            parent1_email  = (parent1_email ?? "").Trim().ToLower();
            parent2_email  = (parent2_email ?? "").Trim().ToLower();
            guardian_email = (guardian_email ?? "").Trim().ToLower();

            if (!string.IsNullOrEmpty(child_passportnric))
            {
                child_passportnric = child_passportnric.Trim().Replace("-", "");
            }
            if (!string.IsNullOrEmpty(parent1_passportnric))
            {
                parent1_passportnric = parent1_passportnric.Trim().Replace("-", "");
            }
            if (!string.IsNullOrEmpty(parent2_passportnric))
            {
                parent2_passportnric = parent2_passportnric.Trim().Replace("-", "");
            }
            if (!string.IsNullOrEmpty(guardian_passportnric))
            {
                guardian_passportnric = guardian_passportnric.Trim().Replace("-", "");
            }


            // check that student does not already exist
            if (!string.IsNullOrEmpty(child_passportnric))
            {
                student = repository.GetUserByNewNRIC(child_passportnric);
                // only match student usergroup to prevent accidently matching with parents or teachers
                if (student != null && student.usergroup != (int)UserGroup.STUDENT)
                {
                    return(AdmissionStatus.INCORRECT_NRIC_PASSPORT);
                }
            }

            if (student == null && !string.IsNullOrEmpty(child_passportnric))
            {
                student = repository.GetUsers().SingleOrDefault(x => string.Compare(x.passportno, child_passportnric, true) == 0);
                // only match student usergroup to prevent accidently matching with parents or teachers
                if (student != null && student.usergroup != (int)UserGroup.STUDENT)
                {
                    return(AdmissionStatus.INCORRECT_NRIC_PASSPORT);
                }
            }

            if (student == null)
            {
                // student
                student             = new ioschools.DB.user();
                student.usergroup   = (int)UserGroup.STUDENT;
                student.settings    = (int)UserSettings.INACTIVE;
                student.email       = "";
                student.name        = child_name;
                student.gender      = child_sex.ToString();
                student.race        = child_race;
                student.dialect     = child_dialect;
                student.dob         = new DateTime(child_dob_year, child_dob_month, child_dob_day);
                student.pob         = child_pob;
                student.citizenship = child_citizenship;
                student.birthcertno = child_birthcertno;
                student.religion    = child_religion;
                student.isbumi      = child_bumi;
                student.address     = child_address;

                var childidtype = GetIDType(child_passportnric);
                switch (childidtype)
                {
                case IdType.NEWIC:
                    student.nric_new = child_passportnric;
                    break;

                case IdType.PASSPORT:
                    student.passportno = child_passportnric;
                    break;

                default:
                    throw new NotImplementedException();
                }

                repository.AddUser(student);
            }

            // father
            password_father = tradelr.Crypto.Utility.GetRandomString(uppercase: true);
            if (!string.IsNullOrEmpty(parent1_name))
            {
                // see if we can find this parent
                if (!string.IsNullOrEmpty(parent1_passportnric))
                {
                    father = repository.GetUserByNewNRIC(parent1_passportnric);
                }

                if (father == null && !string.IsNullOrEmpty(parent1_passportnric))
                {
                    father = repository.GetUsers().SingleOrDefault(x => string.Compare(x.passportno, parent1_passportnric, true) == 0);
                }

                if (father == null)
                {
                    father             = new ioschools.DB.user();
                    father.usergroup   = (int)UserGroup.GUARDIAN;
                    father.settings    = (int)UserSettings.NONE;
                    father.designation = parent1_designation;
                    father.name        = parent1_name;
                    father.gender      = Gender.MALE.ToString();
                    father.race        = parent1_race;
                    father.dialect     = parent1_dialect;
                    father.citizenship = parent1_citizenship;
                    father.address     = parent1_address;
                    father.religion    = parent1_religion;
                    father.isbumi      = parent1_bumi;

                    var fatheridtype = GetIDType(parent1_passportnric);
                    switch (fatheridtype)
                    {
                    case IdType.PASSPORT:
                        father.passportno = parent1_passportnric;
                        break;

                    case IdType.NEWIC:
                        father.nric_new = parent1_passportnric;
                        father.dob      = parent1_passportnric.ToDOB();
                        break;

                    default:
                        throw new NotImplementedException();
                    }

                    if (!string.IsNullOrEmpty(parent1_email))
                    {
                        // checks that email address is not in use
                        if (repository.GetUsers().SingleOrDefault(x => string.Compare(x.email, parent1_email, true) == 0) != null)
                        {
                            return(AdmissionStatus.DUPLICATEEMAIL);
                        }
                        emails.Add(parent1_email);
                        father.email        = parent1_email;
                        father.passwordhash = Utility.GeneratePasswordHash(parent1_email, password_father);
                        noemail             = false;
                    }
                    father.phone_home                = parent1_homephone;
                    father.phone_cell                = parent1_handphone;
                    father.user_parents              = new user_parent();
                    father.marital_status            = parent1_marital;
                    father.user_parents.phone_office = parent1_officephone;
                    father.user_parents.occupation   = parent1_occupation;
                    father.user_parents.employer     = string.IsNullOrEmpty(parent1_employer)?"":parent1_employer.Trim();
                    repository.AddUser(father);
                }
                else
                {
                    if (string.IsNullOrEmpty(father.email))
                    {
                        // let's see if we can update email information
                        if (!string.IsNullOrEmpty(parent1_email))
                        {
                            // checks that email address is not in use
                            if (repository.GetUsers().SingleOrDefault(x => string.Compare(x.email, parent1_email, true) == 0) != null)
                            {
                                return(AdmissionStatus.DUPLICATEEMAIL);
                            }
                            emails.Add(parent1_email);
                            father.email        = parent1_email;
                            father.passwordhash = Utility.GeneratePasswordHash(parent1_email, password_father);
                            noemail             = false;
                        }
                    }
                    else
                    {
                        noemail = false;
                    }
                }
            }

            password_mother = tradelr.Crypto.Utility.GetRandomString(uppercase: true);
            if (!string.IsNullOrEmpty(parent2_name))
            {
                // see if we can find this parent
                if (!string.IsNullOrEmpty(parent2_passportnric))
                {
                    mother = repository.GetUserByNewNRIC(parent2_passportnric);
                }

                if (mother == null && !string.IsNullOrEmpty(parent2_passportnric))
                {
                    mother = repository.GetUsers().SingleOrDefault(x => string.Compare(x.passportno, parent2_passportnric, true) == 0);
                }

                if (mother == null)
                {
                    mother             = new ioschools.DB.user();
                    mother.usergroup   = (int)UserGroup.GUARDIAN;
                    mother.settings    = (int)UserSettings.NONE;
                    mother.designation = parent2_designation;
                    mother.name        = parent2_name;
                    mother.gender      = Gender.FEMALE.ToString();
                    mother.race        = parent2_race;
                    mother.dialect     = parent2_dialect;
                    mother.citizenship = parent2_citizenship;
                    mother.address     = parent2_address;
                    mother.religion    = parent2_religion;
                    mother.isbumi      = parent2_bumi;

                    var motheridtype = GetIDType(parent2_passportnric);
                    switch (motheridtype)
                    {
                    case IdType.PASSPORT:
                        mother.passportno = parent2_passportnric;
                        break;

                    case IdType.NEWIC:
                        mother.nric_new = parent2_passportnric;
                        mother.dob      = parent2_passportnric.ToDOB();
                        break;

                    default:
                        throw new NotImplementedException();
                    }

                    if (!string.IsNullOrEmpty(parent2_email))
                    {
                        // checks that email address is not in use
                        if (repository.GetUsers().SingleOrDefault(x => string.Compare(x.email, parent2_email, true) == 0) != null)
                        {
                            return(AdmissionStatus.DUPLICATEEMAIL);
                        }
                        if (!emails.Contains(parent2_email))
                        {
                            emails.Add(parent2_email);
                            mother.email        = parent2_email;
                            mother.passwordhash = Utility.GeneratePasswordHash(parent2_email, password_mother);
                            noemail             = false;
                        }
                    }
                    mother.phone_home                = parent2_homephone;
                    mother.phone_cell                = parent2_handphone;
                    mother.user_parents              = new user_parent();
                    mother.marital_status            = parent2_marital;
                    mother.user_parents.phone_office = parent2_officephone;
                    mother.user_parents.occupation   = parent2_occupation;
                    mother.user_parents.employer     = string.IsNullOrEmpty(parent2_employer) ? "" : parent2_employer.Trim();

                    repository.AddUser(mother);
                }
                else
                {
                    if (string.IsNullOrEmpty(mother.email))
                    {
                        // let's see if we can update email information
                        if (!string.IsNullOrEmpty(parent2_email))
                        {
                            // checks that email address is not in use
                            if (repository.GetUsers().SingleOrDefault(x => string.Compare(x.email, parent2_email, true) == 0) != null)
                            {
                                return(AdmissionStatus.DUPLICATEEMAIL);
                            }
                            emails.Add(parent2_email);
                            mother.email        = parent2_email;
                            mother.passwordhash = Utility.GeneratePasswordHash(parent2_email, password_mother);
                            noemail             = false;
                        }
                    }
                    else
                    {
                        noemail = false;
                    }
                }
            }

            password_guardian = tradelr.Crypto.Utility.GetRandomString(uppercase: true);
            if (!string.IsNullOrEmpty(guardian_name))
            {
                // see if we can find this parent
                if (!string.IsNullOrEmpty(guardian_passportnric))
                {
                    guardian = repository.GetUserByNewNRIC(guardian_passportnric);
                }

                if (guardian == null && !string.IsNullOrEmpty(guardian_passportnric))
                {
                    guardian = repository.GetUsers().SingleOrDefault(x => string.Compare(x.passportno, guardian_passportnric) == 0);
                }

                if (guardian == null)
                {
                    guardian             = new ioschools.DB.user();
                    guardian.usergroup   = (int)UserGroup.GUARDIAN;
                    guardian.settings    = (int)UserSettings.NONE;
                    guardian.designation = guardian_designation;
                    guardian.name        = guardian_name;
                    guardian.gender      = guardian_sex.ToString();
                    guardian.race        = guardian_race;
                    guardian.dialect     = guardian_dialect;
                    guardian.citizenship = guardian_citizenship;
                    guardian.address     = guardian_address;
                    guardian.religion    = guardian_religion;
                    guardian.isbumi      = guardian_bumi;

                    var guardianidtype = GetIDType(guardian_passportnric);
                    switch (guardianidtype)
                    {
                    case IdType.NEWIC:
                        guardian.nric_new = guardian_passportnric;
                        guardian.dob      = guardian_passportnric.ToDOB();
                        break;

                    case IdType.PASSPORT:
                        guardian.passportno = guardian_passportnric;
                        break;

                    default:
                        throw new NotImplementedException();
                    }

                    if (!string.IsNullOrEmpty(guardian_email))
                    {
                        // checks that email address is not in use
                        if (repository.GetUsers().SingleOrDefault(x => string.Compare(x.email, guardian_email) == 0) != null)
                        {
                            return(AdmissionStatus.DUPLICATEEMAIL);
                        }
                        if (!emails.Contains(guardian_email))
                        {
                            guardian.email        = guardian_email;
                            guardian.passwordhash = Utility.GeneratePasswordHash(guardian_email, password_guardian);
                            noemail = false;
                        }
                    }
                    guardian.phone_home                = guardian_homephone;
                    guardian.phone_cell                = guardian_handphone;
                    guardian.user_parents              = new user_parent();
                    guardian.marital_status            = guardian_marital;
                    guardian.user_parents.phone_office = guardian_officephone;
                    guardian.user_parents.occupation   = guardian_occupation;
                    guardian.user_parents.employer     = string.IsNullOrEmpty(guardian_employer) ? "" : guardian_employer.Trim();

                    repository.AddUser(guardian);
                }
                else
                {
                    if (string.IsNullOrEmpty(guardian.email))
                    {
                        // let's see if we can update email information
                        if (!string.IsNullOrEmpty(guardian_email))
                        {
                            // checks that email address is not in use
                            if (repository.GetUsers().SingleOrDefault(x => string.Compare(x.email, guardian_email, true) == 0) != null)
                            {
                                return(AdmissionStatus.DUPLICATEEMAIL);
                            }
                            emails.Add(guardian_email);
                            guardian.email        = guardian_email;
                            guardian.passwordhash = Utility.GeneratePasswordHash(guardian_email, password_guardian);
                            noemail = false;
                        }
                    }
                    else
                    {
                        noemail = false;
                    }
                }
            }

            // check that there's an email
            if (noemail && !internalsubmission)
            {
                return(AdmissionStatus.NOEMAIL);
            }

            // check that student is not already enrol for the same year
            // should we? possiblity that student may leave and come back in the same year

            /////////////////////// SAVE ////////////////////
            repository.Save();

            // save photo
            if (child_photo != null)
            {
                var photouploader = new FileHandler(child_photo.FileName, UploaderType.PHOTO, null);
                photouploader.Save(child_photo.InputStream);
                var image = new user_image();
                image.url          = photouploader.url;
                student.user_image = image;
            }

            // save child report
            if (child_report != null)
            {
                var reportuploader = new FileHandler(child_report.FileName, UploaderType.REGISTRATION, student.id);
                reportuploader.Save(child_report.InputStream);
                var file = new user_file();
                file.filename = child_report.FileName;
                file.url      = reportuploader.url;
                student.user_files.Add(file);
            }

            // siblings
            for (int i = 0; i < sibling_name.Length; i++)
            {
                var name = sibling_name[i];
                var nric = sibling_nric[i];
                if (!string.IsNullOrEmpty(nric))
                {
                    nric = nric.Trim().Replace("-", "");

                    // try to find user
                    var sibling = repository.GetUserByNewNRIC(nric);

                    if ((sibling != null && sibling.usergroup != (int)UserGroup.STUDENT) ||
                        sibling == null)
                    {
                        // try pasport
                        sibling = repository.GetUsers().SingleOrDefault(x => string.Compare(x.passportno, nric, true) == 0);
                    }

                    if (sibling != null)
                    {
                        var s = new sibling();
                        s.otherid = student.id;
                        sibling.siblings1.Add(s);
                    }
                }
            }

            // relationship
            // parent
            if (father != null)
            {
                var f = new students_guardian();
                f.parentid = father.id;
                f.type     = (byte)GuardianType.FATHER;
                if (!student.students_guardians.Any(x => x.parentid == f.parentid && x.type == f.type))
                {
                    student.students_guardians.Add(f);
                }
            }

            if (mother != null)
            {
                var m = new students_guardian();
                m.parentid = mother.id;
                m.type     = (byte)GuardianType.MOTHER;
                if (!student.students_guardians.Any(x => x.parentid == m.parentid && x.type == m.type))
                {
                    student.students_guardians.Add(m);
                }
            }

            if (guardian != null)
            {
                var g = new students_guardian();
                g.parentid = guardian.id;
                g.type     = (byte)GuardianType.GUARDIAN;
                if (!student.students_guardians.Any(x => x.parentid == g.parentid && x.type == g.type))
                {
                    student.students_guardians.Add(g);
                }
            }

            // registration
            var r = new registration();

            r.enrollingYear      = enrol_year;
            r.created            = DateTime.Now;
            r.schoolid           = school;
            r.schoolyearid       = year;
            r.studentid          = student.id;
            r.status             = RegistrationStatus.PENDING.ToString();
            r.schoolid           = school;
            r.schoolyearid       = year;
            r.previous_school    = child_previous_school;
            r.leaving_reason     = child_leaving_reason;
            r.disability_details = child_disability_details;
            r.hasLearningProblem = child_learning_problems;
            r.isHandicap         = child_handicap;
            r.previous_class     = child_previous_class;
            if (applicant_relationship.HasValue)
            {
                switch (applicant_relationship)
                {
                case GuardianType.FATHER:
                    r.applicantid = father.id;
                    break;

                case GuardianType.MOTHER:
                    r.applicantid = mother.id;
                    break;

                case GuardianType.GUARDIAN:
                    r.applicantid = guardian.id;
                    break;
                }
            }

            repository.AddRegistration(r);

            // success
            try
            {
                repository.Save();
            }
            catch (Exception ex)
            {
                return(AdmissionStatus.UNKNOWN);
            }

            return(AdmissionStatus.SUCCESS);
        }
예제 #43
0
 public byte[] ToNetBytesTrans()
 {
     return(FileHandler.Compress(ToBytesTrans()));
 }
 public DirectoryExporterTests()
 {
     _fileHandler         = new FileHandler();
     _fileHandler.FileSys = TestFileSystem.CreateFileSystem();
 }
예제 #45
0
파일: ZON.cs 프로젝트: x3sphiorx/UnityRose
        /// <summary>
        /// Loads the specified file.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        public void Load(string filePath)
        {
            FileHandler fh = new FileHandler(FilePath = filePath, FileHandler.FileOpenMode.Reading, Encoding.UTF8);

            int blockCount = fh.Read <int>();

            Blocks = new List <Block>(blockCount);

            for (int i = 0; i < blockCount; i++)
            {
                Blocks.Add(new Block()
                {
                    Type   = (BlockType)fh.Read <int>(),
                    Offset = fh.Read <int>()
                });
            }

            for (int i = 0; i < blockCount; i++)
            {
                fh.Seek(Blocks[i].Offset, SeekOrigin.Begin);

                switch (Blocks[i].Type)
                {
                case BlockType.Block0:
                {
                    ZoneInfo = new Block0()
                    {
                        ZoneType   = fh.Read <int>(),
                        ZoneWidth  = fh.Read <int>(),
                        ZoneHeight = fh.Read <int>(),
                        GridCount  = fh.Read <int>(),
                        GridSize   = fh.Read <float>(),

                        XCount = fh.Read <int>(),
                        YCount = fh.Read <int>()
                    };

                    ZoneInfo.ZoneParts = new Block0.ZonePart[ZoneInfo.ZoneWidth, ZoneInfo.ZoneHeight];

                    for (int j = 0; j < ZoneInfo.ZoneWidth; j++)
                    {
                        for (int k = 0; k < ZoneInfo.ZoneHeight; k++)
                        {
                            ZoneInfo.ZoneParts[j, k] = new Block0.ZonePart()
                            {
                                UseMap   = fh.Read <byte>(),
                                Position = fh.Read <Vector2>()
                            };
                        }
                    }
                }
                break;

                case BlockType.SpawnPoints:
                {
                    int spawnPointCount = fh.Read <int>();
                    SpawnPoints = new List <SpawnPoint>(spawnPointCount);

                    for (int j = 0; j < spawnPointCount; j++)
                    {
                        SpawnPoints.Add(new SpawnPoint()
                            {
                                Position = new Vector3()
                                {
                                    x = (fh.Read <float>() + 520000.00f) / 100.0f,
                                    z = fh.Read <float>() / 100.0f,
                                    y = (fh.Read <float>() + 520000.00f) / 100.0f
                                },

                                Name = fh.Read <BString>()
                            });
                    }
                }
                break;

                case BlockType.Textures:
                {
                    int textureCount = fh.Read <int>();
                    Textures = new List <Texture>(textureCount);

                    for (int j = 0; j < textureCount; j++)
                    {
                        Texture tex  = new Texture();
                        string  path = RootPath + fh.Read <BString>();
                        tex.Tex = Utils.loadTex(ref path);                                         //.ToLower().Replace("\\", "/").Replace(".dds",".png");
                        // = Resources.LoadAssetAtPath<Texture2D>(tex.TexPath);
                        tex.TexPath = path;

                        Textures.Add(tex);
                    }
                }
                break;

                case BlockType.Tiles:
                {
                    int tileCount = fh.Read <int>();
                    Tiles = new List <Tile>(tileCount);

                    for (int j = 0; j < tileCount; j++)
                    {
                        Tiles.Add(new Tile()
                            {
                                BaseID1    = fh.Read <int>(),
                                BaseID2    = fh.Read <int>(),
                                Offset1    = fh.Read <int>(),
                                Offset2    = fh.Read <int>(),
                                IsBlending = fh.Read <int>() > 0,
                                Rotation   = (RotationType)fh.Read <int>(),
                                TileType   = fh.Read <int>()
                            });
                    }
                }
                break;

                case BlockType.Economy:
                {
                    try
                    {
                        EconomyInfo = new Economy()
                        {
                            AreaName              = fh.Read <BString>(),
                            IsUnderground         = fh.Read <int>(),
                            ButtonBGM             = fh.Read <BString>(),
                            ButtonBack            = fh.Read <BString>(),
                            CheckCount            = fh.Read <int>(),
                            StandardPopulation    = fh.Read <int>(),
                            StandardGrowthRate    = fh.Read <int>(),
                            MetalConsumption      = fh.Read <int>(),
                            StoneConsumption      = fh.Read <int>(),
                            WoodConsumption       = fh.Read <int>(),
                            LeatherConsumption    = fh.Read <int>(),
                            ClothConsumption      = fh.Read <int>(),
                            AlchemyConsumption    = fh.Read <int>(),
                            ChemicalConsumption   = fh.Read <int>(),
                            IndustrialConsumption = fh.Read <int>(),
                            MedicineConsumption   = fh.Read <int>(),
                            FoodConsumption       = fh.Read <int>()
                        };
                    }
                    catch
                    {
                        Debug.LogError("-- Error reading the Economy Info block");


                        EconomyInfo = new Economy()
                        {
                            AreaName              = string.Empty,
                            IsUnderground         = 0,
                            ButtonBGM             = string.Empty,
                            ButtonBack            = string.Empty,
                            CheckCount            = 0,
                            StandardPopulation    = 0,
                            StandardGrowthRate    = 0,
                            MetalConsumption      = 0,
                            StoneConsumption      = 0,
                            WoodConsumption       = 0,
                            LeatherConsumption    = 0,
                            ClothConsumption      = 0,
                            AlchemyConsumption    = 0,
                            ChemicalConsumption   = 0,
                            IndustrialConsumption = 0,
                            MedicineConsumption   = 0,
                            FoodConsumption       = 0
                        };
                    }
                }
                break;
                }
            }

            fh.Close();
        }
예제 #46
0
        private void fillListView(string filePath, ListView listView, bool isLeft)
        {
            listView.Items.Clear();
            if (isLeft)
            {
                dirsLeft  = FileHandler.GetAllDirectories(filePath);
                filesLeft = FileHandler.GetAllFiles(filePath);
                ListViewItem.ListViewSubItem[] subItems;
                ListViewItem item = null;
                if (dirsLeft != null)
                {
                    foreach (var dir in dirsLeft)
                    {
                        item     = new ListViewItem(dir.Name);
                        subItems = new ListViewItem.ListViewSubItem[] { new ListViewItem.ListViewSubItem(item, dir.Extension),
                                                                        new ListViewItem.ListViewSubItem(item, "<DIR>"),
                                                                        new ListViewItem.ListViewSubItem(item, dir.LastAccessTime.ToShortDateString() + " " + dir.LastAccessTime.ToShortTimeString()) };
                        item.SubItems.AddRange(subItems);
                        listView.Items.Add(item);
                    }
                }

                //long fileSize = FileHandler.GetDirectorySize(filePath);
                string fileSize = "";
                if (dirsLeft != null)
                {
                    foreach (var file in filesLeft)
                    {
                        item     = new ListViewItem(file.Name);
                        subItems = new ListViewItem.ListViewSubItem[] { new ListViewItem.ListViewSubItem(item, file.Extension),
                                                                        new ListViewItem.ListViewSubItem(item, fileSize.ToString()),
                                                                        new ListViewItem.ListViewSubItem(item, file.LastAccessTime.ToShortDateString() + " " + file.LastAccessTime.ToShortTimeString()) };
                        item.SubItems.AddRange(subItems);
                        listView.Items.Add(item);
                    }
                }
            }
            else
            {
                dirsRight  = FileHandler.GetAllDirectories(filePath);
                filesRight = FileHandler.GetAllFiles(filePath);
                ListViewItem.ListViewSubItem[] subItems;
                ListViewItem item = null;
                if (dirsRight != null)
                {
                    foreach (var dir in dirsRight)
                    {
                        item     = new ListViewItem(dir.Name);
                        subItems = new ListViewItem.ListViewSubItem[] { new ListViewItem.ListViewSubItem(item, dir.Extension),
                                                                        new ListViewItem.ListViewSubItem(item, "<DIR>"),
                                                                        new ListViewItem.ListViewSubItem(item, dir.LastAccessTime.ToShortDateString() + " " + dir.LastAccessTime.ToShortTimeString()) };
                        item.SubItems.AddRange(subItems);
                        listView.Items.Add(item);
                    }
                }

                //long fileSize = FileHandler.GetDirectorySize(filePath);
                string fileSize = "";
                if (dirsRight != null)
                {
                    foreach (var file in filesRight)
                    {
                        item     = new ListViewItem(file.Name);
                        subItems = new ListViewItem.ListViewSubItem[] { new ListViewItem.ListViewSubItem(item, file.Extension),
                                                                        new ListViewItem.ListViewSubItem(item, fileSize.ToString()),
                                                                        new ListViewItem.ListViewSubItem(item, file.LastAccessTime.ToShortDateString() + " " + file.LastAccessTime.ToShortTimeString()) };
                        item.SubItems.AddRange(subItems);
                        listView.Items.Add(item);
                    }
                }
            }
        }
예제 #47
0
        public IDictionary <string, List <File <IReplay> > > PreviewSort(List <string> replaysThrowingExceptions, BackgroundWorker worker_ReplaySorter, int currentCriteria, int numberOfCriteria, int currentPositionNested = 0, int numberOfPositions = 0)
        {
            IDictionary <string, List <File <IReplay> > > DirectoryFileReplay = new Dictionary <string, List <File <IReplay> > >();

            var ReplaysByGameTypes = from replay in Sorter.ListReplays
                                     group replay by replay.Content.GameType;

            string sortDirectory = Sorter.CurrentDirectory;

            if (!(IsNested && !Sorter.GenerateIntermediateFolders))
            {
                if (IsNested)
                {
                    sortDirectory = Sorter.CurrentDirectory + @"\" + SortCriteria;
                }
                else
                {
                    sortDirectory = Sorter.CurrentDirectory + @"\" + string.Join(",", Sorter.CriteriaStringOrder);
                }
                sortDirectory = FileHandler.AdjustName(sortDirectory, true);
            }

            int currentPosition    = 0;
            int progressPercentage = 0;

            foreach (var gametype in ReplaysByGameTypes)
            {
                var GameType    = gametype.Key.ToString();
                var FileReplays = new List <File <IReplay> >();
                DirectoryFileReplay.Add(new KeyValuePair <string, List <File <IReplay> > >(sortDirectory + @"\" + GameType, FileReplays));

                foreach (var replay in gametype)
                {
                    if (worker_ReplaySorter.CancellationPending == true)
                    {
                        return(null);
                    }

                    try
                    {
                        if (IsNested == false)
                        {
                            ReplayHandler.CopyReplay(replay, sortDirectory, GameType, KeepOriginalReplayNames, Sorter.CustomReplayFormat, true);
                        }
                        else
                        {
                            ReplayHandler.MoveReplay(replay, sortDirectory, GameType, true, null, true);
                        }

                        FileReplays.Add(replay);
                    }
                    catch (Exception ex)
                    {
                        replaysThrowingExceptions.Add(replay.OriginalFilePath);
                        ErrorLogger.GetInstance()?.LogError("SortOnGameType ArgumentException.", ex: ex);
                    }

                    currentPosition++;
                    if (IsNested == false)
                    {
                        progressPercentage = Convert.ToInt32(((double)currentPosition / Sorter.ListReplays.Count) * 1 / numberOfCriteria * 100);
                    }
                    else
                    {
                        progressPercentage  = Convert.ToInt32((((double)currentPosition / Sorter.ListReplays.Count) * 1 / numberOfPositions * 100 + ((currentPositionNested - 1) * 100 / numberOfPositions)) * ((double)1 / numberOfCriteria));
                        progressPercentage += (currentCriteria - 1) * 100 / numberOfCriteria;
                    }
                    worker_ReplaySorter.ReportProgress(progressPercentage, $"sorting on gametype... {replay.FilePath}");
                }
            }
            return(DirectoryFileReplay);
        }
예제 #48
0
 public void TesReadFromFile()
 {
     FileHandler f  = new FileHandler("E:\\GIT\\OOD\\OOD2\\Project\\PipeLine_System\\PipeLine_System\\NetworkFiles\\Network_02.txt");
     Network     nw = f.ReadFromFile();
 }
예제 #49
0
        private void LoadProvinces()
        {
            var provinces = FileHandler.GetProvinces();

            uxProvinces.DataSource = provinces;
        }
예제 #50
0
 public AbstractTable(string name, FileHandler handler)
 {
     this._name    = name;
     this._handler = handler;
 }
        private void DisplayAllQueueStatus()
        {
            if (!stopwatchLastDisplayed.IsRunning)
            {
                stopwatchLastDisplayed.Start();
            }
            if (stopwatchLastDisplayed.ElapsedMilliseconds < 500)
            {
                return; //Avoid to much refresh
            }
            stopwatchLastDisplayed.Restart();

            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(DisplayAllQueueStatus));
                return;
            }

            UpdateStatusImageListView(string.Format("Files: {0} Selected {1} ", imageListView1.Items.Count, imageListView1.SelectedItems.Count));

            string progressBackgroundStatusText = "";
            int    threadQueuCount = 0;

            if (!string.IsNullOrWhiteSpace(FileHandler.FileLockedByProcess))
            {
                threadQueuCount++;
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                "Locked file: " + Path.GetFileName(FileHandler.FileLockedByProcess);
            }

            if (GetFileEntriesRotateMediaCountDirty() > 0)
            {
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                string.Format("Rotate: {0}", GetFileEntriesRotateMediaCountDirty());
            }
            threadQueuCount += GetFileEntriesRotateMediaCountDirty();

            if (GlobalData.ProcessCounterReadProperties > 0)
            {
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                string.Format("Properties: {0}", GlobalData.ProcessCounterReadProperties);
            }
            threadQueuCount += GlobalData.ProcessCounterReadProperties;


            if (CommonQueueReadMetadataFromSourceWindowsLivePhotoGalleryCountDirty() > 0)
            {
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                string.Format("Read WLPG: {0}", CommonQueueReadMetadataFromSourceWindowsLivePhotoGalleryCountDirty());
            }
            threadQueuCount += CommonQueueReadMetadataFromSourceWindowsLivePhotoGalleryCountDirty();

            if (CommonQueueReadMetadataFromSourceMicrosoftPhotosCountDirty() > 0)
            {
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                string.Format("Read MP: {0}", CommonQueueReadMetadataFromSourceMicrosoftPhotosCountDirty());
            }
            threadQueuCount += CommonQueueReadMetadataFromSourceMicrosoftPhotosCountDirty();

            if (CommonQueueSaveToDatabaseMediaThumbnailCountDirty() > 0)
            {
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                string.Format("Save Thumbnails: {0}", CommonQueueSaveToDatabaseMediaThumbnailCountDirty());
            }
            threadQueuCount += CommonQueueSaveToDatabaseMediaThumbnailCountDirty();

            int regionCount = 0;

            try
            {
                lock (commonQueueSaveToDatabaseRegionAndThumbnailLock) //CommonQueueReadPosterAndSaveFaceThumbnailsCountLock()
                {
                    foreach (Metadata metadataRegionCount in commonQueueSaveToDatabaseRegionAndThumbnail)
                    {
                        regionCount += metadataRegionCount.PersonalRegionList.Count;
                    }
                }
            }
            catch { }

            if (regionCount > 0)
            {
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                string.Format("Save Regions: {0}", regionCount);
            }
            threadQueuCount += regionCount;

            if (CommonQueueReadMetadataFromSourceExiftoolCountDirty() + ExiftoolSave_MediaFilesNotInDatabaseCountDirty() > 0)
            {
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                string.Format("Exiftool: {0} in process: {1}", CommonQueueReadMetadataFromSourceExiftoolCountDirty(), ExiftoolSave_MediaFilesNotInDatabaseCountDirty());
                threadQueuCount += CommonQueueReadMetadataFromSourceExiftoolCountDirty();
                if (!stopwatchLastDisplayedExiftoolWaitCloud.IsRunning)
                {
                    stopwatchLastDisplayedExiftoolWaitCloud.Start();
                }
                if (stopwatchLastDisplayedExiftoolWaitCloud.ElapsedMilliseconds > 10000)
                {
                    try
                    {
                        int countWaitFileInCloud = 0;
                        foreach (FileEntry fileEntry in exiftool_MediaFilesNotInDatabase)
                        {
                            FileStatus fileStatus = FileHandler.GetFileStatus(fileEntry.FileFullPath);
                            if (fileStatus.IsInCloudOrVirtualOrOffline)
                            {
                                countWaitFileInCloud++;
                            }
                        }
                        if (countWaitFileInCloud > 0)
                        {
                            progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") + string.Format("wait cloud:{0} ", countWaitFileInCloud);
                        }
                    }
                    catch
                    {
                    }
                    stopwatchLastDisplayedExiftoolWaitCloud.Restart();
                }
            }

            if (readToCacheQueues.Count > 0)
            {
                try
                {
                    progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                    string.Format("Caching: ");

                    lock (_readToCacheQueuesLock)
                    {
                        foreach (KeyValuePair <int, int> keyValuePair in readToCacheQueues)
                        {
                            progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                            //"#" + keyValuePair.Key.ToString() + " " +
                                                            keyValuePair.Value;
                            threadQueuCount += keyValuePair.Value;
                        }
                    }
                }
                catch
                {
                }
            }

            if (deleteRecordQueues.Count > 0)
            {
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") + "Delete: ";
                try
                {
                    lock (_deleteRecordQueuesLock)
                    {
                        foreach (KeyValuePair <int, int> keyValuePair in deleteRecordQueues)
                        {
                            progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") + keyValuePair.Value;
                            threadQueuCount += keyValuePair.Value;
                        }
                    }
                }
                catch
                {
                }
            }

            if (CountSaveQueueLock() > 0)
            {
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                string.Format("Saving: {0}", CountSaveQueueLock());
            }
            threadQueuCount += CountSaveQueueLock();

            if (CommonQueueMetadataWrittenByExiftoolReadyToVerifyCountDirty() > 0)
            {
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                string.Format("Verify:{0}", CommonQueueMetadataWrittenByExiftoolReadyToVerifyCountDirty());
            }
            threadQueuCount += CommonQueueMetadataWrittenByExiftoolReadyToVerifyCountDirty();

            if (CommonQueueRenameCountDirty() > 0)
            {
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                string.Format("Rename: {0}", CommonQueueRenameCountDirty());
            }
            threadQueuCount += CommonQueueRenameCountDirty();

            if (CommonQueueLazyLoadingAllSourcesAllMetadataAndRegionThumbnailsCountDirty() > 0)
            {
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                string.Format("Metadata: {0}", CommonQueueLazyLoadingAllSourcesAllMetadataAndRegionThumbnailsCountDirty());
            }
            threadQueuCount += CommonQueueLazyLoadingAllSourcesAllMetadataAndRegionThumbnailsCountDirty();

            if (CommonQueueLazyLoadingThumbnailCountDirty() > 0)
            {
                progressBackgroundStatusText += (progressBackgroundStatusText == "" ? "" : " ") +
                                                string.Format("Thumbnail: {0}", CommonQueueLazyLoadingThumbnailCountDirty());
            }
            threadQueuCount += CommonQueueLazyLoadingThumbnailCountDirty();

            //int lasyLoadingDataGridViewCount = ThreadLazyLoadingDataGridViewQueueSizeDirty() + DataGridViewLazyLoadingCount();
            //if (lasyLoadingDataGridViewCount == 0) LazyLoadingDataGridViewProgressEndReached();

            try
            {
                if (threadQueuCount == 0)
                {
                    progressBackgroundStatusText = "";
                }
                else
                {
                    progressBackgroundStatusText = "(" + threadQueuCount + ") " + progressBackgroundStatusText;
                }
                ProgressBackgroundStatusText = progressBackgroundStatusText;
            }
            catch {
            }

            #region Updated progressbar
            try
            {
                int queueRemainding = threadQueuCount;
                ProgressbarBackgroundProgressQueueRemainding(queueRemainding);

                if (queueRemainding != 0)
                {
                    ProgressbarBackgroundProgress(true);
                }
                else
                {
                    ProgressbarBackgroundProgress(false, 1, 0, 1);
                }
            } catch (Exception ex)
            {
                Logger.Error(ex, "DisplayAllQueueStatus");
            }
            #endregion
        }
예제 #52
0
 public void SetHandler(FileHandler handler)
 {
     this._handler = handler;
 }
예제 #53
0
 public static void SaveJson(string json)
 {
     FileHandler.WriteToFile("Database.json", json);
 }
예제 #54
0
        public void Start()
        {
            if (DataFilePath == null || DataFilePath == "")
            {
                MessageBox.Show("Не был выбран файл с данными для классификации", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            else
            {
                FileHandler fileHandler;
                if (ObjectFilePath != null && ObjectFilePath != "")
                {
                    fileHandler = new FileHandler(DataFilePath, ObjectFilePath);
                }
                else
                {
                    fileHandler = new FileHandler(DataFilePath);
                }

                var directory      = Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, resultDirectoryName));
                var resultFileName = string.Concat(Path.GetFileNameWithoutExtension(DataFilePath), resultName);
                var resultPath     = Path.Combine(directory.FullName, resultFileName);

                if (IsDictionaryEnabled)
                {
                    //словарный метод классификации
                    Classifier classifier;
                    if (IsNewDict)
                    {
                        if (DictionaryDataFilePath == null || DictionaryDataFilePath == "")
                        {
                            MessageBox.Show("Не был выбран файл с размеченной выборкой для создания словаря", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }
                        var collector = new DictionaryCollector(DictionaryDataFilePath);
                        classifier = new Classifier(collector, fileHandler);
                    }
                    else
                    {
                        classifier = new Classifier(fileHandler, Classifier.DictionaryMode);
                    }
                    classifier.Classify(resultPath);
                    MessageBox.Show(string.Format("Работа программы успешно завершена! Результаты сохранены в файле {0} в подкаталоге {1}.", resultFileName, resultDirectoryName));
                }
                else if (IsMachineLearningEnabled)
                {
                    //машинное обучение
                    if (TrainFilePath == null || TrainFilePath == "")
                    {
                        MessageBox.Show("Не был выбран файл с обучающей выборкой", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    var classifier = new Classifier(fileHandler, Classifier.MachineLearningMode);
                    if (IsSVM)
                    {
                        classifier.Method = "svm";
                    }
                    else if (IsStochasticGradient)
                    {
                        classifier.Method = "stochastic_gradient";
                    }
                    else if (IsRandomForest)
                    {
                        classifier.Method = "random_forest";
                    }
                    else if (IsLogisticRegression)
                    {
                        classifier.Method = "logistic_regression";
                    }
                    else if (IsBernoulliNB)
                    {
                        classifier.Method = "bernoulli_naive_bayes";
                    }
                    else
                    {
                        MessageBox.Show("Не был выбран способ классификации", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    classifier.TrainFilePath = TrainFilePath;
                    classifier.Classify(resultPath);
                    MessageBox.Show(string.Format("Работа программы успешно завершена! Результаты сохранены в файле {0} в подкаталоге {1}.", resultFileName, resultDirectoryName));
                }
                else
                {
                    MessageBox.Show("Не был выбран способ классификации", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }
        }
예제 #55
0
 public void SetupBattery()
 {
     File = new FileHandler("./Assets/Configs/", "GeneratedTemplate.json", "GeneratedTemplate.meta");
     SceneManager.LoadScene("Battery End", LoadSceneMode.Single);
 }
        private void SaveRename()
        {
            if (GlobalData.IsApplicationClosing)
            {
                return;
            }
            try
            {
                if (IsFileInAnyQueueLock(imageListView1.SelectedItems))
                {
                    DataGridViewHandlerRename.RenameVaribale = Properties.Settings.Default.RenameVariable;

                    using (new WaitCursor())
                    {
                        DataGridView dataGridView = dataGridViewRename;

                        int columnIndex = DataGridViewHandler.GetColumnIndexFirstFullFilePath(dataGridView, DataGridViewHandlerRename.headerNewFilename, false);
                        if (columnIndex == -1)
                        {
                            return;
                        }

                        for (int rowIndex = 0; rowIndex < DataGridViewHandler.GetRowCountWithoutEditRow(dataGridView); rowIndex++)
                        {
                            DataGridViewGenericCell cellGridViewGenericCell = DataGridViewHandler.GetCellDataGridViewGenericCellCopy(dataGridView, columnIndex, rowIndex);

                            if (!cellGridViewGenericCell.CellStatus.CellReadOnly)
                            {
                                DataGridViewGenericRow dataGridViewGenericRow = DataGridViewHandler.GetRowDataGridViewGenericRow(dataGridView, rowIndex);

                                #region Get Old filename from grid
                                string oldFilename     = dataGridViewGenericRow.RowName;
                                string oldDirectory    = dataGridViewGenericRow.HeaderName;
                                string oldFullFilename = FileHandler.CombinePathAndName(oldDirectory, oldFilename);
                                #endregion

                                AddQueueRenameMediaFilesLock(oldFullFilename, DataGridViewHandlerRename.RenameVaribale);
                            }
                        }
                    }
                }
                else
                {
                    Dictionary <string, string> renameSuccess;
                    Dictionary <string, RenameToNameAndResult> renameFailed;
                    HashSet <string> directoriesCreated;

                    DataGridViewHandlerRename.Write(dataGridViewRename, out renameSuccess, out renameFailed, out directoriesCreated, checkBoxRenameShowFullPath.Checked);
                    UpdateImageViewListeAfterRename(imageListView1, renameSuccess, renameFailed, true);

                    foreach (string newDirector in directoriesCreated)
                    {
                        GlobalData.DoNotTrigger_TreeViewFolder_BeforeAndAfterSelect = true;
                        TreeViewFolderBrowserHandler.RefreshFolderWithName(treeViewFolderBrowser1, newDirector, true);
                        GlobalData.DoNotTrigger_TreeViewFolder_BeforeAndAfterSelect = false;
                    }

                    ImageListView_SelectionChanged_Action_ImageListView_DataGridView(false);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Was not able to rename files");
                KryptonMessageBox.Show("Was not able to rename files.\r\n" + ex.Message, "Rename files failed.", MessageBoxButtons.OK, MessageBoxIcon.Error, showCtrlCopy: true);
            }
        }
예제 #57
0
 public PlayerSelectEdit(FileHandler fileHandler)
     : base(fileHandler)
 {
     modalSelect.SetPlayerEdit();
     WireHandlers();
 }
예제 #58
0
 private void clrCacheBtn_Click(object sender, EventArgs e)
 {
     XmlRecordFile.Instance.ClearFile();
     FileHandler.ClearFiles();
     MessageBox.Show("Cache Cleared");
 }
예제 #59
0
파일: STB.cs 프로젝트: osROSE/UnityRose
        /// <summary>
        /// Saves the specified file.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        public void Save(string filePath)
        {
            Encoding encoding = Encoding.UTF8;

            FileHandler fh = new FileHandler(FilePath = filePath, FileHandler.FileOpenMode.Writing, encoding);

            fh.Write<BaseString>("STB1");
            fh.Write<int>(0);

            int rowCount = Cells.Count;
            int columnCount = (Cells.Count > 0) ? Cells[0].Count : 0;

            fh.Write<int>(rowCount + 1);
            fh.Write<int>(columnCount);
            fh.Write<int>(RowSize);

            for (int i = 0; i < ColumnSizes.Count; i++)
                fh.Write<short>((short)ColumnSizes[i]);

            for (int i = 0; i < ColumnNames.Count; i++)
            {
                fh.Write<short>((short)encoding.GetByteCount(ColumnNames[i]));
                fh.Write<string>(ColumnNames[i]);
            }

            for (int i = 0; i < rowCount; i++)
            {
                fh.Write<short>((short)encoding.GetByteCount(Cells[i][0]));
                fh.Write<string>(Cells[i][0]);
            }

            int dataOffset = fh.Tell();

            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 1; j < columnCount; j++)
                {
                    fh.Write<short>((short)encoding.GetByteCount(Cells[i][j]));
                    fh.Write<string>(Cells[i][j]);
                }
            }

            fh.Seek(4, SeekOrigin.Begin);
            fh.Write<int>(dataOffset);

            fh.Close();
        }
예제 #60
0
 private string GetFilePath()
 {
     return(FileHandler.GetPersistantFilePath(soundSettingJsonFileName));
 }