OpenText() private method

private OpenText ( ) : StreamReader
return StreamReader
Esempio n. 1
0
        public void execute(string file_path)
        {
            // read script
            var file = new FileInfo(file_path);
            string script = file.OpenText().ReadToEnd();

            // execute script
            var connection = new SqlConnection(connection_string);
            var server = new Server(new ServerConnection(connection));
            server.ConnectionContext.ExecuteNonQuery(script);
            System.Diagnostics.Debug.WriteLine("Server Instance Name: " + server.InstanceName);
            file.OpenText().Close();
        }
 public static void ClearCreateCoreEntitiesDatabase()
 {
     var clearFile = new FileInfo(ClearCoreEntitiesDatabaseScriptLocation);
     var createFile = new FileInfo(CreateCoreEntitiesDatabaseScriptLocation);
     string clearScript = clearFile.OpenText().ReadToEnd();
     string createScript = createFile.OpenText().ReadToEnd();
     using (var conn = new SqlConnection(ServerConstants.SqlConnectionString))
     {
         var server = new Microsoft.SqlServer.Management.Smo.Server(new ServerConnection(conn));
         server.ConnectionContext.ExecuteNonQuery(clearScript);
         server.ConnectionContext.ExecuteNonQuery(createScript);
     }
     clearFile.OpenText().Close();
     createFile.OpenText().Close();
 }
Esempio n. 3
0
		void LoadHhcFile(string fileName)
		{
			FileInfo fi = new FileInfo(basePath + Path.DirectorySeparatorChar + fileName);
			StreamReader sr = fi.OpenText();
			hhcFileContents = sr.ReadToEnd();
			sr.Close();
		}
Esempio n. 4
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(onError);

            // Loading all configs files
            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig<LauncherConfig>();

            // Loading log level from file
            if (!Log.InitLog(Config.LogLevel, "LauncherServer"))
                ConsoleMgr.WaitAndExit(2000);

            Client = new RpcClient("LauncherServer", Config.RpcInfo.RpcLocalIp, 1);
            if (!Client.Start(Config.RpcInfo.RpcServerIp, Config.RpcInfo.RpcServerPort))
                ConsoleMgr.WaitAndExit(2000);

            Info = new FileInfo("Configs/mythloginserviceconfig.xml");
            if (!Info.Exists)
            {
                Log.Error("Configs/mythloginserviceconfig.xml", "Config file missing !");
                ConsoleMgr.WaitAndExit(5000);
            }

            StrInfo = Info.OpenText().ReadToEnd();

            if (!TCPManager.Listen<TCPServer>(Config.LauncherServerPort, "LauncherServer"))
                ConsoleMgr.WaitAndExit(2000);

            Server = TCPManager.GetTcp<TCPServer>("LauncherServer");

            ConsoleMgr.Start();
        }
 /// <summary>
 /// Opens the file.
 /// </summary>
 /// <param name="file">The file.</param>
 /// <returns></returns>
 public static string OpenFile(FileInfo file)
 {
     using (var fs = file.OpenText())
     {
         return fs.ReadToEnd();
     }
 }
        /// <summary>
        /// Read from a given file, and output to std out.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: ParseSingleDFS <input-filename>");
                return;
            }
            var f = new FileInfo(args[0]);
            if (!f.Exists)
            {
                Console.WriteLine("File {0} does not exist!", f.FullName);
            }

            var text = "";
            using (var reader = f.OpenText())
            {
                text = reader
                    .AsEnumerable()
                    .Where(l => !l.StartsWith("#") && !string.IsNullOrWhiteSpace(l))
                    .ReadAllLines();
            }

            try
            {
                var dfs = text.Parse();

                OWLEmitter.EmitHeaders(Console.Out);
                Console.WriteLine();
                dfs.Emit(Console.Out);
            } catch (Exception e)
            {
                Console.WriteLine($"Parse and translation failed: {e.Message}");
            }
        }
      public void TestCollapseMessageResponses()
      {
         DirectoryInfo di = Directory.GetParent(Environment.CurrentDirectory);

         FileInfo fi = new FileInfo(Path.Combine(di.FullName, "TestSetup\\ExportCommandWithEMessages.xml"));
         TextReader reader = fi.OpenText();
         XDocument xdoc = XDocument.Load(reader);
         ////bool result = TestHelper.ValidateCommandXML(xdoc);
         ////Assert.IsTrue(result);
         IRoot root = new Root(TestConfig.RepositoryPath, TestConfig.ModuleName, TestConfig.CVSHost, TestConfig.CVSPort, TestConfig.Username, TestConfig.Password);
         root.WorkingDirectory = TestConfig.WorkingDirectory;
         PServerFactory factory = new PServerFactory();
         IConnection connection = new PServerConnection();
         ICommand cmd = factory.CreateCommand(xdoc, new object[] { root, connection });
         int count = cmd.Items.OfType<IResponse>().Count();
         Assert.AreEqual(18, count);
         count = cmd.Items.OfType<EMessageResponse>().Count();
         Assert.AreEqual(12, count);
         IList<IResponse> responses = cmd.Items.OfType<IResponse>().ToList();
         IList<IResponse> condensed = ResponseHelper.CollapseMessagesInResponses(responses);
         Assert.AreEqual(7, condensed.Count);
         IMessageResponse message = (IMessageResponse)condensed[5];
         Assert.AreEqual(12, message.Lines.Count);
         Console.WriteLine(message.Display());
      }
Esempio n. 8
0
        public override IEnumerable<LogItem> GetEntries(string dataSource, FilterParams filter)
        {
            if (String.IsNullOrEmpty(dataSource))
                throw new ArgumentNullException("dataSource");
            if (filter == null)
                throw new ArgumentNullException("filter");

            string pattern = filter.Pattern;
            if (String.IsNullOrEmpty(pattern))
                throw new NotValidValueException("filter pattern null");

            FileInfo file = new FileInfo(dataSource);
            if (!file.Exists)
                throw new FileNotFoundException("file not found", dataSource);

            Regex regex = new Regex(@"%\b(date|message|level)\b");
            MatchCollection matches = regex.Matches(pattern);

            using (StreamReader reader = file.OpenText())
            {
                string s;
                while ((s = reader.ReadLine()) != null)
                {
                    string[] items = s.Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries);
                    LogItem entry = CreateEntry(items, matches);
                    entry.Logger = filter.Logger;
                    yield return entry;
                }
            }            
        }
Esempio n. 9
0
        public static void InitializeSearchIndexes()
        {
            ssceDBEntities sse = new ssceDBEntities();
            var indexes = sse.SearchIndexes.ToArray();
            if (sse.SearchIndexes.Count() == 0)
            {
                FileInfo file = new FileInfo("SearchIndeces.txt");
                StreamReader stRead = file.OpenText();
                List<string> titles = new List<string>();
                while (true)
                {
                    string s = stRead.ReadLine();
                    if (s == null) break;
                    else titles.Add(s);
                }

                foreach (string s in titles)
                {
                    SearchIndex index = new SearchIndex();

                    index.ID = GetNextID();

                    index.Title = s;
                    sse.AddToSearchIndexes(index);
                    sse.SaveChanges();
                }

            }
        }
        public void RetryFileActionThrowFileNotFoundException()
        {
            var fileName2 = ".\\test.xml";
            var fileInfo2 = new FileInfo(fileName2);

            fileInfo2.RetryFileActionIfLocked(fi =>{ var reader = fileInfo2.OpenText(); });
        }
        public void Initialize()
        {
            ApiService.SubscribeOnce("api_start2", delegate
            {
                var rDataFile = new FileInfo(DataFilename);
                if (!rDataFile.Exists)
                    Infos = new Dictionary<int, QuestInfo>();
                else
                    using (var rReader = new JsonTextReader(rDataFile.OpenText()))
                    {
                        var rData = JArray.Load(rReader);

                        Infos = rData.Select(r => new QuestInfo(r)).ToDictionary(r => r.ID);
                    }

                if (r_InitializationLock != null)
                {
                    r_InitializationLock.Set();
                    r_InitializationLock.Dispose();
                    r_InitializationLock = null;
                }
            });

            ApiService.Subscribe("api_get_member/require_info", _ =>
            {
                if (r_InitializationLock != null)
                    r_InitializationLock.Wait();

                Progresses = RecordService.Instance.QuestProgress.Reload();
            });

            ApiService.Subscribe("api_get_member/questlist", r => ProcessQuestList(r.Data as RawQuestList));
            ApiService.Subscribe("api_req_quest/clearitemget", r => Progresses.Remove(int.Parse(r.Parameters["api_quest_id"])));
        }
Esempio n. 12
0
        public Signal Import(FileInfo file)
        {
            string textFromFile;
            using (StreamReader sr = file.OpenText())
            {
                textFromFile = sr.ReadToEnd();
            }
            textFromFile = textFromFile.Replace('.', ',');
            textFromFile = textFromFile.Trim('\n', ' ');
            string[] txtValues =  textFromFile.Split(' ', '\n', '\t');
            double[] values = new double[txtValues.Length];
            for (int i = 0; i < txtValues.Length; ++i)
                values[i] = double.Parse(txtValues[i]);

            if (values.Length < 2)
            {
                throw new Exception("Should be at least 2 values in file!");
            }
            try
            {
                var s = new Signal(values, file.Name.Remove(file.Name.Length - 4));
                return s;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Retrieves a template from the system, compiling it if needed.
        /// </summary>
        public ITemplate this[FileInfo file]
        {
            get
            {
                // Check the hash
                ITemplate template = (ITemplate) templates[file.FullName];

                if (template != null)
                    return template;

                // Ignore blanks
                if (!file.Exists)
                {
                    throw new TemplateException("File does not exist: "
                        + file);
                }

                // Create the template
                Debug("Parsing template: " + file);
                TextReader reader = file.OpenText();
                template = factory.Create(reader, file.ToString());
                reader.Close();

                // Save the template and return it
                templates[file.FullName] = template;
                return template;
            }
        }
        public void Import(MigrationToolSettings settings)
        {
            var sourceImportFilePath = Path.Combine(settings.SourceDirectory, "localization-resource-translations.sql");
            if (!File.Exists(sourceImportFilePath))
            {
                throw new IOException($"Source file '{sourceImportFilePath}' for import not found!");
            }

            // create DB structures in target database
            using (var db = new LanguageEntities(settings.ConnectionString))
            {
                var resource = db.LocalizationResources.Where(r => r.Id == 0);
            }

            var fileInfo = new FileInfo(sourceImportFilePath);
            var script = fileInfo.OpenText().ReadToEnd();
            using (var connection = new SqlConnection(settings.ConnectionString))
            {
                connection.Open();

                using (var command = new SqlCommand(script, connection))
                {
                    command.ExecuteNonQuery();
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Инициализирует новый экземпляр класса Thesaurus, сопоставляя его с текстовым файлом на диске.
        /// </summary>
        /// <param name="fileName">Имя файла.</param>
        public Thesaurus(string fileName)
        {
            List<int> indicies = new List<int>();
            indicies.Add(0); //первое слово начинается с нулевого символа

            fi = new FileInfo(fileName);
            var sr = fi.OpenText();
            _size = 0;
            int i = 0;
            while (/*!sr.EndOfStream*/true)
            {
                ++i;
                if (sr.Read() == '\n')
                {
                    indicies.Add(i); //запомнили новый индекс
                    ++_size;  //увеличили размер словаря
                }
                if (sr.EndOfStream)
                {
                    indicies.Add(i+2);
                    ++_size; //////test
                    break;
                }
            }
            sr.Close();
            _indicies = indicies.ToArray();
        }
Esempio n. 16
0
        public static void CreateStoredFuncs(string path)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["ApplicationDbContext"].ConnectionString;

            var file = new FileInfo(path);
            var script = file.OpenText().ReadToEnd();

            using (var connection = new SqlConnection(connectionString))
            {
                var server = new Server(new ServerConnection(connection));
                server.ConnectionContext.ExecuteNonQuery(script);

                var _path = path.Replace("userdefinedtypes", "storedfunc");
                file = new FileInfo(_path);
                script = file.OpenText().ReadToEnd();
                server.ConnectionContext.ExecuteNonQuery(script);

                _path = _path.Replace("storedfunc", "storedproc");
                file = new FileInfo(_path);
                script = file.OpenText().ReadToEnd();
                server.ConnectionContext.ExecuteNonQuery(script);

                _path = _path.Replace("storedproc", "storedtriggers");
                file = new FileInfo(_path);
                script = file.OpenText().ReadToEnd();
                server.ConnectionContext.ExecuteNonQuery(script);
            }
        }
        public void Exports_With_User_Defined_KeyValues_When_Available()
        {
            var service = new ExportService() as IExportService;
            var product = new Product { Id = Guid.NewGuid(), Name = "My Product", };
            var license = new License
            {
                LicenseType = LicenseType.Standard, 
                OwnerName = "License Owner", 
                ExpirationDate = null,
            };
            
            license.Data.Add(new UserData { Key = "KeyOne", Value = "ValueOne"});
            license.Data.Add(new UserData { Key = "KeyTwo", Value = "ValueTwo"});

            var path = Path.GetTempFileName();
            var file = new FileInfo(path);

            service.Export(product, license, file);

            var reader = file.OpenText();
            var content = reader.ReadToEnd();

            Assert.NotNull(content);
            Assert.Contains("KeyOne=\"ValueOne\"", content);
            Assert.Contains("KeyTwo=\"ValueTwo\"", content);
        }
Esempio n. 18
0
        public static void ReadMaterials(string relativePath, FileInfo file)
        {
            StreamReader reader = file.OpenText();

            List<string> matFiles = new List<string>();

            Material mat = null;
            while (!reader.EndOfStream)
            {
                string line = reader.ReadLine().Trim();

                if (line == string.Empty || line[0] == '#')
                    continue;

                string[] lineParts = line.Split(" ".ToCharArray());
                if (lineParts.Length == 1)
                    continue;

                string code = lineParts[0].ToLower();

                if (code == "newmtl")
                    mat = Material.New(lineParts[1]);
                else if (code == "kd")
                {
                    Vector3 c = ReadVector3(lineParts, 1);
                    mat.DiffuseColor = Color.FromArgb(Byte.MaxValue, (int)(Byte.MaxValue * c.X), (int)(Byte.MaxValue * c.Y), (int)(Byte.MaxValue * c.Z));
                }
                else if (code == "map_kd")
                    mat.TextureName = relativePath + "/" + lineParts[1];
            }

            reader.Close();
        }
Esempio n. 19
0
        private static void Main(string[] args)
        {
            if (File.Exists("Data/database.fdb"))
            {
                File.Delete("Data/database.fdb");
            }

            FbConnection.CreateDatabase(GetConnectionString());

            using (var conn = new FbConnection(GetConnectionString()))
            {
                conn.Open();
                if (File.Exists("Data/database.sql"))
                {
                    var file = new FileInfo("Data/database.sql");
                    string script = file.OpenText().ReadToEnd();

                    using (FbCommand createTable = conn.CreateCommand())
                    {
                        createTable.CommandText = script;
                        createTable.ExecuteNonQuery();
                    }
                }
            }
        }
Esempio n. 20
0
 public PowerShellProvider(FileInfo scriptFile)
 {
     using(var reader = scriptFile.OpenText())
     {
         DestinationPath = reader.ReadToEnd();
     }
 }
Esempio n. 21
0
        public List<String> Categories()
        {
            List<String> categories = (new String[] { "System", "Processor", "Memory", "Process", "Paging File", "PhysicalDisk", "Server", "IP", "UDP", "TCP", "Network Interface", "Cache" }).ToList();

            String configName = Assembly.GetExecutingAssembly().Location;
            FileInfo fi = new FileInfo(configName);
            fi = new FileInfo(fi.DirectoryName + "\\categories.txt");
            if (!fi.Exists)
                using (var fw = fi.CreateText())
                {
                    foreach (String row in categories)
                        fw.WriteLine(row);
                }
            else
            {
                using (var fr = fi.OpenText())
                {
                    List<String> s = new List<String>();
                    String line;
                    while ((line = fr.ReadLine()) != null)
                        s.Add(line);
                    categories = s;

                }
            }
            return categories;
        }
Esempio n. 22
0
        protected override void ExecuteTask()
        {
            if (DebugTask && !System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Launch();

            NAnt.Contrib.Functions.FileFunctions contribFileFunctions = new Contrib.Functions.FileFunctions(base.Project, base.Properties);

            if (null != InElement && 0 < InElement.Count && 0 < InElement[0].FileNames.Count)
            {
                for (int idx = 0; idx < InElement.Count; idx++)
                {
                    FileSet fs = InElement[idx];
                    for (int idx2 = 0; idx2 < fs.FileNames.Count; idx2++)
                    {
                        FileInfo fileToCheck = new FileInfo(fs.FileNames[idx2]);
                        FileInfo checksumFile = new FileInfo(fileToCheck.FullName + '.' + Algorithm);

                        if (!checksumFile.Exists) throw new FileNotFoundException("Can't find checksum file", checksumFile.FullName);
                        if (!fileToCheck.Exists) throw new FileNotFoundException("Can't find file to check", fileToCheck.FullName);

                        string actualChecksum = contribFileFunctions.GetChecksum(fileToCheck.FullName, Algorithm);
                        using (StreamReader sr = checksumFile.OpenText())
                        {
                            string expectedChecksum = sr.ReadToEnd();
                            if (actualChecksum != expectedChecksum) throw new Exception(string.Format("The checksum generated does not match the contents of the file's counterpart.  Actual [{0}] from [{1}] was expected to be [{2}]", actualChecksum, fileToCheck.FullName, expectedChecksum));
                        }
                    }
                }
            }
        }
Esempio n. 23
0
 private void btn_filedb_Click(object sender, RoutedEventArgs e)
 {
     string path = System.Environment.CurrentDirectory + "\\filepath.txt";
     string filepath_db = System.Environment.CurrentDirectory + "\\bd4.mdf";
     FileInfo fi1;
     if (System.IO.File.Exists(path))//проверка на существование файла настроек
     {
         fi1 = new FileInfo(path);
         using (StreamReader sr = fi1.OpenText())
         {
             string s = sr.ReadLine();
             if (System.IO.File.Exists(s))//проверка на путь в нем
             {
                 filepath_db = s;
             }
         }
     }
     if (!System.IO.File.Exists(filepath_db))
     {
         filepath_db = @"C:\";
     }
     System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
     dialog.InitialDirectory = filepath_db;
     dialog.Filter = "DB File |*.mdf";
     if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         filepath_db = dialog.FileName;
     }
     else filepath_db = System.Environment.CurrentDirectory + "\\bd4.mdf";
     fi1 = new FileInfo(path);
     using (StreamWriter sr = fi1.CreateText())
     {
         sr.WriteLine(filepath_db);
     }
 }
Esempio n. 24
0
    public XCProject(string filePath) : this()
    {
        if (!System.IO.Directory.Exists(filePath))
        {
            Debug.LogWarning("Path does not exists.");
            return;
        }

        if (filePath.EndsWith(".xcodeproj"))
        {
            this.projectRootPath = Path.GetDirectoryName(filePath);
            this.filePath = filePath;
        }
        else
        {
            string[] projects = System.IO.Directory.GetDirectories(filePath, "*.xcodeproj");
            if (projects.Length == 0)
            {
                Debug.LogWarning("Error: missing xcodeproj file");
                return;
            }

            this.projectRootPath = filePath;
            this.filePath = projects[0];
        }

        projectFileInfo = new FileInfo(Path.Combine(this.filePath, "project.pbxproj"));
        StreamReader sr = projectFileInfo.OpenText();
        string contents = sr.ReadToEnd();
        sr.Close();

        PBXParser parser = new PBXParser();
        _datastore = parser.Decode(contents);
        if (_datastore == null)
        {
            throw new System.Exception("Project file not found at file path " + filePath);
        }

        if (!_datastore.ContainsKey("objects"))
        {
            Debug.Log("Errore " + _datastore.Count);
            return;
        }

        _objects = (PBXDictionary) _datastore["objects"];
        modified = false;

        _rootObjectKey = (string) _datastore["rootObject"];
        if (!string.IsNullOrEmpty(_rootObjectKey))
        {
            _project = new PBXProject(_rootObjectKey, (PBXDictionary) _objects[_rootObjectKey]);
            _rootGroup = new PBXGroup(_rootObjectKey, (PBXDictionary) _objects[_project.mainGroupID]);
        }
        else
        {
            Debug.LogWarning("Error: project has no root object");
            _project = null;
            _rootGroup = null;
        }
    }
Esempio n. 25
0
        public CnmFile(FileInfo source)
        {
            DateTime dt;
            try
            {
                using (StreamReader r =  source.OpenText())
                {
                    for (int i = 0; ; i++)
                    {
                        if (i > 3)
                            throw new ApplicationException("Can't found time");

                        string str = r.ReadLine();
                        int semicolon = str.IndexOf(';');
                        if (semicolon != -1)
                        {
                            if ((semicolon + 1) == str.Length)
                                continue;
                            else
                                str = str.Substring(semicolon + 1);
                        }
                        str = str.Trim();
                        if (DateTime.TryParse(str, out dt))
                            break;
                    }
                }
            }
            catch
            {
                dt = DateTime.MinValue;
            }

            Time = dt;
            File = source;
        }
Esempio n. 26
0
        public static string GetConnectionString()
        {
            string str = "";

            Aes.KeySize keysize;

            keysize = Aes.KeySize.Bits128;
            byte[] cipherText = new byte[16];
            byte[] decipheredText = new byte[16];
            FileInfo inf = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "settings.dat");
            if (inf.Exists)
            {
                StreamReader reader = inf.OpenText();
                gConnectionParam.setServer(reader.ReadLine());
                gConnectionParam.setUserName(reader.ReadLine());
                //base.Server = reader.ReadLine();
                //base.UserName = reader.ReadLine();

                cipherText = Encoding.Unicode.GetBytes(reader.ReadLine());
                AesLib.Aes a = new Aes(keysize, new byte[16]);
                a.InvCipher(cipherText, decipheredText);

                //Password = Encoding.Unicode.GetString(decipheredText);
                gConnectionParam.setPassword(Encoding.Unicode.GetString(decipheredText));

                //base.Database = reader.ReadLine();
                gConnectionParam.setDatabase(reader.ReadLine());
                // Fix error : error for There is already an open DataReader associated with this Command which must be closed first ("MultipleActiveResultSets=True;")
                str = gConnectionParam.getConnString();

            }
            return str;
        }
Esempio n. 27
0
        private void Send_Click(object sender, EventArgs e)
        {
            try
            {
                Output.Text = string.Empty;
                FileInfo file = new FileInfo(_file);
                StreamReader rdr = file.OpenText();
                string messageBody = rdr.ReadToEnd();
                rdr.Dispose();

                SmtpClient client = new SmtpClient("some.mail.server.example.com");
                client.Credentials = new NetworkCredential("someuser", "somepassword");
                MailAddress from = new MailAddress("*****@*****.**");
                MailAddress to = new MailAddress("*****@*****.**");
                MailMessage msg = new MailMessage(from, to);
                msg.Body = messageBody;
                msg.Subject = "Test message";
                //client.Send(msg);

                Output.Text = "Sent email with body: " + Environment.NewLine + messageBody;
            }
            catch (Exception ex)
            {
                Output.Text = ex.ToString();
            }
        }
        static void runFileInfo()
        {
            string path = Path.GetTempFileName();
            FileInfo fi = new FileInfo(path);

            if (!fi.Exists)
            {
                // create a file to write to.
                using (StreamWriter writer = fi.CreateText())
                {
                    writer.WriteLine("Hello");
                    writer.WriteLine("And");
                    writer.WriteLine("Welcome");
                }
            }

            // open the file to read from.
            using (StreamReader reader = fi.OpenText())
            {
                string s = "";
                while ((s = reader.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Loads a <see cref="FileEntryGraph"/> from the specified file.
        /// </summary>
        /// <param name="file">The file to load a new <see cref="FileEntryGraph"/> from.</param>
        /// <param name="forFileName">The initial value for the returned objects <see cref="FileEntryGraph.ForFileName"/></param>
        /// <returns>The newly loaded <see cref="FileEntryGraph"/>.</returns>
        public static FileEntryGraph Load(FileInfo file, string forFileName)
        {
            var graph = new FileEntryGraph(forFileName);
            using (var f = file.OpenText())
            {
                f.ReadLine();//headings
                while (!f.EndOfStream)
                {
                    var line = f.ReadLine().Split(',');
                    if (line.Length != 5)
                        throw new IOException("Expected 5 fields!");
					/* FIX for github issue #23: 
					 * The problem was that old ExpectedOutput files were all prefixed with C:\projects\lessmsi\src\Lessmsi.Tests\bin\Debug\<msiFileNameWithoutExtension> (something like C:\projects\lessmsi\src\Lessmsi.Tests\bin\Debug\NUnit-2.5.2.9222\SourceDir\PFiles\NUnit 2.5.2\fit-license.txt)
					 * We need to remove Since we don't reasonably know what the original msi filename was, we do know it was the subdirectory of C:\projects\lessmsi\src\Lessmsi.Tests\bin\Debug\. So we should remove C:\projects\lessmsi\src\Lessmsi.Tests\bin\Debug\ and the next subdirectory from the path. 
					 * HACK: A better fix would undoubtedly be to cleanup those old file swith code like this and remove this hack from this code forever!
					 */
					var path = line[0];
					const string oldRootPath = @"C:\projects\lessmsi\src\Lessmsi.Tests\bin\Debug\";
					if (path.StartsWith(oldRootPath, StringComparison.InvariantCultureIgnoreCase))
					{	
						//this is an old file that would trigger github issue #23, so we'll fix it here...
						// first remove the old root path: 
						path = path.Substring(oldRootPath.Length);
						// now romove the msi filename (which we don't know, but we know it is the next subdirectory of the old root):
						var lengthOfSubDirectoryName = path.IndexOf('\\', 0);
						path = path.Substring(lengthOfSubDirectoryName);
					}
					graph.Add(new FileEntry(path, Int64.Parse(line[1]), DeserializeDate(line[2]), DeserializeDate(line[3]), DeserializeAttributes(line[4])) );
                }
            }
            return graph;
        }
        public void Initialize()
        {
            SessionService.Instance.SubscribeOnce("api_get_member/require_info", delegate
            {
                try
                {
                    var rDataFile = new FileInfo(DataFilename);
                    if (rDataFile.Exists)
                        using (var rReader = new JsonTextReader(rDataFile.OpenText()))
                        {
                            var rData = JArray.Load(rReader);

                            r_Infos = rData.Select(r => r.ToObject<ExpeditionInfo2>()).ToIDTable();
                        }
                }
                finally
                {
                    if (r_Infos == null)
                        r_Infos = new IDTable<ExpeditionInfo2>();

                    r_InitializationLock.Set();
                    r_InitializationLock.Dispose();
                    r_InitializationLock = null;
                }
            });
        }
Esempio n. 31
0
        public async Task <IActionResult> Get()
        {
            string content;
            var    info = new System.IO.FileInfo("servers.json");

            using (var reader = info.OpenText())
            {
                content = await reader.ReadToEndAsync();
            }

            return(Ok(JsonConvert.DeserializeObject <DeviceRequest>(content)));
        }
Esempio n. 32
0
        public override bool AcceptFile(System.IO.FileInfo file)
        {
            // Set initial state of acceptance
            // If checking "contains" assume not accepted
            // If checking "not contains" assume accepted
            bool accepted = (FilterOperator == FilterOperator.NotEqual);

            try
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug("Testing contents of: " + file);
                }
                using (StreamReader reader = file.OpenText())
                {
                    while (reader.Peek() >= 0)
                    {
                        // Get a line of text
                        string text = reader.ReadLine();

                        if (FilterOperator == FilterOperator.NotEqual)
                        {
                            // If checking for "not contains" and found the text, the filter failed
                            if (MatchText(text))
                            {
                                accepted = false;
                                break;
                            }
                        }
                        else if (FilterOperator != FilterOperator.NotEqual)
                        {
                            // If checking for "contains" and found the text, the filter succeeded
                            if (MatchText(text))
                            {
                                accepted = true;
                                break;
                            }
                        }
                    }
                }
            }
            catch (IOException ioe)
            {
                throw new FileQueryException(ioe.Message);
            }

            return(accepted);
        }
Esempio n. 33
0
    /// <summary>
    /// Reads the security text from file.
    /// </summary>
    /// <param name="filePath">The file path.</param>
    /// <remarks>No content validation is done.</remarks>
    public void ReadFromFile(string filePath)
    {
        if (string.IsNullOrEmpty(filePath))
        {
            throw new ArgumentNullException(nameof(filePath));
        }

        var fileInfo = new System.IO.FileInfo(filePath);

        if (!fileInfo.Exists)
        {
            throw new ArgumentException($"Defined file {fileInfo.Name} does not exist.", nameof(filePath));
        }

        using var stream = fileInfo.OpenText();
        ReadFromFile(stream);
    }
    public static FileClass DeserializeFile(string _filePath)
    {
        if (string.IsNullOrEmpty(_filePath) == false)
        {
            bool exists = EnsureDirectoryExists(_filePath, false);

            if (exists)
            {
                System.IO.FileInfo     info = new System.IO.FileInfo(_filePath);
                System.IO.StreamReader file = info.OpenText();

                string fileText = file.ReadToEnd();
                file.Close();

                return(DeserializeText(fileText));
            }
        }

        return(default(FileClass));
    }
Esempio n. 35
0
        /// <summary>
        /// Parse a configuration text file.
        /// </summary>
        /// <param name="f"></param>
        /// <returns></returns>
        internal static Dictionary <string, Dictionary <string, string> > ParseConfigFile(System.IO.FileInfo f)
        {
            using (var rd = f.OpenText())
            {
                var input   = rd.ReadToEnd();
                var results = File.Parse(input);

                var r = new Dictionary <string, Dictionary <string, string> >();
                foreach (var t in results)
                {
                    if (!r.ContainsKey(t.Item1))
                    {
                        r[t.Item1] = new Dictionary <string, string>();
                    }
                    r[t.Item1][t.Item2] = t.Item3;
                }

                return(r);
            }
        }
Esempio n. 36
0
    /// <summary>
    /// func_txt.ReadSQL(@"SQLFunction\RunCost1.sql");
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public static string ReadSQL(string path)
    {
        string filePath, cmd = "";

        System.IO.FileInfo file;
        try
        {
            filePath = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, path);
            file     = new System.IO.FileInfo(filePath);
            System.IO.StreamReader sr = file.OpenText();
            //System.Diagnostics.Debug.WriteLine(sr.CurrentEncoding);
            cmd = sr.ReadToEnd();
            //cmd = file.OpenText().ReadToEnd();
        }
        catch (Exception ex)
        {
            func_txt.log(func_txt.LogType.error, ex.Message + Environment.NewLine + ex.ToString());
        }
        return(cmd);
    }
Esempio n. 37
0
        private void SetupWorld()
        {
            WorldPreload?.Invoke(this, EventArgs.Empty);

            if (ConfigData.GameData.MapFile != string.Empty)
            {
                System.IO.FileInfo     map = new System.IO.FileInfo(ConfigData.GameData.MapFile);
                System.IO.StreamReader sr  = map.OpenText();
                State.World.Map = BZFlag.IO.BZW.Reader.ReadMap(sr);
                sr.Close();

                if (State.World.Map == null)
                {
                    State.World.Map = new Map.WorldMap();
                }
            }

            WorldPostload?.Invoke(this, EventArgs.Empty);
            State.World.Map.Validate();

            State.Flags.SetupIniitalFlags();
        }
Esempio n. 38
0
        private void CountLines(System.IO.FileInfo file)
        {
            int    count = 0;
            string str;

            using (StreamReader reader = file.OpenText())
            {
                while ((str = reader.ReadLine()) != null)
                {  /*  test
                    *
                    */
                    var trim = str.Trim();
                    if (trim == "" || trim.StartsWith(singleComment))
                    {
                        continue;
                    }
                    if (trim.Contains(multiCommentStart))
                    {
                        if (trim.IndexOf(multiCommentStart) != 0)
                        {
                            ++count;
                        }
                        while ((str = reader.ReadLine()) != null && !str.Trim().Contains(multiCommentEnd))
                        {
                            ;
                        }
                        if (!str.Trim().EndsWith(multiCommentEnd))
                        {
                            ++count;
                        }
                        continue;
                    }
                    ++count;
                }//hhhh
            }
            ///hhhh
            Console.WriteLine("In file {0}: {1} lines", file.Name, count);
            result += count;
        }
Esempio n. 39
0
        private string LoadSQLFromFile(string sqlFile)
        {
            string fileSQL = string.Empty;

            if (!string.IsNullOrEmpty(sqlFile))
            {
                string path = _path + @"\App_Data\SQLFiles\" + sqlFile;
                // validate file exists
                if (System.IO.File.Exists(path))
                {
                    System.IO.FileInfo fi = new System.IO.FileInfo(path);
                    // validate of type sql file, and load text
                    if (fi.Extension.Equals(".sql", StringComparison.CurrentCultureIgnoreCase))
                    {
                        System.IO.StreamReader reader = fi.OpenText();
                        fileSQL = reader.ReadToEnd();
                        // cleanup
                        reader.Close();
                    }
                }
            }
            return(fileSQL);
        }
Esempio n. 40
0
 public void FileToBGMList(string[] SongPath)
 {
     this.szListFileName = contents.AudioFileDirectory + "/BGMList.dat";
     this.szListFileName.Remove(0, Application.get_dataPath().ToString().Length - "Assets".Length);
     System.IO.FileInfo fileInfo = new System.IO.FileInfo(this.szListFileName);
     try
     {
         StreamReader streamReader = fileInfo.OpenText();
         for (int index = 0; index < SongPath.Length; ++index)
         {
             SongPath[index] = streamReader.ReadLine();
             if (SongPath[index] == null)
             {
                 SongPath[index] = "Empty";
             }
         }
         streamReader.Close();
     }
     catch
     {
         Debug.LogWarning((object)"Failed FileOpen Error");
     }
 }
Esempio n. 41
0
        public async Task ReadStateAsync(string grainType,
                                         GrainReference grainRef,
                                         IGrainState grainState)
        {
            var collectionName = grainState.GetType().Name;
            var key            = grainRef.ToKeyString();

            var fName = key + "." + collectionName;
            var path  = System.IO.Path.Combine(RootDirectory, fName);

            var fileInfo = new System.IO.FileInfo(path);

            if (!fileInfo.Exists)
            {
                return;
            }

            using (var stream = fileInfo.OpenText())
            {
                var storedData = await stream.ReadToEndAsync();

                grainState.State = JsonConvert.DeserializeObject(storedData, grainState.State.GetType(), _jsonSettings);
            }
        }
Esempio n. 42
0
    private void CreateSchema(string ConnectionString)
    {
        System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConnectionString);

        System.Data.SqlClient.SqlCommand command = conn.CreateCommand();
        command.CommandType = System.Data.CommandType.Text;

        string FullPath = System.IO.Path.Combine(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"EmptyDatabase"), "HROneSaaSDBScheme.sql");
        System.IO.FileInfo dbPatchFile = new System.IO.FileInfo(FullPath);
        System.IO.StreamReader reader = dbPatchFile.OpenText();
        string PatchString = reader.ReadToEnd();
        reader.Close();
        command.CommandText = PatchString;

        command.Connection.Open();
        command.ExecuteNonQuery();

        //FullPath = System.IO.Path.Combine(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"EmptyDatabase"), "SystemData.sql");
        //dbPatchFile = new System.IO.FileInfo(FullPath);
        //reader = dbPatchFile.OpenText();
        //PatchString = reader.ReadToEnd();
        //reader.Close();
        //command.CommandText = PatchString;

        //command.ExecuteNonQuery();

        //FullPath = System.IO.Path.Combine(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"EmptyDatabase"), "SupplementaryData.sql");
        //dbPatchFile = new System.IO.FileInfo(FullPath);
        //reader = dbPatchFile.OpenText();
        //PatchString = reader.ReadToEnd();
        //reader.Close();
        //command.CommandText = PatchString;

        //command.ExecuteNonQuery();
        command.Connection.Close();
    }
Esempio n. 43
0
    /// <summary>
    /// gets the participant id from the participantid.txt file
    /// Increments the Participant ID
    /// writes the new Participant id to the menu screen
    /// writes the new patticcipant id to the participntid.txt file
    /// increment
    /// </summary>
    /// <returns></returns>
    private int SetNewParticipantId()
    {
        string ParticipantIdFileName = "";

        megaMind.GameProgress.ParticipantId = -1;
        try
        {
            DateTime RunDate = DateTime.Today;
            ParticipantIdFileName = System.IO.Path.Combine(megaMind.GameProgress.baseDirectory, string.Format("LastUsedParticipantId_{0}.DAT", RunDate.ToString("yyyyMMdd")));

            string sLine = null;
            var    fi    = new  System.IO.FileInfo(ParticipantIdFileName);
            if (fi.Exists)
            {
                using (var fPar = fi.OpenText())
                {
                    sLine = fPar.ReadLine();
                }

                if (sLine == null || sLine.Trim() == string.Empty)
                {
                    megaMind.GameProgress.ParticipantId = 1;
                }
                else
                {
                    //parse name:value,name2:value2
                    string[] asLine = sLine.Split(',');
                    foreach (string sParameter in asLine)
                    {
                        string[] asParameter = sParameter.Split(':');
                        if (asParameter[0] == PARTICIPANT_ID_KEY)
                        {
                            int i;
                            if (int.TryParse(asParameter[1], out i))
                            {
                                megaMind.GameProgress.ParticipantId = i;
                            }
                        }
                    }
                }
            }
            else
            {
                megaMind.GameProgress.ParticipantId = 1;
            }

            if (megaMind.GameProgress.ParticipantId < 1)
            {
                //error?
                //dont want to start from 0 and risk overwrites
                throw (new ArgumentException("Invalid Calculation of Participant Id.  Value should be at least 1."));
            }

            return(megaMind.GameProgress.ParticipantId);
        }
        catch (Exception ex)
        {
            // if we get an exception, set the participant id to something based on the hour of day so that we do  get overlap
            // assuming max play rate is no greater than 5 games in 2 minutes;
            //create a unique daily id of that grain
            megaMind.GameProgress.ParticipantId = DateTime.Now.Hour * 30 + DateTime.Now.Minute / 2;
            megaMind.GameProgress.Write(new megaMind.EventRecord()
            {
                EventName = "WARNING:ParticipantId Not sequential", DataKey = "DETAIL", DataValue = "There is a file tha tracks participant Id and gets incremented for each player.  something whent wrong so the Participant Id was set to (Minute Of Day /2) to ensure uniqueness"
            });
            //something is brokej but we dont want to crash the game just because we cannot get the id
            //so create one based on the time of day and and offset that will ensure no overlap occurs.
            //there are 3 digits in the id so start with 500 to isolate the Exception Id's in the second bolock of 499 ids
        }
        finally
        {
            participantId.text = (++megaMind.GameProgress.ParticipantId).ToString().PadLeft(3, '0');
            //write out the new Participant Id to file
            using (var fi = System.IO.File.CreateText(ParticipantIdFileName))
            {
                fi.WriteLine("{0}:{1}", PARTICIPANT_ID_KEY, participantId.text);
                fi.Flush();
                fi.Close();
            }
        }
        return(megaMind.GameProgress.ParticipantId);
    }
Esempio n. 44
0
        public string[] CreateOutput()
        {
            string outputPathHSBC = System.IO.Path.Combine(m_FileOutputFolder, "APSMPFI." + m_VendorCode + "." + m_SubmissionCutOffDateTime.ToString("yyyyMMdd") + ".M60");
            string outputPathHASE = System.IO.Path.Combine(m_FileOutputFolder, "APSMPFI." + m_VendorCode + "." + m_SubmissionCutOffDateTime.ToString("yyyyMMdd") + ".E60");

            HSBCFileExchangeProcess HSBCAutoPayFileExchange = new HSBCFileExchangeProcess();

            HSBCAutoPayFileExchange.FileID      = HSBCFileIDEnum.AISTN;
            HSBCAutoPayFileExchange.Environment = Environment;
            HSBCAutoPayFileExchange.CreateWriter(outputPathHSBC);

            HSBCFileExchangeProcess HangSengAutoPayFileExchange = new HSBCFileExchangeProcess();

            HangSengAutoPayFileExchange.FileID      = HSBCFileIDEnum.AISTN;
            HangSengAutoPayFileExchange.Environment = Environment;
            HangSengAutoPayFileExchange.CreateWriter(outputPathHASE);

            DBFilter filter = new DBFilter();

            filter.add(new NullTerm("CompanyAutopayFileConsolidateDateTime"));
            filter.add(new Match("CompanyAutopayFileConfirmDateTime", "<=", m_SubmissionCutOffDateTime));

            ArrayList list = ECompanyAutopayFile.db.select(m_dbConn, filter);

            foreach (ECompanyAutopayFile autoPayFile in list)
            {
                string transactionRefreence = "HREXA" + autoPayFile.CompanyAutopayFileID.ToString("0000000000");
                transactionRefreence += CheckDigit(transactionRefreence);

                HSBCFileExchangeProcess currentFileProcess = null;
                if (autoPayFile.CompanyAutopayFileBankCode.Equals("004"))
                {
                    currentFileProcess = HSBCAutoPayFileExchange;
                }
                else if (autoPayFile.CompanyAutopayFileBankCode.Equals("024"))
                {
                    currentFileProcess = HangSengAutoPayFileExchange;
                }

                EHSBCExchangeProfile exchangeProfile = new EHSBCExchangeProfile();
                exchangeProfile.HSBCExchangeProfileID = autoPayFile.HSBCExchangeProfileID;
                EHSBCExchangeProfile.db.select(m_dbConn, exchangeProfile);
                string[] submissionHeader = new string[6];
                submissionHeader[0] = "S";
                submissionHeader[1] = exchangeProfile.HSBCExchangeProfileRemoteProfileID.PadRight(18).Substring(0, 18);
                submissionHeader[2] = string.Empty.PadRight(28);
                submissionHeader[3] = transactionRefreence.PadRight(16).Substring(0, 16);
                submissionHeader[4] = "   ";
                submissionHeader[5] = autoPayFile.CompanyAutopayFileConfirmDateTime.ToString("yyyyMMddHHmmss");

                string strSubmissionHeader = string.Join(string.Empty, submissionHeader);
                if (strSubmissionHeader.Length != currentFileProcess.RecordLength)
                {
                    throw new Exception("Invalid submission header length");
                }

                currentFileProcess.AddLine(strSubmissionHeader);

                string   currentBankFilePath = System.IO.Path.Combine(m_DefaultBankFilePath, autoPayFile.CompanyAutopayFileDataFileRelativePath);
                FileInfo fileInfo            = new System.IO.FileInfo(currentBankFilePath);

                StreamReader bankFileStream = fileInfo.OpenText();
                char[]       charRead       = new char[80];

                try
                {
                    while (bankFileStream.Read(charRead, 0, 80) > 0)
                    {
                        string line = new string(charRead);
                        currentFileProcess.AddLine(line);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    bankFileStream.Close();
                }
                if (Environment == HSBCEnvironmentIndicatorEnum.Production)
                {
                    autoPayFile.CompanyAutopayFileConsolidateDateTime  = AppUtils.ServerDateTime();
                    autoPayFile.CompanyAutopayFileTransactionReference = transactionRefreence;
                    ECompanyAutopayFile.db.update(m_dbConn, autoPayFile);
                }
            }
            HSBCAutoPayFileExchange.Close();
            HangSengAutoPayFileExchange.Close();
            return(new string[] { outputPathHSBC, outputPathHASE });
        }
Esempio n. 45
0
        public bool ParseConnectDataInfo()
        {
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("./Data");
            if (!di.Exists)
            {
                di.Create();
            }

            System.IO.FileInfo fi = new System.IO.FileInfo("./Data/ConnectData.txt");
            if (!fi.Exists)
            {
                fi.Create().Close();

                using (StreamWriter wr = new StreamWriter("./Data/ConnectData.txt"))
                {
                    wr.WriteLine("# 클라이언트에 필요한 연결 정보입니다.");
                    wr.WriteLine("# Tag 종류");
                    wr.WriteLine("# '#' 주석");
                    wr.WriteLine("# 'IP' ip 주소");
                    wr.WriteLine("# 'PORT' port 주소");
                    wr.WriteLine("# 입력 방식은 'Tag 입력' 입니다.");
                    wr.WriteLine("");
                    wr.WriteLine("# Connect 정보");
                    wr.WriteLine("");
                    wr.WriteLine("IP 127.0.0.1");
                    wr.WriteLine("");
                    wr.WriteLine("PORT 9199");
                }
            }

            bool IsParsingIP   = false;
            bool IsParsingPort = false;

            using (StreamReader stream = fi.OpenText())
            {
                string line;
                while ((line = stream.ReadLine()) != null)
                {
                    string tag  = null;
                    string data = null;

                    int index = line.IndexOf(' ');
                    if (index > 0)
                    {
                        tag  = line.Substring(0, index);
                        data = line.Substring(index + 1);
                    }
                    else
                    {
                        continue;
                    }

                    switch (tag)
                    {
                    case "#":
                        continue;
                        break;

                    case "IP":
                        IsParsingIP  = true;
                        strIpAddress = data;
                        break;

                    case "PORT":
                        IsParsingPort  = true;
                        strPortAddress = data;
                        break;

                    default:
                        continue;
                    }
                }
            }



            if (!IsParsingIP)
            {
                MessageBox.Show($"{fi.DirectoryName} 파일에서 IP 주소 정보를 읽어올 수 없습니다.");
                return(false);
            }
            if (!IsParsingPort)
            {
                MessageBox.Show($"{fi.DirectoryName} 파일에서 PORT 주소 정보를 읽어올 수 없습니다.");
                return(false);
            }

            return(true);
        }
Esempio n. 46
0
        public string[] CreateOutput()
        {
            string outputPathAMPFF_HSBC = System.IO.Path.Combine(m_FileOutputFolder, "APSMPFI." + m_VendorCode + "." + m_SubmissionCutOffDateTime.ToString("yyyyMMdd") + ".M50");
            string outputPathAMPFF_HASE = System.IO.Path.Combine(m_FileOutputFolder, "APSMPFI." + m_VendorCode + "." + m_SubmissionCutOffDateTime.ToString("yyyyMMdd") + ".E50");

            string outputPathAMCND_HSBC = System.IO.Path.Combine(m_FileOutputFolder, "APSMPFI." + m_VendorCode + "." + m_SubmissionCutOffDateTime.ToString("yyyyMMdd") + ".M23");
            string outputPathAMCND_HASE = System.IO.Path.Combine(m_FileOutputFolder, "APSMPFI." + m_VendorCode + "." + m_SubmissionCutOffDateTime.ToString("yyyyMMdd") + ".E23");


            HSBCFileExchangeProcess HSBCAMPFFFileExchange = new HSBCFileExchangeProcess();

            HSBCAMPFFFileExchange.FileID      = HSBCFileIDEnum.AMPFF;
            HSBCAMPFFFileExchange.Environment = Environment;
            HSBCAMPFFFileExchange.CreateWriter(outputPathAMPFF_HSBC);

            HSBCFileExchangeProcess HangSengAMPFFFileExchange = new HSBCFileExchangeProcess();

            HangSengAMPFFFileExchange.FileID      = HSBCFileIDEnum.AMPFF;
            HangSengAMPFFFileExchange.Environment = Environment;
            HangSengAMPFFFileExchange.CreateWriter(outputPathAMPFF_HASE);

            HSBCFileExchangeProcess HSBCAMCNDFileExchange = new HSBCFileExchangeProcess();

            HSBCAMCNDFileExchange.FileID      = HSBCFileIDEnum.AMCND;
            HSBCAMCNDFileExchange.Environment = Environment;
            HSBCAMCNDFileExchange.CreateWriter(outputPathAMCND_HSBC);

            HSBCFileExchangeProcess HangSengAMCNDFileExchange = new HSBCFileExchangeProcess();

            HangSengAMCNDFileExchange.FileID      = HSBCFileIDEnum.AMCND;
            HangSengAMCNDFileExchange.Environment = Environment;
            HangSengAMCNDFileExchange.CreateWriter(outputPathAMCND_HASE);

            DBFilter filter = new DBFilter();

            filter.add(new NullTerm("CompanyMPFFileConsolidateDateTime"));
            filter.add(new Match("CompanyMPFFileConfirmDateTime", "<=", m_SubmissionCutOffDateTime));

            ArrayList list = ECompanyMPFFile.db.select(m_dbConn, filter);

            foreach (ECompanyMPFFile mpfFile in list)
            {
                string transactionRefreence = "HREXM" + mpfFile.CompanyMPFFileID.ToString("0000000000");
                transactionRefreence += CheckDigit(transactionRefreence);

                HSBCFileExchangeProcess currentFileProcess = null;

                if (mpfFile.CompanyMPFFileFileType.Equals("AMPFF"))
                {
                    if (mpfFile.CompanyMPFFileTrusteeCode.Equals("HSBC"))
                    {
                        currentFileProcess = HSBCAMPFFFileExchange;
                    }
                    else if (mpfFile.CompanyMPFFileTrusteeCode.Equals("HangSeng"))
                    {
                        currentFileProcess = HangSengAMPFFFileExchange;
                    }

                    EHSBCExchangeProfile exchangeProfile = new EHSBCExchangeProfile();
                    exchangeProfile.HSBCExchangeProfileID = mpfFile.HSBCExchangeProfileID;
                    EHSBCExchangeProfile.db.select(m_dbConn, exchangeProfile);
                    string[] submissionHeader = new string[6];
                    submissionHeader[0] = "S";
                    submissionHeader[1] = exchangeProfile.HSBCExchangeProfileRemoteProfileID.PadRight(18).Substring(0, 18);
                    submissionHeader[2] = string.Empty.PadRight(28);
                    submissionHeader[3] = transactionRefreence.PadRight(16).Substring(0, 16);
                    submissionHeader[4] = "   ";
                    submissionHeader[5] = mpfFile.CompanyMPFFileConfirmDateTime.ToString("yyyyMMddHHmmss");

                    string strSubmissionHeader = string.Join(string.Empty, submissionHeader);
                    if (strSubmissionHeader.Length != currentFileProcess.RecordLength)
                    {
                        throw new Exception("Invalid submission header length");
                    }

                    currentFileProcess.AddLine(strSubmissionHeader);


                    string   currentBankFilePath = System.IO.Path.Combine(m_DefaultBankFilePath, mpfFile.CompanyMPFFileDataFileRelativePath);
                    FileInfo fileInfo            = new System.IO.FileInfo(currentBankFilePath);

                    StreamReader bankFileStream = fileInfo.OpenText();
                    char[]       charRead       = new char[80];

                    try
                    {
                        while (bankFileStream.Read(charRead, 0, 80) > 0)
                        {
                            string line = new string(charRead);
                            currentFileProcess.AddLine(line);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        bankFileStream.Close();
                    }
                }
                else if (mpfFile.CompanyMPFFileFileType.Equals("AMCND"))
                {
                    if (mpfFile.CompanyMPFFileTrusteeCode.Equals("HSBC"))
                    {
                        currentFileProcess = HSBCAMCNDFileExchange;
                    }
                    else if (mpfFile.CompanyMPFFileTrusteeCode.Equals("HangSeng"))
                    {
                        currentFileProcess = HangSengAMCNDFileExchange;
                    }

                    ECompanyDatabase companyDB = new ECompanyDatabase();
                    companyDB.CompanyDBID = mpfFile.CompanyDBID;
                    ECompanyDatabase.db.select(m_dbConn, companyDB);
                    //string[] submissionHeader = new string[7];
                    //submissionHeader[0] = "S";
                    //submissionHeader[1] = companyDB.CompanyDBClientCode.PadRight(18).Substring(0, 18);
                    //submissionHeader[2] = string.Empty.PadRight(28);
                    //submissionHeader[3] = transactionRefreence.PadRight(16).Substring(0, 16);
                    //submissionHeader[4] = "   ";
                    //submissionHeader[5] = mpfFile.CompanyMPFFileConfirmDateTime.ToString("yyyyMMddHHmmss");
                    //submissionHeader[6] = string.Empty.PadRight(1420);

                    //string strSubmissionHeader = string.Join(string.Empty, submissionHeader);
                    //if (strSubmissionHeader.Length != currentFileProcess.RecordLength)
                    //    throw new Exception("Invalid submission header length");

                    //currentFileProcess.AddLine(strSubmissionHeader);


                    string   currentBankFilePath = System.IO.Path.Combine(m_DefaultBankFilePath, mpfFile.CompanyMPFFileDataFileRelativePath);
                    FileInfo fileInfo            = new System.IO.FileInfo(currentBankFilePath);

                    StreamReader bankFileStream = fileInfo.OpenText();

                    try
                    {
                        while (!bankFileStream.EndOfStream)
                        {
                            string line = bankFileStream.ReadLine();
                            if (!line.StartsWith("HEADER "))
                            {
                                currentFileProcess.AddLine(line.PadRight(currentFileProcess.RecordLength));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        bankFileStream.Close();
                    }
                }
                if (Environment == HSBCEnvironmentIndicatorEnum.Production)
                {
                    mpfFile.CompanyMPFFileConsolidateDateTime  = AppUtils.ServerDateTime();
                    mpfFile.CompanyMPFFileTransactionReference = transactionRefreence;
                    ECompanyMPFFile.db.update(m_dbConn, mpfFile);
                }
            }
            HSBCAMPFFFileExchange.Close();
            HangSengAMPFFFileExchange.Close();
            HSBCAMCNDFileExchange.Close();
            HangSengAMCNDFileExchange.Close();


            return(new string[] { outputPathAMPFF_HSBC, outputPathAMPFF_HASE, outputPathAMCND_HSBC, outputPathAMCND_HASE });
        }