public static void ConfigurePlan(TextFile textFile, TemplatePlan plan)
 {
     textFile.ReadLines().Each(line => {
         var parts = line.ToDelimitedArray();
         plan.Add(new GemReference(parts.First(), parts.Last()));
     });
 }
Beispiel #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Expires = -1;
            try
            {
                HttpPostedFile postedFile = Request.Files["uploaded"];
                string contentType = postedFile.ContentType;
                if (contentType.StartsWith("application/octet-stream") && postedFile.FileName.EndsWith(".zip") ||
                    contentType.StartsWith("application/x-zip-compressed") ||
                    contentType.StartsWith("application/zip") ||
                    contentType.StartsWith("multipart/x-zip"))
                {
                    using (var context = new StorageEntities())
                    {
                        using (ZipFile zipFile = ZipFile.Read(postedFile.InputStream))
                        {
                            foreach (ZipEntry zipEntry in zipFile.Entries.Where(ze => !ze.IsDirectory))
                            {
                                using (MemoryStream memoryStream = new MemoryStream())
                                {
                                    zipEntry.Extract(memoryStream);

                                    // return the reader to the beginning,
                                    // otherwise no data will be read
                                    memoryStream.Position = 0;

                                    using (StreamReader reader = new StreamReader(memoryStream))
                                    {
                                        string entryContents = reader.ReadToEnd();

                                        var textFile = new TextFile
                                        {
                                            Name = zipEntry.FileName,
                                            Contents = entryContents
                                        };

                                        context.TextFiles.Add(textFile);
                                    }
                                }
                            }
                        }

                        context.SaveChanges();
                    }
                }
                else
                {
                    throw new InvalidOperationException("This file type is not supported.");
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
Beispiel #3
0
 /// <summary>
 /// Decorates the specified code.
 /// </summary>
 /// <param name="code">The code.</param>
 /// <param name="options">The options.</param>
 public void Decorate(ExtendedCodeDomTree code, CustomCodeGenerationOptions options)
 {
     if (options.GenerateService && options.GenerateSvcFile)
     {
         foreach (CodeTypeExtension type in code.ServiceTypes)
         {
             string fqTypeName = GetFullyQulifiedTypeName(options, type.ExtendedObject.Name);
             string content = string.Format("<%@ ServiceHost Service=\"{0}\" %>", fqTypeName);
             string filename = string.Format("{0}.svc", type.ExtendedObject.Name);
             TextFile svcFile = new TextFile(filename, content);
             code.TextFiles.Add(svcFile);
         }
     }
 }
		public IEditableTextFile GetFile (FilePath name)
		{
			if (files != null) {
				IEditableTextFile ef = files.GetEditableTextFile (name);
				if (ef != null) return ef;
			}
			foreach (IEditableTextFile f in textFiles)
				if (f.Name == name)
					return f;
					
			TextFile file = new TextFile (name);
			textFiles.Add (file);
			return file;
		}
Beispiel #5
0
        private void txtMessages_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                int i = txtMessages.Text.Substring(0, txtMessages.SelectionStart + 1).LastIndexOf("\r\n");
                i = i == -1 ? 0 : i + 2;
                int j = txtMessages.Text.Substring(i).IndexOf("\r\n");
                j = j == -1 ? txtMessages.Text.Length - i : j;
                string linha = txtMessages.Text.Substring(i, j);

                Match match = Regex.Match(linha, @"([A-Za-z]:\\|\\\\)([\w\s.-\[\]{}();~^`´¨,!@#$%&=+°'§¬¢-]+\\)*[\w\s.-\[\]{}();~^`´¨,!@#$%&=+°'§¬¢-]*\s*");

                if (match.Success)
                {
                    TextFile.Open(match.Value);
                }
            }
            catch (Exception ex)
            {
                MyMessage.ShowError(ex.Message);
            }
        }
Beispiel #6
0
        public override string GetTextAtRevision(string repositoryPath, Revision revision, string rootPath)
        {
            var          ms = new MemoryStream();
            SvnUriTarget target;

            lock (client)
                target = client.GetUriFromWorkingCopy(rootPath);
            // Redo path link.
            repositoryPath = repositoryPath.TrimStart(new [] { '/' });
            foreach (var segment in target.Uri.Segments)
            {
                if (repositoryPath.StartsWith(segment, StringComparison.Ordinal))
                {
                    repositoryPath = repositoryPath.Remove(0, segment.Length);
                }
            }

            lock (client) {
                // repositoryPath already contains the relative URL path.
                try {
                    client.Write(new SvnUriTarget(target.Uri.AbsoluteUri + repositoryPath, GetRevision(revision)), ms);
                } catch (SvnFileSystemException e) {
                    // File got added/deleted at some point.
                    if (e.SvnErrorCode == SvnErrorCode.SVN_ERR_FS_NOT_FOUND)
                    {
                        return("");
                    }
                    throw;
                } catch (SvnClientNodeKindException e) {
                    // We're trying on a directory.
                    if (e.SvnErrorCode == SvnErrorCode.SVN_ERR_CLIENT_IS_DIRECTORY)
                    {
                        return("");
                    }
                    throw;
                }
            }
            return(TextFile.ReadFile(repositoryPath, ms).Text);
        }
Beispiel #7
0
        private static Packet DemoAnimation()
        {
            var text = new TextFile('A') {
                new TextFileLine("<speed 5 /><picture 1/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 2/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 3/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 4/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 5/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 6/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 6/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 5/> <picture 3/> <picture 1/> <picture 2/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 4/> <picture 2/> <picture 1/> <picture 3/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 3/> <picture 1/> <picture 2/> <picture 4/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 2/> <picture 1/> <picture 3/> <picture 5/>", DisplayMode.Hold),
                new TextFileLine("<speed 5 /><picture 1/> <picture 2/> <picture 4/> <picture 6/>", DisplayMode.Hold),
            };

            var pic1 = new PictureFile('1', "kirby/frame1.png", ColorFormat.Monochrome);
            var pic2 = new PictureFile('2', "kirby/frame2.png", ColorFormat.Monochrome);
            var pic3 = new PictureFile('3', "kirby/frame3.png", ColorFormat.Monochrome);
            var pic4 = new PictureFile('4', "kirby/frame4.png", ColorFormat.Monochrome);
            var pic5 = new PictureFile('5', "kirby/frame5.png", ColorFormat.Monochrome);
            var pic6 = new PictureFile('6', "kirby/frame6.png", ColorFormat.Monochrome);

            var packet = new Packet();
            packet.SetMemory(new FileTable {
                text,
                pic1, pic2, pic3, pic4, pic5, pic6
            });
            packet.Add(new WriteTextCommand(text));
            packet.Add(new WritePictureCommand(pic1));
            packet.Add(new WritePictureCommand(pic2));
            packet.Add(new WritePictureCommand(pic3));
            packet.Add(new WritePictureCommand(pic4));
            packet.Add(new WritePictureCommand(pic5));
            packet.Add(new WritePictureCommand(pic6));

            return packet;
        }
Beispiel #8
0
        /// <summary>
        /// Create sorted file from unsorted file
        /// </summary>
        /// <param name="textFile">unsorted file</param>
        /// <returns>sorted file</returns>
        public TextFile CreateSortedTextFile(TextFile textFile)
        {
            if (textFile.DataRows == null)
            {
                return(textFile);
            }
            var nameList = _nameService.CreateNameList(textFile.DataRows);

            nameList = _nameService.SortedNameList(nameList);
            var dataRows = new List <string>();

            foreach (var name in nameList)
            {
                dataRows.Add(name.GetLastNameFirstName());
            }

            return(new TextFile {
                FileName = textFile.FileName + "-sorted",
                FilePath = textFile.FilePath,
                DataRows = dataRows
            });
        }
Beispiel #9
0
 public override TextFile.Token[] MagicPowers(TextFile.Formatting format)
 {   // %mpw
     if (parent.IsArtifact)
     {
         // Use appropriate artifact description message. (8700-8721)
         try {
             ArtifactsSubTypes artifactType = ItemHelper.GetArtifactSubType(parent.shortName);
             return(DaggerfallUnity.Instance.TextProvider.GetRSCTokens(8700 + (int)artifactType));
         } catch (KeyNotFoundException e) {
             Debug.Log(e.Message);
             return(null);
         }
     }
     else if (!parent.IsIdentified)
     {
         // Powers unknown.
         TextFile.Token nopowersToken = TextFile.CreateTextToken(HardStrings.powersUnknown);
         return(new TextFile.Token[] { nopowersToken });
     }
     else
     {
         // List item powers.
         // TODO: Update once magic effects have been implemented. (just puts "Power number N" for now)
         // Pretty sure low numbers are type of application, and higher ones are effects.
         // e.g. shield of fortitude is [1, 87] which maps to "Cast when held: Fortitude" in classic.
         List <TextFile.Token> magicPowersTokens = new List <TextFile.Token>();
         for (int i = 0; i < parent.legacyMagic.Length; i++)
         {
             if (parent.legacyMagic[i] == 0xffff)
             {
                 break;
             }
             magicPowersTokens.Add(TextFile.CreateTextToken("Power number " + parent.legacyMagic[i]));
             magicPowersTokens.Add(TextFile.CreateFormatToken(format));
         }
         return(magicPowersTokens.ToArray());
     }
 }
        private static Writer.Data.TextFile CreateWriterFileFromTextfile(TextFile file)
        {
            var writerFileFromThis = new Writer.Data.TextFile
            {
                Colors                = file.Colors,
                Tags                  = file.Tags,
                CaretOffset           = file.CaretOffset,
                CharacterNames        = file.CharacterNames,
                Characters            = CopyCharacter(file.Characters),
                ClosingQuote          = file.ClosingQuote,
                Document              = file.Document,
                Filepath              = file.Filepath,
                IncFontWhenPrinting   = file.IncFontWhenPrinting,
                IsChangeString        = file.IsChangeString,
                IsExtended            = file.IsExtended,
                OpeningQuote          = file.OpeningQuote,
                PageCountElement      = CopyPageCountElement(file.PageCountElement),
                Password              = file.Password,
                PasswordQuestion      = file.PasswordQuestion,
                PrintBackground       = file.PrintBackground,
                PrintBackgroundString = file.PrintBackgroundString,
                QuotationButtonState  = file.QuotationButtonState,
                ReadOnly              = file.ReadOnly,
                ScrollOffset          = file.ScrollOffset,
                ShowPageNumber        = file.ShowPageNumber,
                SingleClosingQuote    = file.SingleClosingQuote,
                SingleOpeningQuote    = file.SingleOpeningQuote,
                SpellCheckEnabled     = file.SpellCheckEnabled, Styles = CopyStyles(file.Styles),
                UseBlackAndWhite      = file.UseBlackAndWhite,
                UseCharacters         = file.UseCharacters,
                UseOldNumbering       = file.UseOldNumbering,
                UseWatermark          = file.UseWatermark,
                Watermark             = CopyWatermark(file.Watermark)
            };


            return(writerFileFromThis);
        }
Beispiel #11
0
        public static TimeSeriesDatabaseDataSet.RatingTableDataTable GetRatingTable(string cbtt, string pcode, string ratingName)
        {
            string url = "";


            if (HydrometInfoUtility.HydrometServerFromPreferences() == HydrometHost.GreatPlains)
            {
                url = "https://www.usbr.gov/gp-bin/expandrtf.pl?site=pali&pcode=q&form=col";
                url = url.Replace("site=pali", "site=" + cbtt.Trim());
                url = url.Replace("pcode=q", "pcode=" + pcode.Trim());
            }
            else if (HydrometInfoUtility.HydrometServerFromPreferences() == HydrometHost.PN)
            {
                url = "http://lrgs1.pn.usbr.gov/rating_tables/" + ratingName + ".csv";
                if (!NetworkUtility.Intranet)
                {
                    url = "https://www.usbr.gov/pn/hydromet/configurationdata/rating_tables/" + ratingName + ".csv";
                }

                var tmp = FileUtility.GetTempFileName(".csv");
                Web.GetFile(url, tmp);

                var rt = new TimeSeriesDatabaseDataSet.RatingTableDataTable();
                rt.ReadFile(tmp);
                return(rt);
            }
            else if (HydrometInfoUtility.HydrometServerFromPreferences() == HydrometHost.Yakima)
            {            // yakima ?
                url = "https://www.usbr.gov/pn-bin/yak/expandrtf.pl?site=kee&pcode=af&form=col";
                url = url.Replace("site=kee", "site=" + cbtt.Trim());
                url = url.Replace("pcode=af", "pcode=" + pcode.Trim());
            }

            string[] data = Web.GetPage(url);
            TextFile tf   = new TextFile(data);

            return(ParseRatingTableData(tf, cbtt, pcode));
        }
Beispiel #12
0
        internal static bool ReadConfigFile()
        {
            string[] dati = null;
            try
            {
#if DEBUG
                dati = TextFile.FileToArray(Commons.PathAndFileConfig + "_DEBUG");
#else
                dati = TextFile.FileToArray(Commons.PathAndFileConfig);
#endif
                if (dati != null)
                {
                    Commons.FileDatabase        = dati[0];
                    Commons.PathImages          = dati[1];
                    Commons.PathStartLinks      = dati[2]; // not longer used; left for compatibility of configuration file
                    Commons.PathDatabase        = dati[3];
                    Commons.PathAndFileDatabase = Commons.PathDatabase + "\\" + Commons.FileDatabase;
                    Commons.PathDocuments       = dati[4];
                    // we try the next to avoid stopping the program whem we have a new config file,
                    // with another field will show up. You have to add some data in.config file.
                    try
                    {
                        Commons.SaveBackupWhenExiting = bool.Parse(dati[5]);
                        return(true);
                    }
                    catch
                    {
                        return(false);
                    }
                }
            }
            catch
            {
                // if error do nothing. the rest of the code will generate the default data
                return(false);
            }
            return(false);
        }
Beispiel #13
0
        public void Match_Comments_CorrectMatchingPosition()
        {
            TextFile source = new TextFile(
                "<?php\n" +
                "#password=secret\n" +
                "/*password=secret*/\n" +
                "/*\n" +
                "\n" +
                "    password\n" +
                "              =secret\n" +
                "*/" +
                "?>",
                "code.php");
            var pattern = "Comment: <[ \"(?i)(password|pwd)\\s*(\\=|is|\\:)\" ]>";

            MatchResultDto[] matchResults = PatternMatchingUtils.GetMatches(source, pattern, Language.Php);

            LineColumnTextSpan textSpan0 = matchResults[0].LineColumnTextSpan;

            Assert.AreEqual(2, textSpan0.BeginLine);
            Assert.AreEqual(2, textSpan0.BeginColumn);
            Assert.AreEqual(2, textSpan0.EndLine);
            Assert.AreEqual(11, textSpan0.EndColumn);

            LineColumnTextSpan textSpan1 = matchResults[1].LineColumnTextSpan;

            Assert.AreEqual(3, textSpan1.BeginLine);
            Assert.AreEqual(3, textSpan1.BeginColumn);
            Assert.AreEqual(3, textSpan1.EndLine);
            Assert.AreEqual(12, textSpan1.EndColumn);

            LineColumnTextSpan textSpan2 = matchResults[2].LineColumnTextSpan;

            Assert.AreEqual(6, textSpan2.BeginLine);
            Assert.AreEqual(5, textSpan2.BeginColumn);
            Assert.AreEqual(7, textSpan2.EndLine);
            Assert.AreEqual(16, textSpan2.EndColumn);
        }
Beispiel #14
0
        /// <summary>
        /// Parsing IPL files<para/>
        /// Разбор файлов IPL
        /// </summary>
        public static void ReadPlacements()
        {
            List <ItemPlacement> pl = new List <ItemPlacement>();

            foreach (string IPL in FileManager.PlacementFiles)
            {
                TextFile f = new TextFile(PathManager.GetAbsolute(IPL), true, true);
                foreach (TextFile.Line p in f.Lines)
                {
                    switch (p.Section.ToLower())
                    {
                    // Object installation
                    // Расстановка объектов
                    case "inst":
                        ItemPlacement g = new ItemPlacement()
                        {
                            ID         = p.Text[0].ToInt(),
                            ModelName  = p.Text[1],
                            InteriorID = ItemPlacement.Interior.World,
                            Position   = new Vector3(p.Text[p.Text.Length - 10].ToFloat(), p.Text[p.Text.Length - 8].ToFloat(), p.Text[p.Text.Length - 9].ToFloat()),
                            Scale      = new Vector3(p.Text[p.Text.Length - 7].ToFloat(), p.Text[p.Text.Length - 5].ToFloat(), p.Text[p.Text.Length - 6].ToFloat()),
                            Angle      = new Quaternion(-p.Text[p.Text.Length - 4].ToFloat(), -p.Text[p.Text.Length - 2].ToFloat(), -p.Text[p.Text.Length - 3].ToFloat(), -p.Text[p.Text.Length - 1].ToFloat()),
                        };
                        if (p.Text.Length > 12)
                        {
                            g.InteriorID = (ItemPlacement.Interior)p.Text[2].ToInt();
                        }
                        pl.Add(g);
                        break;
                    }
                    // Operation is threadable, so sleep for a while
                    // Операция потоковая, поэтому отдадим времени основному процессу
                    System.Threading.Thread.Sleep(0);
                }
            }
            Placements = pl.ToArray();
            Dev.Console.Log("[ObjectManager] Parsed " + FileManager.PlacementFiles.Length + " placement files (" + pl.Count + " entries)");
        }
        private string createTXTFile(Mail email)
        {
            file = new TextFile();
            int    index        = 0;
            string fechaForName = email.form.txtFecha;

            while (fechaForName.IndexOf('-') != -1)
            {
                index        = fechaForName.IndexOf('-');
                fechaForName = fechaForName.Remove(index, 1);
            }
            while (fechaForName.IndexOf(':') != -1)
            {
                index        = fechaForName.IndexOf(':');
                fechaForName = fechaForName.Remove(index, 1);
            }
            file.fileName = ("WebformsLog_" + fechaForName + email.sender.CSRCode).Trim();
            file.ext      = ".txt";
            file.path     = System.IO.Path.GetDirectoryName(string.Format("~/App_Data"));
            file.Write(email);

            return((file.fileName + file.ext).Trim());
        }
Beispiel #16
0
        public static void Test()
        {
            AbstractFile file1, file2, file3, file4, folder1, folder2, folder3;

            file1 = new ImageFile("图片1.gif");
            file2 = new ImageFile("图片2.png");
            file3 = new TextFile("文本1.txt");
            file4 = new TextFile("文本2.docx");

            folder1 = new Folder("图");
            folder1.add(file1);
            folder1.add(file2);

            folder2 = new Folder("文本");
            folder2.add(file3);
            folder2.add(file4);

            folder3 = new Folder("root");
            folder3.add(folder1);
            folder3.add(folder2);

            folder3.display();
        }
        public IEditableTextFile GetFile(FilePath name)
        {
            if (files != null)
            {
                IEditableTextFile ef = files.GetEditableTextFile(name);
                if (ef != null)
                {
                    return(ef);
                }
            }
            foreach (IEditableTextFile f in textFiles)
            {
                if (f.Name == name)
                {
                    return(f);
                }
            }

            TextFile file = new TextFile(name);

            textFiles.Add(file);
            return(file);
        }
        protected override string PreprocessText(TextFile file)
        {
            string data = file.Data;
            string shortenedData;

            if (data.Length > MaxCharsCount)
            {
                // Remove trailing not spaces
                int lastInd = MaxCharsCount - 1;
                while (lastInd > 0 && !char.IsWhiteSpace(data[lastInd]))
                {
                    lastInd--;
                }

                shortenedData = data.Remove(lastInd + 1);
            }
            else
            {
                shortenedData = data;
            }

            return(base.PreprocessText(new TextFile(shortenedData)));
        }
Beispiel #19
0
        static void Main(string[] args)
        {
            long product1 = 0;
            long product2 = 0;

            List <int> numbers = null;

            Performance.TimeRun("Parse and solve", () =>
            {
                numbers = TextFile.ReadPositiveIntList("puzzle1.txt");

                int[] arr = null;
                arr       = numbers.ToArray();
                Array.Sort(arr);

                (int num1, int num2)           = FindPair(arr, 2020);
                product1                       = num1 * num2;
                (int num3, int num4, int num5) = FindTriplet(arr, 2020);
                product2                       = num3 * num4 * num5;
            });
            Console.WriteLine($"Answer 1: {product1}");
            Console.WriteLine($"Answer 2: {product2}");
        }
Beispiel #20
0
        private void btnAddData_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Title = "Select File Name";
            if (Param == null) Param = new FileParam("open filename");
            FileParam p = Param as FileParam;
            if (p != null) dialog.Filter = p.DialogFilter;

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                TextFile tmpTextFile = new TextFile(dialog.FileName);
                _addedTextFile = new DataSetArray(Path.GetFileNameWithoutExtension(dialog.FileName), tmpTextFile);

                Param.ModelName = _addedTextFile.Name;
                Param.Value = _addedTextFile.DataSet;
                Refresh();
                base.Status = ToolStatus.Ok;
            }
            else
            {
                return;
            }
        }
Beispiel #21
0
        public void IsExist_CorrectNameAndPathButFileDoesNotExist_ReturnFalse()
        {
            // Act
            var file = new TextFile()
            {
                Filename = "tets.txt",
                Path     = "Correct path"
            };

            var mockFileProvider = new Mock <IFileProvider>();
            var mockPathProvider = new Mock <IPathProvider>();

            mockPathProvider.Setup(f => f.Combine(It.IsAny <string>(), It.IsAny <string>())).Returns(It.IsAny <string>());
            mockFileProvider.Setup(f => f.Exist(It.IsAny <string>())).Returns(false);
            file.FileProvider = mockFileProvider.Object;
            file.PathProvider = mockPathProvider.Object;

            // Arrange
            var result = file.IsExist(file.Filename, file.Path);

            // Assert
            result.Should().BeFalse();
        }
        /// <summary>
        /// Runs multiple Archive commands in a single batch
        /// </summary>
        /// <param name="user"></param>
        /// <param name="password"></param>
        /// <param name="commands"></param>
        /// <returns></returns>
        public static string RunArchiveCommands(string user, string password, string[] commands)
        {
            //interpret/nodebug acm 2010Jun14 mck fb
            string rval = "";

            var      tmpFile = FileUtility.GetTempFileName(".txt");
            TextFile tf      = new TextFile(tmpFile);

            AddVmsScriptHeader(user, tf);
            foreach (var item in commands)
            {
                tf.Add(item);
                rval += "\n" + item;
            }

            tf.SaveAsVms(tf.FileName);
            string t              = DateTime.Now.ToString(timeFormat).ToLower();
            string remoteFile     = "huser1:[edits]run_archiver_" + user + t + ".com";
            string unixRemoteFile = VmsToUnixPath(remoteFile);

            rval += "\n" + SendFileAndRunCommand(user, password, tmpFile, unixRemoteFile, "@" + remoteFile);
            return(rval);
        }
        public static TextFile CompressTextFile(string text)
        {
            byte[] originalData     = Encoding.UTF8.GetBytes(text);
            uint   originalDataSize = (uint)originalData.Length;

            byte[] compressedData = new byte[originalDataSize * (101 / 100) + 384];

            var _compressedData = Compress(originalData, compressedData, originalDataSize);

            byte[] originalDataSizeByte   = BitConverter.GetBytes(originalDataSize);
            byte[] compressedDataSizeByte = BitConverter.GetBytes(_compressedData.Count);

            List <byte> listOfBytes = new List <byte>(originalDataSizeByte);

            listOfBytes.AddRange(compressedDataSizeByte);
            listOfBytes.AddRange(_compressedData);

            byte[] newCompressedData = listOfBytes.ToArray();

            TextFile compressedFile = new TextFile(newCompressedData, _compressedData.Count);

            return(compressedFile);
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            Editor editor = new Editor(args);

            editor.ObtainFileName += (s, e) =>
            {
                Console.Write(editor.lbl_File);
                e.FileName = Console.ReadLine();
            };

            editor.ReceiveInput += (s, e) =>
            {
                if (e.Message != string.Empty)
                {
                    Console.WriteLine(e.Message);
                }

                e.InputValue = Console.ReadLine();
            };

            editor.Output += (s, e) => Console.WriteLine(e.Message);

            TextFile textFile = editor.Enter();

            if (textFile != null)
            {
                bool exit = false;

                while (!exit)
                {
                    Console.Write(editor.Lbl_Prompt);
                    string command = Console.ReadLine();

                    exit = editor.Command(command);
                }
            }
        }
Beispiel #25
0
        public static void Apply(FileSource menuSource, State settings)
        {
            // pull the relevant file out of the archive
            var file      = menuSource.GetFile(ArchivePath);
            var mes3bytes = file.Skip(FileOffset).Take(FileLength);
            var mes3      = TextFile.FromBytes(mes3bytes, true);

            // set names
            mes3.Pages[NamesPage].Strings[Squall]    = settings.NameSquall;
            mes3.Pages[NamesPage].Strings[Rinoa]     = settings.NameRinoa;
            mes3.Pages[NamesPage].Strings[Angelo]    = settings.NameAngelo;
            mes3.Pages[NamesPage].Strings[Quezacotl] = settings.NameQuezacotl;
            mes3.Pages[NamesPage].Strings[Shiva]     = settings.NameShiva;
            mes3.Pages[NamesPage].Strings[Ifrit]     = settings.NameIfrit;
            mes3.Pages[NamesPage].Strings[Siren]     = settings.NameSiren;
            mes3.Pages[NamesPage].Strings[Brothers]  = settings.NameBrothers;
            mes3.Pages[NamesPage].Strings[Diablos]   = settings.NameDiablos;
            mes3.Pages[NamesPage].Strings[Carbuncle] = settings.NameCarbuncle;
            mes3.Pages[NamesPage].Strings[Leviathan] = settings.NameLeviathan;
            mes3.Pages[NamesPage].Strings[Pandemona] = settings.NamePandemona;
            mes3.Pages[NamesPage].Strings[Cerberus]  = settings.NameCerberus;
            mes3.Pages[NamesPage].Strings[Alexander] = settings.NameAlexander;
            mes3.Pages[NamesPage].Strings[Doomtrain] = settings.NameDoomtrain;
            mes3.Pages[NamesPage].Strings[Bahamut]   = settings.NameBahamut;
            mes3.Pages[NamesPage].Strings[Cactuar]   = settings.NameCactuar;
            mes3.Pages[NamesPage].Strings[Tonberry]  = settings.NameTonberry;
            mes3.Pages[NamesPage].Strings[Eden]      = settings.NameEden;
            mes3.Pages[NamesPage].Strings[Boko]      = settings.NameBoko;
            mes3.Pages[NamesPage].Strings[Griever]   = settings.NameGriever;

            // apply changes
            var newFile = file.Take(FileOffset).ToList();

            newFile.AddRange(mes3.Encode());
            newFile.AddRange(file.Skip(FileOffset + FileLength));
            menuSource.ReplaceFile(ArchivePath, newFile);
        }
Beispiel #26
0
        public MainForm() : base("SummerGUI Demo", 800, 600)
        {
            this.Title = "SummerEdit - X-Platform Texteditor";

            this.TabMain.AdTabPage("texteditor", "Editor", Color.Empty, (char)FontAwesomeIcons.fa_edit);
            m_Editor = this.TabMain.TabPages["texteditor"].AddChild(new TextEditorEnsemble("editor1"));

            mnuNew        = this.MenuPanel.MainMenu.FindItem("New");
            mnuNew.Click += (object sender, EventArgs e) =>
            {
                m_Editor.Text = null;
            };

            mnuOpen        = this.MenuPanel.MainMenu.FindItem("Open");
            mnuOpen.Click += (object sender, EventArgs e) => {
                SummerGUI.SystemSpecific.Linux.SystemDialogs dlg = new SummerGUI.SystemSpecific.Linux.SystemDialogs();
                string fpath = dlg.OpenFileDialog("Open File", this);
                if (Strings.FileExists(fpath))
                {
                    ShowStatus(String.Format("Loading {0}..", Strings.GetFilename(fpath)), true);
                    System.Threading.Tasks.Task.Factory.StartNew(() => {
                        m_Editor.FilePath = fpath;
                        m_Editor.Text     = TextFile.LoadTextFile(fpath);
                    }).ContinueWith(t => ShowStatus());
                }
            };

            mnuSave        = this.MenuPanel.MainMenu.FindItem("Save");
            mnuSave.Click += (object sender, EventArgs e) =>
            {
                this.LogWarning("mnuSave not implemented.");
            };

            //this.LeftSideMenu.Style.BackColorBrush = new LinearGradientBrush (Theme.Colors.Base0, Theme.Colors.Base00);

            m_Editor.Focus();
        }
Beispiel #27
0
        private void buttonRunRawData_Click(object sender, EventArgs e)
        {
            if (!File.Exists(this.textBoxCbttFilename.Text))
            {
                MessageBox.Show("File does not exist");
                return;
            }

            TextFile tf = new TextFile(this.textBoxCbttFilename.Text);


            Login login = new Login();

            if (login.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            try
            {
                Cursor = Cursors.WaitCursor;
                string pc = Pcode;
                if (checkBoxAllPcodes.Checked)
                {
                    pc = "ALL";
                }

                string status = HydrometEditsVMS.RunArchiver(login.Username, login.Password, tf.FileData, pc, T1, T2, checkBoxPreview.Checked);
                FormStatus.ShowStatus(status);
                Logger.WriteLine("", "ui");
            }
            finally
            {
                Cursor = Cursors.Default;
                checkBoxAllPcodes.Checked = false;
            }
        }
Beispiel #28
0
        private void BuildTable(string filename, string forecastName)
        {
            Table = new DataTable();
            TextFile tf = new TextFile(filename);

            int idx = FindIndexToForecastName(forecastName, tf);

            if (idx >= 0)
            {
                idx++;
                int idx2 = tf.IndexOfRegex("^[a-zA-Z]", idx);

                if (idx2 > 0)
                {
                    CreateColumns(tf, idx);
                    while (idx < idx2)
                    {
                        var row = Table.NewRow();
                        Table.Rows.Add(row);

                        var tokens = TextFile.Split(tf[idx]);
                        for (int col = 0; col < tokens.Length; col++)
                        {
                            if (col == tokens.Length - 1)
                            {
                                row[0] = Convert.ToDouble(tokens[col]);
                            }
                            else
                            {
                                row[col + 1] = Convert.ToDouble(tokens[col]);
                            }
                        }
                        idx++;
                    }
                }
            }
        }
        public async Task TestAllLines()
        {
            var garcGameText = await ORASConfig.GameConfig.GetGarc(GarcNames.GameText);

            byte[] tf0Data = await garcGameText.GetFile(0);

            TextFile tf0 = await ORASConfig.GameConfig.GetTextFile(0);

            byte[][] encData = TextFileHelper.EncryptLines(tf0, tf0.Lines).Select(el => el.Item2).ToArray();
            byte[][] oriData = new byte[tf0.Lines.Count][];

            Assert.AreEqual(tf0.Lines.Count, encData.Length, "Number of data blobs returned does not equal number of lines");

            for (int l = 0; l < encData.Length; l++)
            {
                byte[]            testData = encData[l];
                TextFile.LineInfo lineInfo = tf0.LineInfos[l];
                oriData[l] = tf0Data.Skip((int)lineInfo.Offset + 0x10).Take(lineInfo.Length * 2).ToArray();

                if (testData.Length == oriData[l].Length + 2 &&
                    testData[testData.Length - 1] == 0 &&
                    testData[testData.Length - 2] == 0)
                {
                    testData = testData.Take(testData.Length - 2).ToArray();                       // don't compare the padding thing
                }
                Assert.AreEqual(oriData[l], testData, $"Blob for line {l} does not match original file");
            }

            string[] tfhText = TextFileHelper.DecryptLines(tf0, oriData);

            Assert.AreEqual(tf0.Lines.Count, tfhText.Length, "Number of strings returned does not equal number of lines");

            for (int l = 0; l < tfhText.Length; l++)
            {
                Assert.AreEqual(tf0.Lines[l], tfhText[l], $"Line {l} does not match original file");
            }
        }
        private void ToSingleFile(object sender, RoutedEventArgs e)
        {
            var dlg = new SaveFileDialog
            {
                FileName   = "exports",
                DefaultExt = "rtf",
                Filter     = "Rich Text Files|*.rtf"
            };

            if (dlg.ShowDialog(this) != true)
            {
                return;
            }

            var document = new FlowDocument();


            foreach (var source in TextFileItems.Where(elem => elem.IsChecked && !elem.IsFolder))
            {
                var file = TextFile.Load(source.Filename);
                if (file == null)
                {
                    continue;
                }

                document = document.AddFlowDocument(file.Document);
            }

            //TextFile.SaveFile(dlg.FileName,document);

            var blubb = XamlWriter.Save(document);

            System.Diagnostics.Debug.WriteLine(blubb);
            var test = ConvertXamlToRtf(blubb);

            File.AppendAllText(dlg.FileName, test);
        }
Beispiel #31
0
        private void button11_Click(object sender, System.EventArgs e)
        {
            Project       myProject = new Project();
            TextFile      txt       = new TextFile();
            HexaSnapShot  hexa      = new HexaSnapShot();
            TBLFile       tbl       = new TBLFile();
            TableFixeFile fixe      = new TableFixeFile();
            Favoris       mark      = new Favoris();
            Task          task      = new Task();

            myProject.CreateProject("FF2", @"c:", "ff2.smc", "ff2.tbl");

            for (int i = 0; i < 4; i++)
            {
                myProject.Textes.Add(txt);
                myProject.HexaSnapShot.Add(hexa);
                myProject.Tables.Add(tbl);
                myProject.TableFixe.Add(fixe);
                myProject.Favoris.Add(mark);
                myProject.Taches.Add(task);
            }

            myProject.Save();
        }
Beispiel #32
0
        /// <summary>
        /// Carrega o arquivo para o array de itens
        /// </summary>
        public void Load(string FileName)
        {
            this.FileName = FileName;
            TextFile TextFile = new TextFile();

            TextFile.Open(enmOpenMode.Reading, FileName);
            string[] lines = TextFile.GetLines();
            TextFile.Close();

            string buffer = "";

            for (int i = 0; i < lines.Length; i++)
            {
                if (lines[i].IndexOf(IniStr) != -1)
                {
                    Items.Add(new ItemUpdate(GetNumber(lines[i]), true));
                }
                else
                {
                    if (Items.Count != 0)
                    {
                        buffer += lines[i] + " ";
                        if (lines[i].IndexOf(';') != -1)
                        {
                            Items[Items.Count - 1].Sql.Add(buffer);
                            buffer = "";
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(buffer.Trim()))
            {
                Items[Items.Count - 1].Sql.Add(buffer);
            }
        }
Beispiel #33
0
        private void openToolSelectionForm()
        {
            if (toolSelectionForm == null)
            {
                toolSelectionForm = new ajkControls.SelectionForm();
                toolSelectionForm.InputAreaForecolor = Color.FromArgb(250, 250, 250);
                toolSelectionForm.InputAreaBackcolor = Color.FromArgb(90, 90, 90);
                toolSelectionForm.ForeColor          = Color.FromArgb(240, 240, 240);
                toolSelectionForm.BackColor          = Color.FromArgb(50, 50, 50);
                toolSelectionForm.Style         = Global.DefaultDrawStyle;
                toolSelectionForm.SelectedColor = Color.FromArgb(128, (int)(52 * 3), (int)(58 * 3), (int)(64 * 3));
                toolSelectionForm.Selected     += ApplyTool;
            }
            if (toolSelectionForm.Visible)
            {
                return;
            }

            List <ToolItem> tools = TextFile.GetToolItems(CodeDocument.CaretIndex);
            List <ajkControls.SelectionItem> items = new List <ajkControls.SelectionItem>();

            foreach (ToolItem item in tools)
            {
                items.Add(item);
            }

            items.Add(new Snippets.ToLower());
            items.Add(new Snippets.ToUpper());

            toolSelectionForm.SetSelectionItems(items);
            toolSelectionForm.Font = codeTextbox.Font;

            Point screenPosition = PointToScreen(codeTextbox.GetCaretTopPoint());

            Controller.ShowForm(toolSelectionForm, screenPosition);
        }
Beispiel #34
0
        public DataTable ReadShefFile(string fileName)
        {
            m_filename    = fileName;
            shefDataTable = new DataTable();
            shefDataTable.Columns.Add(new DataColumn("location", typeof(string)));
            shefDataTable.Columns.Add(new DataColumn("datetime", typeof(DateTime)));
            shefDataTable.Columns.Add(new DataColumn("shefcode", typeof(string)));
            shefDataTable.Columns.Add(new DataColumn("value", typeof(double)));

            if (!s_cache.ContainsKey(m_filename))
            {
                GetFileReference();
            }

            TextFile lines = s_cache[m_filename];

            for (int i = 0; i < lines.Length; i++)
            {
                addShefDataTableLine(lines[i]);
            }


            return(shefDataTable);
        }
Beispiel #35
0
        protected virtual DaggerfallMessageBox CreateDialogBox(string entryStr, string baseKey)
        {
            string heading     = TextManager.Instance.GetLocalizedText(baseKey + "Head");
            string action      = TextManager.Instance.GetLocalizedText(baseKey);
            string explanation = TextManager.Instance.GetLocalizedText(baseKey + "2");

            TextFile.Token[] tokens = new TextFile.Token[] {
                TextFile.CreateTextToken(heading), TextFile.CreateFormatToken(TextFile.Formatting.JustifyCenter), TextFile.NewLineToken,
                TextFile.CreateTextToken(action), TextFile.NewLineToken, TextFile.NewLineToken,
                new TextFile.Token()
                {
                    text = entryStr, formatting = TextFile.Formatting.TextHighlight
                }, TextFile.CreateFormatToken(TextFile.Formatting.JustifyCenter), TextFile.NewLineToken,
                TextFile.CreateTextToken(explanation), TextFile.CreateFormatToken(TextFile.Formatting.EndOfRecord)
            };

            DaggerfallMessageBox dialogBox = new DaggerfallMessageBox(uiManager, this);

            dialogBox.SetHighlightColor(Color.white);
            dialogBox.SetTextTokens(tokens);
            dialogBox.AddButton(DaggerfallMessageBox.MessageBoxButtons.Yes);
            dialogBox.AddButton(DaggerfallMessageBox.MessageBoxButtons.No);
            return(dialogBox);
        }
            public void Save(FileName file)
            {
                TextFile f = new TextFile(file);

                f.OpenNewToWrite(FileShare.None);

                foreach (string line in Header)
                   f.WriteLine(line);

                int i = 0;

                if (HorizGrid != null)
                {
                   f.WriteLine("<BeginXX>");
                   for (i = 0; i < HorizGrid.XX.Count; i++)
                  f.WriteLine(HorizGrid.XX[i].ToString(DataFormat));
                   f.WriteLine("<EndXX>");
                   f.WriteLine("<BeginYY>");
                   for (i = 0; i < HorizGrid.YY.Count; i++)
                  f.WriteLine(HorizGrid.YY[i].ToString(DataFormat));
                   f.WriteLine("<EndYY>");
                }

                f.WriteLine("<BeginGridData2D>");
                for (i = 0; i < Data.Count; i++)
                   f.WriteLine(Data[i].ToString(DataFormat));
                f.WriteLine("<EndGridData2D>");
                f.Close();
            }
Beispiel #37
0
		protected void Start (string test)
		{
			TargetRuntime runtime;

			switch (EngineId) {
			case "MonoDevelop.Debugger.Win32":
				runtime = Runtime.SystemAssemblyService.GetTargetRuntime ("MS.NET");
				break;
			case "Mono.Debugger.Soft":
				runtime = Runtime.SystemAssemblyService.GetTargetRuntimes ()
					.OfType<MonoTargetRuntime> ()
					.OrderByDescending(o => o.Version)
					.FirstOrDefault ();
				break;
			default:
				runtime = Runtime.SystemAssemblyService.DefaultRuntime;
				break;
			}

			if (runtime == null) {
				Assert.Ignore ("Runtime not found for: {0}", EngineId);
				return;
			}

			Console.WriteLine ("Target Runtime: " + runtime.DisplayRuntimeName + " " + runtime.Version);

			// main/build/tests
			FilePath path = Path.GetDirectoryName (GetType ().Assembly.Location);
			var exe = Path.Combine (path, "MonoDevelop.Debugger.Tests.TestApp.exe");

			var cmd = new DotNetExecutionCommand ();
			cmd.TargetRuntime = runtime;
			cmd.Command = exe;
			cmd.Arguments = test;

			if (Platform.IsWindows) {
				var monoRuntime = runtime as MonoTargetRuntime;
				if (monoRuntime != null) {
					var psi = new System.Diagnostics.ProcessStartInfo (Path.Combine (monoRuntime.Prefix, "bin", "pdb2mdb.bat"), cmd.Command);
					psi.UseShellExecute = false;
					psi.CreateNoWindow = true;
					System.Diagnostics.Process.Start (psi).WaitForExit ();
				}
			}

			var dsi = engine.CreateDebuggerStartInfo (cmd);
			var soft = dsi as SoftDebuggerStartInfo;

			if (soft != null) {
				var assemblyName = AssemblyName.GetAssemblyName (exe);

				soft.UserAssemblyNames = new List<AssemblyName> ();
				soft.UserAssemblyNames.Add (assemblyName);
			}

			Session = engine.CreateSession ();
			var ops = new DebuggerSessionOptions ();
			ops.EvaluationOptions = EvaluationOptions.DefaultOptions;
			ops.EvaluationOptions.AllowTargetInvoke = AllowTargetInvokes;
			ops.EvaluationOptions.EvaluationTimeout = 100000;

			path = path.ParentDirectory.ParentDirectory.Combine ("src", "addins", "MonoDevelop.Debugger", "MonoDevelop.Debugger.Tests.TestApp", test + ".cs").FullPath;
			SourceFile = TextFile.ReadFile (path);
			TestName = test;
			AddBreakpoint ("break");
			
			var done = new ManualResetEvent (false);
			
			Session.OutputWriter = (isStderr, text) => Console.WriteLine ("PROC:" + text);

			Session.TargetHitBreakpoint += (sender, e) => {
				done.Set ();
				Frame = e.Backtrace.GetFrame (0);
				lastStoppedPosition = Frame.SourceLocation;
				targetStoppedEvent.Set ();
			};

			Session.TargetExceptionThrown += (sender, e) => {
				Frame = e.Backtrace.GetFrame (0);
				for (int i = 0; i < e.Backtrace.FrameCount; i++) {
					if (!e.Backtrace.GetFrame (i).IsExternalCode) {
						Frame = e.Backtrace.GetFrame (i);
						break;
					}
				}
				lastStoppedPosition = Frame.SourceLocation;
				targetStoppedEvent.Set ();
			};

			Session.TargetStopped += (sender, e) => {
				Frame = e.Backtrace.GetFrame (0);
				lastStoppedPosition = Frame.SourceLocation;
				targetStoppedEvent.Set ();
			};

			var targetExited = new ManualResetEvent (false);
			Session.TargetExited += delegate {
				targetExited.Set ();
			};

			Session.Run (dsi, ops);
			switch (WaitHandle.WaitAny (new WaitHandle[]{ done, targetExited }, 30000)) {
			case 0:
				//Breakpoint is hit good... run tests now
				break;
			case 1:
				throw new Exception ("Test application exited before hitting breakpoint");
			default:
				throw new Exception ("Timeout while waiting for initial breakpoint");
			}
		}
Beispiel #38
0
            public virtual bool Load()
            {
                ConfigNode n = Root;
                Dictionary<string, string> defines = new Dictionary<string, string>();
                string [] defSeps = { "=" };
                string value;

                TextFile cf = new TextFile(ConfigFile);
                cf.OpenToRead();
                bool newBlockFound = false;
                bool newArrayBlockFound = false;

                int line = 0;

                try
                {
                   List<string> lines = cf.ReadLines();

                   string toRead = "";
                   string temp;
                   string t;

                   foreach (string t_l in lines)
                   {
                  line++;

                  if ((temp = t_l.Trim()) == "")
                     continue;
                  else if (temp.EndsWith(" _"))
                  {
                     toRead += temp.Substring(0, temp.Length - 2);
                     continue;
                  }
                  else if(temp == "{")
                  {
                     if (newBlockFound)
                     {
                        newBlockFound = false;
                        continue;
                     }
                     else if (newArrayBlockFound)
                     {
                        newArrayBlockFound = false;
                        continue;
                     }
                     else
                     {
                        throw new Exception("Found unexpected '{'");
                     }
                  }
                  else
                     toRead += temp;

                  if (toRead[0] == '.') //it's a new block
                  {
                     ConfigNode newNode = new ConfigNode(toRead.Substring(1).Trim().ToLower());
                     newNode.NodeType = NodeType.COMMON;
                     n.ChildNodes.Add(newNode);
                     newNode.Father = n;
                     n = newNode;
                     newBlockFound = true;
                     //Console.WriteLine("New '.' found on line {0}", line.ToString());
                  }
                  else if (toRead[0] == '+')
                  {
                     ConfigNode newNode = new ConfigNode(toRead.Substring(1).Trim().ToLower());
                     newNode.NodeType = NodeType.ARRAY;
                     n.ChildNodes.Add(newNode);
                     newNode.Father = n;
                     n = newNode;
                     newArrayBlockFound = true;
                     //Console.WriteLine("New '+' found on line {0}", line.ToString());
                  }
                  else if (toRead == "}") //it's the end of the current block
                  {
                     n = n.Father;
                  }
                  else if (toRead[0] == '#') //it's a pre-processing directive
                  {
                     if (toRead.StartsWith("#define "))
                     {
                        string[] tokens = toRead.Substring(8).Split(defSeps, StringSplitOptions.RemoveEmptyEntries);
                        if (tokens.Length == 2)
                        {
                           defines[tokens[0].Trim()] = tokens[1].Trim();
                        }
                     }
                  }
                  else if(toRead[0] != '!') //it's a keyword
                  {
                     if (n.NodeType == NodeType.COMMON)
                     {
                        string[] tokens = toRead.Split(keywordSplit, 2, StringSplitOptions.RemoveEmptyEntries);
                        value = tokens[1].Trim();

                        foreach (KeyValuePair<string, string> def in defines)
                        {
                           t = value.Replace(def.Key, def.Value);
                           value = t;
                        }
                        n.NodeData[tokens[0].Trim().ToLower()] = new KeywordData(value.Trim());
                     }
                     else if (n.NodeType == NodeType.ARRAY)
                     {
                        value = toRead.Trim();
                        foreach (KeyValuePair<string, string> def in defines)
                        {
                           t = value.Replace(def.Key, def.Value);
                           value = t;
                        }
                        n.NodeData[(n.NodeData.Count + 1).ToString()] = new KeywordData(value);
                     }
                  }

                  toRead = "";
                   }

                   cf.Close();

                   return true;
                }
                catch(Exception ex)
                {
                   exceptionMessage = "Error on line " + line.ToString() + ": " + ex.Message;
                   cf.Close();
                   return false;
                }
            }
 public MergedFileSavedEventArgs(TextFile mergedFile, TextFileInformation fileInfo)
 {
     this.mergedFile = mergedFile;
     fileInformation = fileInfo;
 }
Beispiel #40
0
            private string LoadCSharpScript(FileName scriptFileName)
            {
                TextFile scriptFile;

                try
                {
                   scriptFile = new TextFile(scriptFileName);
                }
                catch (Exception ex)
                {
                   throw new Exception ("Error when creating script text object. " + ex.Message);
                }

                try
                {
                   scriptFile.OpenToRead();
                }
                catch (Exception ex)
                {
                   throw new Exception("Error when opening script file. " + ex.Message);
                }

                List<string> script = scriptFile.ReadLines();

                int lineNumber = 0;
                string line;
                string[] dllName;
                string[] seps = { ":" };

                for (lineNumber = 0; lineNumber < script.Count; lineNumber++)
                {
                   line = script[lineNumber].Trim();
                   if (line == "") continue;

                   if (line.StartsWith("//DLLNAME:"))
                   {
                  dllName = line.Split(seps, StringSplitOptions.RemoveEmptyEntries);
                  if (!dllName[1].Trim().EndsWith(".dll"))
                     dllName[1] = dllName[1].Trim() + ".dll";

                  dllList.Add(dllName[1].Trim());
                   }
                }

                StringBuilder temp = new StringBuilder();
                for (lineNumber = 0; lineNumber < script.Count; lineNumber++)
                   temp.AppendLine(script[lineNumber]);

                scriptFile.Close();

                Console.WriteLine("Finished reading script file.");

                return temp.ToString();
            }
Beispiel #41
0
            public int Glue()
            {
                if (filesToGlue != null && filesToGlue.Count <= 0)
                   return ThrowException(-3, "No files to glue.");

                if (filesToGlue2 != null && filesToGlue2.Count <= 0)
                   return ThrowException(-3, "No files to glue.");

                try
                {
                   TextFile datafile = new TextFile();

                   if (Verbose)
                  Console.WriteLine("Creating input file: {0}", fWorkingDirectory + GlueInpuFile);

                   datafile.File = new FileName(fWorkingDirectory + GlueInpuFile);

                   datafile.OpenNewToWrite(System.IO.FileShare.None);

                   if (!String.IsNullOrEmpty(fOutwatch) && fOutwatch.Trim() != "")
                  datafile.WriteLine("OUTWATCH         : " + fOutwatch.Trim());
                   datafile.WriteLine("<begin_file>");
                   datafile.WriteLine("  ACTION           : GLUES HDF5 FILES");
                   datafile.WriteLine("  OUTPUTFILENAME   : " + fOutput);
                   if (Is3DFile)
                  datafile.WriteLine("  3D_FILE          : 1");
                   else
                  datafile.WriteLine("  3D_FILE          : 0");
                   datafile.WriteLine("  BASE_GROUP       : " + BaseGroup);
                   datafile.WriteLine("  TIME_GROUP       : " + TimeGroup);
                   datafile.WriteLine("  <<begin_list>>");
                   if (filesToGlue != null)
                   {
                  foreach (string file in filesToGlue)
                     datafile.WriteLine("      " + file);
                   }
                   else if (filesToGlue2 != null)
                   {
                  foreach (FileName file in filesToGlue2)
                     datafile.WriteLine("      " + file.FullPath);
                   }
                   datafile.WriteLine("  <<end_list>>");
                   datafile.WriteLine("<end_file>");
                   datafile.Close();
                }
                catch (Exception ex)
                {
                   return ThrowException(-1, ex.Message);
                }

                TextToCheck = "successfully terminated";
                if (!ExecuteApp())
                   return ThrowException(-2);

                return 0;
            }
Beispiel #42
0
            public virtual bool Save()
            {
                TextFile cf = new TextFile(ConfigFile);
                cf.OpenNewToWrite();

                bool result = false;

                try
                {
                   result = SaveToConfigFile(ref cf, Root);
                }
                catch(Exception ex)
                {
                   exceptionMessage = ex.Message;
                   cf.Close();
                   return false;
                }

                cf.Close();
                return result;
            }
Beispiel #43
0
            protected bool SaveToConfigFile(ref TextFile cf, ConfigNode nodeToSave)
            {
                if (nodeToSave.NodeData != null)
                   foreach (KeyValuePair<string, KeywordData> pair in nodeToSave.NodeData)
                   {
                  if (nodeToSave.NodeType == NodeType.COMMON)
                     cf.WriteLine(pair.Key + keywordSplit[0] + pair.Value.AsString());
                  else if (nodeToSave.NodeType == NodeType.ARRAY)
                     cf.WriteLine(pair.Value.AsString());
                   }

                if (nodeToSave.SimpleData != null)
                   foreach (string simple in nodeToSave.SimpleData)
                   {
                  cf.WriteLine(simple);
                   }

                if (nodeToSave.ChildNodes != null)
                   foreach (ConfigNode child in nodeToSave.ChildNodes)
                   {
                  if (child.NodeType == NodeType.COMMON)
                     cf.WriteLine("." + child.Name);
                  else if (child.NodeType == NodeType.ARRAY)
                     cf.WriteLine("+" + child.Name);

                  cf.WriteLine("{");
                  if (!SaveToConfigFile(ref cf, child))
                     return false;
                  cf.WriteLine("}");
                   }

                return true;
            }
Beispiel #44
0
        private static void DemoStrings(IConnection conn)
        {
            var packet = new Packet();

            var text = new TextFile('A') {
                {"<string C/>", DisplayMode.Scroll}
            };

            packet.SetMemory(new FileTable {
                {'C', new StringFileInfo(10)},
                text
            });

            packet.Add(new WriteTextCommand(text));
            conn.Send(packet);

            for(int i = 0; i < 60; i++)
            {
                packet = new Packet();
                packet.Add(new WriteStringCommand(new StringFile('C', i.ToString("000"))));
                conn.Send(packet);
                Thread.Sleep(1000);
            }
        }
Beispiel #45
0
        static void Main(string[] args)
        {
            DateTime start, end;
             FilePath rootResultsPath;
             FileName hdfResultsFile;
             List<FilePath> timeseriesOutputPath = new List<FilePath>();
             FileName exporterEXE;
             FilePath exporterWorkingPath;
             bool joinTimeseries = false;
             bool useDateOnTimeseriesName = true;
             string folderFormat, startFormat, endFormat;
             StringBuilder exporterCFGBase = new StringBuilder();
             StringBuilder exporterCFG = new StringBuilder();
             List<ConfigNode> nodes;
             double runLenght;
             bool verbose;
             List<FileInfo> tsFileInfoList = new List<FileInfo>();
             Dictionary<string, TimeSeries> outTS = new Dictionary<string,TimeSeries>();
             TimeSeries newTS = new TimeSeries();
             TextFile txtFile, errors;
             int timeseriesSaveCounter = 1, saveCounter;
             int timeseriesNameCounter;
             errors = new TextFile("errors.log");
             errors.OpenNewToWrite();
             verbose = true;
             FilePath path;
             bool dateAndTimeInOutputFolder;
             string outputFolderFormat = "", outputFolderStartFormat = "", outputFolderEndFormat = "", outputPath, outputPath2;
             bool useCounter;

             try
             {
            CmdArgs cmdArgs = new CmdArgs(args);

            if (cmdArgs.HasOption("v"))
               verbose = true;
            else
               verbose = false;

            if (cmdArgs.HasParameter("cfg"))
            {
               if (verbose)
                  Console.Write("Reading configuration file...");

               Config conf = new Config(cmdArgs.Parameters["cfg"]);
               conf.Load();

               if (verbose)
                  Console.WriteLine("[OK]");

               if (verbose)
                  Console.Write("Looking for 'timeseries.to.extract' blocks...");

               List<ConfigNode> tsList = conf.Root.ChildNodes.FindAll(delegate(ConfigNode node) { return node.Name == "timeseries.to.extract"; });

               if (tsList == null || tsList.Count <= 0)
                  throw new Exception("No 'timeseries.to.extract' block found in configuration file.");

               if (verbose)
               {
                  Console.WriteLine("[OK]");
                  Console.WriteLine("{0} 'timeseries.to.extract' block(s) found.", tsList.Count);
               }

               dateAndTimeInOutputFolder = conf.Root["user.def.output.folder", false].AsBool();
               if (dateAndTimeInOutputFolder)
               {
                   outputFolderFormat = conf.Root["user.def.output.folder.format", "start-end"].AsString();
                   outputFolderStartFormat = conf.Root["user.def.output.start.format", "yyyyMMddHH"].AsString();
                   outputFolderEndFormat = conf.Root["user.def.output.end.format", "yyyyMMddHH"].AsString();
               }

               int tscCount = 1;
               foreach (ConfigNode tsc in tsList)
               {
                  timeseriesNameCounter = 1;

                  if (verbose)
                     Console.Write("Processing 'timeseries.to.extract' block {0}...", tscCount);

                  start                   = tsc["start"].AsDateTime();
                  end                     = tsc["end"].AsDateTime();
                  rootResultsPath         = tsc["root.results.path", @".\"].AsFilePath();
                  hdfResultsFile          = tsc["hdf.results.file"].AsFileName();
                  if (tsc.Contains("backup_path"))
                  {
                      path = tsc["backup_path"].AsFilePath();
                      timeseriesOutputPath.Add(path);
                  }
                  if (tsc.Contains("storage_path"))
                  {
                      path = tsc["storage_path"].AsFilePath();
                      timeseriesOutputPath.Add(path);
                  }
                  if (tsc.Contains("publish_path"))
                  {
                      path = tsc["publish_path"].AsFilePath();
                      timeseriesOutputPath.Add(path);
                  }

                  if (timeseriesOutputPath.Count <= 0)
                  {
                      throw new Exception("An error was found in the configuration file. Missing keyword." + "At least ONE of the following keywords must be provided:" +
                                          "BACKUP_PATH, STORAGE_PATH, PUBLISH_PATH");
                  }
                  exporterEXE             = tsc["exporter.exe"].AsFileName();
                  exporterWorkingPath     = tsc["exporter.working.path"].AsFilePath();
                  joinTimeseries          = tsc["join.timeseries", true].AsBool();
                  if (joinTimeseries && dateAndTimeInOutputFolder)
                  {
                      throw new Exception("join.timeseries can't be used with user.def.output.folder");
                  }
                  folderFormat            = tsc["folder.format", "start-end"].AsString();
                  startFormat             = tsc["start.format", "yyyyMMddHH"].AsString();
                  endFormat               = tsc["end.format", "yyyyMMddHH"].AsString();
                  runLenght               = tsc["run.lenght"].AsDouble();
                  useCounter              = tsc["use.counter.on.names", false].AsBool();

                  if (joinTimeseries)
                  {
                     outTS = new Dictionary<string, TimeSeries>();
                     newTS = new TimeSeries();

                     timeseriesSaveCounter = tsc["save.counter"].AsInt();
                  }
                  else
                  {
                     useDateOnTimeseriesName = tsc["use.date.on.timeseries.name", true].AsBool();
                  }

                  exporterCFGBase.Append("EXPORT_TYPE      : "); exporterCFGBase.AppendLine(tsc["export.type", 1].AsString());
                  exporterCFGBase.Append("COMPUTE_RESIDUAL : "); exporterCFGBase.AppendLine(tsc["compute.residual", 0].AsString());
                  exporterCFGBase.Append("VARIABLE_GRID    : "); exporterCFGBase.AppendLine(tsc["variable.grid", 0].AsString());
                  exporterCFGBase.Append("WATERPOINTS_NAME : "); exporterCFGBase.AppendLine(tsc["points.name", "WaterPoints2D"].AsString());
                  exporterCFGBase.Append("GRID_FILENAME    : "); exporterCFGBase.AppendLine(tsc["grid.file.name", "grid.dat"].AsString());

                  nodes = tsc.ChildNodes.FindAll(delegate(ConfigNode node) { return node.Name == "timeseries"; });

                  if (nodes == null || nodes.Count <= 0)
                     throw new Exception("No 'timeseries' block found in configuration file.");

                  foreach (ConfigNode param in nodes)
                  {
                     exporterCFGBase.AppendLine();
                     exporterCFGBase.AppendLine("<BeginTimeSerie>");
                     exporterCFGBase.Append("  NAME            : "); exporterCFGBase.AppendLine(param["name"].AsString());

                     if (param.NodeData.ContainsKey("coord.y"))
                     {
                        exporterCFGBase.Append("  COORD_Y        : ");
                        exporterCFGBase.AppendLine(param["coord.y"].AsString());
                     }
                     if (param.NodeData.ContainsKey("coord.x"))
                     {
                        exporterCFGBase.Append("  COORD_X        : ");
                        exporterCFGBase.AppendLine(param["coord.x"].AsString());
                     }
                     if (param.NodeData.ContainsKey("depth.level"))
                     {
                        exporterCFGBase.Append("  DEPTH_LEVEL    : ");
                        exporterCFGBase.AppendLine(param["depth.level"].AsString());
                     }
                     if (param.NodeData.ContainsKey("localization.i"))
                     {
                        exporterCFGBase.Append("  LOCALIZATION_I : ");
                        exporterCFGBase.AppendLine(param["localization.i"].AsString());
                     }
                     if (param.NodeData.ContainsKey("localization.j"))
                     {
                        exporterCFGBase.Append("  LOCALIZATION_J : ");
                        exporterCFGBase.AppendLine(param["localization.j"].AsString());
                     }
                     if (param.NodeData.ContainsKey("localization.k"))
                     {
                        exporterCFGBase.Append("  LOCALIZATION_K : ");
                        exporterCFGBase.AppendLine(param["localization.k"].AsString());
                     }
                     if (param.NodeData.ContainsKey("latitude"))
                     {
                        exporterCFGBase.Append("  LATITUDE       : ");
                        exporterCFGBase.AppendLine(param["latitude"].AsString());
                     }
                     if (param.NodeData.ContainsKey("longitude"))
                     {
                        exporterCFGBase.Append("  LONGITUDE      : ");
                        exporterCFGBase.AppendLine(param["longitude"].AsString());
                     }

                     exporterCFGBase.AppendLine("<EndTimeSerie>");

                     if (joinTimeseries)
                     {
                        outTS[param["name"].AsString()] = new TimeSeries();
                     }
                  }

                  nodes = tsc.ChildNodes.FindAll(delegate(ConfigNode node) { return node.Name == "parameter"; });

                  if (nodes == null || nodes.Count <= 0)
                     throw new Exception("No 'parameter' block found in configuration file.");

                  foreach (ConfigNode param in nodes)
                  {
                     exporterCFGBase.AppendLine();
                     exporterCFGBase.AppendLine("<BeginParameter>");
                     exporterCFGBase.Append("  HDF_GROUP : "); exporterCFGBase.AppendLine(param["hdf.group"].AsString());
                     exporterCFGBase.Append("  PROPERTY  : "); exporterCFGBase.AppendLine(param["hdf.property"].AsString());
                     exporterCFGBase.AppendLine("<EndParameter>");
                  }

                  txtFile = new TextFile(exporterWorkingPath.Path + "nomfich.dat");
                  txtFile.OpenNewToWrite();
                  txtFile.WriteLine("IN_MODEL : hdfexporter.dat");
                  txtFile.Close();

                  ExternalApp hdf5exporter = new ExternalApp();
                  hdf5exporter.CheckSuccessMethod = CheckSuccessMethod.DEFAULTOUTPUT;
                  hdf5exporter.TextToCheck = "Program HDF5Exporter successfully terminated";
                  hdf5exporter.Wait = true;
                  hdf5exporter.WorkingDirectory = exporterWorkingPath.Path;
                  hdf5exporter.Executable = exporterEXE.FullPath;

                  bool fail;
                  DateTime actual = start;
                  FilePath hdfResultsPath = new FilePath();
                  saveCounter = 1;
                  while (actual.AddDays(runLenght) <= end)
                  {
                     fail = false;

                     hdfResultsPath.Path = rootResultsPath.Path +
                           (folderFormat.Replace("start", actual.ToString(startFormat)).Replace("end", actual.AddDays(runLenght).ToString(endFormat)));

                     if (System.IO.Directory.Exists(hdfResultsPath.Path))
                     {

                        exporterCFG.Clear();
                        exporterCFG.Append("START_TIME : "); exporterCFG.AppendLine(actual.ToString("yyyy M d H m s"));
                        exporterCFG.Append("END_TIME : "); exporterCFG.AppendLine(actual.AddDays(runLenght).ToString("yyyy M d H m s"));
                        exporterCFG.AppendLine();
                        exporterCFG.AppendLine("<BeginHDF5File>");
                        exporterCFG.Append("  NAME : "); exporterCFG.AppendLine(hdfResultsPath.Path + hdfResultsFile.FullName);
                        exporterCFG.AppendLine("<EndHDF5File>");

                        txtFile.File.FullPath = exporterWorkingPath.Path + "hdfexporter.dat";
                        txtFile.OpenNewToWrite();
                        txtFile.Write(exporterCFGBase.ToString());
                        txtFile.Write(exporterCFG.ToString());
                        txtFile.Close();

                        try
                        {
                           bool res = hdf5exporter.Run();
                           if (!res)
                           {
                              throw new Exception("Unsuccessfull HDF5Exporter run");
                           }
                        }
                        catch (Exception e_run)
                        {
                           errors.WriteLine("[" + DateTime.Now.ToString() + "] HDF5Exporter Run Exception when processing '" + hdfResultsFile + "' on results folder '" + hdfResultsPath.Path + "'");
                           errors.WriteLine("[" + DateTime.Now.ToString() + "] The exception returned this message: " + e_run.Message);
                           fail = true;
                        }

                        if (!fail)
                        {
                           FileTools.FindFiles(ref tsFileInfoList, exporterWorkingPath, "*.ets", true, "", System.IO.SearchOption.TopDirectoryOnly);

                           if (joinTimeseries)
                           {
                              foreach (FileInfo file in tsFileInfoList)
                              {
                                 if (outTS[file.FileName.Name].NumberOfInstants > 0)
                                 {
                                    saveCounter++;

                                    try
                                    {
                                       newTS.Load(file.FileName);
                                       outTS[file.FileName.Name].AddTimeSeries(newTS);
                                    }
                                    catch
                                    {
                                       errors.WriteLine("[" + DateTime.Now.ToString() + "] Was not possible to read timeseries '" + file.FileName.FullName + "' from HDF file '" + hdfResultsFile + "' on results folder '" + hdfResultsPath.Path + "'");
                                    }

                                    System.IO.File.Delete(file.FileName.FullPath);

                                    if (saveCounter > timeseriesSaveCounter)
                                    {
                                       try
                                       {
                                           if (dateAndTimeInOutputFolder)
                                           {
                                               outputPath = timeseriesOutputPath[0].Path +
                                                   (outputFolderFormat.Replace("start", actual.ToString(outputFolderStartFormat)).Replace("end", actual.AddDays(runLenght).ToString(outputFolderEndFormat))) + System.IO.Path.DirectorySeparatorChar;
                                           }
                                           else
                                           {
                                               outputPath = timeseriesOutputPath[0].Path;
                                           }
                                           if (!System.IO.Directory.Exists(outputPath))
                                               System.IO.Directory.CreateDirectory(outputPath);

                                          outTS[file.FileName.Name].Save(new FileName(outputPath + file.FileName.FullName));
                                          saveCounter = 1;
                                          if (timeseriesOutputPath.Count > 1)
                                          {
                                              for (int i = 1; i < timeseriesOutputPath.Count; i++)
                                              {
                                                  outputPath2 = timeseriesOutputPath[i].Path +
                                                   (outputFolderFormat.Replace("start", actual.ToString(outputFolderStartFormat)).Replace("end", actual.AddDays(runLenght).ToString(outputFolderEndFormat))) + System.IO.Path.DirectorySeparatorChar;
                                                  if (!System.IO.Directory.Exists(outputPath2))
                                                      System.IO.Directory.CreateDirectory(outputPath2);
                                                  FileTools.CopyFile(new FileName(outputPath + file.FileName.FullName),
                                                                     new FileName(outputPath2 + file.FileName.FullName), CopyOptions.OVERWRIGHT);
                                              }
                                          }

                                       }
                                       catch (Exception ex)
                                       {
                                          errors.WriteLine("[" + DateTime.Now.ToString() + "] Was not possible to save joined timeseries '" + file.FileName.FullName + "' from HDF file '" + hdfResultsFile + "' when processing results folder '" + hdfResultsPath.Path + "'");
                                          errors.WriteLine("[" + DateTime.Now.ToString() + "] The exception returned this message: " + ex.Message);
                                       }
                                    }
                                 }
                                 else
                                 {
                                    outTS[file.FileName.Name].Load(file.FileName);
                                    System.IO.File.Delete(file.FileName.FullPath);
                                 }
                              }
                           }
                           else
                           {
                              FileName timeseriesTarget = new FileName();

                              foreach (FileInfo file in tsFileInfoList)
                              {
                                  if (dateAndTimeInOutputFolder)
                                  {
                                      outputPath = timeseriesOutputPath[0].Path +
                                          (outputFolderFormat.Replace("start", actual.ToString(outputFolderStartFormat)).Replace("end", actual.AddDays(runLenght).ToString(outputFolderEndFormat))) + System.IO.Path.DirectorySeparatorChar;
                                  }
                                  else
                                  {
                                      outputPath = timeseriesOutputPath[0].Path;
                                  }
                                  timeseriesTarget.Path = outputPath;
                                  if (!System.IO.Directory.Exists(outputPath))
                                      System.IO.Directory.CreateDirectory(outputPath);
                                  if (useDateOnTimeseriesName)
                                 {

                                    timeseriesTarget.FullName = file.FileName.FullName.Insert(file.FileName.FullName.LastIndexOf('.'), actual.ToString(startFormat) + "_" + actual.AddDays(runLenght).ToString(endFormat));
                                 }
                                  else if (useCounter)
                                  {
                                      timeseriesTarget.FullName = file.FileName.FullName.Insert(file.FileName.FullName.LastIndexOf('.'), timeseriesNameCounter.ToString());
                                      timeseriesNameCounter++;
                                  }
                                  else
                                  {
                                      timeseriesTarget.FullName = file.FileName.FullName;
                                  }
                                 FileTools.CopyFile(file.FileName, timeseriesTarget, CopyOptions.OVERWRIGHT);
                                 if (timeseriesOutputPath.Count > 1)
                                 {
                                     for (int i = 1; i < timeseriesOutputPath.Count; i++)
                                     {
                                         outputPath2 = timeseriesOutputPath[i].Path +
                                          (outputFolderFormat.Replace("start", actual.ToString(outputFolderStartFormat)).Replace("end", actual.AddDays(runLenght).ToString(outputFolderEndFormat))) + System.IO.Path.DirectorySeparatorChar;
                                         if (!System.IO.Directory.Exists(outputPath2))
                                             System.IO.Directory.CreateDirectory(outputPath2);
                                         FileTools.CopyFile(new FileName(outputPath + file.FileName.FullName),
                                                            new FileName(outputPath2 + file.FileName.FullName), CopyOptions.OVERWRIGHT);
                                     }
                                 }
                              }
                           }
                        }
                     }

                     actual = actual.AddDays(runLenght);
                  }

                  tscCount++;

                  if (joinTimeseries)
                  {
                     foreach (KeyValuePair<string, TimeSeries> pair in outTS)
                     {
                         if (dateAndTimeInOutputFolder)
                         {
                             outputPath = timeseriesOutputPath[0].Path +
                                 (outputFolderFormat.Replace("start", actual.ToString(outputFolderStartFormat)).Replace("end", actual.AddDays(runLenght).ToString(outputFolderEndFormat))) + System.IO.Path.DirectorySeparatorChar;
                         }
                         else
                         {
                             outputPath = timeseriesOutputPath[0].Path;
                         }
                         if (!System.IO.Directory.Exists(outputPath))
                             System.IO.Directory.CreateDirectory(outputPath);
                         pair.Value.Save(new FileName(outputPath + pair.Key + ".ets"));
                         for (int i = 1; i < timeseriesOutputPath.Count; i++)
                         {
                             outputPath2 = timeseriesOutputPath[i].Path +
                              (outputFolderFormat.Replace("start", actual.ToString(outputFolderStartFormat)).Replace("end", actual.AddDays(runLenght).ToString(outputFolderEndFormat))) + System.IO.Path.DirectorySeparatorChar;
                             if (!System.IO.Directory.Exists(outputPath2))
                                 System.IO.Directory.CreateDirectory(outputPath2);
                             FileTools.CopyFile(new FileName(outputPath + pair.Key + ".ets"),
                                                new FileName(outputPath2 + pair.Key + ".ets"), CopyOptions.OVERWRIGHT);
                         }
                     }
                  }

               }
            }
            Console.WriteLine("[OK]");
             }
             catch(Exception ex)
             {
            if (verbose)
            {
               Console.WriteLine("[FAIL]");
               Console.WriteLine("");
               Console.WriteLine("An EXCEPTION was raised. The message returned was:");
               Console.WriteLine(ex.Message);
            }
             }

             Console.WriteLine("GetTSFromModelResultsHDF finished.");
             errors.Close();
        }
Beispiel #46
0
		private async void LoadTextFile(int id)
		{
			try
			{
				if (id == -1)
				{
					m_textFile = m_repository.NewFile();
				}
				else
				{
					m_textFile = await m_repository.FileById(id);
				}
				m_textFile.IsDirty = false;
				m_text.DataContext = m_textFile;
				Title = string.Format("TextEditor - {0}", string.IsNullOrEmpty(m_textFile.Name) ? "*" : m_textFile.Name);
				m_textFile.PropertyChanged += TextFileBecomeDirtyHandler;
			}
			catch (Exception exc)
			{
				MessageBox.Show(this, exc.Message + "\n" + exc.StackTrace, "Exception on loading text file", MessageBoxButton.OK,
					MessageBoxImage.Error);
			}
		}
        private void ExportByFileList(ExportHDFToTSOptions opts, DoWorkEventArgs e)
        {
            string config_name = "";
             TextFile cfg = new TextFile();
             ExternalApp app = new ExternalApp();

             //Find a file name for the configuration file.
             bool Found = false;
             int n = 1;
             int tentatives = 0;
             while (!Found)
             {
            config_name = opts.ConfigFile + n + ".cfg";
            if (System.IO.File.Exists(opts.WorkingFolder + config_name))
            {
               n++;
            }
            else
            {
               try
               {
                  cfg.File.FullPath = opts.WorkingFolder + config_name;
                  cfg.OpenNewToWrite();
                  Found = true;
               }
               catch
               {
                  n++;
                  tentatives++;

                  if (tentatives > 20)
                  {
                     MessageBox.Show("Was not possibe to create the configuration file to the HDFExporter tool.", "ATTENTION", MessageBoxButtons.OK, MessageBoxIcon.Error);
                     return;
                  }
               }
            }
             }

             //Create the Config Data File
             cfg.WriteLine("!File created using Mohid Toolbox");

             foreach (string file in opts.List)
             {
            cfg.WriteLine("<BeginHDF5File>");
            cfg.WriteLine("  NAME : " + file);
            cfg.WriteLine("<EndHDF5File>");
             }

             if (opts.Type == ExportHDFToTSType.ByMask) //by Mask
             {
            cfg.WriteLine("EXPORT_TYPE       : 2");
            cfg.WriteLine("MASK_GRID         : " + opts.MaskFile);
            cfg.WriteLine("AREA_FILL_VALUE   : " + opts.AreaFillValue);
            if (opts.UsePoints)
            {
               cfg.WriteLine("USE_POINTS        : 1");
               cfg.WriteLine("WATERPOINTS_NAME  : " + opts.PointsName);
               cfg.WriteLine("WATERPOINTS_GROUP : " + opts.PointsGroup);
            }
            else
               cfg.WriteLine("USE_POINTS        : 0");
             }
             else //By coordinates
             {
            cfg.WriteLine("EXPORT_TYPE       : 1");
            cfg.WriteLine("WATERPOINTS_NAME  : " + opts.PointsName);
            cfg.WriteLine("WATERPOINTS_GROUP : " + opts.PointsGroup);
             }

             if (opts.CheckPropertyName)
            cfg.WriteLine("CHECK_PROPERTY    : 1");
             else
            cfg.WriteLine("CHECK_PROPERTY    : 0");

             if (opts.UseStart)
            cfg.WriteLine("START_TIME        : " + opts.Start.ToString("yyyy MM dd HH mm ss"));
             if (opts.UseEnd)
            cfg.WriteLine("END_TIME          : " + opts.End.ToString("yyyy MM dd HH mm ss"));

             if (opts.Variable)
            cfg.WriteLine("VARIABLE_GRID     : 1");
             else
            cfg.WriteLine("VARIABLE_GRID     : 0");

             if (!string.IsNullOrWhiteSpace(opts.GridFile))
            cfg.WriteLine("GRID_FILENAME     : " + opts.GridFile);

             if (!string.IsNullOrWhiteSpace(opts.TimeGroup))
            cfg.WriteLine("TIME_GROUP        : " + opts.TimeGroup);

             if (!string.IsNullOrWhiteSpace(opts.DecimationFactor))
            cfg.WriteLine("DECIMATION_FACTOR : " + opts.DecimationFactor);

             foreach (TimeseriesBlock ts in opts.TimeSeries)
             {
            cfg.WriteLine("<BeginTimeSerie>");

            if (opts.Type == ExportHDFToTSType.ByMask) //by Mask
            {
               cfg.WriteLine("  NAME              : " + (new FilePath(opts.PathToOutputTimeSeries)).Path + ts.Name);
               if (!string.IsNullOrWhiteSpace(ts.MaskID))
                  cfg.WriteLine("  MASK_ID           : " + ts.MaskID);
               if (!string.IsNullOrWhiteSpace(ts.Layer))
                  cfg.WriteLine("  LAYER             : " + ts.Layer);
            }
            else
            {
               cfg.WriteLine("  NAME              : " + (new FilePath(opts.PathToOutputTimeSeries)).Path + ts.Name);
               if (!string.IsNullOrWhiteSpace(ts.I))
                  cfg.WriteLine("  LOCALIZATION_I    : " + ts.I);
               if (!string.IsNullOrWhiteSpace(ts.J))
                  cfg.WriteLine("  LOCALIZATION_J    : " + ts.J);
               if (!string.IsNullOrWhiteSpace(ts.K))
                  cfg.WriteLine("  LOCALIZATION_J    : " + ts.K);
               if (!string.IsNullOrWhiteSpace(ts.Latitude))
                  cfg.WriteLine("  LATITUDE          : " + ts.Latitude);
               if (!string.IsNullOrWhiteSpace(ts.Longitude))
                  cfg.WriteLine("  LONGITUDE         : " + ts.Longitude);
               if (!string.IsNullOrWhiteSpace(ts.X))
                  cfg.WriteLine("  COORD_X           : " + ts.X);
               if (!string.IsNullOrWhiteSpace(ts.Y))
                  cfg.WriteLine("  COORD_Y           : " + ts.Y);
            }
            cfg.WriteLine("<EndTimeSerie>");
             }

             foreach (ParameterBlock p in opts.Parameters)
             {
            cfg.WriteLine("<BeginParameter>");
            cfg.WriteLine("  PROPERTY          : " + p.Name);
            cfg.WriteLine("  HDF_GROUP         : " + p.Group);
            cfg.WriteLine("<EndParameter>");
             }
             cfg.Close();

             //run HDFExporter Tool
             app.Executable = opts.PathToHDFExporter;
             app.UseShell = false;
             app.WorkingDirectory = opts.WorkingFolder;
             app.Arguments = "-c " + config_name;
             app.CheckSuccessMethod = CheckSuccessMethod.DEFAULTOUTPUT;
             app.TextToCheck = "successfully terminated";
             app.Verbose = false;
             app.Wait = false;
             app.SearchTextOrder = SearchTextOrder.FROMEND;

             Software.AppExitStatus es;

             if ((es = app.Run(this, e)) != AppExitStatus.Finished)
             {
            if (es != AppExitStatus.Canceled)
               MessageBox.Show("HDFExporter tool has failed.", "ATTENTION", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
             }

             if (!opts.KeepConfigFile)
             {
            try
            {
               System.IO.File.Delete(opts.WorkingFolder + config_name);
            }
            catch
            {
            }
             }
        }
        private void ExportByFolderList(ExportHDFToTSOptions opts, DoWorkEventArgs e)
        {
            string config_name = "";
             TextFile cfg = new TextFile();
             ExternalApp app = new ExternalApp();
             List<TimeSeries> outputTS = new List<TimeSeries>();
             bool first = true;

             System.IO.SearchOption so;
             FileName file = new FileName();
             FilePath path = new FilePath();
             List<Mohid.Files.FileInfo> files = new List<Mohid.Files.FileInfo>();

             if (opts.SearchSubFolders)
            so = System.IO.SearchOption.AllDirectories;
             else
            so = System.IO.SearchOption.TopDirectoryOnly;

             foreach (string folder in opts.List)
             {
            path.Path = folder;
            FileTools.FindFiles(ref files, path, Path.GetFileName(opts.File), false, null, so);
             }

             int totalFiles = files.Count;
             int filesProcessed = 0;

             foreach (Mohid.Files.FileInfo fi in files)
             {
            //Find a file name for the configuration file.
            if (this.CancellationPending)
            {
               return;
            }

            bool Found = false;
            int n = 1;
            int tentatives = 0;
            while (!Found)
            {
               config_name = opts.ConfigFile + n + ".cfg";
               if (System.IO.File.Exists(opts.WorkingFolder + config_name))
               {
                  n++;
               }
               else
               {
                  try
                  {
                     cfg.File.FullPath = opts.WorkingFolder + config_name;
                     cfg.OpenNewToWrite();
                     Found = true;
                  }
                  catch
                  {
                     n++;
                     tentatives++;

                     if (tentatives > 20)
                     {
                        MessageBox.Show("Was not possibe to create the configuration file to the HDFExporter tool.", "ATTENTION", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                     }
                  }
               }
            }

            //Create the Config Data File
            cfg.WriteLine("!File created using Mohid Toolbox");

            file.FullPath = fi.FileName.FullPath;
            cfg.WriteLine("<BeginHDF5File>");
            cfg.WriteLine("  NAME : " + file.FullPath);
            cfg.WriteLine("<EndHDF5File>");

            if (opts.Type == ExportHDFToTSType.ByMask) //by Mask
            {
               cfg.WriteLine("EXPORT_TYPE       : 2");
               cfg.WriteLine("MASK_GRID         : " + opts.MaskFile);
               cfg.WriteLine("AREA_FILL_VALUE   : " + opts.AreaFillValue);
               if (opts.UsePoints)
               {
                  cfg.WriteLine("USE_POINTS        : 1");
                  cfg.WriteLine("WATERPOINTS_NAME  : " + opts.PointsName);
                  cfg.WriteLine("WATERPOINTS_GROUP : " + opts.PointsGroup);
               }
               else
                  cfg.WriteLine("USE_POINTS        : 0");
            }
            else //By coordinates
            {
               cfg.WriteLine("EXPORT_TYPE       : 1");
               cfg.WriteLine("WATERPOINTS_NAME  : " + opts.PointsName);
               cfg.WriteLine("WATERPOINTS_GROUP : " + opts.PointsGroup);
            }

            if (opts.CheckPropertyName)
               cfg.WriteLine("CHECK_PROPERTY    : 1");
            else
               cfg.WriteLine("CHECK_PROPERTY    : 0");

            if (opts.UseStart)
               cfg.WriteLine("START_TIME        : " + opts.Start.ToString("yyyy MM dd HH mm ss"));
            if (opts.UseEnd)
               cfg.WriteLine("END_TIME          : " + opts.End.ToString("yyyy MM dd HH mm ss"));

            if (opts.Variable)
               cfg.WriteLine("VARIABLE_GRID     : 1");
            else
               cfg.WriteLine("VARIABLE_GRID     : 0");

            if (!string.IsNullOrWhiteSpace(opts.GridFile))
               cfg.WriteLine("GRID_FILENAME     : " + opts.GridFile);

            if (!string.IsNullOrWhiteSpace(opts.TimeGroup))
               cfg.WriteLine("TIME_GROUP        : " + opts.TimeGroup);

            if (!string.IsNullOrWhiteSpace(opts.DecimationFactor))
               cfg.WriteLine("DECIMATION_FACTOR : " + opts.DecimationFactor);

            foreach (TimeseriesBlock ts in opts.TimeSeries)
            {
               cfg.WriteLine("<BeginTimeSerie>");

               if (opts.Type == ExportHDFToTSType.ByMask) //by Mask
               {
                  cfg.WriteLine("  NAME              : " + file.Path + ts.Name);
                  if (!string.IsNullOrWhiteSpace(ts.MaskID))
                     cfg.WriteLine("  MASK_ID           : " + ts.MaskID);
                  if (!string.IsNullOrWhiteSpace(ts.Layer))
                     cfg.WriteLine("  LAYER             : " + ts.Layer);
               }
               else
               {
                  cfg.WriteLine("  NAME              : " + file.Path + ts.Name);
                  if (!string.IsNullOrWhiteSpace(ts.I))
                     cfg.WriteLine("  LOCALIZATION_I    : " + ts.I);
                  if (!string.IsNullOrWhiteSpace(ts.J))
                     cfg.WriteLine("  LOCALIZATION_J    : " + ts.J);
                  if (!string.IsNullOrWhiteSpace(ts.K))
                     cfg.WriteLine("  LOCALIZATION_J    : " + ts.K);
                  if (!string.IsNullOrWhiteSpace(ts.Latitude))
                     cfg.WriteLine("  LATITUDE          : " + ts.Latitude);
                  if (!string.IsNullOrWhiteSpace(ts.Longitude))
                     cfg.WriteLine("  LONGITUDE         : " + ts.Longitude);
                  if (!string.IsNullOrWhiteSpace(ts.X))
                     cfg.WriteLine("  COORD_X           : " + ts.X);
                  if (!string.IsNullOrWhiteSpace(ts.Y))
                     cfg.WriteLine("  COORD_Y           : " + ts.Y);
               }
               cfg.WriteLine("<EndTimeSerie>");
            }

            foreach (ParameterBlock p in opts.Parameters)
            {
               cfg.WriteLine("<BeginParameter>");
               cfg.WriteLine("  PROPERTY          : " + p.Name);
               cfg.WriteLine("  HDF_GROUP         : " + p.Group);
               cfg.WriteLine("<EndParameter>");
            }
            cfg.Close();

            //run HDFExporter Tool
            app.Executable = opts.PathToHDFExporter;
            app.UseShell = false;
            app.WorkingDirectory = opts.WorkingFolder;
            app.Arguments = "-c " + config_name;
            app.CheckSuccessMethod = CheckSuccessMethod.DEFAULTOUTPUT;
            app.TextToCheck = "successfully terminated";
            app.Verbose = false;
            app.Wait = true;
            app.SearchTextOrder = SearchTextOrder.FROMEND;

            AppExitStatus es;

            if ((es = app.Run(this, e)) != AppExitStatus.Finished)
            {
               if (es != AppExitStatus.Canceled)
                  MessageBox.Show("HDFExporter tool has failed.", "ATTENTION", MessageBoxButtons.OK, MessageBoxIcon.Error);
               return;
            }

            if (!opts.KeepConfigFile)
            {
               try
               {
                  System.IO.File.Delete(opts.WorkingFolder + config_name);
               }
               catch
               {
               }
            }

            if (opts.JoinTimeseries)
            {
               if (first)
               {
                  foreach (TimeseriesBlock tsb in opts.TimeSeries)
                  {
                     TimeSeries new_ts = new TimeSeries();
                     new_ts.Load(new FileName(file.Path + tsb.Name + ".ets"));
                     new_ts.Name = tsb.Name + ".ets";
                     outputTS.Add(new_ts);
                  }

                  first = false;
               }
               else
               {
                  int count = 0;
                  foreach (TimeseriesBlock tsb in opts.TimeSeries)
                  {
                     TimeSeries new_ts = new TimeSeries();
                     new_ts.Load(new FileName(file.Path + tsb.Name + ".ets"));
                     TimeSeries this_ts = outputTS[count];
                     this_ts.AddTimeSeries(new_ts);
                     new_ts = null;
                     if (!opts.KeepIntermediateTSFiles)
                     {
                        try
                        {
                           System.IO.File.Delete(file.Path + tsb.Name + ".ets");
                        }
                        catch
                        {
                        }
                     }
                     count++;
                  }
               }
            }

            if (this.WorkerReportsProgress)
            {
               filesProcessed++;
               int percentComplete = (int)((float)filesProcessed / (float)totalFiles * 100);
               this.ReportProgress(percentComplete);
            }
             }

             if (opts.JoinTimeseries)
             {
            foreach (TimeSeries ts in outputTS)
            {
               ts.Save(new FileName(new FilePath(opts.PathToOutputTimeSeries).Path + ts.Name + ".ets"));
            }
             }
        }
            public void Save(FileName file, List<int> columnsToSave, Interval interval)
            {
                //Check to see if the interval exists
                if (interval.Start < 0 || interval.Start >= instants.Count || interval.End >= instants.Count)
                   throw new Exception("Invalid Interval");

                //Check to see if the columns chosen exists
                foreach (int col in columnsToSave)
                   if (col < 0 || col >= dataColumns.Count)
                  throw new Exception("Invalid column index");

                int endRow;
                if (interval.End < 0)
                   endRow = instants.Count - 1;
                else
                   endRow = interval.End;

                TextFile ts = new TextFile(file);
                ts.OpenNewToWrite();

                string toSave;

                //Save TimeSeries Header
                ts.WriteLines(extraLines);
                ts.WriteLine("SERIE_INITIAL_DATA : " + startInstant.ToString("yyyy M d H m s"));
                ts.WriteLine("TIME_UNITS : " + timeUnits.ToString());
                toSave = timeUnits.ToString();
                foreach(int col in columnsToSave)
                   toSave += " " + dataColumns[col].Header;
                ts.WriteLine(toSave);

                //Save Data
                ts.WriteLine("<BeginTimeSerie>");
                for (int row = interval.Start; row <= endRow; row++)
                {
                   toSave = ((double)instants[row]).ToString(instants.DataFormat);
                   //Save the columns to file
                   foreach (int col in columnsToSave)
                  toSave += " " + string.Format("{0" + dataColumns[col].DataFormat + "}", dataColumns[col][row]);
                   ts.WriteLine(toSave);
                }
                ts.WriteLine("<EndTimeSerie>");

                ts.Close();
            }
            public void Load(FileName file)
            {
                string line;
                string[] seps = new string[1];
                string[] tokens;
                string[] header;

                TextFile ts = new TextFile(file);
                ts.OpenToRead();

                try
                {
                   dataColumns.Clear();
                   extraLines.Clear();
                   instants.Clear();

                   //Find Header and columns
                   while ((line = ts.ReadLine()) != null)
                   {
                  line = line.Trim();

                  if (line == "") continue;
                  if (line[0] == '!')
                  {
                     extraLines.Add(line);
                     continue;
                  }

                  seps[0] = ":";
                  tokens = line.Split(seps, 2, StringSplitOptions.RemoveEmptyEntries);

                  if (tokens[0].Trim() == "SERIE_INITIAL_DATA")
                  {
                     string[] tseps = { ".", " " };
                     string[] ttokens = tokens[1].Trim().Split(tseps, StringSplitOptions.RemoveEmptyEntries);
                     startInstant = new DateTime((int)float.Parse(ttokens[0]),
                                                 (int)float.Parse(ttokens[1]),
                                                 (int)float.Parse(ttokens[2]),
                                                 (int)float.Parse(ttokens[3]),
                                                 (int)float.Parse(ttokens[4]),
                                                 (int)float.Parse(ttokens[5])); //DateTime.ParseExact(temp, "yyyy M d H m s", null);
                  }
                  else if (tokens[0].Trim() == "TIME_UNITS")
                  {
                     timeUnits = (TimeUnits)Enum.Parse(typeof(TimeUnits), tokens[1].Trim(), true);
                  }
                  else
                  {
                     seps[0] = " ";
                     tokens = line.Trim().Split(seps, StringSplitOptions.RemoveEmptyEntries);

                     if (tokens[0].Trim() == "<BeginTimeSerie>")
                     {
                        if (extraLines.Count < 1)
                        {
                           ts.Close();
                           throw new Exception("The '" + file.FullName + "' is not a valid time series");
                        }

                        header = extraLines.Last().Trim().Split(seps, StringSplitOptions.RemoveEmptyEntries);
                        instants.Header = header[0];

                        for (int i = 1; i < header.Length; i++)
                        {
                           Column column = new Column();
                           dataColumns.Add(column);
                           column.Header = header[i];
                        }

                        extraLines.Remove(extraLines.Last());
                        break;
                     }
                     else if (tokens[0].Trim() == "<BeginResidual>")
                     {
                        while ((line = ts.ReadLine()) != null)
                        {
                           if (line.Trim() == "<EndResidual>")
                              break;
                        }

                        if (line == null)
                           throw new Exception("Invalid TimeSeries file.");
                     }
                     else
                     {
                        extraLines.Add(line);
                     }
                  }
                   }

                   int index;
                   seps[0] = " ";

                   line = ts.ReadLine();
                   if (line == null)
                  throw new Exception ("Invalid TimeSeries file.");

                   tokens = line.Trim().Split(seps, StringSplitOptions.RemoveEmptyEntries);
                   if (tokens == null)
                  throw new Exception("Invalid TimeSeries file.");

                   index = AddInstant(double.Parse(tokens[0], CultureInfo.InvariantCulture));

                   for (int i = 1; i < tokens.Length; i++)
                   {
                  dataColumns[i - 1].ColumnType = GetColumnType(tokens[i]);

                  if (dataColumns[i - 1].ColumnType == typeof(double))
                     dataColumns[i - 1][index] = double.Parse(tokens[i], CultureInfo.InvariantCulture);
                  else
                     dataColumns[i - 1][index] = tokens[i];
                   }

                   while ((line = ts.ReadLine()) != null)
                   {
                  //line = ts.ReadLine();
                  if (line == null)
                     throw new Exception("Invalid TimeSeries file.");

                  tokens = line.Trim().Split(seps, StringSplitOptions.RemoveEmptyEntries);

                  if (tokens == null)
                     throw new Exception("Invalid TimeSeries file.");

                  if (tokens[0][0] == '<')
                     break;
                  else
                  {
                     index = AddInstant(double.Parse(tokens[0], CultureInfo.InvariantCulture));

                     for (int i = 1; i < tokens.Length; i++)
                        if (dataColumns[i - 1].ColumnType == typeof(double))
                           dataColumns[i - 1][index] = double.Parse(tokens[i], CultureInfo.InvariantCulture);
                        else
                           dataColumns[i - 1][index] = tokens[i];
                  }
                   }

                   while ((line = ts.ReadLine()) != null)
                  extraLines.Add(line);

                   ts.Close();
                }
                catch
                {
                   ts.Close();
                   throw;
                }
            }
Beispiel #51
0
        static void Main(string[] args)
        {
            bool verbose = false;

             try
             {

            CmdArgs cmdArgs = new CmdArgs(args);

            if (cmdArgs.HasOption("v"))
               verbose = true;
            else
               verbose = false;

            if (cmdArgs.HasParameter("cfg"))
            {
               if (verbose)
               {
                  Console.WriteLine("");
                  Console.Write("Reading configuration file...");
               }

               Config conf = new Config(cmdArgs.Parameters["cfg"]);
               conf.Load();

               if (verbose)
                  Console.WriteLine("[OK]");

               if (verbose)
                  Console.Write("Looking for 'xyz.to.process' blocks...");

               List<ConfigNode> bkList = conf.Root.ChildNodes.FindAll(delegate(ConfigNode node) { return node.Name == "xyz.to.process"; });

               if (bkList == null || bkList.Count <= 0)
                  throw new Exception("No 'xyz.to.process' block found in configuration file.");

               if (verbose)
               {
                  Console.WriteLine("[OK]");
                  Console.WriteLine("{0} 'xyz.to.process' block(s) found.", bkList.Count);
               }

               int bkCount = 1;
               foreach (ConfigNode bk in bkList)
               {
                  if (verbose)
                     Console.Write("Processing 'xyz.to.process' block #{0}...", bkCount);

                  FileName input = bk["input.file"].AsFileName();
                  FileName output = bk["output.file"].AsFileName();
                  bool eraseNoData = bk["erase.no.data", true].AsBool();
                  double noData = -99.0;
                  if (eraseNoData)
                     noData = bk["no.data.value", -99.0].AsDouble();
                  bool applyScaleFator = bk["apply.scale.fator", true].AsBool();
                  double scaleFactor = 1.0;
                  if (applyScaleFator)
                     scaleFactor = bk["scale.factor", 1.0].AsDouble();

                  Dictionary<string, string> lookupTable = new Dictionary<string, string>();
                  List<ConfigNode> lookupTables = bk.ChildNodes.FindAll(delegate(ConfigNode node) { return node.Name == "lookup.table"; });

                  foreach (ConfigNode lt in lookupTables)
                  {
                     foreach (KeyValuePair<string, KeywordData> kp in lt.NodeData)
                        lookupTable[kp.Key] = kp.Value.AsString();
                  }

                  //Start processing XYZ
                  TextFile file_i = new TextFile(input); file_i.OpenToRead();
                  TextFile file_o = new TextFile(output); file_o.OpenNewToWrite();

                  string line_i = null;
                  string line_o = null;
                  string [] tokens;
                  string [] sep = {" "};
                  double res;
                  while ((line_i = file_i.ReadLine()) != null)
                  {
                     tokens = line_i.Split(sep, StringSplitOptions.RemoveEmptyEntries);
                     if (tokens.Length == 3)
                     {
                        foreach (KeyValuePair<string, string> kp in lookupTable)
                           if (double.Parse(tokens[2]) == double.Parse(kp.Key))
                           {
                              tokens[2] = kp.Value;
                              break;
                           }

                        res = double.Parse(tokens[2]);

                        if (eraseNoData && res == noData)
                           continue;

                        if (applyScaleFator)
                           res *= scaleFactor;

                        line_o = string.Format("{0} {1} {2}  ", tokens[0], tokens[1], res);
                     }
                     else
                        line_o = line_i;

                     file_o.WriteLine(line_o);
                  }

                  file_i.Close();
                  file_o.Close();

                  bkCount++;
                  if (verbose)
                     Console.WriteLine("[OK]");
               }
            }
             }
             catch (Exception ex)
             {
            if (verbose)
            {
               Console.WriteLine("[FAIL]");
               Console.WriteLine("");
               Console.WriteLine("An EXCEPTION was raised. The message returned was:");
               Console.WriteLine(ex.Message);
            }
             }
             if (verbose)
             {
            Console.WriteLine("Process finished.");
            Console.WriteLine("");
             }
        }
            public void Load(FileName file, bool loadHG)
            {
                TextFile f = new TextFile(file);
                string [] seps = new string[] {":", " "};
                string [] tokens;
                int i = 0, j = 0, elements = 0, pos = 0;
                string line, line_u;

                if (loadHG && HorizGrid == null)
                   HorizGrid = new MohidHorizontalGrid();

                f.OpenToRead(FileShare.Read);
                Header.Clear();

                for(;;)
                {
                   line = f.ReadLine();

                   if (line == null)
                  break;

                   line = line.Trim();

                   if (string.IsNullOrWhiteSpace(line))
                  continue;

                   line_u = line.ToUpper();

                   if (line_u == "<BEGINXX>")
                   {
                  if (loadHG)
                  {
                     pos = 0;

                     for(;;)
                     {
                        line = f.ReadLine();

                        if (line == null)
                           throw new Exception("Invalid GridData file.");

                        line = line.Trim();
                        if (line.ToUpper() == "<ENDXX>")
                           break;

                        HorizGrid.XX.Add(double.Parse(line, CultureInfo.InvariantCulture));
                        pos = pos + 1;
                     }
                  }
                   }
                   else if (line_u == "<BEGINYY>")
                   {
                  if (loadHG)
                  {
                     pos = 0;
                     for(;;)
                     {
                        line = f.ReadLine();
                        if (line == null)
                           throw new Exception("Invalid GridData file");

                        line = line.Trim();
                        if (line.ToUpper() == "<ENDYY>")
                           break;

                        HorizGrid.YY.Add(double.Parse(line, CultureInfo.InvariantCulture));
                        pos = pos + 1;
                     }
                  }
                   }
                   else if (line_u == "<BEGINGRIDDATA2D>")
                   {
                  pos = 0;
                  for(;;)
                  {
                     line = f.ReadLine();
                     if (line == null)
                        throw new Exception("Invalid GridData file.");

                     line = line.Trim();
                     if (line.ToUpper() == "<ENDGRIDDATA2D>")
                        break;

                     Data.Add(double.Parse(line, CultureInfo.InvariantCulture));
                     pos = pos + 1;
                  }
                   }
                   else
                   {
                  Header.Add(line);
                  tokens = line.ToUpper().Split(seps, StringSplitOptions.RemoveEmptyEntries);
                  switch (tokens[0])
                  {
                     case "ILB_IUB":
                        i = int.Parse(tokens[2]) - int.Parse(tokens[1]) + 1;
                        elements = i * j;
                        if (loadHG)
                        {
                           HorizGrid.ILB = int.Parse(tokens[1]);
                           HorizGrid.IUB = int.Parse(tokens[2]);
                           HorizGrid.Elements = elements;
                        }
                        break;
                     case "JLB_JUB":
                        j = int.Parse(tokens[2]) - int.Parse(tokens[1]) + 1;
                        elements = i * j;
                        if (loadHG)
                        {
                           HorizGrid.JLB = int.Parse(tokens[1]);
                           HorizGrid.JUB = int.Parse(tokens[2]);
                           HorizGrid.Elements = elements;
                        }
                        break;
                   }
                   }
                }

                f.Close();
            }
		void FindDerivedThread (object state)
		{
			monitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor (true, true);
			using (monitor) {
				IType cls = (IType) item;
				if (cls == null) return;
				
				CodeRefactorer cr = IdeApp.Workspace.GetCodeRefactorer (IdeApp.ProjectOperations.CurrentSelectedSolution);
				foreach (IType sub in cr.FindDerivedClasses (cls)) {
					if (!sub.Location.IsEmpty) {
						IEditableTextFile textFile = cr.TextFileProvider.GetEditableTextFile (sub.CompilationUnit.FileName);
						if (textFile == null) 
							textFile = new TextFile (sub.CompilationUnit.FileName);
						int position = textFile.GetPositionFromLineColumn (sub.Location.Line, sub.Location.Column);
						monitor.ReportResult (new MonoDevelop.Ide.FindInFiles.SearchResult (new FileProvider (sub.CompilationUnit.FileName, sub.SourceProject as Project), position, 0));
					}
				}
			}
		}
Beispiel #54
0
            public static int Replace(string old_file, string new_file, ref Dictionary<string, string> replace_list, bool warning_on_exception = true)
            {
                try
                {
                   TextFile input = null;
                   TextFile output = null;
                   int NumberOfChanges = 0;

                   input = new TextFile(old_file);
                   output = new TextFile(new_file);

                   input.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
                   output.Open(FileMode.Create, FileAccess.Write, FileShare.None);

                   string line = "";
                   string new_line = "";

                   line = input.ReadLine();

                   while (line != null)
                   {
                  foreach (KeyValuePair<string, string> keyPair in replace_list)
                  {
                     new_line = line.Replace(keyPair.Key, replace_list[keyPair.Key]);
                     if (new_line != line) NumberOfChanges++;
                     line = new_line;
                  }

                  output.WriteLine(line);
                  line = input.ReadLine();
                   }

                   input.Close();
                   output.Close();

                   return NumberOfChanges;
                }
                catch (Exception ex)
                {
                   if (warning_on_exception)
                   {
                  Console.WriteLine();
                  while (ex != null)
                  {
                     Console.WriteLine("=> {0}", ex.Message);
                     ex = ex.InnerException;
                  }
                  Console.WriteLine();
                   }

                   return -1;
                }
            }
Beispiel #55
0
        static int Main(string[] args)
        {
            TextFile log = null;
             CmdArgs cmd_args = null;
             Engine eng = null;
             int result = 0;
             bool debug = false;

             try
             {
            cmd_args = new CmdArgs(args);
             }
             catch (Exception ex)
             {
            Console.WriteLine("Error when trying to parse the command line arguments.");
            Console.WriteLine("The message returned was:");
            Console.WriteLine(ex.Message);
            result = -1;
             }

             if (result == 0)
            try
            {
               string log_file;
               if (cmd_args.HasParameter("log"))
               {
                  log_file = cmd_args.Parameters["log"];
               }
               else
               {
                  if (cmd_args.HasParameter("logpath"))
                     log_file = (new FilePath(cmd_args.Parameters["logpath"])).Path + "log_";
                  else
                     log_file = "log_";

                  DateTime DateNow = DateTime.Now;

                  log_file += DateNow.Year.ToString("D4") + DateNow.Month.ToString("D2") + DateNow.Day.ToString("D2") + "-" +
                              DateNow.Hour.ToString("D2") + DateNow.Minute.ToString("D2") + DateNow.Second.ToString("D2") + ".dat";

                  //Console.WriteLine("WARNING: Missing 'log' parameter.");
                  //Console.WriteLine("A log file will be created with the name:");
                  //Console.WriteLine(log_file);
               }

               log = new TextFile(log_file);
            }
            catch (Exception ex)
            {
               Console.WriteLine("Error when trying to create log file.");
               Console.WriteLine("The message returned was:");
               Console.WriteLine(ex.Message);
               result = -2;
            }

             bool verbose = false;
             if (cmd_args.HasOption("verbose")) verbose = true;

             if (cmd_args.HasOption("debug")) debug = true;

             if (result == 0)
            try
             {
               DateTime d_and_t = DateTime.Now;

               if (!cmd_args.HasParameter("cfg"))
                  throw new Exception("No configuration file was provided.");
               if (cmd_args.HasParameter("date"))
                  d_and_t = DateTime.ParseExact(cmd_args.Parameters["date"], "yyyy mm dd", CultureInfo.InvariantCulture);

               if (verbose) Console.WriteLine("Starting sms engine.");
               eng = new Engine();
               eng.Debug = debug;

               if (verbose) Console.WriteLine("Loading configuration.");
               if (!eng.LoadConfig(new Mohid.Files.FileName(cmd_args.Parameters["cfg"])))
                  throw new Exception("Error when loading the configuration file.");

               if (verbose) Console.WriteLine("Sending messages.");
               if (!eng.SendMessages(d_and_t))
                  throw new Exception("Error when trying to send the messages.");
             }
             catch (Exception ex)
             {
               Console.WriteLine("Error when trying to send messages.");
               Console.WriteLine("The exception returned was:");
               Console.WriteLine(ex.Message);
               result = -3;
             }

             if (log != null)
             {
            if (eng.HasErrors)
            {
               log.OpenNewToWrite();
               log.Write(eng.Errors);
               log.Close();
            }
             }

             return result;
        }
        bool IMohidTask.Run(ConfigNode cfg)
        {
            last_exception = null;
             this.cfg = cfg;
             bool result = true;

             if (!LoadGlobalConfig())
            return false;

             files_to_process.Clear();

             for (; ; )
             {
            if (!CreateFileList())
            {
               if (last_exception == null)
               {
                  result = true;
                  break;
               }
               else
               {
                  result = false;
                  break;
               }
            }

            if (!RunForFileList())
            {
               result = false;
               break;
            }
             }

             if (do_log && log.Length > 0)
             {
            try
            {
               if (add_date_time)
                  log_file.FullName = log_file.Name + "_" + DateTime.Now.ToString(log_dateonfile_format) + "." + log_file.Extension;

               TextFile log_f = new TextFile(log_file);
               log_f.OpenNewToWrite();

               log_f.Write(log);

               log_f.Close();
            }
            catch (Exception ex)
            {
               last_exception = ex;
               result = false;
            }
             }

             return result;
        }
		protected void Start (string test)
		{
			TargetRuntime runtime;

			switch (EngineId) {
			case "MonoDevelop.Debugger.Win32":
				runtime = Runtime.SystemAssemblyService.GetTargetRuntime ("MS.NET");
				break;
			case "Mono.Debugger.Soft":
				runtime = Runtime.SystemAssemblyService.GetTargetRuntimes ()
					.OfType<MonoTargetRuntime> ()
					.OrderByDescending ((o) => {
					//Attempt to find latest version of Mono registred in IDE and use that for unit tests
					if (string.IsNullOrWhiteSpace (o.Version) || o.Version == "Unknown")
						return new Version (0, 0, 0, 0);
					int indexOfBeforeDetails = o.Version.IndexOf (" (", StringComparison.Ordinal);
					if (indexOfBeforeDetails == -1)
						return new Version (0, 0, 0, 0);
					string hopefullyVersion = o.Version.Remove (indexOfBeforeDetails);
					Version version;
					if (Version.TryParse (hopefullyVersion, out version)) {
						return version;
					} else {
						return new Version (0, 0, 0, 0);
					}
				}).FirstOrDefault ();
				break;
			default:
				runtime = Runtime.SystemAssemblyService.DefaultRuntime;
				break;
			}

			if (runtime == null) {
				Assert.Ignore ("Runtime not found for: {0}", EngineId);
				return;
			}

			Console.WriteLine ("Target Runtime: " + runtime.DisplayRuntimeName + " " + runtime.Version);

			// main/build/tests
			FilePath path = Path.GetDirectoryName (GetType ().Assembly.Location);
			var exe = Path.Combine (path, "MonoDevelop.Debugger.Tests.TestApp.exe");

			var cmd = new DotNetExecutionCommand ();
			cmd.TargetRuntime = runtime;
			cmd.Command = exe;
			cmd.Arguments = test;

			if (Platform.IsWindows) {
				var monoRuntime = runtime as MonoTargetRuntime;
				if (monoRuntime != null) {
					var psi = new System.Diagnostics.ProcessStartInfo (Path.Combine (monoRuntime.Prefix, "bin", "pdb2mdb.bat"), cmd.Command);
					psi.UseShellExecute = false;
					psi.CreateNoWindow = true;
					System.Diagnostics.Process.Start (psi).WaitForExit ();
				}
			}

			var dsi = engine.CreateDebuggerStartInfo (cmd);
			var soft = dsi as SoftDebuggerStartInfo;

			if (soft != null) {
				var assemblyName = AssemblyName.GetAssemblyName (exe);

				soft.UserAssemblyNames = new List<AssemblyName> ();
				soft.UserAssemblyNames.Add (assemblyName);
			}

			Session = engine.CreateSession ();
			var ops = new DebuggerSessionOptions ();
			ops.ProjectAssembliesOnly = true;
			ops.EvaluationOptions = EvaluationOptions.DefaultOptions;
			ops.EvaluationOptions.AllowTargetInvoke = AllowTargetInvokes;
			ops.EvaluationOptions.EvaluationTimeout = 100000;

			path = path.ParentDirectory.ParentDirectory.Combine ("src", "addins", "MonoDevelop.Debugger", "MonoDevelop.Debugger.Tests.TestApp", test + ".cs").FullPath;
			SourceFile = TextFile.ReadFile (path);
			TestName = test;
			AddBreakpoint ("break");
			
			var done = new ManualResetEvent (false);

			Session.TargetHitBreakpoint += (sender, e) => {
				Frame = e.Backtrace.GetFrame (0);
				lastStoppedPosition = Frame.SourceLocation;
				targetStoppedEvent.Set ();
				done.Set ();
			};

			Session.TargetExceptionThrown += (sender, e) => {
				Frame = e.Backtrace.GetFrame (0);
				for (int i = 0; i < e.Backtrace.FrameCount; i++) {
					if (!e.Backtrace.GetFrame (i).IsExternalCode) {
						Frame = e.Backtrace.GetFrame (i);
						break;
					}
				}
				lastStoppedPosition = Frame.SourceLocation;
				targetStoppedEvent.Set ();
			};

			Session.TargetStopped += (sender, e) => {
				//This can be null in case of ForcedStop
				//which is called when exception is thrown
				//when Continue & Stepping is executed
				if (e.Backtrace != null) {
					Frame = e.Backtrace.GetFrame (0);
					lastStoppedPosition = Frame.SourceLocation;
					targetStoppedEvent.Set ();
				} else {
					Console.WriteLine ("e.Backtrace is null");
				}
			};

			var targetExited = new ManualResetEvent (false);
			Session.TargetExited += delegate {
				targetExited.Set ();
			};

			Session.Run (dsi, ops);
			Session.ExceptionHandler = (ex) => {
				Console.WriteLine ("Session.ExceptionHandler:" + Environment.NewLine + ex.ToString ());
				return true;
			};
			switch (WaitHandle.WaitAny (new WaitHandle[]{ done, targetExited }, 30000)) {
			case 0:
				//Breakpoint is hit good... run tests now
				break;
			case 1:
				throw new Exception ("Test application exited before hitting breakpoint");
			default:
				throw new Exception ("Timeout while waiting for initial breakpoint");
			}
			if (Session is SoftDebuggerSession) {
				Console.WriteLine ("SDB protocol version:" + ((SoftDebuggerSession)Session).ProtocolVersion);
			}
		}
 public static void ConfigurePlan(TextFile textFile, TemplatePlan plan)
 {
     var ignores = textFile.ReadLines().Where(x => x.IsNotEmpty()).ToArray();
     var step = new GitIgnoreStep(ignores);
     plan.Add(step);
 }
Beispiel #59
0
        static void Main(string[] args)
        {
            string stepMessage = "";
             List<ConfigNode> timeseries, parameters;
             List<string> cfg = new List<string>();
             List<string> blocks = new List<string>();
             DateTime start, end, actual;
             FilePath root;
             bool hasFolders;
             TextFile config, errors;
             string hdfTag;
             FileName hdf5EXE = new FileName();
             FilePath workingFolder = new FilePath();
             FilePath tsPath;
             Dictionary<string, TimeSeries> outTS = new Dictionary<string, TimeSeries>();
             TimeSeries newTS = new TimeSeries();
             List<string> failedPeriods = new List<string>();
             int count_to_save;
             bool use_year_on_path;
             bool join_time_series;
             string startFormat, endFormat, folderFormat;

             errors = new TextFile("errors.log");
             errors.OpenNewToWrite();
             count_to_save = 0;

             try
             {
            stepMessage = "command line arguments loading.";
            CmdArgs cmdArgs = new CmdArgs(args);

            if (cmdArgs.HasParameter("cfg"))
            {
               stepMessage = "configuration file loading.";
               Config conf = new Config(cmdArgs.Parameters["cfg"]);
               conf.Load();

               stepMessage = "configuration file parsing.";
               ConfigNode tsc = conf.Root.ChildNodes.Find(delegate(ConfigNode node) { return node.Name == "timeseries.to.extract"; });

               if (tsc == null)
                  throw new Exception("block 'timeseries.to.extract' is missing.");

               start = tsc["start.date"].AsDateTime();
               end = tsc["end.date"].AsDateTime();
               hdfTag = tsc["hdf.tag"].AsString();
               hdf5EXE = tsc["exporter.exe"].AsFileName();
               workingFolder = tsc["exporter.working"].AsFilePath();
               tsPath = tsc["timeseries.output.path"].AsFilePath();
               //root = tsc["root", ".\\"].AsFilePath();
               hasFolders = tsc["has.folders", true].AsBool();
               use_year_on_path = tsc["use.year.on.path", true].AsBool();
               join_time_series = tsc["join.timeseries", true].AsBool();
               folderFormat = tsc["folder.format", "{start}_{end}"].AsString();
               startFormat = tsc["start.format", "yyyyMMddHH"].AsString();
               endFormat = tsc["end.format", "yyyyMMddHH"].AsString();

               blocks.Add("EXPORT_TYPE      : " + tsc["export.type", 1].AsString());
               blocks.Add("COMPUTE_RESIDUAL : " + tsc["compute.residual", 0].AsString());
               blocks.Add("VARIABLE_GRID    : " + tsc["variable.grid", 0].AsString());
               blocks.Add("WATERPOINTS_NAME : " + tsc["points.name", "WaterPoints2D"].AsString());
               blocks.Add("GRID_FILENAME    : " + tsc["grid.name", "grid.dat"].AsString());
               blocks.Add("");

               timeseries = tsc.ChildNodes.FindAll(delegate(ConfigNode node) { return node.Name == "timeseries"; });
               if (timeseries.Count < 1)
                  throw new Exception("Block 'timeseries' is missing. There must be at least one.");

               //Creates the blocks of timeseries
               foreach (ConfigNode n in timeseries)
               {
                  blocks.Add("<BeginTimeSerie>");
                  blocks.Add("  NAME    : " + n["name"].AsString());
                  blocks.Add("  COORD_Y : " + n["y"].AsString());
                  blocks.Add("  COORD_X : " + n["x"].AsString());
                  blocks.Add("<EndTimeSerie>");
                  blocks.Add("");

                  outTS[n["name"].AsString()] = new TimeSeries();
                  if (System.IO.File.Exists(tsPath.Path + n["name"].AsString() + ".ets"))
                  {
                     outTS[n["name"].AsString()].Load(new FileName(tsPath.Path + n["name"].AsString() + ".ets"));
                  }
               }

               parameters = tsc.ChildNodes.FindAll(delegate(ConfigNode node) { return node.Name == "parameters"; });
               if (parameters.Count < 1)
                  throw new Exception("Block 'parameters' is missing. There must be at least one.");

               //Creates the blocks of parameters
               foreach (ConfigNode n in parameters)
               {
                  blocks.Add("<BeginParameter>");
                  blocks.Add("  HDF_GROUP : " + n["group"].AsString());
                  blocks.Add("  PROPERTY  : " + n["property"].AsString());
                  blocks.Add("<EndParameter>");
                  blocks.Add("");
               }

               config = new TextFile();
               config.File.FullPath = workingFolder.Path + "HDF5Exporter.dat";

               bool quit = false;
               actual = start;
               FilePath yearFolder = new FilePath();
               ExternalApp hdf5exporter = new ExternalApp();
               hdf5exporter.CheckSuccessMethod = CheckSuccessMethod.DEFAULTOUTPUT;
               hdf5exporter.TextToCheck = "Program HDF5Exporter successfully terminated";
               hdf5exporter.Wait = true;
               hdf5exporter.WorkingDirectory = workingFolder.Path;
               hdf5exporter.Executable = hdf5EXE.FullPath;

               FilePath wp = workingFolder;
               List<FileInfo> tsList = new List<FileInfo>();
               bool failed, res;
               do
               {
                  failed = false;
                  if (use_year_on_path)
                     yearFolder.Path = root.Path + actual.Year.ToString();
                  else
                     yearFolder.Path = root.Path;

                  if (FileTools.FolderExists(yearFolder))
                  {
                     if (System.IO.File.Exists(yearFolder.Path + hdfTag + actual.ToString("yyyyMMddHH") + "_" + actual.AddHours(5).ToString("yyyyMMddHH") + ".hdf5"))
                     {
                        config.OpenNewToWrite();

                        cfg.Clear();
                        cfg.Add("");
                        cfg.Add("START_TIME : " + actual.ToString("yyyy M d H m s"));
                        cfg.Add("END_TIME   : " + actual.AddHours(5).ToString("yyyy M d H m s"));
                        cfg.Add("");
                        cfg.Add("<BeginHDF5File>");
                        cfg.Add("  NAME : " + yearFolder.Path + hdfTag + actual.ToString("yyyyMMddHH") + "_" + actual.AddHours(5).ToString("yyyyMMddHH") + ".hdf5");
                        cfg.Add("<EndHDF5File>");
                        cfg.Add("");
                        config.WriteLines(cfg);
                        config.WriteLines(blocks);

                        config.Close();

                        //executes HDF5Exporter
                        try
                        {
                           Console.Write("Running HDF5Exporter to file " + hdfTag + actual.ToString("yyyyMMddHH") + "_" + actual.AddHours(5).ToString("yyyyMMddHH") + ".hdf5 ...");
                           res = hdf5exporter.Run();
                           if (!res)
                           {
                              errors.WriteLine("Unsuccessfull HDF5Exporter run on file '" + hdfTag + actual.ToString("yyyyMMddHH") + "_" + actual.AddHours(5).ToString("yyyyMMddHH") + ".hdf5'");
                              failed = true;
                              Console.WriteLine("[Failed]");
                           }
                           else
                           {
                              Console.WriteLine("[OK]");
                           }
                        }
                        catch(Exception e_run)
                        {
                           errors.WriteLine("HDF5Exporter Run Exception on file '" + hdfTag + actual.ToString("yyyyMMddHH") + "_" + actual.AddHours(5).ToString("yyyyMMddHH") + ".hdf5'");
                           errors.WriteLine("Exception returned this message: " + e_run.Message);
                           failed = true;
                           Console.WriteLine("[Exception]");
                        }

                        if (!failed)
                        {
                           FileTools.FindFiles(ref tsList, wp, "*.ets", true, "", System.IO.SearchOption.TopDirectoryOnly);
                           foreach (FileInfo file in tsList)
                           {
                              if (outTS[file.FileName.Name].NumberOfInstants > 0)
                              {
                                 try
                                 {
                                    newTS.Load(file.FileName);
                                    //outTS.Load(new FileName(tsPath.Path + file.FileName.FullName));
                                    outTS[file.FileName.Name].AddTimeSeries(newTS);
                                 }
                                 catch
                                 {
                                    errors.WriteLine("Was not possible to read timeseries '" + file.FileName + "' from HDF file '" + hdfTag + actual.ToString("yyyyMMddHH") + "_" + actual.AddHours(5).ToString("yyyyMMddHH") + ".hdf5'");
                                 }
                                 //outTS.Save(new FileName(tsPath.Path + file.FileName.FullName));
                                 System.IO.File.Delete(file.FileName.FullPath);
                              }
                              else
                              {
                                 //FileTools.CopyFile(file.FileName, new FileName(tsPath.Path + file.FileName.FullName), CopyOptions.OVERWRIGHT);
                                 //outTS[file.FileName.Name].Load(new FileName(tsPath.Path + file.FileName.FullName));

                                 outTS[file.FileName.Name].Load(file.FileName);
                                 System.IO.File.Delete(file.FileName.FullPath);
                              }
                           }

                           count_to_save++;
                           if (count_to_save >= 60)
                           {
                              count_to_save = 0;
                              foreach (FileInfo file in tsList)
                              {
                                 Console.Write("Saving Timeseries '" + file.FileName.Name + "' ...");
                                 try
                                 {
                                    outTS[file.FileName.Name].Save(new FileName(tsPath.Path + file.FileName.Name + ".ets"));
                                    Console.WriteLine("[OK]");
                                    FileTools.CopyFile(new FileName(tsPath.Path + file.FileName.Name + ".ets"), new FileName((new FilePath(tsPath.Path + "bkp")).Path + file.FileName.Name + ".ets"), CopyOptions.OVERWRIGHT);
                                 }
                                 catch(Exception e_run)
                                 {
                                    Console.WriteLine("[FAILED]");
                                    errors.WriteLine("Was not possible to save timeseries '" + file.FileName.Name + ".ets'");
                                    errors.WriteLine("Exception returned this message: " + e_run.Message);
                                 }
                              }
                           }
                        }
                     }
                  }

                  actual = actual.AddHours(6);
                  if (actual >= end)
                     quit = true;
               }
               while (!quit);

               foreach (KeyValuePair<string, TimeSeries> pair in outTS)
               {
                  pair.Value.Save(new FileName(tsPath.Path + pair.Key + ".ets"));
               }

               //TimeUnits timeUnits = (TimeUnits)Enum.Parse(typeof(TimeUnits), conf.Root["time.units", "seconds"].AsString(), true);

               //   List<FileName> list = new List<FileName>();
               //   foreach (KeyValuePair<string, KeywordData> item in nodeList.NodeData)
               //      list.Add(item.Value.AsFileName());

               //   if (list.Count <= 1)
               //      throw new Exception("Block 'timeseries.to.join' must contain at least 2 entries");

               //   stepMessage = "loading timeseries.";
               //   List<TimeSeries> timeSeries = new List<TimeSeries>();

               //   foreach (FileName ts in list)
               //   {
               //      TimeSeries newTS = new TimeSeries();
               //      newTS.Load(ts);
               //      timeSeries.Add(newTS);
               //   }

               //   start = timeSeries[0].StartInstant;
               //   for (int i = 1; i < timeSeries.Count; i++)
               //   {
               //      if (timeSeries[i].StartInstant < start)
               //         start = timeSeries[i].StartInstant;
               //   }

               //   stepMessage = "creating output timeseries.";
               //   TimeSeries outTS = new TimeSeries();
               //   outTS.StartInstant = start;
               //   outTS.TimeUnits = timeUnits;

               //   foreach (Column col in timeSeries[0].Columns)
               //   {
               //      Column newCol = new Column(col.ColumnType);
               //      newCol.Header = col.Header;
               //      outTS.AddColumn(newCol);
               //   }

               //   foreach (TimeSeries toJoin in timeSeries)
               //      outTS.AddTimeSeries(toJoin);

               //   stepMessage = "saving output timeseries.";
               //   outTS.Save(outputFileName);

               //   Console.WriteLine("Process complete with success.");
               //}
               //else
               //{
               //   Console.WriteLine("Parameter --cfg is missing.");
               //   Console.WriteLine("Execution aborted.");
               //   return;
               //}
            }
             }
             catch (Exception ex)
             {
            Console.WriteLine("An exception was raised while {0}", stepMessage);
            Console.WriteLine("Exception message: {0}", ex.Message);
             }

             errors.Close();
        }
Beispiel #60
0
        private static Packet DemoPicture()
        {
            var uri = new Uri("blackfin.png", UriKind.Relative);
            var image = new BitmapImage(uri);

            var text = new TextFile('A') {{"<picture B/>", DisplayMode.Rotate}};
            var pic = new PictureFile('B', image, ColorFormat.Monochrome);

            var files = new FileTable {
                text, pic,
            };

            var packet = new Packet();
            packet.SetMemory(files);
            packet.Add(new WriteTextCommand(text));
            packet.Add(new WritePictureCommand(pic));
            return packet;
        }