Ejemplo n.º 1
0
		public static VirtualFile OpenAsFormat(Stream baseStream, string filename, int offset = 0, int length = -1, FileFormat format = FileFormat.None, CacheMethod m = CacheMethod.Default) {
			if (length == -1) length = (int)baseStream.Length;
			if (format == FileFormat.None) {
				format = GuessFormat(filename);
				logger.Debug("Guessed format: {0}", format);
			}
		
			switch (format) {
				case FileFormat.Csf:
					return new CsfFile(baseStream, filename, offset, length, m != CacheMethod.NoCache); // defaults to cache
				case FileFormat.Hva:
					return new HvaFile(baseStream, filename, offset, length, m != CacheMethod.NoCache); // defaults to not cache
				case FileFormat.Ini:
					return new IniFile(baseStream, filename, offset, length, m != CacheMethod.NoCache);
				case FileFormat.Missions:
					return new MissionsFile(baseStream, filename, offset, length, m != CacheMethod.NoCache);
				case FileFormat.Mix:
					return new MixFile(baseStream, filename, offset, length, m == CacheMethod.Cache);
				case FileFormat.Pal:
					return new PalFile(baseStream, filename, offset, length, m != CacheMethod.NoCache);
				case FileFormat.Pkt:
					return new PktFile(baseStream, filename, offset, length, m != CacheMethod.NoCache);
				case FileFormat.Shp:
					return new ShpFile(baseStream, filename, offset, length, m != CacheMethod.NoCache);
				case FileFormat.Tmp:
					return new TmpFile(baseStream, filename, offset, length, m != CacheMethod.NoCache);
				case FileFormat.Vpl:
					return new VplFile(baseStream, filename, offset, length, m != CacheMethod.NoCache);
				case FileFormat.Vxl:
					return new VxlFile(baseStream, filename, offset, length, m != CacheMethod.NoCache);
				case FileFormat.Ukn:
				default:
					return new VirtualFile(baseStream, filename, offset, length, m != CacheMethod.NoCache);
			}
		}
Ejemplo n.º 2
0
        public HfzFile loadFile(string fileName, FileFormat format)
        {
            HfzFile file = new HfzFile();

            Stream fs = null;
            EndianBinaryReader reader = null;
            try
            {
                debugLine("File format: " + format + ", file name: " + fileName);
                //create a file stream to work with during load
                fs = Util.openStream(fileName, format, FileMode.Open);
                reader = Util.createEndianBinaryReaderForStream(fs);

                HfzHeader header = hfzReadHeader(reader);
                file.header = header;
                Dictionary<short, HfzTile> tiles = readTiles(header, reader);
                file.mapData = tiles;
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                reader.Close();
                if (debug)
                {
                    writeLog.Close();
                }
            }

            return file;
        }
Ejemplo n.º 3
0
        public AmfFile loadFile(string fileName, FileFormat format)
        {
            Stream fs = null;
            EndianBinaryReader reader = null;
            try
            {
                debugLine("File format: " + format + ", file name: " + fileName);
                fs = Util.openStream(fileName, format, FileMode.Open);
                reader = Util.createEndianBinaryReaderForStream(fs);

                AmfFile file = readAmfFile(reader);
                return file;
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
Ejemplo n.º 4
0
        public void saveFile(string fileName, FileFormat format, AmfFile file)
        {
            Stream fs = null;
            EndianBinaryWriter writer = null;
            try
            {
                debugLine("File format: " + format + ", file name: " + fileName);
                fs = Util.openStream(fileName, format, FileMode.Create);
                writer = Util.createEndianBinaryWriterForStream(fs);

                writeAmfFile(writer, file);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    if (format == FileFormat.COMPRESSED)
                    {
                        Util.compressFile(fileName);
                    }
                }
            }
        }
Ejemplo n.º 5
0
 public Asset(SNOGroup group, Int32 snoId, string name)
 {
     this.Data = null;
     this.Group = group;
     this.SNOId = snoId;
     this.Name = name;
     this.FileName = group + "\\" + this.Name + FileExtensions.Extensions[(int)group];
 }
Ejemplo n.º 6
0
    public DdsSaveConfig(FileFormat fileFormat, int compressorType, int errorMetric, bool weightColorByAlpha, bool generateMipMaps) {
      FileFormat = fileFormat;

      CompressorType = compressorType;
      ErrorMetric    = errorMetric;

      WeightColorByAlpha = weightColorByAlpha;
      GenerateMipMaps    = generateMipMaps;
    }
Ejemplo n.º 7
0
 public void UpdateFile(short webFileID, FileFormat fileFormat)
 {
     InvokeSafeSingleCall(() => {
         var f = SiteFileStore.DataSource.GetByKey(webFileID);
         f.DateupDatedutc = DateTime.UtcNow;
         f.Fileformat = fileFormat;
         f.Save();
         return f.ID;
     }, default(short));
 }
Ejemplo n.º 8
0
        private void Load()
        {
            if (!MPQStorage.CoreData.AssetFormats.ContainsKey(this.Group)) return;
            var formatType = MPQStorage.CoreData.AssetFormats[this.Group];
            
            var file = MPQStorage.CoreData.FileSystem.FindFile(this.FileName);
            if (file == null || file.Size < 10) return;

            this.Data = (FileFormat) Activator.CreateInstance(formatType, new object[] {file});
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Gets file format.
        /// </summary>
        /// <param name="fileFormat">Select <see cref="FileFormat"/>.</param>
        /// <returns>Proper file format as <see cref="string"/>.</returns>
        public static string Get(FileFormat fileFormat)
        {
            switch (fileFormat)
            {
                case FileFormat.Generic:
                    return "YYYYMMHH";
            }

            return string.Empty;
        }
Ejemplo n.º 10
0
        public void DownloadAudioAsync(AudioInformation audioInformation, FileFormat format, AudioBitrate bitrate, string destinationFileName)
        {
            if (!audioInformation.IsAvailableInFormatAndBitrate(format, bitrate))
                throw new QualityNotAvailableException();
            
            audioInProgress = audioInformation;

            var downloadLink = audioInformation.GetDownloadURL(format, bitrate);
            webClient.DownloadFileAsync(new Uri(downloadLink), destinationFileName);
        }
        /// <summary>
        /// Occurs before an action is executed
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            FileFormat format = GetFileFormat(filterContext.HttpContext.Request.Path);
            if (IsDisallowed(format))
            {
                throw new ArgumentException("Requested format has been disallowed");
            }

            RequestedFormat = format;
        }
Ejemplo n.º 12
0
 /// <summary>
 /// 获取文件类型格式扩展名字符串
 /// </summary>
 /// <param name="fileFormat">格式枚举</param>
 /// <returns>扩展名字符串</returns>
 public static string GetFileFormat(FileFormat fileFormat)
 {
     switch (fileFormat) {
         case FileFormat.JPG:
             return ".jpg";
         case FileFormat.PNG:
             return ".png";
         default:
             return string.Empty;
     }
 }
Ejemplo n.º 13
0
 public short GetNextFileID(FileFormat imageFormat)
 {
     return InvokeSafeSingleCall(() => {
         var f = new SiteFileStore {
             Accesscount = default(int),
             Fileformat = imageFormat
         };
         f.Save();
         return f.ID;
     }, default(short));
 }
Ejemplo n.º 14
0
        /// <summary>
        /// The get.
        /// </summary>
        /// <param name="fileFormat">
        /// The file format.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string Get(FileFormat fileFormat)
        {
            switch (fileFormat)
            {
                case FileFormat.Generic:
                    // 20140101 000200;1.30111;1.309610;1.306350;1.306455;10
                    return @"^(?<date>\d{8}) (?<time>\d{6});(?<open>[0-9]*\.?[0-9]+);(?<high>[0-9]*\.?[0-9]+);(?<low>[0-9]*\.?[0-9]+);(?<close>[0-9]*\.?[0-9]+);(?<vol>[0-9]*\.?[0-9]+)";
            }

            return string.Empty;
        }
Ejemplo n.º 15
0
        public Asset(SNOGroup group, Int32 snoId, byte[] name)
        {
            this.Data = null;
            this.Group = group;
            this.SNOId = snoId;
            int count = 0; while (count < 128 && name[count] != 0) count++;
            this.Name = Encoding.UTF8.GetString(name.Take(count).ToArray());
            this.FileName = group + "\\" + this.Name + FileFormats.FileExtensions.Extensions[(int)group];                        

            this.Load();
        }
Ejemplo n.º 16
0
 // Constructor
 public FileReader(string path)
 {
     // Init instance vars
     reading = false;
     clip = null;
     this.path = path;
     path = path.ToLower();
     if (path.EndsWith(".wav")) this.format = FileFormat.WAV;
     else if (path.EndsWith(".mp3")) this.format = FileFormat.MPEG;
     else if (path.EndsWith(".ogg")) this.format = FileFormat.OGG;
     else if (path.EndsWith(".ryt")) this.format = FileFormat.RYT;
     else this.format = FileFormat.ERROR;
     readDataPointer = 0;
 }
Ejemplo n.º 17
0
        private async Task<StorageFile> WriteableBitmapToStorageFile(WriteableBitmap wb, FileFormat fileFormat)
        {
            string FileName = "MyFile.";
            Guid BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
            switch (fileFormat)
            {
                case FileFormat.Jpeg:
                    FileName += "jpeg";
                    BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
                    break;

                case FileFormat.Png:
                    FileName += "png";
                    BitmapEncoderGuid = BitmapEncoder.PngEncoderId;
                    break;

                case FileFormat.Bmp:
                    FileName += "bmp";
                    BitmapEncoderGuid = BitmapEncoder.BmpEncoderId;
                    break;

                case FileFormat.Tiff:
                    FileName += "tiff";
                    BitmapEncoderGuid = BitmapEncoder.TiffEncoderId;
                    break;

                case FileFormat.Gif:
                    FileName += "gif";
                    BitmapEncoderGuid = BitmapEncoder.GifEncoderId;
                    break;
            }

            var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);
            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);
                Stream pixelStream = wb.PixelBuffer.AsStream();
                byte[] pixels = new byte[pixelStream.Length];
                await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                                    (uint)wb.PixelWidth,
                                    (uint)wb.PixelHeight,
                                    96.0,
                                    96.0,
                                    pixels);
                await encoder.FlushAsync();
            }
            return file;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Вернуть класс сохраняюший EPROM устройства в указанном формате
        /// </summary>
        /// <param name="format">Формат в котором неоходимо сохранить EPROM устройства</param>
        /// <returns>Класс, выполняющий сохранение EPROM в файл</returns>
        public static IEFSaver CreateSaver(FileFormat format)
        {
            switch (format)
            {
                case FileFormat.EF1TXT:

                    return new EF1TXTSaver();

                case FileFormat.EF2XML:

                    return new EF2XMLSaver();

            }
            return null;
        }
        public void RunExport(List<Item> itemsToExport, List<ID> fieldsToExport, string fileName, FileFormat format)
        {
            if (itemsToExport.Count > 0 && fieldsToExport.Count > 0)
            {
                ImportExportManager.GenerateFile(itemsToExport, fieldsToExport, fileName, format);

                JobStatus status = Sitecore.Context.Job.Status;

                status.State = JobState.Finished;
            }
            else
            {

            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Возвращает загрузчик EPROM для указанного формата файла
        /// </summary>
        /// <param name="format">Формат в котором хранится EPROM устройства</param>
        /// <returns>Загрузчик для указанного формата</returns>
        public static IEFLoader CreateLoader(FileFormat format)
        {
            switch (format)
            {
                case FileFormat.EF1TXT:

                    return new EF1TXTLoader();

                case FileFormat.EF2XML:

                    return new EF2XMLLoader();

                case FileFormat.EF2XMLOLD:

                    return new EF2XMLOLDLoader();
            }
            return null;
        }
        /// <summary>
        /// Archives a file, zipping it up and moving it or just moving it based on the passed in params. Also removes the un-zipped file from the file system
        /// </summary>
        /// <param name="sourcePath">Absolute path to the source file including file name</param>
        /// <param name="destinationPath">Path to the directory that source file will be archived to</param>
        /// <param name="zip">Set this to true if the file you are archiving needs to be zipped</param>
        /// <param name="format">Enum based</param>
        /// <param name="tempFolder"></param>
        /// <returns>Bool</returns>
        public static bool Archive(string sourcePath, string destinationPath, bool zip, FileFormat format, string tempFolder)
        {
            if (zip)
            {
                if (!S3FileExists(sourcePath))
                    throw new FileNotFoundException(String.Format("File {0} does not exist.", sourcePath));

                // zip and if successful, delete the unzipped source file
                var file = new FileInfo(sourcePath);
                var tempFile = tempFolder + Guid.NewGuid().ToString() + ".zip";
                var zipSuccess = zipFile(sourcePath, tempFile);
                if (zipSuccess)
                {
                    try
                    {
                        using (var zipStream = new FileStream(tempFile, FileMode.Open, FileAccess.Read))
                        {

                            CopyFileToS3Archive(destinationPath, zipStream, file.Name.Replace(file.Extension, ".zip"), tempFolder);
                            DeleteS3File(sourcePath);
                            return true;
                        }
                    }
                    finally
                    {
                        if (File.Exists(tempFile))
                            File.Delete(tempFile);
                    }


                }

            }
            using (var fileStream = GetS3File(sourcePath))
                if (fileStream != null)
                {
                    var file = new FileInfo(sourcePath);
                    CopyFileToS3Archive(destinationPath, fileStream, file.Name, tempFolder);
                    DeleteS3File(sourcePath);
                    return true;
                }
            throw new FileNotFoundException(String.Format("File {0} does not exist.", sourcePath));
        }
Ejemplo n.º 22
0
        public void saveFile(string fileName, FileFormat format, HfzFile file)
        {
            HfzHeader fh = validateHeader(file);

            // initiate the writing procedure
            EndianBinaryWriter fileWriter = null;

            try
            {
                // open file for writing
                Stream stream = Util.openStream(fileName, format, FileMode.Create);
                fileWriter = Util.createEndianBinaryWriterForStream(stream);

                hfzWriteHeader(ref fileWriter, fh);

                // writing tiles
                List<short> keys = file.getTileKeys();
                foreach (short key in keys)
                {
                    hfzWriteTile(ref fileWriter, fh, file.getTileData(key));
                }

                fileWriter.Close();
            }
            catch(Exception ex)
            {
                throw new Exception("Error writing file " + fileName, ex);
            }
            finally
            {
                // close file
                if (fileWriter != null)
                {
                    fileWriter.Close();
                    if (format == FileFormat.COMPRESSED)
                    {
                        Util.compressFile(fileName);
                    }
                }
            }
        }
        public static bool LoadFromFile(FileFormat fileFormat, string path, int startingRow, int rowsLimit, out TimeSpan period, out List<BarData> datas)
        {
            datas = null;
            period = TimeSpan.Zero;
            if (fileFormat == FileFormat.CVSDefault)
            {
                LoadFromFileCSV(path, startingRow, rowsLimit, out datas);
            }
            else
            {
                return false;
            }

            // Find out what is the most oftenly occuring period - use it (for ex. consider weekends, holidays).
            SortedDictionary<double, int> periodOccurences = new SortedDictionary<double, int>();

            for (int i = 1; i < datas.Count; i++)
            {
                TimeSpan timeInterval = datas[i].DateTime - datas[i - 1].DateTime;
                if (periodOccurences.ContainsKey(timeInterval.TotalMinutes) == false)
                {
                    periodOccurences.Add(timeInterval.TotalMinutes, 1);
                }
                else
                {
                    periodOccurences[timeInterval.TotalMinutes]++;
                }
            }

            int totalOccurences = 0;
            foreach (double periodMinutes in periodOccurences.Keys)
            {// Keep going looking for the period with most occurences.
                if (periodOccurences[periodMinutes] > totalOccurences)
                {
                    period = TimeSpan.FromMinutes(periodMinutes);
                    totalOccurences = periodOccurences[periodMinutes];
                }
            }

            return true;
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Prepares a text description which is compatible with 'rtpsend' among other 'rtp tools'.
        /// </summary>
        /// <param name="format">The <see cref="FileFormat"/> to output.</param>
        /// <param name="packets">The <see cref="Rtcp.RtcpPacket"/>'s to describe</param>
        /// <param name="time">Timeoffset from when recoding began, should be 0 for the first packet.</param>
        /// <param name="source">The <see cref="System.Net.IPEndPoint"/> from which the packet was received.</param>
        /// <returns>The text which describes the packet if the <paramref name="format"/> is a text format, otherwise an empty string</returns>
        public static string ToTextualConvention(FileFormat format, IEnumerable<Rtcp.RtcpPacket> packets, TimeSpan time, System.Net.IPEndPoint source)
        {
            //Short form does not allow Rtcp, Binary Formats have no textual convention.
            if (packets == null || format == FileFormat.Short || format <= FileFormat.Dump) return string.Empty;

            //Store the hex payload in one builder
            StringBuilder hexPayload = format == FileFormat.Hex ? new StringBuilder(64) : null;

            //And the overall result in another
            StringBuilder builder = new StringBuilder(64);

            int totalLength = 0;

            foreach (Rtcp.RtcpPacket packet in packets)
            {
                //Build the Expression of the packet given as an individual expression
                //(T=>)
                builder.Append(RtpSend.ToTextualConvention(format, packet));

                //Increment for totalLength
                totalLength += packet.Length;

                if (format == FileFormat.Hex)
                    hexPayload.Append(BitConverter.ToString(packet.Payload.ToArray()).Replace("-", string.Empty));
            }

            //Insert the header
            builder.Insert(0, string.Format(RtpSend.Format,
                //0
                time.TotalSeconds.ToString("0.000000"),
                //1
                string.Format(RtpSend.RtcpPacketFormat,
                //0
                    totalLength,
                //1
                    source.Address.ToString() + ':' + source.Port.ToString())));

            //hex dump
            if (format == FileFormat.Hex)
                if (totalLength > 0) builder.Append(string.Format(HexFormat, "data", hexPayload, (char)Common.ASCII.LineFeed));
                else builder.Append(string.Format(HexFormat, "data", NullSpecifier, (char)Common.ASCII.LineFeed));

            //Return the allocated result
            return builder.ToString();
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Save a Microsoft Word document as PDF
 /// </summary>
 /// <param name="filename"></param>
 /// <param name="format"></param>
 public void SaveWordDocumentAs(String filename, FileFormat format)
 {
     switch (format) {
         case FileFormat.PDF:
             SaveWordDocumentAsPdf(filename);
             break;
         case FileFormat.HTML:
             break;
         case FileFormat.TXT:
             break;
         case FileFormat.DOC:
             break;
         case FileFormat.DOCX:
             break;
         case FileFormat.RTF:
             break;
     }
 }
Ejemplo n.º 26
0
        public void Initialise()
        {
            Simulations basicFile = Utilities.GetRunnableSim();

            IModel simulation = basicFile.FindInScope <Simulation>();
            IModel paddock    = basicFile.FindInScope <Zone>();

            // Add a weather component.
            Models.Climate.Weather weather = new Models.Climate.Weather();
            weather.Name     = "Weather";
            weather.FileName = "asdf.met";
            Structure.Add(weather, simulation);

            // Add a second weather component.
            Models.Climate.Weather weather2 = new Models.Climate.Weather();
            weather2.FileName = "asdf.met";
            weather2.Name     = "Weather2";
            Structure.Add(weather2, simulation);

            // Add a third weather component.
            Models.Climate.Weather weather3 = new Models.Climate.Weather();
            weather3.FileName = "asdf.met";
            weather3.Name     = "Weather3";
            Structure.Add(weather3, simulation);

            // Add a third weather component.
            Models.Climate.Weather weather4 = new Models.Climate.Weather();
            weather4.FileName = "asdf.met";
            weather4.Name     = "Weather4";
            Structure.Add(weather4, simulation);

            // Add a report.
            Models.Report report = new Models.Report();
            report.Name = "Report";
            Structure.Add(report, paddock);

            // Add the wheat model.
            string json  = ReflectionUtilities.GetResourceAsString(typeof(IModel).Assembly, "Models.Resources.Wheat.json");
            Plant  wheat = FileFormat.ReadFromString <IModel>(json, out _).Children[0] as Plant;

            wheat.ResourceName = "Wheat";
            Structure.Add(wheat, paddock);

            Manager manager = new Manager();

            manager.Code = @"using Models.PMF;
using Models.Core;
using System;
namespace Models
{
    [Serializable]
    public class Script : Model
    {
        [Description(""an amount"")]
        public double Amount { get; set; }
    }
}";
            Structure.Add(manager, paddock);

            Physical physical = new Physical();

            physical.BD     = new double[5];
            physical.AirDry = new double[5];
            physical.LL15   = new double[5];
            Structure.Add(physical, paddock);

            basicFile.Write(basicFile.FileName);
            fileName = basicFile.FileName;

            // Create a new .apsimx file containing two weather nodes.
            Simulations test = Utilities.GetRunnableSim();
            IModel      sim  = test.FindInScope <Simulation>();

            Models.Climate.Weather w1 = new Models.Climate.Weather();
            w1.FileName = "w1.met";
            w1.Name     = "w1";
            Structure.Add(w1, sim);

            Models.Climate.Weather w2 = new Models.Climate.Weather();
            w2.Name     = "w2";
            w2.FileName = "w2.met";
            Structure.Add(w2, sim);

            extFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".apsimx");
            test.Write(extFile);
        }
Ejemplo n.º 27
0
        public void TestEditing()
        {
            string configFile = Path.GetTempFileName();

            File.WriteAllLines(configFile, new[]
            {
                // Modify an array
                "[Report].VariableNames = x,y,z",

                // Modify a date - try a few different formats.
                "[Clock].StartDate = 2000-01-01",
                "[Clock].EndDate = 2000-01-10T00:00:00",

                // Modify a string
                "[Weather].FileName = fdsa.met",
                @"[Weather2].FullFileName = .\jkl.met",

                // Replace a model with a model from another file.
                $"[Weather3] = {extFile}",
                $"[Weather4] = {extFile};[w2]",
            });

            string models = typeof(IModel).Assembly.Location;
            string args   = $"{fileName} /Edit {configFile}";

            var proc = new ProcessUtilities.ProcessWithRedirectedOutput();

            proc.Start(models, args, Path.GetTempPath(), true, true);
            proc.WaitForExit();

            // Children of simulation are, in order:
            // Clock, summary, zone, Weather, Weather2, w1, w2

            Assert.AreEqual(null, proc.StdOut);
            Assert.AreEqual(null, proc.StdErr);

            Simulations file = FileFormat.ReadFromFile <Simulations>(fileName, out List <Exception> errors);

            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            var report = Apsim.Find(file, typeof(Models.Report)) as Models.Report;

            string[] variableNames = new[] { "x", "y", "z" };
            Assert.AreEqual(variableNames, report.VariableNames);

            IModel sim = Apsim.Child(file, typeof(Simulation));

            // Use an index-based lookup to locate child models.
            // When we replace an entire model, we want to ensure
            // that the replacement is inserted at the correct index.

            Clock clock = sim.Children[0] as Clock;

            Assert.AreEqual(new DateTime(2000, 1, 1), clock.StartDate);
            Assert.AreEqual(new DateTime(2000, 1, 10), clock.EndDate);

            var weather = sim.Children[3] as Models.Weather;

            Assert.NotNull(weather);
            Assert.AreEqual("Weather", weather.Name);
            Assert.AreEqual("fdsa.met", weather.FileName);

            var weather2 = sim.Children[4] as Models.Weather;

            Assert.NotNull(weather2);
            Assert.AreEqual("Weather2", weather2.Name);
            Assert.AreEqual(@".\jkl.met", weather2.FileName);

            // Weather3 and Weather4 should have been
            // renamed to w1 and w2, respectively.
            var weather3 = sim.Children[5] as Models.Weather;

            Assert.NotNull(weather3);
            Assert.AreEqual("w1", weather3.Name);
            Assert.AreEqual("w1.met", weather3.FileName);

            var weather4 = sim.Children[6] as Models.Weather;

            Assert.NotNull(weather4);
            Assert.AreEqual("w2", weather4.Name);
            Assert.AreEqual("w2.met", weather4.FileName);
        }
Ejemplo n.º 28
0
        public void TestManagerParameterChanges()
        {
            Manager m = new Manager()
            {
                Name = "Manager",
                Code = "using System; namespace Models { using Core; [Serializable] public class Script : Models.Core.Model { [Description(\"x\")] public string X { get; set; } } }"
            };
            Simulations sims = new Simulations()
            {
                Children = new List <IModel>()
                {
                    new DataStore(),
                    new Experiment()
                    {
                        Name     = "expt",
                        Children = new List <IModel>()
                        {
                            new Factors()
                            {
                                Children = new List <IModel>()
                                {
                                    new Factor()
                                    {
                                        Name          = "x",
                                        Specification = "[Manager].Script.X = 1"
                                    }
                                }
                            },
                            new Simulation()
                            {
                                Name     = "sim",
                                Children = new List <IModel>()
                                {
                                    new Clock()
                                    {
                                        StartDate = new DateTime(2020, 1, 1),
                                        EndDate   = new DateTime(2020, 1, 2),
                                        Name      = "Clock"
                                    },
                                    new Summary(),
                                    m
                                }
                            }
                        }
                    }
                }
            };

            sims.ParentAllDescendants();
            m.OnCreated();
            Runner runner = new Runner(sims);
            string temp   = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            try
            {
                IEnumerable <string> files = GenerateApsimXFiles.Generate(runner, 1, temp, _ => {});
                Assert.AreEqual(1, files.Count());
                string file = files.First();
                sims = FileFormat.ReadFromFile <Simulations>(file, e => throw e, false);
                Assert.AreEqual("1", sims.FindByPath("[Manager].Script.X").Value);
            }
            finally
            {
                if (Directory.Exists(temp))
                {
                    Directory.Delete(temp, true);
                }
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Export the
        /// </summary>
        /// <param name="ToFile"></param>
        /// <param name="listSections"></param>
        /// <param name="outputFormat"></param>
        public static void Export(string toFile, UltraGrid grid, ExportSectionList listSections, FileFormat outputFormat)
        {
            // Create the report itself
            Report report = new Report();

            // ...then the sections for header, footer and body
            ISection mainSection = report.AddSection();

            mainSection.PageMargins = new Infragistics.Documents.Reports.Report.Margins(50);
            ISectionHeader headerSection = mainSection.AddHeader();

            headerSection.Height = 50;
            headerSection.Repeat = true;
            ISectionFooter footerSection = mainSection.AddFooter();

            footerSection.Height = 50;

            // Add the body of the report which is the contents of the grid
            UltraGridDocumentExporter exporter = new UltraGridDocumentExporter();

            exporter.Export(grid, mainSection);

            // Setup the page numbering
            PageNumbering pn = mainSection.PageNumbering;

            // The Template property is the actual string that shows the page numbering. Use the [Page #] place-
            // holder for the current page and the [TotalPages] place-holder for the total amount of pages in
            // the entire document.
            pn.Template = "Page [Page #] of [TotalPages]";

            // Setting SkipFirst to true does not place page numbering on the first page of the section. This
            // is useful if the first page is a Title page.
            pn.SkipFirst = false;

            // The page numbering will be aligned with the right side of the page. Valid values off the
            // Alignment enum include Left, Center, and Right.
            pn.Alignment.Horizontal = Alignment.Right;

            // The page numbering will be located at the bottom of the page. Valid values off the
            // Alignment enum include Top and Bottom.
            pn.Alignment.Vertical = Alignment.Bottom;

            // The page numbering is at the extreme bottom of the page, so we need to change the Y Offset
            // in order to bring it in line with the rest of the page footer text.
            pn.OffsetY = -18;

            // Delete the old report if it exists
            try
            {
                if (File.Exists(toFile))
                {
                    File.Delete(toFile);
                }
            }
            catch (Exception)
            {
                //Ignore any errors
            }

            // Generate the report
            try
            {
                report.Generate();
                report.Publish(toFile, outputFormat);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to write the export file " + toFile + ", the error was " + ex.Message);
            }
        }
Ejemplo n.º 30
0
		public ObjectWriter (XmlDocument doc, FileFormat format)
		{
			this.doc = doc;
			this.format = format;
		}
Ejemplo n.º 31
0
        // -------- вернуть загрузчика -------

        public IEFLoader GetEFLoader(FileFormat format)
        {
            return(EFLoader.CreateLoader(format));
        }
Ejemplo n.º 32
0
 /// <summary>
 /// 文档加载后的处理
 /// </summary>
 /// <param name="format">加载文档的格式</param>
 public virtual void AfterLoad(FileFormat format)
 {
 }
Ejemplo n.º 33
0
            internal void AddSubRecord(string name, string description, bool required, FileFormat format)
            {
                SubRecords.Add((this._name, $"{this._name}_{name}"));
                var p = new Field($"{this._name}_{name}", name)
                {
                    Modifiers = Modifiers.Public
                };

                if (required)
                {
                    p.Modifiers |= Modifiers.ReadOnly;
                    p.Value      = $"new {this._name}_{name}()";
                }

                this._genClass.Members.Add(p);

                if (required)
                {
                    this._constructorRead.Body.AppendLine(
                        $"this.{name} = this.Fields.First(x => x.Type == {this._name}_{name}.FieldType) as {this._name}_{name};");
                    this._getSubRecordsForWriting.Body.AppendLine($"ret.Add(this.{name});");
                }
                else
                {
                    this._constructorRead.Body.AppendLine(
                        $"this.{name} = this.Fields.FirstOrDefault(x => x.Type == {this._name}_{name}.FieldType) as {this._name}_{name};");
                    this._getSubRecordsForWriting.Body.AppendLine($"if(this.{name} != null) ret.Add(this.{name});");
                }

                this.AddSubRecordNoField(name, description, required, format);
            }
Ejemplo n.º 34
0
 internal override Class259 vmethod_9(FileFormat fileFormat)
 {
     return((Class259) new DxfDimensionObjectContextData.Class313((DxfHandledObject)this));
 }
Ejemplo n.º 35
0
 public override TargetFrameworkMoniker GetDefaultTargetFrameworkForFormat(FileFormat format)
 {
     return(new TargetFrameworkMoniker("4.0"));
 }
Ejemplo n.º 36
0
 public override bool SupportsFormat(FileFormat format)
 {
     return(format.Id == "MSBuild10");
 }
Ejemplo n.º 37
0
        //Move to RtpSendExtensions?
        /// <summary>
        /// Parses the data contained in the given <see cref="System.IO.BinaryReader"/> for data which corresponds to a format compatible with <see href="http://www.cs.columbia.edu/irt/software/rtptools/#rtpsend">rtpsend</see>.
        /// If a Binary format is encoutered (by the presence of the "#!rtpplay1.0" file header then <see cref="RtpTools.RtpDump.RtpDumpExtensions.ReadBinaryToolEntry"/> will be called implicitly with the reader given,
        /// In such a case, unexpected will contain the data which matched the file header.
        /// </summary>
        /// <param name="reader">The <see cref="System.IO.BinaryReader"/> which should be created using <see cref="System.Text.Encoding.ASCII"/></param>
        /// <param name="format">The format found while parsing the description.</param>
        /// <param name="unexpected">Will only contain data if format was unknown, and contains the data encountered in the stream while attempting to parse.</param>
        /// <returns>The item which was created as a result of reading from the stream.</returns>
        internal static RtpToolEntry ParseText(System.IO.BinaryReader reader, System.Net.IPEndPoint source, ref FileFormat format, out byte[] unexpected)
        {
            unexpected = null;

            double timeOffset = 0;

            System.Net.IPEndPoint sourceInfo = source;

            long position = reader.BaseStream.Position;

            Common.IPacket builtPacket = null;

            //Keep track of making a Rtp or Rtcp entry.
            bool rtp = false;

            Rtp.RtpPacket rtpP = null;

            Rtcp.RtcpPacket rtcP = null;

            ///<summary>
            /// each entry starts with a time value, in seconds, relative to the beginning of the trace.
            /// The time value must appear at the beginning of a line, without white space. Within an RTP or RTCP packet description,
            /// parameters may appear in any order, without white space around the equal sign.
            /// Lines are continued with initial white space on the next line.
            /// Comment lines start with #. Strings are enclosed in quotation marks.
            /// <see cref="Tokens"/>
            ///</summary>

            //The amount of tokens consumed from the reader, where a token is defined as above
            int tokensParsed = -1,

            //The amount of bytes read
            lineBytesLength = 0,

            //Used for token parsing, the index of the recognized token in 'Tokens'
            tokenIndex = -1;

            //Indicates if in a comment
            bool parsingCommentOrWhitespace = false;

            //Contains the data read from the stream until '\n' occurs.
            byte[] lineBytes;

            //Indicates if the parsing of the entry is complete
            bool doneParsing = false, formatUnknown = format == FileFormat.Unknown, needAnyToken = true;

            //A string instance which was used to compare to known `Tokens`
            string token;

            //No bytes have actually been consumed from the stream yet, while not done parsing and not at the end of the stream
            while (!doneParsing && reader.BaseStream.Position < reader.BaseStream.Length)
            {
                //Determine the following character (ASCIIEncoding SHOULD have been specified in creation of the reader) [If not could possibly have also found out without consuming a byte here]
                int peek = reader.PeekChar();

                //If no data can be read
                if (peek == -1)
                {
                    //then indiate an unknown format and then return null
                    format = FileFormat.Unknown;
                    return null;
                }
                else if (peek == RtpDump.RtpDumpExtensions.Hash || peek == (char)Common.ASCII.Space)
                {
                    //Comment lines start with # (Hash). Strings are enclosed in quotation marks.
                    parsingCommentOrWhitespace = true;

                    //Could be a binary format however....
                }
                else if (tokensParsed > 0 && peek == 'r' || peek == Common.ASCII.R) //Don't read any further a new entry follows (Could be a malformed entry with rXXX=YYY\n)
                {
                    //doneParsing = true;
                    break;
                }

                //Read until '\n' occurs
                RtpSendExtensions.ReadLineFeed(reader.BaseStream, out lineBytes);

                //Keep track of the amount of bytes read
                lineBytesLength = lineBytes.Length;

                //If nothing was read return
                if (lineBytesLength == 0) return null;

                //If the format is unknown then
                if (formatUnknown)
                {
                    //check for the Binary format at the known ordinal, if found
                    if (lineBytesLength > 2 && lineBytes[0] == RtpDump.RtpDumpExtensions.Hash && lineBytes[1] == RtpDump.RtpDumpExtensions.Bang)
                    {
                        //Indicate a binary format so far
                        format = FileFormat.Binary;

                        //give the `unexpected` data back to the caller, which consisted of the header
                        unexpected = lineBytes;

                        //Remove the reference to the token now
                        token = null;

                        //Return the result of reading the binary entry.
                        return null;
                    }

                    //Check for the short form before parsing a token

                    //Search for '='

                    tokenIndex = Array.IndexOf<byte>(lineBytes, Common.ASCII.EqualsSign);

                    //If not found then this must be a Short entry.
                    if (tokenIndex == -1)
                    {
                        //No longer unknown because,
                        formatUnknown = false;

                        //This seems to be Short format
                        format = FileFormat.Short;
                    }
                    else //There was a '=' sign
                    {
                        //No longer still unknown because,
                        //This seems to be a Text format
                        format = FileFormat.Text;

                        //but we need to consume tokens until data in tokens as they occur to be sure
                    }
                }

                //If not found then this must be a Short entry.
                if (format == FileFormat.Short) return RtpToolEntry.CreateShortEntry(DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(timeOffset)), sourceInfo, lineBytes, 0, position);
                else if (parsingCommentOrWhitespace)//If parsing a whitespace or a comment
                {
                    //Not parsing the comment / whitespace any more
                    parsingCommentOrWhitespace = false;

                    //Perform another iteration
                    continue;
                }
                else if (needAnyToken) //If a token is needed
                {

                    //Extract all tokens from the lineBytes
                    string[] tokens = Encoding.ASCII.GetString(lineBytes).Split((char)Common.ASCII.Space, (char)Common.ASCII.EqualsSign, '(', ')');

                    //Any hex data will need a length, and we start at offset 0.
                    int dataLen = 0, tokenOffset = 0;

                    //If nothing was tokenized then return the unexpected data.
                    if (tokens.Length == 0)
                    {
                        unexpected = lineBytes;
                        return null;
                    }

                    //The first token must be a timeOffset
                    if (timeOffset == 0) timeOffset = double.Parse(tokens[tokenOffset++]);

                    //For each token in the tokens after the timeOffset
                    for (int e = tokens.Length; tokenOffset < e; ++tokenOffset)
                    {
                        //Get the token at the index
                        token = tokens[tokenOffset];

                        //Determine what to do based on if there was a matching token in the Tokens array.
                        tokenIndex = Array.IndexOf<string>(Tokens, token);

                        //The entry must be finished.
                        if (-1 == tokenIndex)
                        {
                            unexpected = lineBytes;
                            break;
                        }

                        //Increment for a token parsed within the entry so far
                        ++tokensParsed;

                        //Switch out logic based on token
                        switch (tokenIndex)
                        {
                            //RTP
                            case 1:
                                {
                                    //The created structure will have a packetLength = 8 + dataLen
                                    rtp = true;

                                    rtpP = new Rtp.RtpPacket(0, false, false, Media.Common.MemorySegment.EmptyBytes);

                                    builtPacket = rtpP;

                                    //Do another iteration
                                    continue;
                                }
                            //RTCP
                            case 17:
                                {

                                    rtcP = new Rtcp.RtcpPacket(0, 0, 0, 0, 0, 0);

                                    //The created structure will have packetLen = 0 to indicate Rtcp.
                                    builtPacket = rtcP;

                                    //Do another iteration

                                    continue;
                                }
                            case 35: //from
                                {

                                    string[] parts = tokens[++tokenOffset].Split((char)Common.ASCII.Colon);

                                    System.Net.IPAddress ip = System.Net.IPAddress.Parse(parts[0]);

                                    int port = int.Parse(parts[1]);

                                    System.Diagnostics.Debug.WriteLine(ip + " " + port);

                                    sourceInfo = new System.Net.IPEndPoint(ip, port);

                                    continue;
                                }
                            case 2:
                                {
                                    //version

                                    int version = int.Parse(tokens[++tokenOffset]);

                                    System.Diagnostics.Debug.WriteLine(version);

                                    if (rtp) rtpP.Header.Version = version;
                                    else rtcP.Header.Version = version;

                                    continue;
                                }
                            case 3: //p
                                {
                                    int paddingCount = int.Parse(tokens[++tokenOffset]);

                                    System.Diagnostics.Debug.WriteLine(paddingCount);

                                    break;
                                }
                            case 4: //x
                                {
                                    if (rtp)
                                    {
                                        bool hasExtension = int.Parse(tokens[++tokenOffset]) == 1;

                                        System.Diagnostics.Debug.WriteLine(hasExtension);

                                        rtpP.Header.Extension = hasExtension;
                                    }

                                    break;
                                }
                            case 5: //m
                                {
                                    if (rtp)
                                    {
                                        bool hasMarker = int.Parse(tokens[++tokenOffset]) == 1;

                                        System.Diagnostics.Debug.WriteLine(hasMarker);

                                        rtpP.Header.Marker = hasMarker;
                                    }
                                    break;
                                }
                            case 6: //pt
                                {

                                    int payloadType = int.Parse(tokens[++tokenOffset]);

                                    System.Diagnostics.Debug.WriteLine(payloadType);

                                    if (rtp) rtpP.Header.PayloadType = payloadType;
                                    else rtcP.Header.PayloadType = payloadType;

                                    break;
                                }
                            case 7: //ts
                                {
                                    if (rtp)
                                    {
                                        int ts = int.Parse(tokens[++tokenOffset]);

                                        System.Diagnostics.Debug.WriteLine(ts);

                                        rtpP.Header.Timestamp = ts;
                                    }

                                    break;
                                }
                            case 8: //seq
                                {
                                    if (rtp)
                                    {
                                        int seq = int.Parse(tokens[++tokenOffset]);

                                        System.Diagnostics.Debug.WriteLine(seq);

                                        rtpP.Header.SequenceNumber = seq;
                                    }
                                    break;
                                }
                            case 9: //ssrc
                                {

                                    token = tokens[++tokenOffset];

                                    token = token.Remove(token.Length - 1).Replace(HexSpecifier, string.Empty);

                                    int ssrc = 0;

                                    if (!int.TryParse(token, out ssrc)) //plain int
                                        ssrc = int.Parse(token, System.Globalization.NumberStyles.HexNumber);//hex

                                    System.Diagnostics.Debug.WriteLine(ssrc);

                                    if (rtp) rtpP.Header.SynchronizationSourceIdentifier = ssrc;
                                    else rtcP.Header.SendersSynchronizationSourceIdentifier = ssrc;

                                    break;
                                }
                            case 10: //cc
                                {

                                    int cc = int.Parse(tokens[++tokenOffset]);

                                    System.Diagnostics.Debug.WriteLine(cc);

                                    if (rtp) rtpP.Header.ContributingSourceCount = cc;
                                    else rtcP.Header.BlockCount = cc;

                                    break;
                                }
                            case 11: //csrc
                                {

                                    int csrc = int.Parse(tokens[++tokenOffset]);

                                    System.Diagnostics.Debug.WriteLine(csrc);

                                    //Add to a list.

                                    break;
                                }
                            case 12://data
                                {
                                    //Token based reading may not be required anymore
                                    needAnyToken = false;

                                    //Not unknown anymore because,
                                    formatUnknown = false;

                                    //Definitely hex format
                                    format = FileFormat.Hex;

                                    //The next token is the string in hex format of the payload.
                                    ++tokenIndex;

                                    //If it begins with Hash then its NIL

                                    //Done parsing the entry.
                                    doneParsing = true;

                                    continue;
                                }
                            case 13: //ext_type
                                {

                                    int ext_type = int.Parse(tokens[++tokenOffset]);

                                    System.Diagnostics.Debug.WriteLine(ext_type);

                                    break;
                                }
                            case 14: //ext_len
                                {

                                    int ext_len = int.Parse(tokens[++tokenOffset]);

                                    System.Diagnostics.Debug.WriteLine(ext_len);

                                    break;
                                }
                            case 15: //ext_data
                                {

                                    //The next token is the string in hex format of the payload.

                                    ++tokenIndex;

                                    //If it begins with Hash then its NIL

                                    break;
                                }
                            case 16: //len
                                {
                                    dataLen = int.Parse(tokens[++tokenOffset]);

                                    System.Diagnostics.Debug.WriteLine(dataLen);

                                    continue;
                                }
                            default:
                                {
                                    //If the format was unknown
                                    if (formatUnknown)
                                    {
                                        //It is no longer so because,
                                        formatUnknown = false;

                                        //it is no longer unknown, it is definitely a Text format
                                        format = FileFormat.Text;
                                    }

                                    break;
                                }
                        }//Done determining what to do with a token
                    }//Done with tokens
                }//Don't need to parse any tokens

            }

            //Create the resulting entry with the data contained in memory read from the reader by the writer
            return new RtpToolEntry(DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(timeOffset)), sourceInfo, builtPacket, (int)timeOffset, position);
        }
Ejemplo n.º 38
0
 public OperationRepairLayers(FileFormat slicerFile) : base(slicerFile)
 {
 }
Ejemplo n.º 39
0
 protected override int GetSize(FileFormat fmt)
 {
     return((fmt.IsPS2) ? 0x80 : 0x88);
 }
Ejemplo n.º 40
0
        public static async Task <bool> HasFormat(this ILocalFileInfoRepository localFileInfoRepository, FilePath filePath, FileFormat fileFormat)
        {
            var itemfileFormat = await localFileInfoRepository.GetFileFormat(filePath);

            var output = fileFormat == itemfileFormat;

            return(output);
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="toFile">Name of the file to export to</param>
        /// <param name="headerText">Main Header text</param>
        /// <param name="subheadingText">Sub-heading text</param>
        /// <param name="footerText">footer text</param>
        /// <param name="grid">Grid View to export</param>
        /// <param name="outputFormat">Output format</param>
        public static void Export(String toFile
                                  , String headerText
                                  , String subheadingText
                                  , String footerText
                                  , UltraGrid grid
                                  , FileFormat outputFormat)
        {
            // Create the report itself
            Report report = new Report();

            // ...then the sections for header, footer and body
            ISection mainSection = report.AddSection();

            mainSection.PageMargins = new Infragistics.Documents.Reports.Report.Margins(50);
            ISectionHeader headerSection = mainSection.AddHeader();

            headerSection.Height = 50;
            headerSection.Repeat = true;

            // Add a footer for page numbering
            ISectionFooter footerSection = mainSection.AddFooter();

            // Create place-holder for header text
            Infragistics.Documents.Reports.Report.Text.IText headerTextSection = headerSection.AddText(0, 0);

            // ...and add the header in to this section, centralized
            headerTextSection.AddContent(headerText);
            headerTextSection.Alignment.Horizontal = Alignment.Center;
            headerTextSection.Alignment.Vertical   = Alignment.Middle;

            // Set style for the header
            Infragistics.Documents.Reports.Report.Text.Style HeaderStyle = new Infragistics.Documents.Reports.Report.Text.Style(new Infragistics.Documents.Reports.Graphics.Font("Verdana", 10, Infragistics.Documents.Reports.Graphics.FontStyle.Underline), Infragistics.Documents.Reports.Graphics.Brushes.DarkBlue);
            headerTextSection.Style = HeaderStyle;

            // Add in a sub-heading if required
            if (subheadingText != null && subheadingText != "")
            {
                headerTextSection = headerSection.AddText(0, 20);
                Infragistics.Documents.Reports.Report.Text.Style subHeaderStyle = new Infragistics.Documents.Reports.Report.Text.Style(new Infragistics.Documents.Reports.Graphics.Font("Verdana", 8, Infragistics.Documents.Reports.Graphics.FontStyle.Underline), Infragistics.Documents.Reports.Graphics.Brushes.DarkBlue);
                headerTextSection.Style = subHeaderStyle;
                headerTextSection.AddContent(subheadingText);
            }

            // Add the body of the report which is the contents of the grid
            UltraGridDocumentExporter exporter = new UltraGridDocumentExporter();

            exporter.Export(grid, mainSection);

            //-------------------------
            // Setup Footer content
            //-------------------------
            footerSection.Height = 50;

            // Do we have a footer to display?
            if (footerText != null && footerText != "")
            {
                // Create place-holder for footer text
                Infragistics.Documents.Reports.Report.Text.IText footerTextSection = footerSection.AddText(0, 0);

                // ...and add the footer text in to this section, left aligned
                footerTextSection.Alignment.Horizontal = Alignment.Left;
                footerTextSection.Alignment.Vertical   = Alignment.Top;

                // Set style for the text
                Infragistics.Documents.Reports.Report.Text.Style footerStyle = new Infragistics.Documents.Reports.Report.Text.Style(new Infragistics.Documents.Reports.Graphics.Font("Verdana", 6, Infragistics.Documents.Reports.Graphics.FontStyle.Underline), Infragistics.Documents.Reports.Graphics.Brushes.DarkBlue);
                footerTextSection.Style = footerStyle;

                // ...and set the text itself
                footerTextSection.AddContent(footerText);
            }

            PageNumbering pn = mainSection.PageNumbering;

            // The Template property is the actual string that shows the page numbering. Use the [Page #] place-
            // holder for the current page and the [TotalPages] place-holder for the total amount of pages in
            // the entire document.
            pn.Template = "Page [Page #] of [TotalPages]";

            // Setting SkipFirst to true does not place page numbering on the first page of the section. This
            // is useful if the first page is a Title page.
            pn.SkipFirst = false;

            // The page numbering will be aligned with the right side of the page. Valid values off the
            // Alignment enum include Left, Center, and Right.
            pn.Alignment.Horizontal = Alignment.Right;

            // The page numbering will be located at the bottom of the page. Valid values off the
            // Alignment enum include Top and Bottom.
            pn.Alignment.Vertical = Alignment.Bottom;

            // The page numbering is at the extreme bottom of the page, so we need to change the Y Offset
            // in order to bring it in line with the rest of the page footer text.
            pn.OffsetY = -18;

            // Delete the old report if it exists
            try
            {
                if (File.Exists(toFile))
                {
                    File.Delete(toFile);
                }
            }
            catch (Exception)
            {
                //Ignore any errors
            }

            // Generate the report
            try
            {
                report.Generate();
                report.Publish(toFile, outputFormat);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to write the export file " + toFile + ", the error was " + ex.Message);
            }
        }
Ejemplo n.º 42
0
 public OutputDescriptor(TextWriter writer, FileFormat format, Type dataType)
 {
     Writer   = writer;
     Format   = format;
     DataType = dataType;
 }
Ejemplo n.º 43
0
        public void RunDirectoryOfFiles()
        {
            var simulations = new Simulations()
            {
                Name     = "Simulations",
                Version  = Converter.LatestVersion,
                Children = new List <IModel>()
                {
                    new Simulation()
                    {
                        Name     = "Sim1",
                        FileName = Path.GetTempFileName(),
                        Children = new List <IModel>()
                        {
                            new Clock()
                            {
                                StartDate = new DateTime(1980, 1, 1),
                                EndDate   = new DateTime(1980, 1, 2)
                            },
                            new Summary()
                        }
                    },
                    new DataStore(),
                }
            };

            // Create a temporary directory.
            var path = Path.Combine(Path.GetTempPath(), "RunDirectoryOfFiles");

            if (Directory.Exists(path))
            {
                Directory.Delete(path, true);
            }
            Directory.CreateDirectory(path);

            File.WriteAllText(Path.Combine(path, "Sim1.apsimx"), FileFormat.WriteToString(simulations));

            simulations.Children[0].Name = "Sim2";
            File.WriteAllText(Path.Combine(path, "Sim2.apsimx"), FileFormat.WriteToString(simulations));

            var runner = new Runner(Path.Combine(path, "*.apsimx"));

            runner.Run();

            // Check simulation 1 database
            database = new SQLite();
            database.OpenDatabase(Path.Combine(path, "Sim1.db"), readOnly: true);

            Assert.IsTrue(
                Utilities.CreateTable(new string[]                      { "Message" },
                                      new List <object[]> {
                new object[] { "Simulation terminated normally" }
            })
                .IsSame(database.ExecuteQuery("SELECT [Message] FROM _Messages")));

            database.CloseDatabase();

            // Check simulation 2 database
            database = new SQLite();
            database.OpenDatabase(Path.Combine(path, "Sim2.db"), readOnly: true);
            Assert.IsTrue(
                Utilities.CreateTable(new string[]                      { "Message" },
                                      new List <object[]> {
                new object[] { "Simulation terminated normally" }
            })
                .IsSame(database.ExecuteQuery("SELECT [Message] FROM _Messages")));

            database.CloseDatabase();
        }
Ejemplo n.º 44
0
        private void OnGUI()
        {
            Camera camera = null;

            renderCamera = EditorGUILayout.ObjectField("Render Camera", renderCamera, typeof(Camera), true) as Camera;

            if (renderCamera == null)
            {
                if (SceneView.lastActiveSceneView != null)
                {
                    camera = SceneView.lastActiveSceneView.camera;
                    EditorGUILayout.HelpBox("If you don't choose a render camera, the scene camera will be used. It is recommended to use a real camera", MessageType.Warning);
                }
                else
                {
                    EditorGUILayout.HelpBox("No valid cameras found to render, please assign a camera or open a scene view", MessageType.Warning);
                    return;
                }
            }
            else
            {
                camera = renderCamera;
            }

            var renderTexture = camera.targetTexture;

            fileFileFormat = (FileFormat)EditorGUILayout.EnumPopup("Format", fileFileFormat);
            if (fileFileFormat == FileFormat.JPEG)
            {
                RenderJPEGOptions();
            }

            textureFormat = (TextureFormat)EditorGUILayout.EnumPopup("Texture Format", textureFormat);

            EditorGUILayout.BeginHorizontal();
            width  = EditorGUILayout.IntField("Width", width);
            height = EditorGUILayout.IntField("Height", height);
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.Space();
            nameRendersByDate = EditorGUILayout.ToggleLeft("Name Renders By Date", nameRendersByDate);
            if (nameRendersByDate)
            {
                lastPath = EditorGUILayout.TextField("Output Directory", lastPath);
                if (GUILayout.Button("Choose Path"))
                {
                    lastPath = EditorUtility.OpenFolderPanel(
                        "Select Directory",
                        string.IsNullOrEmpty(lastPath) ? Application.dataPath : lastPath, "Screenshots");
                }
            }

            EditorGUILayout.Space();
            if (GUILayout.Button("Render"))
            {
                string path = "";
                if (nameRendersByDate)
                {
                    path  = lastPath + "/Render_" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss");
                    path += fileFileFormat == FileFormat.PNG ? ".png" : ".jpeg";
                }
                else
                {
                    var currentObj = Selection.activeObject;
                    var filename   = currentObj == null ? "Render" : currentObj.name;
                    filename = filename.ToLower().Replace(' ', '_');

                    path = EditorUtility.SaveFilePanel(
                        "Save as",
                        string.IsNullOrEmpty(lastPath) ? Application.dataPath : lastPath,
                        filename,
                        fileFileFormat == FileFormat.PNG ? "png" : "jpeg");

                    lastPath = path;
                }

                Debug.Log("Outputting to: " + path);
                Debug.Log("Last Path: " + lastPath);

                if (string.IsNullOrEmpty(path))
                {
                    return;
                }

                var texture   = camera.RenderToTexture(width, height, textureFormat);
                var imageData = fileFileFormat == FileFormat.PNG ? texture.EncodeToPNG() : texture.EncodeToJPG(jpegQuality);
                File.WriteAllBytes(path, imageData);
                DestroyImmediate(texture);

                AssetDatabase.Refresh();
            }
        }
Ejemplo n.º 45
0
        public void TestEditing()
        {
            string configFile = Path.GetTempFileName();

            File.WriteAllLines(configFile, new[]
            {
                // Modify an array
                "[Report].VariableNames = x,y,z",

                // Modify a date - try a few different formats.
                "[Clock].StartDate = 2000-01-01",
                "[Clock].EndDate = 2000-01-10T00:00:00",

                // Modify a string
                "[Weather].FileName = fdsa.met",
                @"[Weather2].FullFileName = jkl.met",

                // Replace a model with a model from another file.
                $"[Weather3] = {extFile}",
                $"[Weather4] = {extFile};[w2]",

                // Change a property of a resource model.
                "[Wheat].Leaf.Photosynthesis.RUE.FixedValue = 0.4",

                // Change a property of a manager script.
                "[Manager].Script.Amount = 1234",

                // Set an entire array.
                "[Physical].BD = 1, 2, 3, 4, 5",

                // Modify a single element of an array.
                "[Physical].AirDry[2] = 6",

                // Modify multiple elements of an array.
                "[Physical].LL15[3:4] = 7",
            });

            string models = typeof(IModel).Assembly.Location;
            string args   = $"{fileName} /Edit {configFile}";

            var proc = new ProcessUtilities.ProcessWithRedirectedOutput();

            proc.Start(models, args, Path.GetTempPath(), true, writeToConsole: true);
            proc.WaitForExit();

            // Children of simulation are, in order:
            // Clock, summary, zone, Weather, Weather2, w1, w2
            Assert.AreEqual(null, proc.StdOut);
            Assert.AreEqual(null, proc.StdErr);

            Simulations file = FileFormat.ReadFromFile <Simulations>(fileName, out List <Exception> errors);

            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            var report = file.FindInScope <Models.Report>();

            string[] variableNames = new[] { "x", "y", "z" };
            Assert.AreEqual(variableNames, report.VariableNames);

            IModel sim = file.FindChild <Simulation>();

            // Use an index-based lookup to locate child models.
            // When we replace an entire model, we want to ensure
            // that the replacement is inserted at the correct index.

            Clock clock = sim.Children[0] as Clock;

            Assert.AreEqual(new DateTime(2000, 1, 1), clock.StartDate);
            Assert.AreEqual(new DateTime(2000, 1, 10), clock.EndDate);

            var weather = sim.Children[3] as Models.Climate.Weather;

            Assert.NotNull(weather);
            Assert.AreEqual("Weather", weather.Name);
            Assert.AreEqual("fdsa.met", weather.FileName);

            var weather2 = sim.Children[4] as Models.Climate.Weather;

            Assert.NotNull(weather2);
            Assert.AreEqual("Weather2", weather2.Name);
            Assert.AreEqual(@"jkl.met", weather2.FileName);

            // Weather3 and Weather4 should have been
            // renamed to w1 and w2, respectively.
            var weather3 = sim.Children[5] as Models.Climate.Weather;

            Assert.NotNull(weather3);
            Assert.AreEqual("w1", weather3.Name);
            Assert.AreEqual("w1.met", weather3.FileName);

            var weather4 = sim.Children[6] as Models.Climate.Weather;

            Assert.NotNull(weather4);
            Assert.AreEqual("w2", weather4.Name);
            Assert.AreEqual("w2.met", weather4.FileName);

            // The edit file operation should have changed RUE value to 0.4.
            var wheat = sim.Children[2].Children[2] as Plant;
            var rue   = wheat.Children[6].Children[4].Children[0] as Constant;

            Assert.AreEqual(0.4, rue.FixedValue);

            double amount = (double)sim.FindByPath("[Manager].Script.Amount")?.Value;

            Assert.AreEqual(1234, amount);

            Physical physical = sim.Children[2].Children[4] as Physical;

            Assert.AreEqual(new double[5] {
                1, 2, 3, 4, 5
            }, physical.BD);
            Assert.AreEqual(new double[5] {
                0, 6, 0, 0, 0
            }, physical.AirDry);
            Assert.AreEqual(new double[5] {
                0, 0, 7, 7, 0
            }, physical.LL15);
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Create the library.
        /// </summary>
        private void Run()
        {
            // Create the librarian and add the extension data.
            Librarian librarian = new Librarian();

            foreach (IExtensionData data in this.extensionData)
            {
                librarian.AddExtensionData(data);
            }

            // Add the sections to the librarian
            List <Section> sections = new List <Section>();

            foreach (string file in this.commandLine.Files)
            {
                string     inputFile = Path.GetFullPath(file);
                FileFormat format    = FileStructure.GuessFileFormatFromExtension(Path.GetExtension(inputFile));
                bool       retry;
                do
                {
                    retry = false;

                    try
                    {
                        switch (format)
                        {
                        case FileFormat.Wixobj:
                            Intermediate intermediate = Intermediate.Load(inputFile, librarian.TableDefinitions, this.commandLine.SuppressVersionCheck);
                            sections.AddRange(intermediate.Sections);
                            break;

                        default:
                            Library loadedLibrary = Library.Load(inputFile, librarian.TableDefinitions, this.commandLine.SuppressVersionCheck);
                            sections.AddRange(loadedLibrary.Sections);
                            break;
                        }
                    }
                    catch (WixUnexpectedFileFormatException e)
                    {
                        format = e.FileFormat;
                        retry  = (FileFormat.Wixobj == format || FileFormat.Wixlib == format); // .wixobj and .wixout are supported by lit.
                        if (!retry)
                        {
                            Messaging.Instance.OnMessage(e.Error);
                        }
                    }
                } while (retry);
            }

            // Stop processing if any errors were found loading object files.
            if (Messaging.Instance.EncounteredError)
            {
                return;
            }

            // and now for the fun part
            Library library = librarian.Combine(sections);

            // Add any localization files and save the library output if an error did not occur
            if (null != library)
            {
                foreach (string localizationFile in this.commandLine.LocalizationFiles)
                {
                    Localization localization = Localizer.ParseLocalizationFile(localizationFile, librarian.TableDefinitions);
                    if (null != localization)
                    {
                        library.AddLocalization(localization);
                    }
                }

                // If there was an error adding localization files, then bail.
                if (Messaging.Instance.EncounteredError)
                {
                    return;
                }

                LibraryBinaryFileResolver resolver = null;
                if (this.commandLine.BindFiles)
                {
                    resolver = new LibraryBinaryFileResolver();
                    resolver.FileManagers     = this.fileManagers;
                    resolver.VariableResolver = new WixVariableResolver();

                    BinderFileManagerCore core = new BinderFileManagerCore();
                    core.AddBindPaths(this.commandLine.BindPaths, BindStage.Normal);

                    foreach (IBinderFileManager fileManager in resolver.FileManagers)
                    {
                        fileManager.Core = core;
                    }
                }

                library.Save(this.commandLine.OutputFile, resolver);
            }
        }
Ejemplo n.º 47
0
        private async Task <StorageFile> WriteableBitmapToStorageFile(WriteableBitmap wb, FileFormat fileFormat)
        {
            string FileName          = "MyFile.";
            Guid   BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;

            switch (fileFormat)
            {
            case FileFormat.Jpeg:
                FileName         += "jpeg";
                BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
                break;

            case FileFormat.Png:
                FileName         += "png";
                BitmapEncoderGuid = BitmapEncoder.PngEncoderId;
                break;

            case FileFormat.Bmp:
                FileName         += "bmp";
                BitmapEncoderGuid = BitmapEncoder.BmpEncoderId;
                break;

            case FileFormat.Tiff:
                FileName         += "tiff";
                BitmapEncoderGuid = BitmapEncoder.TiffEncoderId;
                break;

            case FileFormat.Gif:
                FileName         += "gif";
                BitmapEncoderGuid = BitmapEncoder.GifEncoderId;
                break;
            }

            var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);

                Stream pixelStream = wb.PixelBuffer.AsStream();
                byte[] pixels      = new byte[pixelStream.Length];
                await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                                     (uint)wb.PixelWidth,
                                     (uint)wb.PixelHeight,
                                     96.0,
                                     96.0,
                                     pixels);
                await encoder.FlushAsync();
            }
            return(file);
        }
Ejemplo n.º 48
0
        public async Task <ImageFileIdentity> AddImage(Stream imageFileStream, FileName imageFileName, FileFormat fileFormat)
        {
            var imageFileIdentity = ImageFileIdentity.New();

            // Get unique file-name from image file identity.
            var uniqueImageFileName = imageFileIdentity.GetUniqueFileName();

            // Get the storage file path of the image file, using a single directory path and a globally-unique file name.
            var uniqueImageFilePath = this.GetUniqueImageFilePath(uniqueImageFileName);

            // Write the image file from its input stream to its unique local file path.
            using (var file = File.Open(uniqueImageFilePath.Value, FileMode.CreateNew)) // Throw an exception if the file already exists by using create-new.
            {
                await imageFileStream.CopyToAsync(file);
            }

            // Add the file info to the repository.
            var fileIdentity = imageFileIdentity.GetFileIdentity();

            var fileInfo = new FileInfoAppType()
            {
                FileIdentity = fileIdentity,
                FilePath     = uniqueImageFilePath,
                FileFormat   = fileFormat,
            };

            await this.LocalFileInfoRepository.Add(fileInfo);

            // Now add the unique file-name to original file-name mapping.
            await this.OriginalFileNameMappingRepository.Add(uniqueImageFileName, imageFileName);

            // Return the image file identity.
            return(imageFileIdentity);
        }
Ejemplo n.º 49
0
        public async void OpenFile(string fileName)
        {
            FileFormat format = FileFormat.Detect(fileName);

            if (format == null)
            {
                MessageBox.Show(this, "Unsupported file format", "Open file", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //create load option and allow user to modify the load options
            LoadOptions opt = format.CreateLoadOptions();

            if (opt != null && opt.GetType() != typeof(LoadOptions))
            {
                if (OptionDialog.ShowDialog(this, "Import Settings", opt) == DialogResult.Cancel)
                {
                    return;
                }
            }



            currentFileName = fileName;
            UpdateTitle();
            long elapsed = 0;

            try
            {
                lblStatus.Text               = string.Format("Loading {0}", fileName);
                fileListView1.Enabled        = false;
                propertyGrid1.SelectedObject = null;
                Stopwatch st = Stopwatch.StartNew();
                OnMovementChanged(btnStandardMovement, null);
                Console.WriteLine("Loading file {0}", fileName);
                //open the scene using user modified load option in background thread.
                await Task.Run(() => scene.Open(fileName, opt));

                elapsed = st.ElapsedMilliseconds;
                Console.WriteLine("Loaded in {0}ms", elapsed);

                renderView1.SceneUpdated(fileName);
                sceneHierarchy.UpdateHierarchy(scene);
            }
            catch (Exception e)
            {
                MessageBox.Show(this, "Cannot open file " + fileName + "\n" + e.Message, "Open file",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (elapsed > 0)
                {
                    lblStatus.Text = string.Format("Loaded in {0}ms, Ready.", elapsed);
                }
                else
                {
                    lblStatus.Text = "Ready.";
                }
                fileListView1.Enabled = true;
            }
        }
Ejemplo n.º 50
0
        protected override void ReadData(DataBuffer buf, FileFormat fmt)
        {
            buf.Skip(8); // unused
            CurrentLevel = buf.ReadInt32();
            CurrentArea  = buf.ReadInt32();
            Language     = buf.ReadInt32();
            MillisecondsPerGameMinute = buf.ReadInt32();
            LastClockTick             = buf.ReadUInt32();
            GameClockHours            = buf.ReadByte();
            GameClockMinutes          = buf.ReadByte();
            GameClockSeconds          = buf.ReadInt16();
            TimeInMilliseconds        = buf.ReadUInt32();
            TimeScale          = buf.ReadFloat();
            TimeStep           = buf.ReadFloat();
            TimeStepNonClipped = buf.ReadFloat();
            FramesPerUpdate    = buf.ReadFloat();
            FrameCounter       = buf.ReadUInt32();
            OldWeatherType     = (WeatherType)buf.ReadInt16();
            NewWeatherType     = (WeatherType)buf.ReadInt16();
            ForcedWeatherType  = (WeatherType)buf.ReadInt16();
            buf.Skip(2);
            WeatherTypeInList         = buf.ReadInt32();
            WeatherInterpolationValue = buf.ReadFloat();
            CameraPosition            = buf.ReadStruct <Vector3>();
            CameraModeInCar           = buf.ReadFloat();
            CameraModeOnFoot          = buf.ReadFloat();
            ExtraColor              = buf.ReadInt32(); // for interiors, I think
            IsExtraColorOn          = buf.ReadBool(4);
            ExtraColorInterpolation = buf.ReadFloat();
            Brightness              = buf.ReadInt32();
            DisplayHud              = buf.ReadBool();
            ShowSubtitles           = buf.ReadBool();
            buf.Skip(2);
            RadarMode = (RadarMode)buf.ReadInt32();
            if (fmt.IsPS2)
            {
                BlurOn        = buf.ReadBool(4);
                Unknown78hPS2 = buf.ReadInt32();    // possibly unused setting
                Unknown7ChPS2 = buf.ReadInt32();    // possibly unused setting
                UseWideScreen = buf.ReadBool(4);
                MusicVolume   = buf.ReadInt32();
                SfxVolume     = buf.ReadInt32();
                RadioStation  = (RadioStation)buf.ReadByte();
                StereoOutput  = buf.ReadBool();
                buf.Skip(2);
                Unknown90hPS2 = buf.ReadInt32();
                buf.Skip(9 * 4);    // unused
                PadMode = buf.ReadInt16();
                buf.Skip(2);
                InvertLook   = !buf.ReadBool(4); // negated
                UseVibration = buf.ReadBool();
                buf.Skip(3);
                HasPlayerCheated  = buf.ReadBool(4);
                AllTaxisHaveNitro = buf.ReadBool(4);
                TargetIsOn        = buf.ReadBool();
                buf.Skip(3);
                TargetPosition = buf.ReadStruct <Vector2>();
                UnknownD8hPS2  = buf.ReadByte();
                UnknownD9hPS2  = buf.ReadByte();
                buf.Skip(2);
                PlayerPosition = buf.ReadStruct <Vector3>();
                TrailsOn       = buf.ReadBool(4);
                TimeStamp      = buf.ReadStruct <Date>();
            }
            else if (fmt.IsPSP)
            {
                BlurOn = buf.ReadBool();
                buf.Skip(3);
                MusicVolume  = buf.ReadInt32();
                SfxVolume    = buf.ReadInt32();
                RadioStation = (RadioStation)buf.ReadByte();
                StereoOutput = buf.ReadBool();
                buf.Skip(2);
                buf.Skip(9 * 4);                     // unused
                PadMode           = buf.ReadInt16();
                InvertLook        = !buf.ReadBool(); // negated
                SwapNippleAndDPad = buf.ReadBool();
                HasPlayerCheated  = buf.ReadBool();
                AllTaxisHaveNitro = buf.ReadBool();
                TargetIsOn        = buf.ReadBool();
                buf.Skip(1);
                TargetPosition = buf.ReadStruct <Vector2>();
                UnknownB8hPSP  = buf.ReadInt32();
                PlayerPosition = buf.ReadStruct <Vector3>();
            }

            Debug.Assert(buf.Offset == GetSize(fmt));
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Prepares the text in the stream which corresponds to the RtcpData of a Rtcp.RtcpPacket.
        /// </summary>
        /// <param name="format">The <see cref="FileFormat"/> to output.</param>
        /// <param name="packet">The <see cref="Rtcp.RtcpPacket"/> to describe</param>
        /// <returns>The text describes the packet if the <paramref name="format"/> is a text format, otherwise an empty string</returns>
        public static string ToTextualConvention(FileFormat format, Rtcp.RtcpPacket packet)
        {
            if (packet == null || packet.Payload.Count == 0 || format < FileFormat.Text || format == FileFormat.Short) return string.Empty;

            if(format == FileFormat.Unknown) return UnknownSpecifier;

            //Determine the format to use as well as the `Conventional Abbreviation`
            switch (packet.PayloadType)
            {
                case Rtcp.SourceDescriptionReport.PayloadType:
                    //Use a SourceDescriptionReport to enumerate the SourceDescriptionChunk's and SourceDescriptionItem's contained in the packet.
                    using (var sdes = new Rtcp.SourceDescriptionReport(packet, false)) //Don't dispose the packet when done.
                    {
                        return string.Format(RtcpExpressionFormat,
                            "SDES",
                            packet.SynchronizationSourceIdentifier,
                            packet.Padding ? 1.ToString() : 0.ToString(),
                            packet.BlockCount,
                            packet.Header.LengthInWordsMinusOne, ToTextualConvention(sdes));
                    }
                case Rtcp.SendersReport.PayloadType:
                    using (var sr = new Rtcp.SendersReport(packet, false))
                    {
                        return string.Format(RtcpExpressionFormat,
                            "SR",
                            packet.SynchronizationSourceIdentifier,
                            packet.Padding ? 1.ToString() : 0.ToString(),
                            packet.BlockCount,
                            packet.Header.LengthInWordsMinusOne,
                            (ToTextualConvention(sr) + (char)Common.ASCII.Space + string.Format(RtcpSendersInformationFormat,
                            //0
                                (DateTime.UtcNow - sr.NtpTime).TotalSeconds.ToString("0.000000"), //ts=
                            //1
                                sr.NtpTimestamp, //ntp=
                            //2
                                sr.SendersOctetCount, //osent=
                            //3
                                sr.SendersPacketCount))); //psent=
                    }
                case Rtcp.ReceiversReport.PayloadType:
                    using (var rr = new Rtcp.ReceiversReport(packet, false))
                    {
                        return string.Format(RtcpExpressionFormat,
                            "RR",
                            packet.SynchronizationSourceIdentifier,
                            packet.Padding ? 1.ToString() : 0.ToString(),
                            packet.BlockCount,
                            packet.Header.LengthInWordsMinusOne,
                            ToTextualConvention(rr));
                    }
                case Rtcp.GoodbyeReport.PayloadType:
                    using (var bye = new Rtcp.GoodbyeReport(packet, false))
                    {
                        return string.Format(RtcpExpressionFormat,
                            "BYE",
                            packet.SynchronizationSourceIdentifier, packet.Padding ? 1.ToString() : 0.ToString(),
                            packet.BlockCount,
                            packet.Header.LengthInWordsMinusOne, ToTextualConvention(bye));
                    }
                case Rtcp.ApplicationSpecificReport.PayloadType:
                    return string.Format(RtcpExpressionFormat, "APP", packet.SynchronizationSourceIdentifier, packet.Padding ? 1.ToString() : 0.ToString(), packet.BlockCount, packet.Header.LengthInWordsMinusOne, string.Empty);
                default:
                    //Unknown PayloadType use a Hex Representation of the PayloadType
                    return string.Format(RtcpExpressionFormat, packet.PayloadType.ToString("X"), packet.SynchronizationSourceIdentifier, packet.Padding ? 1.ToString() : 0.ToString(), packet.BlockCount, packet.Header.LengthInWordsMinusOne, string.Empty);
            }
        }
Ejemplo n.º 52
0
        protected override void WriteData(DataBuffer buf, FileFormat fmt)
        {
            buf.Skip(4);    // unused
            buf.Write(3);   // always 3
            buf.Write(CurrentLevel);
            buf.Write(CurrentArea);
            buf.Write(Language);
            buf.Write(MillisecondsPerGameMinute);
            buf.Write(LastClockTick);
            buf.Write(GameClockHours);
            buf.Write(GameClockMinutes);
            buf.Write(GameClockSeconds);
            buf.Write(TimeInMilliseconds);
            buf.Write(TimeScale);
            buf.Write(TimeStep);
            buf.Write(TimeStepNonClipped);
            buf.Write(FramesPerUpdate);
            buf.Write(FrameCounter);
            buf.Write((short)OldWeatherType);
            buf.Write((short)NewWeatherType);
            buf.Write((short)ForcedWeatherType);
            buf.Skip(2);
            buf.Write(WeatherTypeInList);
            buf.Write(WeatherInterpolationValue);
            buf.Write(CameraPosition);
            buf.Write(CameraModeInCar);
            buf.Write(CameraModeOnFoot);
            buf.Write(ExtraColor);
            buf.Write(IsExtraColorOn, 4);
            buf.Write(ExtraColorInterpolation);
            buf.Write(Brightness);
            buf.Write(DisplayHud);
            buf.Write(ShowSubtitles);
            buf.Skip(2);
            buf.Write((int)RadarMode);
            if (fmt.IsPS2)
            {
                buf.Write(BlurOn, 4);
                buf.Write(Unknown78hPS2);
                buf.Write(Unknown7ChPS2);
                buf.Write(UseWideScreen, 4);
                buf.Write(MusicVolume);
                buf.Write(SfxVolume);
                buf.Write((byte)RadioStation);
                buf.Write(StereoOutput);
                buf.Skip(2);
                buf.Write(Unknown90hPS2);
                buf.Skip(9 * 4);            // unused
                buf.Write(PadMode);
                buf.Skip(2);
                buf.Write(!InvertLook, 4);  // negated
                buf.Write(UseVibration);
                buf.Skip(3);
                buf.Write(HasPlayerCheated, 4);
                buf.Write(AllTaxisHaveNitro, 4);
                buf.Write(TargetIsOn);
                buf.Skip(3);
                buf.Write(TargetPosition);
                buf.Write(UnknownD8hPS2);
                buf.Write(UnknownD9hPS2);
                buf.Skip(2);
                buf.Write(PlayerPosition);
                buf.Write(TrailsOn, 4);
                buf.Write(TimeStamp);
            }
            else if (fmt.IsPSP)
            {
                buf.Write(BlurOn);
                buf.Skip(3);
                buf.Write(MusicVolume);
                buf.Write(SfxVolume);
                buf.Write((byte)RadioStation);
                buf.Write(StereoOutput);
                buf.Skip(2);
                buf.Skip(9 * 4);        // unused
                buf.Write(PadMode);
                buf.Write(!InvertLook); // negated
                buf.Write(SwapNippleAndDPad);
                buf.Write(HasPlayerCheated);
                buf.Write(AllTaxisHaveNitro);
                buf.Write(TargetIsOn);
                buf.Skip(1);
                buf.Write(TargetPosition);
                buf.Write(UnknownB8hPSP);
                buf.Write(PlayerPosition);
            }

            Debug.Assert(buf.Offset == GetSize(fmt));
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Prepares a text description which is compatible with 'rtpsend' among other 'rtp tools'.
        /// </summary>
        /// <param name="format">The <see cref="FileFormat"/> to output.</param>
        /// <param name="packet">The <see cref="Rtp.RtpPacket"/> to describe</param>
        /// <param name="time">Timeoffset from when recoding began, should be 0 for the first packet.</param>
        /// <param name="source">The <see cref="System.Net.IPEndPoint"/> from which the packet was received.</param>
        /// <returns>The text which describes the packet if the <paramref name="format"/> is a text format, otherwise an empty string</returns>
        public static string ToTextualConvention(FileFormat format, Rtp.RtpPacket packet, TimeSpan time, System.Net.IPEndPoint source)
        {
            //StringBuilder?

            //If the format is Short (Vat or Rtp Data in tablular form)
            if (format == FileFormat.Short)
            {
                //Then return that format
                return string.Format(RtpSend.ShortFormat,
                    //0
                    time.TotalSeconds.ToString("0.000000"),
                    //1
                    (packet.Marker ? (-packet.SequenceNumber) : packet.SequenceNumber).ToString(),
                    //2
                    source.Port.ToString());
            }

            StringBuilder builder = new StringBuilder(64);

            //All Rtp are described with this format
            builder.Append(string.Format(RtpSend.Format,
                //0
                time.TotalSeconds.ToString("0.000000"),
                //1
                string.Format(RtpSend.RtpPacketFormat,
                    //0
                    packet.Length, //Packet size in bytes including header
                    //1
                    source.Address.ToString() + ':' + source.Port.ToString(),
                    //2
                    packet.Version.ToString(),
                    //3
                    packet.Padding ? "1" : "0",
                    //4
                    packet.Extension ? "1" : "0",
                    //5
                    packet.ContributingSourceCount.ToString(),
                    //6
                    packet.Marker ? "1" : "0",
                    //7
                    packet.PayloadType,
                    //8 (Format description)
                    string.Format(RtpSend.PayloadDescriptionFormat, packet.PayloadType, RtpSendExtensions.PayloadDescription(packet)),
                    //9
                    packet.SequenceNumber,
                    //10
                    packet.SynchronizationSourceIdentifier,
                    //11
                    packet.Timestamp                )));

            //Write the textual representation of the items in the sourceList
            if (packet.ContributingSourceCount > 0)
            {

                //Note
                //http://www.cs.columbia.edu/irt/software/rtptools/ChangeLog.html
                //States the format is not hex when in the format csrc[n]
                //However -
                //http://www.cs.columbia.edu/irt/software/rtptools/#rtpsend
                //States that the format is :
                //cc=<CSRC count>
                //csrc=<CSRC>
                //This is basically the same thing and a parsing semantic.

                using (Media.RFC3550.SourceList sl = new Media.RFC3550.SourceList(packet))
                {

                    if (sl == null)
                    {
                        builder.Append("#Incomplete Source List Not Included");
                        builder.Append((char)Common.ASCII.LineFeed);
                    }
                    else
                    {
                        //csrc=
                        while (sl.MoveNext())
                        {
                            builder.Append(string.Format(RtpSend.HexFormat, "csrc", HexSpecifier, sl.CurrentSource.ToString("X"), (char)Common.ASCII.LineFeed));
                        }
                    }
                }
            }

            //Write the textual representation of the Extension
            if (packet.Extension)
            {
                using (var rtpExtension = packet.GetExtension())
                {

                    if (rtpExtension == null)
                    {
                        builder.Append("#Incomplete Extension Not Included");
                        builder.Append((char)Common.ASCII.LineFeed);
                    }
                    else
                    {
                        builder.Append(string.Format(RtpSend.HexFormat, "ext_type", HexSpecifier + rtpExtension.Flags.ToString("X"), (char)Common.ASCII.LineFeed));

                        builder.Append(string.Format(RtpSend.NonQuotedFormat, "ext_len", rtpExtension.LengthInWords));
                        builder.Append((char)Common.ASCII.LineFeed);

                        builder.Append(string.Format(RtpSend.HexFormat, "ext_data",  BitConverter.ToString(rtpExtension.Data.ToArray()).Replace("-", string.Empty), (char)Common.ASCII.LineFeed));
                    }
                }
            }

            //If the format is hex then add the payload dump
            if (format == FileFormat.Hex)
            {
                var data = packet.PayloadData;
                if (data.Any()) builder.Append(string.Format(RtpSend.HexFormat, "data", BitConverter.ToString(data.ToArray()).Replace("-", string.Empty), (char)Common.ASCII.LineFeed));
                else builder.Append(string.Format(HexFormat, "data", NullSpecifier, (char)Common.ASCII.LineFeed));
            }

            //Return the result
            return builder.ToString();
        }
Ejemplo n.º 54
0
        //[End]

        private static async Task <AudioInformation> ParseVideoFromHTML(string html)
        {
            try
            {
                // Parse basic video information from the HTML
                string url          = new Regex(URL_PATTERN).Match(html).Groups[1].Value;
                string title        = new Regex(TITLE_PATTERN).Match(html).Groups[1].Value;
                string description  = new Regex(DESCRIPTION_PATTERN).Match(html).Groups[1].Value;
                string thumbnailURL = new Regex(THUMBNAIL_PATTERN).Match(html).Groups[1].Value;

                // Make sure that the title and description don't contain any HTML-escaped characters like &amp;
                title       = WebUtility.HtmlDecode(title);
                description = WebUtility.HtmlDecode(description);

                if (url.Contains("&"))
                {
                    url = url.Split('&')[0];                    // If the URL contains more stuff in the query string, get rid of it
                }
                // Separate the JSON string, which is what we need for the download URLs and qualities
                string jsonString = html.Split(new[] { "ytplayer.config = " }, StringSplitOptions.None)[1];
                jsonString = jsonString.Split(new [] { "};" }, StringSplitOptions.None)[0] + "}";

                // Parse video information from the JSON
                dynamic  json          = new JavaScriptSerializer().Deserialize <object>(jsonString);
                string[] keywords      = json["args"]["keywords"].Split(',');
                string[] adaptive_fmts = json["args"]["adaptive_fmts"].Split(new[] { "," }, StringSplitOptions.None);

                // Create a dictionary with different qualities, formats and URL's
                Dictionary <Tuple <FileFormat, AudioBitrate>, string> availableQualities = new Dictionary <Tuple <FileFormat, AudioBitrate>, string>();
                foreach (string stream in adaptive_fmts)
                {
                    if (!stream.Contains("url="))
                    {
                        continue;
                    }
                    if (!stream.Contains("itag="))
                    {
                        continue;
                    }

                    string formatString = Uri.UnescapeDataString(ParseFieldFromQueryString("type", stream));
                    if (!IsAudio(formatString))
                    {
                        continue;
                    }

                    string       videoURL = Uri.UnescapeDataString(ParseFieldFromQueryString("url", stream));
                    string       itag     = Uri.UnescapeDataString(ParseFieldFromQueryString("itag", stream));
                    AudioBitrate bitrate  = ParseBitrate(itag);
                    FileFormat   format   = ParseFormat(formatString);

                    Tuple <FileFormat, AudioBitrate> qualityTuple = Tuple.Create(format, bitrate);
                    if (!availableQualities.ContainsKey(qualityTuple))
                    {
                        availableQualities.Add(qualityTuple, videoURL);
                    }
                }

                // Download the thumbnail
                Image thumbnail;
                using (var http = new HttpClient())
                {
                    thumbnail = Image.FromStream(new MemoryStream(await http.GetByteArrayAsync(thumbnailURL)));
                }

                // Create the video instance
                AudioInformation audioInformation = new AudioInformation
                {
                    URL                = url,
                    Title              = title,
                    Description        = description,
                    Keywords           = keywords,
                    Thumbnail          = thumbnail,
                    AvailableQualities = availableQualities
                };

                foreach (Tuple <FileFormat, AudioBitrate> qualityTuple in availableQualities.Keys)
                {
                    Console.WriteLine(qualityTuple.ToString());
                }

                // And return it :)
                return(audioInformation);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(null);
            }
        }
Ejemplo n.º 55
0
 public static IAssetLoader GetLoader(FileFormat type) => Loaders[type];
Ejemplo n.º 56
0
        protected void InsertFileContent(object sender, WriterCommandEventArgs args)
        {
            if (args.Mode == WriterCommandEventMode.QueryState)
            {
                args.Enabled = args.DocumentControler != null &&
                               args.Document != null &&
                               args.DocumentControler.CanInsertElementAtCurrentPosition(
                    typeof(DomElement));
            }
            else if (args.Mode == WriterCommandEventMode.Invoke)
            {
                args.Result = false;
                DomDocument document = null;
                string      fileName = null;
                if (args.Parameter is string)
                {
                    fileName = (string)args.Parameter;
                }
                else if (args.Parameter is DomDocument)
                {
                    document = (DomDocument)args.Parameter;
                }
                if (document == null)
                {
                    IFileSystem fs = args.Host.FileSystems.Docuemnt;
                    if (fs != null)
                    {
                        if (args.ShowUI)
                        {
                            // 浏览文件
                            fileName = fs.BrowseOpen(args.Host.Services, fileName);
                        }
                        if (string.IsNullOrEmpty(fileName))
                        {
                            return;
                        }
                        VFileInfo info = fs.GetFileInfo(args.Host.Services, fileName);
                        if (info.Exists == false)
                        {
                            // 文件不存在
                            return;
                        }
                        //打开文件
                        if (args.Host.Debuger != null)
                        {
                            args.Host.Debuger.DebugLoadingFile(fileName);
                        }
                        System.IO.Stream stream = fs.Open(args.Host.Services, fileName);
                        if (stream != null)
                        {
                            FileFormat format = WriterUtils.ParseFileFormat(info.Format);
                            using (stream)
                            {
                                // 读取文件,加载文档对象
                                document         = new DomDocument();
                                document.Options = args.Document.Options;

                                document.ServerObject = args.Document.ServerObject;
                                document.Load(stream, format);
                                if (args.Host.Debuger != null)
                                {
                                    args.Host.Debuger.DebugLoadFileComplete((int)stream.Length);
                                }
                            }
                        }
                    }
                }
                if (document != null &&
                    document.Body != null &&
                    document.Body.Elements.Count > 0)
                {
                    // 导入文档内容
                    DomElementList list = document.Body.Elements;
                    args.Document.ImportElements(list);
                    args.DocumentControler.InsertElements(list);
                    args.Result = list;
                }
            }
        }
Ejemplo n.º 57
0
            private void AddSubRecordNoField(string name, string description, bool required, FileFormat format)
            {
                SubRecords.Add((this._name, $"{this._name}_{name}"));
                var c = new Class($"{this._name}_{name}")
                {
                    Modifiers = Modifiers.Public | Modifiers.Sealed
                };

                c.Extends.Add("SubRecord");
                var s1 = new Field("Signature", "FieldType")
                {
                    Value     = $"Signature.FromString(\"{name}\")",
                    Modifiers = Modifiers.Static | Modifiers.Public | Modifiers.ReadOnly
                };

                c.Members.Add(s1);

                var f = new Field(format.To, "Value")
                {
                    Modifiers = Modifiers.Public
                };

                c.Members.Add(f);

                var baseCon = new Method(null, c.Name)
                {
                    Modifiers             = Modifiers.Internal,
                    Parameters            = "IReader headerReader, IReader dataReader, uint overrideDataSize = 0",
                    ConstructorInvocation = "base(headerReader, dataReader, overrideDataSize)",
                    Body = new Builder()
                };

                baseCon.Body.AppendLine($"this.Value = dataReader.{format.Read}(0);");
                c.Members.Add(baseCon);

                var emtpyCon = new Method(null, c.Name)
                {
                    ConstructorInvocation = "base(FieldType)",
                    Modifiers             = required ? Modifiers.Internal : Modifiers.Public
                };

                c.Members.Add(emtpyCon);

                if (!required)
                {
                    var valueConstructor = new Method(null, c.Name)
                    {
                        Modifiers             = Modifiers.Public,
                        ConstructorInvocation = "base(FieldType)",
                        Parameters            = $"{format.To} value",
                        Body = new Builder()
                    };
                    valueConstructor.Body.AppendLine("this.Value = value;");
                    c.Members.Add(valueConstructor);
                }

                var writer = new Method("void", "WriteData")
                {
                    Modifiers  = Modifiers.Override | Modifiers.Protected,
                    Parameters = "IWriter writer",
                    Body       = new Builder()
                };

                writer.Body.AppendLine($"writer.{format.Write}(this.Value);");
                c.Members.Add(writer);

                var length = new Method("ushort", "DataLength")
                {
                    Modifiers = Modifiers.Override | Modifiers.Protected, Body = new Builder()
                };

                length.Body.AppendLine($"return (ushort) ({GetLength(null, format)});");
                c.Members.Add(length);

                var bse = new Base
                {
                    Comment =
                        "ReSharper disable RedundantUsingDirective\nReSharper disable InconsistentNaming\nReSharper disable UseObjectOrCollectionInitializer\nReSharper disable RedundantCast"
                };

                bse.Using.Add("System.Collections.Generic");
                bse.Using.Add("System.Linq");
                var ns = new Namespace("SkyrimLib");

                bse.Namespaces.Add(ns);
                ns.Types.Add(c);
                File.WriteAllText($"../../../../SkyrimLib/Generated/{this._name}_{name}.cs", bse.BuildCode(true));
            }
Ejemplo n.º 58
0
        // ----- вернуть хранителя -------

        public IEFSaver GetEFSaver(FileFormat format)
        {
            return(EFSaver.CreateSaver(format));
        }
Ejemplo n.º 59
0
        /// <summary>
        /// Выполняет загрузку Eprom с файла
        /// </summary>
        /// <param name="filePath">Путь к файлу</param>
        /// <param name="format">Формат в котором сохранен Eprom</param>
        /// <returns></returns>
        public Eprom LoadEpromFromFile(string filePath, FileFormat format)
        {
            IEFLoader ldr = null;
            Eprom eprom = new Eprom();

            switch (format)
            {
                case FileFormat.EF1TXT:

                    ldr = platform.GetEFLoader(FileFormat.EF1TXT);
                    break;

                case FileFormat.EF2XMLOLD:

                    ldr = platform.GetEFLoader(FileFormat.EF2XMLOLD);
                    break;

                case FileFormat.EF2XML:

                    ldr = platform.GetEFLoader(FileFormat.EF2XML);
                    break;
            }
            eprom = ldr.Load(filePath);
            return eprom;
        }
Ejemplo n.º 60
0
            internal void AddSubRecordList(string name, string description, FileFormat format)
            {
                SubRecords.Add((this._name, $"{this._name}_{name}"));
                /* Property */
                var p = new Field($"{this._name}_{name}", name)
                {
                    Modifiers = Modifiers.Public | Modifiers.ReadOnly, Value = $"new {this._name}_{name}()"
                };

                this._genClass.Members.Add(p);

                this._constructorRead.Body.AppendLine(
                    $"this.{name} = this.Fields.First(x => x.Type == {this._name}_{name}.FieldType) as {this._name}_{name};");
                this._getSubRecordsForWriting.Body.AppendLine(
                    $"if(this.{name}.Values.Count > 0) ret.Add(this.{name});");

                /* Backing class */
                var c = new Class($"{this._name}_{name}")
                {
                    Modifiers = Modifiers.Public | Modifiers.Sealed
                };

                c.Extends.Add("SubRecord");
                var s1 = new Field("Signature", "FieldType")
                {
                    Value     = $"Signature.FromString(\"{name}\")",
                    Modifiers = Modifiers.Static | Modifiers.Public | Modifiers.ReadOnly
                };

                c.Members.Add(s1);

                var f = new Field($"List<{format.To}>", "Values")
                {
                    Modifiers = Modifiers.Public | Modifiers.ReadOnly, Value = $"new List<{format.To}>()"
                };

                c.Members.Add(f);

                var baseCon = new Method(null, c.Name)
                {
                    Modifiers             = Modifiers.Internal,
                    Parameters            = "IReader headerReader, IReader dataReader, uint overrideDataSize = 0",
                    ConstructorInvocation = "base(headerReader, dataReader, overrideDataSize)",
                    Body = new Builder()
                };

                baseCon.Body.AppendLine("var idx = 0;");
                baseCon.Body.AppendLine($"while (dataReader.Length > idx + {format.Size}){{");
                baseCon.Body.EnterBlock();
                baseCon.Body.AppendLine($"this.Values.Add(dataReader.{format.Read}(idx));");
                baseCon.Body.AppendLine($"idx += {format.Size};");
                baseCon.Body.LeaveBlock();
                baseCon.Body.AppendLine("}");
                c.Members.Add(baseCon);

                var emtpyCon = new Method(null, c.Name)
                {
                    ConstructorInvocation = "base(FieldType)", Modifiers = Modifiers.Internal
                };

                c.Members.Add(emtpyCon);

                var writer = new Method("void", "WriteData")
                {
                    Modifiers  = Modifiers.Override | Modifiers.Protected,
                    Parameters = "IWriter writer",
                    Body       = new Builder()
                };

                writer.Body.AppendLine($"foreach(var value in this.Values) writer.{format.Write}(value);");
                c.Members.Add(writer);

                var length = new Method("ushort", "DataLength")
                {
                    Modifiers = Modifiers.Override | Modifiers.Protected, Body = new Builder()
                };

                length.Body.AppendLine($"return (ushort) (this.Values.Count * {format.Size});");
                c.Members.Add(length);

                var bse = new Base
                {
                    Comment =
                        "ReSharper disable RedundantUsingDirective\nReSharper disable InconsistentNaming\nReSharper disable UseObjectOrCollectionInitializer\nReSharper disable RedundantCast"
                };

                bse.Using.Add("System.Collections.Generic");
                bse.Using.Add("System.Linq");
                var ns = new Namespace("SkyrimLib");

                bse.Namespaces.Add(ns);
                ns.Types.Add(c);
                File.WriteAllText($"../../../../SkyrimLib/Generated/{this._name}_{name}.cs", bse.BuildCode(true));
            }