Exemplo n.º 1
0
 public void FileVersionMajorMinorParts()
 {
     var userDataRoot = "test";
     var fileVersion = new FileVersion(12, 34, userDataRoot);
     Assert.AreEqual(12, fileVersion.MajorPart);
     Assert.AreEqual(34, fileVersion.MinorPart);
     Assert.AreEqual(userDataRoot, fileVersion.UserDataRoot);
 }
Exemplo n.º 2
0
        public void FileVersionCompare_Sorting()
        {
            var fv1 = new FileVersion(0, 7);
            var fv2 = new FileVersion(0, 8);

            Assert.IsTrue(fv1 < fv2);
            Assert.IsTrue(fv2 > fv1);

            fv1 = new FileVersion(0, 0);
            fv2 = new FileVersion(0, 0);
            Assert.IsFalse(fv1 < fv2);
            Assert.IsFalse(fv1 > fv2);
            Assert.IsFalse(fv2 < fv1);
            Assert.IsFalse(fv2 > fv1);

            fv1 = new FileVersion(1, 7);
            fv2 = new FileVersion(1, 8);
            Assert.IsTrue(fv1 < fv2);
            Assert.IsTrue(fv2 > fv1);

            fv1 = new FileVersion(1, 9);
            fv2 = new FileVersion(2, 0);
            Assert.IsTrue(fv1 < fv2);
            Assert.IsTrue(fv2 > fv1);

            fv1 = new FileVersion(-1, 9);
            fv2 = new FileVersion(0, 0);
            Assert.IsTrue(fv1 < fv2);
            Assert.IsTrue(fv2 > fv1);

            fv1 = new FileVersion(-2, 9);
            fv2 = new FileVersion(-1, 0);
            Assert.IsTrue(fv1 < fv2);
            Assert.IsTrue(fv2 > fv1);

            fv1 = new FileVersion(2, -9);
            fv2 = new FileVersion(3, 0);
            Assert.IsTrue(fv1 < fv2);
            Assert.IsTrue(fv2 > fv1);

            fv1 = new FileVersion(2, -9);
            fv2 = new FileVersion(2, -8);
            Assert.IsTrue(fv1 < fv2);
            Assert.IsTrue(fv2 > fv1);

            fv1 = new FileVersion(-2, -9);
            fv2 = new FileVersion(-2, -8);
            Assert.IsTrue(fv1 < fv2);
            Assert.IsTrue(fv2 > fv1);

            fv1 = new FileVersion(-2, -9);
            fv2 = new FileVersion(-1, -9);
            Assert.IsTrue(fv1 < fv2);
            Assert.IsTrue(fv2 > fv1);
        }
Exemplo n.º 3
0
        public MemoryStream GetExcel(string[] fieldsToExpose, DataTable data)
        {
            MemoryStream stream = new MemoryStream();
            UInt32 rowcount = 0;

            // Create the Excel document
            var document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);
            var workbookPart = document.AddWorkbookPart();
            var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
            var relId = workbookPart.GetIdOfPart(worksheetPart);

            var workbook = new Workbook();
            var fileVersion = new FileVersion { ApplicationName = "Microsoft Office Excel" };
            var worksheet = new Worksheet();
            var sheetData = new SheetData();
            worksheet.Append(sheetData);
            worksheetPart.Worksheet = worksheet;

            var sheets = new Sheets();
            var sheet = new Sheet { Name = "Sheet1", SheetId = 1, Id = relId };
            sheets.Append(sheet);
            workbook.Append(fileVersion);
            workbook.Append(sheets);
            document.WorkbookPart.Workbook = workbook;
            document.WorkbookPart.Workbook.Save();

            // Add header to the sheet
            var row = new Row { RowIndex = ++rowcount };
            for (int i = 0; i < fieldsToExpose.Length; i++)
            {
                row.Append(CreateTextCell(ColumnLetter(i), rowcount, fieldsToExpose[i]));
            }
            sheetData.AppendChild(row);
            worksheetPart.Worksheet.Save();

            // Add data to the sheet
            foreach (DataRow dataRow in data.Rows)
            {
                row = new Row { RowIndex = ++rowcount };
                for (int i = 0; i < fieldsToExpose.Length; i++)
                {
                    row.Append(CreateTextCell(ColumnLetter(i), rowcount, dataRow[fieldsToExpose[i]].ToString()));
                }
                sheetData.AppendChild(row);
            }
            worksheetPart.Worksheet.Save();
            document.Close();
            return stream;
        }
Exemplo n.º 4
0
        public void Create(string fileName)
        {
            FileName = fileName;

            using (SpreadsheetDocument doc = SpreadsheetDocument.Create(FileName, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
            {
                var workbookPart = doc.AddWorkbookPart();
                var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();

                //	Create Styles
                var stylesPart = doc.WorkbookPart.AddNewPart<WorkbookStylesPart>();
                Style = new CustomStylesheet();
                LoadCustomFonts();
                LoadCustomBorders();
                LoadCustomStyles();
                Style.Save(stylesPart);

                string relId = workbookPart.GetIdOfPart(worksheetPart);

                //	create workbook and sheet
                var workbook = new Workbook();
                var worksheet = new Worksheet();
                var fileVersion = new FileVersion { ApplicationName = "Microsoft Office Excel" };

                //	create columns
                var columns = new Columns();
                CreateColumns(columns);
                worksheet.Append(columns);

                //	create Sheet
                var sheets = new Sheets();
                var sheet = new Sheet { Name = "My sheet", SheetId = 1, Id = relId };
                sheets.Append(sheet);

                workbook.Append(fileVersion);
                workbook.Append(sheets);

                var sheetData = new SheetData();
                LoadData(sheetData);
                worksheet.Append(sheetData);

                worksheetPart.Worksheet = worksheet;
                worksheetPart.Worksheet.Save();

                doc.WorkbookPart.Workbook = workbook;
                doc.WorkbookPart.Workbook.Save();
                //doc.Close();
            }
        }
Exemplo n.º 5
0
        private File3di(BinaryReader reader, FileVersion version)
        {
            if (version != FileVersion.V8)
                throw new NotSupportedException();

            reader.BaseStream.Seek(0, SeekOrigin.Begin);
            var header = reader.ReadBytes(Header.STRUCT_SIZE).ToStruct<Header>();

            Textures = new List<ModelTexture>(header.TextureCount);
            for (var i = 0; i < header.TextureCount; i++)
            {
                var newTex = new ModelTexture(reader, header.Signature);
                Textures.Add(newTex);
            }

            Lods = new List<ModelLod>();
            for (var i = 0; i < header.LodInfo.Count; i++)
            {
                var lod = new ModelLod(reader, header.Signature);
                Lods.Add(lod);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// FileVersion.Current - need 2000 bytes
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="offset"></param>
        /// <param name="version"></param>
        public ProgramCode(byte[] bytes, Prg prg, int offset = 0,
                           FileVersion version = FileVersion.Current)
            : base(bytes, 2000, offset, version)
        {
            var maxSize = GetSize(FileVersion);

            Version = bytes.ToInt16(ref offset);

            //DEPRECATED: Line objects are incomplete to decode Program.
            //Leaving this task to the REAL DECODER

            ////////while (offset < maxSize)
            ////////{
            ////////    //Console.WriteLine($"{offset}: Line {Lines.Count}");
            ////////    var line = new Line(bytes, prg, ref offset, FileVersion);

            ////////    Lines.Add(line);
            ////////}

            offset = 2000;
            CheckOffset(offset, GetSize(FileVersion));
        }
Exemplo n.º 7
0
        /// <summary>
        /// 更新文件
        /// </summary>
        /// <param name="version">版本信息</param>
        /// <param name="bytes">文件字节流</param>
        /// <returns>bool 是否重命名</returns>
        public bool updateFile(FileVersion version, byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
            {
                return(false);
            }

            var rename   = false;
            var filePath = Application.StartupPath;

            if (string.IsNullOrEmpty(version.localPath))
            {
                filePath = $"{filePath}\\{version.localPath}\\";
            }

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

            var file = filePath + version.file;

            try
            {
                File.Delete(file);
            }
            catch
            {
                File.Move(file, file + ".bak");
                rename = true;
            }

            using (var fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                fs.Write(bytes, 0, bytes.Length);
            }

            return(rename);
        }
Exemplo n.º 8
0
        public static ReplayFile Open(string path)
        {
            if (!File.Exists(path))
            {
                return(null);
            }

            using (Stream input = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                ReplayFile replayFile = null;

                var binaryReader = new BinaryReader(input);
                var fileVersion  = new FileVersion();
                fileVersion.fileVersion = binaryReader.ReadUInt32();
                if (fileVersion.fileVersion == 2816)
                {
                    var contractJsonSerializer = new DataContractJsonSerializer(typeof(ReplayFile));
                    var count    = binaryReader.ReadInt32();
                    var numArray = binaryReader.ReadBytes(count);

                    var json = Encoding.ASCII.GetString(numArray);
                    if (!json.EndsWith("}"))
                    {
                        System.Diagnostics.Debug.WriteLine(json);
                    }

                    MemoryStream memoryStream = new MemoryStream(numArray);
                    replayFile = contractJsonSerializer.ReadObject(memoryStream) as ReplayFile;
                    memoryStream.Close();

                    replayFile.version   = fileVersion;
                    replayFile.path      = path;
                    replayFile.dataStart = binaryReader.BaseStream.Position;
                }

                input.Close();
                return(replayFile);
            }
        }
Exemplo n.º 9
0
        private void Init()
        {
            //判断是否在debug模式
            #if DEBUG
            this.Text += "   -DEBUG";
            #endif

            //从文件详细信息中获取程序名称
            ProgName    = Application.ProductName.ToString();
            ProgVersion = Application.ProductVersion.ToString();

            this.Text += "   -Ver." + ProgVersion;

            HttpURL = GetHttpURL();

            //自动下载组件
            componentFileDt.Columns.Add("FileName", Type.GetType("System.String"));
            componentFileDt.Columns.Add("FileVersion", Type.GetType("System.String"));
            DataRow dr = componentFileDt.NewRow();
            dr["FileName"] = "AutoUpdate.exe"; dr["FileVersion"] = "1.0.0.0";
            componentFileDt.Rows.Add(dr);
            dr             = componentFileDt.NewRow();
            dr["FileName"] = "NPOI.xml"; dr["FileVersion"] = "";
            componentFileDt.Rows.Add(dr);

            FileVersion.JudgeFile(HttpURL + @"/WgFile/", componentFileDt);


            //检查软件是否存在更新版本
            if (GetNewVersion())
            {
                UpdateMe.ProgUpdate(ProgName, UpdateUrl);
            }

            //开始工作
            WorkStart();
            logAppendText("Initialization Succeed!" + "   -Ver " + ProgVersion);
            logger.Instance.WriteLog("Inittialization Succeed!" + "   -Ver " + ProgVersion);
        }
Exemplo n.º 10
0
        public void LoadFromStream(BinaryReader stream, FileVersion version)
        {
            Background = StreamUtils.ReadWord(stream);
            Foreground = StreamUtils.ReadWord(stream);
            States     = StreamUtils.ReadByte(stream);

            // extData begin
            FogID  = StreamUtils.ReadWord(stream);
            FogAge = StreamUtils.ReadSByte(stream);

            Trap_Discovered = StreamUtils.ReadBoolean(stream);
            Lake_LiquidID   = StreamUtils.ReadInt(stream);

            // runtime init
            FogExtID = 0;
            // extData end

            // runtime init
            BackgroundExt = 0;
            ForegroundExt = 0;
            CreaturePtr   = null;
        }
Exemplo n.º 11
0
        internal static FileVersion ParseName(string name)
        {
            var index = name.LastIndexOf(".", StringComparison.OrdinalIgnoreCase);

            if (index > 0)
            {
                name = name.Substring(0, index);
            }

            index = name.IndexOf("_", StringComparison.InvariantCultureIgnoreCase);
            if (index <= 0 || index == name.Length)
            {
                return(null);
            }

            var result = new FileVersion
            {
                From = ParseVersion(name.Substring(0, index)),
                To   = ParseVersion(name.Substring(index + 1))
            };

            return(result.From != null && result.To != null && result.From < result.To ? result : null);
        }
        private Expression ToExpression(byte[] bytes, Prg prg, int offset = 0,
                                        FileVersion version = FileVersion.Current, bool isTrace = false)
        {
            var expressions = GetExpressions(bytes, prg, ref offset, FileVersion, isTrace: isTrace);

            if (offset != bytes.Length || expressions.Count != 1)
            {
                Debug.WriteLine($@"Bad part:
    bytes: {DebugUtilities.CompareBytes(bytes, bytes, onlyDif: false, toText: false)}
    offset: {offset}
    bytes.Length: {bytes.Length}
    expressions: {expressions.Count}
    ");
            }

            //One expression
            if (expressions.Count == 1)
            {
                return(expressions[0]);
            }

            return(null);
        }
Exemplo n.º 13
0
        /// <summary>
        /// FileVersion.Current - Need 48 bytes
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="offset"></param>
        /// <param name="version"></param>
        public UserPoint(byte[] bytes, int offset = 0,
                         FileVersion version      = FileVersion.Current)
            : base(version)
        {
            switch (FileVersion)
            {
            case FileVersion.Current:
                Name          = bytes.GetString(ref offset, 16).ClearBinarySymvols();
                Password      = bytes.GetString(ref offset, 9).ClearBinarySymvols();
                AccessLevel   = bytes.ToByte(ref offset);
                Rights        = bytes.ToUInt32(ref offset);
                DefaultPanel  = bytes.ToByte(ref offset);
                DefaultGroup  = bytes.ToByte(ref offset);
                ScreenRights  = bytes.ToBytes(ref offset, 8);
                ProgramRights = bytes.ToBytes(ref offset, 8);
                break;

            default:
                throw new FileVersionNotImplementedException(FileVersion);
            }

            CheckOffset(offset, GetSize(FileVersion));
        }
        /// <summary>
        /// FileVersion.Current - Need 37 bytes
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="offset"></param>
        /// <param name="version"></param>
        public ProgramPoint(byte[] bytes, int offset = 0,
                            FileVersion version      = FileVersion.Current)
            : base(bytes, offset, version)
        {
            offset += BasePoint.GetSize(FileVersion);

            switch (FileVersion)
            {
            case FileVersion.Current:
                Length     = bytes.ToUInt16(ref offset);
                Control    = (OffOn)bytes.ToByte(ref offset);
                AutoManual = (AutoManual)bytes.ToByte(ref offset);
                NormalCom  = (NormalCom)bytes.ToByte(ref offset);
                ErrorCode  = bytes.ToByte(ref offset);
                Unused     = bytes.ToByte(ref offset);
                break;

            default:
                throw new FileVersionNotImplementedException(FileVersion);
            }

            CheckOffset(offset, GetSize(FileVersion));
        }
Exemplo n.º 15
0
        private void resourceConvertBtn_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(resourceInputPath.Text) || String.IsNullOrEmpty(resourceOutputPath.Text))
            {
                MessageBox.Show("Please specify both input and output file path first!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                try
                {
                    _resource = ResourceUtils.LoadResource(resourceInputPath.Text);
                    ResourceFormat format        = ResourceUtils.ExtensionToResourceFormat(resourceOutputPath.Text);
                    FileVersion    outputVersion = _form.GetGame().IsDOS2() ? FileVersion.VerExtendedNodes : FileVersion.VerChunkedCompress;
                    ResourceUtils.SaveResource(_resource, resourceOutputPath.Text, format, outputVersion);

                    MessageBox.Show("Resource saved successfully.");
                }
                catch (Exception exc)
                {
                    MessageBox.Show($"Internal error!{Environment.NewLine}{Environment.NewLine}{exc}", "Conversion Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Exemplo n.º 16
0
        void _wpfTextView_MouseHover(object sender, MouseHoverEventArgs e)
        {
            CheckDisposed();
            var pointOpt = e.TextPosition.GetPoint(_wpfTextView.TextBuffer, PositionAffinity.Predecessor);

            _lastMouseHoverPointOpt = pointOpt;

            if (!pointOpt.HasValue)
            {
                return;
            }

            var point    = pointOpt.Value;
            var snapshot = point.Snapshot;
            var server   = this.FileModel.Server;
            var pos      = point.Position;
            var fileVer  = snapshot.Version.Convert();

            _previosMouseHoverFileVersion = fileVer;

            if (_wpfTextView.TextBuffer.Properties.TryGetProperty(Constants.NitraQuickInfoSourceKey, out _quickInfoOpt))
            {
                var extent = _quickInfoOpt.GetTextExtent(point);

                if (_previosActiveSpanOpt == extent.Span)
                {
                    return;
                }

                _previosActiveSpanOpt = extent.Span;

                var fileModel = this.FileModel;
                fileModel.OnMouseHover(this);

                server.Client.Send(new ClientMessage.GetHint(fileModel.GetProjectId(), fileModel.Id, snapshot.Version.Convert(), point.Position));
            }
        }
        /// <summary>
        /// FileVersion.Current - Need 45 bytes
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="offset"></param>
        /// <param name="version"></param>
        public OutputPoint(byte[] bytes, int offset = 0,
                           FileVersion version      = FileVersion.Current)
        {
            FileVersion = version;

            int  valueRaw;
            Unit unit;

            switch (FileVersion)
            {
            case FileVersion.Current:
                Description    = bytes.GetString(ref offset, 19).ClearBinarySymvols();
                LowVoltage     = bytes.ToByte(ref offset);
                HighVoltage    = bytes.ToByte(ref offset);
                Label          = bytes.GetString(ref offset, 9).ClearBinarySymvols();
                valueRaw       = bytes.ToInt32(ref offset);
                AutoManual     = (AutoManual)bytes.ToByte(ref offset);
                DigitalAnalog  = (DigitalAnalog)bytes.ToByte(ref offset);
                HwSwitchStatus = (SwitchStatus)bytes.ToByte(ref offset);
                Control        = (OffOn)bytes.ToByte(ref offset);
                DigitalControl = (OffOn)bytes.ToByte(ref offset);
                Decommissioned = bytes.ToByte(ref offset);
                unit           = UnitFromByte(bytes.ToByte(ref offset), DigitalAnalog);
                SubId          = bytes.ToBoolean(ref offset);
                SubProduct     = bytes.ToBoolean(ref offset);
                SubNumber      = SubNumberFromByte(bytes.ToByte(ref offset));
                PwmPeriod      = bytes.ToByte(ref offset);
                break;

            default:
                throw new FileVersionNotImplementedException(FileVersion);
            }

            Value = new VariableValue(valueRaw, unit);

            CheckOffset(offset, GetSize(FileVersion));
        }
        private void FromASSIGN(byte[] bytes, Prg prg, ref int offset,
                                FileVersion version = FileVersion.Current)
        {
            Expressions.Add(new VariableExpression(bytes, prg, ref offset, FileVersion));

            var        first      = new VariableExpression(bytes, prg, ref offset, FileVersion);
            var        second     = new VariableExpression(bytes, prg, ref offset, FileVersion);
            var        type       = (TYPE_TOKEN)bytes.ToByte(ref offset);
            Expression expression = new BinaryExpression(first, second, type, FileVersion);

            //var temp = offset;
            var check = bytes.ToByte(ref offset);

            --offset;
            //Console.WriteLine($"{Number} {check} before");
            if (check != (byte)TYPE_TOKEN.NUMBER)
            {
                if (ProgramCodeUtilities.IsVariable(check))
                {
                    var third = new VariableExpression(bytes, prg, ref offset, FileVersion);
                    var type2 = (TYPE_TOKEN)bytes.ToByte(ref offset);
                    expression = new BinaryExpression(expression, third, type2, FileVersion);
                }
                else if (ProgramCodeUtilities.IsFunction(check))
                {
                    var token = (FUNCTION_TOKEN)bytes.ToByte(ref offset);
                    expression = new FunctionExpression(token, FileVersion, expression);
                }

                //++offset;
                //check = (ExpressionType)bytes.ToByte(ref offset);
                //--offset;
                //Console.WriteLine($"{Number} {check} after");
            }

            Expressions.Add(expression);
        }
Exemplo n.º 19
0
        public override void LoadFromStream(BinaryReader stream, FileVersion version)
        {
            try {
                fID  = (BuildingID)StreamUtils.ReadInt(stream);
                Area = StreamUtils.ReadRect(stream);

                Doors.Clear();
                sbyte count = (sbyte)StreamUtils.ReadByte(stream);
                for (int i = 0; i < count; i++)
                {
                    int       dx  = StreamUtils.ReadInt(stream);
                    int       dy  = StreamUtils.ReadInt(stream);
                    int       dir = StreamUtils.ReadByte(stream);
                    DoorState st  = (DoorState)StreamUtils.ReadByte(stream);
                    AddDoor(dx, dy, dir, st);
                }

                int idx = StreamUtils.ReadInt(stream);
                Holder = ((idx == -1) ? null : (CreatureEntity)((NWField)Owner).Creatures.GetItem(idx));
            } catch (Exception ex) {
                Logger.Write("Building.loadFromStream(): " + ex.Message);
                throw ex;
            }
        }
Exemplo n.º 20
0
        public override void SaveToStream(BinaryWriter stream, FileVersion version)
        {
            try {
                StreamUtils.WriteInt(stream, (int)fID);
                StreamUtils.WriteRect(stream, Area);

                int count = Doors.Count;
                StreamUtils.WriteByte(stream, (byte)count);
                for (int i = 0; i < count; i++)
                {
                    Door dr = Doors[i];
                    StreamUtils.WriteInt(stream, dr.X);
                    StreamUtils.WriteInt(stream, dr.Y);
                    StreamUtils.WriteByte(stream, (byte)dr.Dir);
                    StreamUtils.WriteByte(stream, (byte)dr.State);
                }

                int idx = ((Holder == null) ? -1 : ((NWField)Owner).Creatures.IndexOf(Holder));
                StreamUtils.WriteInt(stream, idx);
            } catch (Exception ex) {
                Logger.Write("Building.saveToStream(): " + ex.Message);
                throw ex;
            }
        }
Exemplo n.º 21
0
        // Generates content of workbook.
        private void GenerateWorkbookContent(WorkbookPart workbook)
        {
            workbook.Workbook = new Workbook {
                MCAttributes = new MarkupCompatibilityAttributes {
                    Ignorable = "x15"
                }
            };
            workbook.Workbook.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            workbook.Workbook.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            workbook.Workbook.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
            FileVersion fileVersion = new FileVersion {
                ApplicationName = "xl", LastEdited = "6", LowestEdited = "6", BuildVersion = "14420"
            };

            Sheets sheets = new Sheets();
            Sheet  sheet  = new Sheet {
                Name = "Sheet1", SheetId = (UInt32Value)1U, Id = "rId1"
            };

            sheets.Append(sheet);

            workbook.Workbook.Append(fileVersion);
            workbook.Workbook.Append(sheets);
        }
Exemplo n.º 22
0
        private File3di(BinaryReader reader, FileVersion version)
        {
            if (version != FileVersion.V8)
            {
                throw new NotSupportedException();
            }

            reader.BaseStream.Seek(0, SeekOrigin.Begin);
            var header = reader.ReadBytes(Header.STRUCT_SIZE).ToStruct <Header>();

            Textures = new List <ModelTexture>(header.TextureCount);
            for (var i = 0; i < header.TextureCount; i++)
            {
                var newTex = new ModelTexture(reader, header.Signature);
                Textures.Add(newTex);
            }

            Lods = new List <ModelLod>();
            for (var i = 0; i < header.LodInfo.Count; i++)
            {
                var lod = new ModelLod(reader, header.Signature);
                Lods.Add(lod);
            }
        }
Exemplo n.º 23
0
 /// <summary>
 /// 输出需要更新文件
 /// </summary>
 public void OutNeedUpdateFile(List <FileVersion> listFileVersion, string fileDir, string outDir)
 {
     string[] file = Directory.GetFiles(fileDir);
     foreach (var item in file)
     {
         string outFilePath = outDir + item.Replace(fileDir, "");
         string hashValue   = GetMD5HashFromFile(item);
         var    fileVersion = listFileVersion.FirstOrDefault(f => f.FilePath == item);
         if (fileVersion == null)
         {
             if (!Directory.Exists(outDir))
             {
                 Directory.CreateDirectory(outDir);
             }
             File.Copy(item, outFilePath, true);
             fileVersion           = new FileVersion();
             fileVersion.FilePath  = item;
             fileVersion.HashValue = hashValue;
             listFileVersion.Add(fileVersion);
         }
         else if (fileVersion.HashValue != hashValue)
         {
             if (!Directory.Exists(outDir))
             {
                 Directory.CreateDirectory(outDir);
             }
             File.Copy(item, outFilePath, true);
             fileVersion.HashValue = hashValue;
         }
     }
     string[] dir = Directory.GetDirectories(fileDir);
     for (int i = 0; i < dir.Length; i++)
     {
         OutNeedUpdateFile(listFileVersion, dir[i], outDir + dir[i].Replace(fileDir, ""));
     }
 }
Exemplo n.º 24
0
		/// <summary>
		/// Produces a stream for a file version. This may involve reading the database for the base for the version,
		/// if the version is a diff.
		/// </summary>
		/// <param name="version"> The version to stream. </param>
		/// <returns> The resultant full-text stream. </returns>
		private StreamCombiner GetFileStream(FileVersion version)
		{
			if (version.IsFullText)
				return new StreamCombiner(version.Text);

			var baseVersionQuery = from fl in DataContext.FileVersions
								   where fl.FileId == version.FileId && fl.Revision == version.Revision && fl.IsRevisionBase
								   select fl;
			if (baseVersionQuery.Count() != 1)
			{
				ErrorOut("Base revision not found. This can happen if the file changed type from binary to text " +
					"as part of this change. If this is not the case, it might be a bug - report it!");
				return null;
			}

			FileVersion baseVersion = baseVersionQuery.Single();

			return new StreamCombiner(baseVersion.Text, version.Text);
		}
Exemplo n.º 25
0
        /// <summary>
        /// Computes the displayed name of the file version. Similar to ComputeMoniker, but without the action.
        /// </summary>
        /// <param name="name"> The base name of a file (excluding the path). </param>
        /// <param name="version"> The version. </param>
        /// <returns> The string to display. </returns>
        private static string FileDisplayName(string name, FileVersion version)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(name);
            sb.Append('#');
            sb.Append(version.Revision.ToString());
            if (!version.IsRevisionBase && version.TimeStamp != null)
                sb.Append(" " + version.TimeStamp);

            return sb.ToString();
        }
Exemplo n.º 26
0
        private static void ConvertResource(string sourcePath, string destinationPath, FileVersion fileVersion)
        {
            try
            {
                ResourceFormat resourceFormat = ResourceUtils.ExtensionToResourceFormat(destinationPath);
                CommandLineLogger.LogDebug($"Using destination extension: {resourceFormat}");

                Resource resource = ResourceUtils.LoadResource(sourcePath);

                ResourceUtils.SaveResource(resource, destinationPath, resourceFormat, fileVersion);

                CommandLineLogger.LogInfo($"Wrote resource to: {destinationPath}");
            }
            catch (Exception e)
            {
                CommandLineLogger.LogFatal($"Failed to convert resource: {e.Message}", 2);
                CommandLineLogger.LogTrace($"{e.StackTrace}");
            }
        }
Exemplo n.º 27
0
 void UpdateSpanInfos(HighlightingType highlightingType, ImmutableArray<SpanInfo> spanInfos, FileVersion version)
 {
   var classifierOpt = GetClassifierOpt();
   if (classifierOpt == null)
     return;
   classifierOpt.Update(highlightingType, spanInfos, version);
 }
Exemplo n.º 28
0
        // Generates content of workbookPart1.
        private void GenerateWorkbookPart1Content(WorkbookPart workbookPart1)
        {
            Workbook workbook1 = new Workbook();
            workbook1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            FileVersion fileVersion1 = new FileVersion() { ApplicationName = "xl", LastEdited = "4", LowestEdited = "4", BuildVersion = "4506" };
            WorkbookProperties workbookProperties1 = new WorkbookProperties() { DefaultThemeVersion = (UInt32Value)124226U };

            BookViews bookViews1 = new BookViews();
            WorkbookView workbookView1 = new WorkbookView() { XWindow = 360, YWindow = 150, WindowWidth = (UInt32Value)14355U, WindowHeight = (UInt32Value)4680U };

            bookViews1.Append(workbookView1);

            Sheets sheets1 = new Sheets();
            Sheet sheet1 = new Sheet() { Name = "Sheet1", SheetId = (UInt32Value)1U, Id = "rId1" };

            sheets1.Append(sheet1);
            CalculationProperties calculationProperties1 = new CalculationProperties() { CalculationId = (UInt32Value)125725U };

            workbook1.Append(fileVersion1);
            workbook1.Append(workbookProperties1);
            workbook1.Append(bookViews1);
            workbook1.Append(sheets1);
            workbook1.Append(calculationProperties1);

            workbookPart1.Workbook = workbook1;
        }
Exemplo n.º 29
0
 public void FileVersionMajorMinorParts()
 {
     var fileVersion = new FileVersion(12, 34);
     Assert.AreEqual(12, fileVersion.MajorPart);
     Assert.AreEqual(34, fileVersion.MinorPart);
 }
Exemplo n.º 30
0
 public FileParseErrorArgs(ParserSyntaxError parseError, FileVersion fileVersion, IFileInformation fileInfo)
 {
     this.parseError = parseError;
     this.fileVersion = fileVersion;
     this.fileInfo = fileInfo;
 }
        //Main class function, export the mutationList to XLSX file, sets file name to testName.
        public static void saveXLS(String testName, List<Mutation> mutationList)
        {
            SpreadsheetDocument xl = null;
            string fullPath = Properties.Settings.Default.ExportSavePath + @"\" + testName;
            fullPath += ".xlsx";
            try
            {
                xl = SpreadsheetDocument.Create(fullPath, SpreadsheetDocumentType.Workbook);
            }
            catch (IOException )
            {
                throw ;
            }
            WorkbookPart wbp = xl.AddWorkbookPart();
            WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
            Workbook wb = new Workbook();
            FileVersion fv = new FileVersion();
            fv.ApplicationName = "Microsoft Office Excel";
            Worksheet ws = new Worksheet();
            SheetData sd = new SheetData();
            WorkbookStylesPart wbsp = wbp.AddNewPart<WorkbookStylesPart>();
            wbsp.Stylesheet = GenerateStyleSheet();
            wbsp.Stylesheet.Save();

            //save the longest width for each column.
            string[] longestWordPerColumn = new string[12];

            int k = 0;

            //create and add header row.
            Row headerRow = new Row();
            foreach (string s in Mutation.getHeaderForExport())
            {
                Cell cell = new Cell();
                cell.DataType = CellValues.String;
                cell.CellValue = new CellValue(s);
                cell.StyleIndex = 1;
                headerRow.AppendChild(cell);
                longestWordPerColumn[k] = s;
                k++;
            }
            sd.AppendChild(headerRow);

            //create and add rows for each mutation.
            foreach (Mutation m in mutationList)
            {
                Row newRow = new Row();
                string[] infoString = m.getInfoForExport();
                for (int i = 0; i < infoString.Length; i++)
                {
                    Cell cell1 = new Cell();
                    if (i == 1)
                        cell1.DataType = CellValues.Number;
                    else
                        cell1.DataType = CellValues.String;
                    cell1.CellValue = new CellValue(infoString[i]);
                    if (!m.CosmicName.Equals("-----"))
                        cell1.StyleIndex = 2;
                    else
                        cell1.StyleIndex = 3;
                    newRow.AppendChild(cell1);
                    if (longestWordPerColumn[i].Length < infoString[i].Length)
                        longestWordPerColumn[i] = infoString[i];
                }
                sd.AppendChild(newRow);
            }

            //Sets the column width to longest width for each column.
            Columns columns = new Columns();
            for (int i = 0; i < 12; i++)
            {
                columns.Append(CreateColumnData((UInt32)i + 1, (UInt32)i + 1, GetWidth("Calibri", 11, longestWordPerColumn[i])));
            }
            ws.Append(columns);


            ws.Append(sd);
            wsp.Worksheet = ws;
            wsp.Worksheet.Save();
            Sheets sheets = new Sheets();
            Sheet sheet = new Sheet();
            sheet.Name = "Sheet1";
            sheet.SheetId = 1;
            sheet.Id = wbp.GetIdOfPart(wsp);
            sheets.Append(sheet);
            wb.Append(fv);
            wb.Append(sheets);
            xl.WorkbookPart.Workbook = wb;
            xl.WorkbookPart.Workbook.Save();
            xl.Close();
        }
Exemplo n.º 32
0
        public List <AdditionalLayerInformationBlock> Read(Stream stream, AdditionalLayerInformation additionalLayerInformation, FileVersion fileVersion)
        {
            var reader = new BigEndianBinaryReader(stream);

            stream.Position = additionalLayerInformation.Offset;
            var list = new List <AdditionalLayerInformationBlock>();

            while (stream.Position < additionalLayerInformation.Offset + additionalLayerInformation.Length)
            {
                var block = new AdditionalLayerInformationBlock();
                block.Signature = new string(reader.ReadChars(4));
                block.Key       = new string(reader.ReadChars(4));

                if (fileVersion == FileVersion.Psb && LongDataKeys.Contains(block.Key))
                {
                    block.Length = reader.ReadInt64();
                }
                else
                {
                    block.Length = reader.ReadInt32();
                }

                if ((block.Length % 2) != 0)
                {
                    block.Length += 3; // should be 1, but 3 works there for unknown reason
                }

                block.Offset     = stream.Position;
                stream.Position += block.Length;
                list.Add(block);
            }

            return(list);
        }
 public DescriptionPoint(string description = "", FileVersion version = FileVersion.Current)
     : base(version)
 {
     Description = description;
 }
Exemplo n.º 34
0
 public static int AddFileVersion(FileVersion version) => _db.Insert(version);
Exemplo n.º 35
0
        public void ConvertResources(string inputDir, string outputDir, ResourceFormat inputFormat, ResourceFormat outputFormat, FileVersion outputVersion = 0x0)
        {
            this.progressUpdate("Enumerating files ...", 0, 1);
            var paths = new List <string>();

            EnumerateFiles(paths, inputDir, inputDir, "." + inputFormat.ToString().ToLower());

            this.progressUpdate("Converting resources ...", 0, 1);
            for (var i = 0; i < paths.Count; i++)
            {
                var path    = paths[i];
                var inPath  = inputDir + "/" + path;
                var outPath = outputDir + "/" + Path.ChangeExtension(path, outputFormat.ToString().ToLower());

                FileManager.TryToCreateDirectory(outPath);

                this.progressUpdate("Converting: " + inPath, i, paths.Count);
                var resource = LoadResource(inPath, inputFormat);
                SaveResource(resource, outPath, outputFormat, outputVersion);
            }
        }
Exemplo n.º 36
0
        public double AddFile(AddFileModel model)
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            User ownerUser = context.Users.First(user => user.UserId == model.Owner);
            File file      = new File
            {
                FileId    = model.Id,
                FileName  = model.Name,
                Size      = model.Size,
                Copies    = model.Chunks.Max(chunk => chunk.MirrorIndex),
                OwnerUser = ownerUser
            };

            context.Files.Add(file);
            context.SaveChanges();

            File insertedFile = context.Files.First(_file => _file.FileId == file.FileId);

            model.Users.ForEach(user =>
            {
                Permission permission = new Permission
                {
                    PermissionId = Guid.NewGuid(),
                    User         = context.Users.First(_user => _user.UserId == user),
                    File         = insertedFile
                };

                context.Permissions.Add(permission);
                context.SaveChanges();
            });


            AccessLog accessLog = new AccessLog
            {
                LogId      = Guid.NewGuid(),
                LastAccess = DateTime.Now,
                File       = insertedFile,
                User       = context.Users.First(user => user.UserId == model.Owner)
            };

            context.AccessLogs.Add(accessLog);
            context.SaveChanges();

            FileVersion fileVersion = new FileVersion
            {
                FileVersionId = Guid.NewGuid(),
                File          = insertedFile,
                FileDateTime  = DateTime.Now
            };

            context.FileVersions.Add(fileVersion);
            context.SaveChanges();

            FileVersion insertedFileVersion = context.FileVersions.First(_fileVersion => _fileVersion.FileVersionId == fileVersion.FileVersionId);

            model.Chunks.ForEach(chunk =>
            {
                Disk disk           = context.Disks.First(disk => disk.DiskId == chunk.DiskId);
                FileChunk fileChunk = new FileChunk
                {
                    FileChunkId   = chunk.ChunkId,
                    FileChunkSize = chunk.Size,
                    FileVersion   = insertedFileVersion,
                    Disk          = disk,
                    FileIndex     = chunk.FileIndex,
                    MirrorIndex   = chunk.MirrorIndex
                };

                context.FileChunks.Add(fileChunk);
                context.SaveChanges();
            });

            stopWatch.Stop();
            return(stopWatch.Elapsed.TotalSeconds);
        }
Exemplo n.º 37
0
        protected void ExcelDl_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=ViewHistoryChart.xlsx");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.Charset = "";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            Chart1.RenderControl(hw);

            using (MemoryStream stream = new MemoryStream())
            {
                using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
                {
                    var fileName = HttpContext.Current.Request.PhysicalApplicationPath + @"\Charts\ChartImage.png";

                    WorkbookPart wbp = spreadsheetDocument.AddWorkbookPart();
                    WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
                    Workbook wb = new Workbook();
                    FileVersion fv = new FileVersion();
                    fv.ApplicationName = "Microsoft Office Excel";
                    Worksheet ws = new Worksheet();
                    SheetData sd = new SheetData();

                    // add contents
                    List<string> values = new List<string>();

                    //values.Add(lblSectionFunctionSelected.Text);

                    uint i = 1;
                    foreach (var value in values)
                    {
                        UInt32Value rowIndex = UInt32Value.FromUInt32(i);
                        var row = new Row { RowIndex = rowIndex }; // add a row at the top of spreadsheet
                        sd.Append(row);

                        var cell = new Cell
                        {
                            CellValue = new CellValue(value),
                            DataType = new EnumValue<CellValues>(CellValues.String)
                        };
                        row.InsertAt(cell, 0);
                        i++;
                    }
                    // add image
                    DrawingsPart dp = wsp.AddNewPart<DrawingsPart>();
                    ImagePart imgp = dp.AddImagePart(ImagePartType.Png, wsp.GetIdOfPart(dp));
                    using (FileStream fs = new FileStream(fileName, FileMode.Open))
                    {
                        imgp.FeedData(fs);
                    }
                    DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties nvdp = new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties();
                    nvdp.Id = 1025;
                    nvdp.Name = "Picture 1";
                    nvdp.Description = "Chart";
                    DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
                    picLocks.NoChangeAspect = true;
                    picLocks.NoChangeArrowheads = true;
                    DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureDrawingProperties nvpdp = new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureDrawingProperties();
                    nvpdp.PictureLocks = picLocks;
                    DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureProperties nvpp = new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureProperties();
                    nvpp.NonVisualDrawingProperties = nvdp;
                    nvpp.NonVisualPictureDrawingProperties = nvpdp;

                    DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
                    stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();

                    DocumentFormat.OpenXml.Drawing.Spreadsheet.BlipFill blipFill = new DocumentFormat.OpenXml.Drawing.Spreadsheet.BlipFill();
                    DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
                    blip.Embed = dp.GetIdOfPart(imgp);
                    blip.CompressionState = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
                    blipFill.Blip = blip;
                    blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
                    blipFill.Append(stretch);

                    DocumentFormat.OpenXml.Drawing.Transform2D t2d = new DocumentFormat.OpenXml.Drawing.Transform2D();
                    DocumentFormat.OpenXml.Drawing.Offset offset = new DocumentFormat.OpenXml.Drawing.Offset();
                    offset.X = 0;
                    offset.Y = 0;
                    t2d.Offset = offset;
                    Bitmap bm = new Bitmap(fileName);
                    //http://en.wikipedia.org/wiki/English_Metric_Unit#DrawingML
                    //http://stackoverflow.com/questions/1341930/pixel-to-centimeter
                    //http://stackoverflow.com/questions/139655/how-to-convert-pixels-to-points-px-to-pt-in-net-c
                    DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();
                    extents.Cx = (long)bm.Width * (long)((float)914400 / bm.HorizontalResolution);
                    extents.Cy = (long)bm.Height * (long)((float)914400 / bm.VerticalResolution);
                    bm.Dispose();
                    t2d.Extents = extents;
                    DocumentFormat.OpenXml.Drawing.Spreadsheet.ShapeProperties sp = new DocumentFormat.OpenXml.Drawing.Spreadsheet.ShapeProperties();
                    sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
                    sp.Transform2D = t2d;
                    DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
                    prstGeom.Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
                    prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
                    sp.Append(prstGeom);
                    sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());

                    DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
                    picture.NonVisualPictureProperties = nvpp;
                    picture.BlipFill = blipFill;
                    picture.ShapeProperties = sp;

                    DocumentFormat.OpenXml.Drawing.Spreadsheet.Position pos = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Position();
                    pos.X = 0;
                    pos.Y = 10;
                    Extent ext = new Extent();
                    ext.Cx = extents.Cx;
                    ext.Cy = extents.Cy;
                    AbsoluteAnchor anchor = new AbsoluteAnchor();
                    anchor.Position = pos;
                    anchor.Extent = ext;
                    anchor.Append(picture);
                    anchor.Append(new ClientData());
                    WorksheetDrawing wsd = new WorksheetDrawing();
                    wsd.Append(anchor);
                    Drawing drawing = new Drawing();
                    drawing.Id = dp.GetIdOfPart(imgp);

                    wsd.Save(dp);

                    ws.Append(sd);
                    ws.Append(drawing);
                    wsp.Worksheet = ws;
                    wsp.Worksheet.Save();
                    Sheets sheets = new Sheets();
                    Sheet sheet = new Sheet();
                    sheet.Name = "history chart";
                    sheet.SheetId = 1;
                    sheet.Id = wbp.GetIdOfPart(wsp);
                    sheets.Append(sheet);
                    wb.Append(fv);
                    wb.Append(sheets);

                    spreadsheetDocument.WorkbookPart.Workbook = wb;
                    spreadsheetDocument.WorkbookPart.Workbook.Save();
                    spreadsheetDocument.Close();
                }
                File.WriteAllBytes(HttpContext.Current.Request.PhysicalApplicationPath + @"\Charts\temp.xlsx", stream.ToArray());
            }
            Response.WriteFile(HttpContext.Current.Request.PhysicalApplicationPath + @"\Charts\temp.xlsx");
            Response.Flush();
            Response.Close();
            Response.End();
        }
Exemplo n.º 38
0
    internal void Update(HighlightingType highlightingType, ImmutableArray<SpanInfo> spanInfos, FileVersion version)
    {
      if (ClassificationChanged == null)
        return;

      var snapshot = _buffer.CurrentSnapshot;

      if (snapshot.Version.Convert() != version)
        return;

      _snapshots[(int)highlightingType] = snapshot;
      _spanInfos[(int)highlightingType] = spanInfos;
      ClassificationChanged(this, new ClassificationChangedEventArgs(new SnapshotSpan(snapshot, new Span(0, snapshot.Length))));
    }
Exemplo n.º 39
0
        public void GetLatestVersionToMigrate_AllInvalidData()
        {
            var mockLookup = new Mock<IDynamoLookUp>();
            mockLookup.Setup(x => x.GetDynamoUserDataLocations()).Returns(new[] { "x", "y", "z" });

            var current = new FileVersion(1, 0, "a");
            var latest = DynamoMigratorBase.GetLatestVersionToMigrate(null, mockLookup.Object, current);
            Assert.IsTrue(!latest.HasValue || latest.Value.UserDataRoot == null);
        }
        //OverRide
        public void saveXLS(String testName, DataSet ds)
        {
            SpreadsheetDocument xl = null;
            string fullPath = Properties.Settings.Default.ExportSavePath + @"\" + testName;
            fullPath += ".xlsx";
            try
            {
                xl = SpreadsheetDocument.Create(fullPath, SpreadsheetDocumentType.Workbook);
            }
            catch (IOException)
            {
                MessageBox.Show("Another Copy of the Document is open, Please close the document and retry export");
                throw;
            }
            WorkbookPart wbp = xl.AddWorkbookPart();
            WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
            Workbook wb = new Workbook();
            FileVersion fv = new FileVersion();
            fv.ApplicationName = "Microsoft Office Excel";
            Worksheet ws = new Worksheet();
            SheetData sd = new SheetData();
            WorkbookStylesPart wbsp = wbp.AddNewPart<WorkbookStylesPart>();
            wbsp.Stylesheet = GenerateStyleSheet();
            wbsp.Stylesheet.Save();

            //save the longest width for each column.
            string[] longestWordPerColumn = new string[35];

            int k = 0;

            //create and add header row.
            Row headerRow = new Row();
            //add headers for germline mutation export
            string[] germlineHeaders =  { "Chromosome", "Position", "Gene Name", "Ref", "Var", "Strand", "Ref Codon", "Var Codon", "Ref AA", "Var AA", "AA Name", "CDS Name", "Cosmic Details", "Shows", "History", "RefSNP", "Clinical Significance", "MAF", "Chromosome Sample Count",  "Alleles", "Allepe pop %" };
            foreach (string s in germlineHeaders)
            {
                Cell cell = new Cell();
                cell.DataType = CellValues.String;
                cell.CellValue = new CellValue(s);
                cell.StyleIndex = 1;
                headerRow.AppendChild(cell);
                longestWordPerColumn[k] = s;
                k++;
            }
            sd.AppendChild(headerRow);
            List<Mutation> mutationList = new List<Mutation>();//remove this
            //create and add rows for each mutation.


            //Here we go through ds
            int tbllength = ds.Tables[0].Rows.Count;
            String[] infoString = new String[21];


            for (int rowNum = 0; rowNum < tbllength; rowNum++)//for each mutation m
            {
                Row newRow = new Row();
                for (int j = 0; j < 21; j++)
                {
                    infoString[j] = (string)ds.Tables[0].Rows[rowNum].ItemArray[j];
                }
                //string[] infoString = m.getInfoForExport();
                for (int i = 0; i < infoString.Length; i++)
                {
                    Cell cell1 = new Cell();
                    if (i == 1)
                        cell1.DataType = CellValues.Number;
                    else
                        cell1.DataType = CellValues.String;
                    cell1.CellValue = new CellValue(infoString[i]);
                    if (!infoString[12].Equals("-----"))//index 12 is the Cosmic Name postion so
                        cell1.StyleIndex = 2;
                    else
                        cell1.StyleIndex = 3;
                    newRow.AppendChild(cell1);
                    //if (longestWordPerColumn[i].Length < infoString[i].Length)
                    //    longestWordPerColumn[i] = infoString[i];
                }
                sd.AppendChild(newRow);
            }

            //Sets the column width to longest width for each column.
            Columns columns = new Columns();
            for (int i = 0; i < 21; i++)
            {
                columns.Append(CreateColumnData((UInt32)i + 1, (UInt32)i + 1, GetWidth("Calibri", 11, longestWordPerColumn[i])));
            }
            ws.Append(columns);


            ws.Append(sd);
            wsp.Worksheet = ws;
            wsp.Worksheet.Save();
            Sheets sheets = new Sheets();
            Sheet sheet = new Sheet();
            sheet.Name = "Sheet1";
            sheet.SheetId = 1;
            sheet.Id = wbp.GetIdOfPart(wsp);
            sheets.Append(sheet);
            wb.Append(fv);
            wb.Append(sheets);
            xl.WorkbookPart.Workbook = wb;
            xl.WorkbookPart.Workbook.Save();
            xl.Close();
        }
Exemplo n.º 41
0
        private void generateWorkbookPartContent(WorkbookPart workbookPart)
        {
            var workbook = new Workbook();
            workbook.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            var fileVersion = new FileVersion { ApplicationName = "xl", LastEdited = "5", LowestEdited = "5", BuildVersion = "9303" };
            var workbookProperties = new WorkbookProperties { DefaultThemeVersion = 124226 };

            var bookViews = new BookViews();
            var workbookView = new WorkbookView { XWindow = 630, YWindow = 600, WindowWidth = 27495, WindowHeight = 11955 };

            bookViews.Append(workbookView);

            var sheets = new Sheets();
            var sheet = new Sheet { Name = "Документ", SheetId = 1, Id = "rId1" };

            sheets.Append(sheet);
            var calculationProperties = new CalculationProperties { CalculationId = 0 };

            workbook.Append(fileVersion);
            workbook.Append(workbookProperties);
            workbook.Append(bookViews);
            workbook.Append(sheets);
            workbook.Append(calculationProperties);

            workbookPart.Workbook = workbook;
        }
Exemplo n.º 42
0
        public void GetLatestVersionToMigrate_PartiallyValidData()
        {
            var mockLookup = new Mock<IDynamoLookUp>();
            mockLookup.Setup(x => x.GetDynamoUserDataLocations()).Returns(MockUserDirectories);

            var current = new FileVersion(0, 9, TempFolder);
            var latest = DynamoMigratorBase.GetLatestVersionToMigrate(null, mockLookup.Object, current);
            Assert.IsTrue(latest.HasValue);
            Assert.AreEqual(0, latest.Value.MajorPart);
            Assert.AreEqual(8, latest.Value.MinorPart);
            Assert.AreEqual(TempFolder, latest.Value.UserDataRoot);
        }
Exemplo n.º 43
0
		/// <summary>
		/// Computes the displayed name of the file version.
		/// Should be kept in sync with the AbstractFileVersion version.
		/// </summary>
		/// <param name="name"> The base name of a file (excluding the path). </param>
		/// <param name="version"> The version. </param>
		/// <returns> The string to display. </returns>
		private string ComputeMoniker(string name, FileVersion version)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append(name);
			sb.Append('#');
			sb.Append(version.Revision.ToString());
			if (!version.IsRevisionBase)
			{
				if (version.TimeStamp != null)
					sb.Append(" " + WrapTimeStamp(version.TimeStamp.Value) + " ");
				if (version.Action == (int)SourceControlAction.ADD)
					sb.Append(" ADD ");
				else if (version.Action == (int)SourceControlAction.EDIT)
					sb.Append(" EDIT ");
				else if (version.Action == (int)SourceControlAction.DELETE)
					sb.Append(" DELETE ");
				else if (version.Action == (int)SourceControlAction.BRANCH)
					sb.Append(" BRANCH ");
				else if (version.Action == (int)SourceControlAction.INTEGRATE)
					sb.Append(" INTEGRATE ");
				else if (version.Action == (int)SourceControlAction.RENAME)
					sb.Append(" RENAME ");
			}

			return sb.ToString();
		}
Exemplo n.º 44
0
		/// <summary>
		/// Computes and displays the diff between two distinct versions. Uses unix "diff" command to actually
		/// produce the diff. This is relatively slow operation and involves spooling the data into two temp
		/// files and running an external process.
		/// </summary>
		/// <param name="left"> File version on the left. </param>
		/// <param name="right"> File version on the right. </param>
		/// <param name="name"> Base name (no path) of the file for display purposes. </param>
		/// <param name="baseReviewId"> The id of the base review. </param>
		/// <param name="ignoreWhiteSpaces"> Whether to ignore white spaces. </param>
		private void DisplayDiff(FileVersion left, FileVersion right, string name, int baseReviewId, bool ignoreWhiteSpaces)
		{
			using (var leftFile = SaveToTempFile(left))
			using (var rightFile = SaveToTempFile(right))
			{
				if (leftFile == null)
					return;

				if (rightFile == null)
					return;

				string args = leftFile.FullName + " " + rightFile.FullName;
				if (ignoreWhiteSpaces && !string.IsNullOrEmpty(DiffArgsIgnoreWhiteSpace))
					args = DiffArgsIgnoreWhiteSpace + " " + args;

				if (!string.IsNullOrEmpty(DiffArgsBase))
					args = DiffArgsBase + " " + args;

				string stderr = null;
				string result = null;

				using (Process diff = new Process())
				{
					diff.StartInfo.UseShellExecute = false;
					diff.StartInfo.RedirectStandardError = true;
					diff.StartInfo.RedirectStandardOutput = true;
					diff.StartInfo.CreateNoWindow = true;
					diff.StartInfo.FileName = DiffExe;
					diff.StartInfo.Arguments = args;
					diff.Start();

					result = Malevich.Util.CommonUtils.ReadProcessOutput(diff, false, out stderr);
				}

				if (!stderr.IsNullOrEmpty())
				{
					ErrorOut("Diff failed.");
					ErrorOut(stderr);

					return;
				}

				using (StreamCombiner leftStream = new StreamCombiner(new StreamReader(leftFile.FullName)))
				using (StreamCombiner rightStream = new StreamCombiner(new StreamReader(rightFile.FullName)))
				using (StreamCombiner rawDiffStream = new StreamCombiner(result))
				{
					ActivePage.Controls.Add(GenerateFileDiffView(
						leftStream, left.Id, GetComments(left.Id, baseReviewId), ComputeMoniker(name, left),
						rightStream, right.Id, GetComments(right.Id, baseReviewId), ComputeMoniker(name, right),
						true, rawDiffStream, name));
				}
			}
		}
        // Generates content of workbookPart1.
        private void GenerateWorkbookPart1Content(WorkbookPart workbookPart1)
        {
            Workbook workbook1 = new Workbook();
            workbook1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            FileVersion fileVersion1 = new FileVersion() { ApplicationName = "xl", LastEdited = "4", LowestEdited = "4", BuildVersion = "4505" };
            WorkbookProperties workbookProperties1 = new WorkbookProperties();

            BookViews bookViews1 = new BookViews();
            WorkbookView workbookView1 = new WorkbookView() { XWindow = 600, YWindow = 105, WindowWidth = (UInt32Value)13995U, WindowHeight = (UInt32Value)8190U };

            bookViews1.Append(workbookView1);

            Sheets sheets1 = new Sheets();
            Sheet sheet1 = new Sheet() { Name = "Hoja1", SheetId = (UInt32Value)1U, Id = "rId1" };

            sheets1.Append(sheet1);

            DefinedNames definedNames1 = new DefinedNames();
            DefinedName definedName1 = new DefinedName() { Name = "_xlnm.Print_Area", LocalSheetId = (UInt32Value)0U };
            definedName1.Text = "Hoja1!$A$1:$AK$31";

            definedNames1.Append(definedName1);
            CalculationProperties calculationProperties1 = new CalculationProperties() { CalculationId = (UInt32Value)124519U };

            workbook1.Append(fileVersion1);
            workbook1.Append(workbookProperties1);
            workbook1.Append(bookViews1);
            workbook1.Append(sheets1);
            workbook1.Append(definedNames1);
            workbook1.Append(calculationProperties1);

            workbookPart1.Workbook = workbook1;
        }
Exemplo n.º 46
0
		/// <summary>
		/// Saves the text of a file version to a temp file.
		/// </summary>
		/// <param name="version"> The version to save. </param>
		/// <returns> The name of the file, or null if it fails. </returns>
		private TempFile SaveToTempFile(FileVersion version)
		{
			StreamCombiner reader = GetFileStream(version);
			if (reader == null)
				return null;

			TempFile file = new TempFile();

			using (reader)
			using (StreamWriter writer = new StreamWriter(file.FullName))
			{
				foreach (string line in reader.ReadLines())
					writer.WriteLine(line);
			}

			// We created the temp file, but because of the security settings for %TEMP% might not have access to it.
			// Grant it explicitly.
			AddFileSecurity(file.FullName, WellKnownSidType.AuthenticatedUserSid, FileSystemRights.Read,
				AccessControlType.Allow);
			AddFileSecurity(file.FullName, WellKnownSidType.CreatorOwnerSid, FileSystemRights.FullControl,
				AccessControlType.Allow);

			return file;
		}
Exemplo n.º 47
0
        // Generates content of workbookPart1.
        private void GenerateWorkbookPart1Content(WorkbookPart workbookPart1)
        {
            Workbook workbook1 = new Workbook(){ MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "x15" }  };
            workbook1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            workbook1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            workbook1.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
            FileVersion fileVersion1 = new FileVersion(){ ApplicationName = "xl", LastEdited = "6", LowestEdited = "6", BuildVersion = "14420" };
            WorkbookProperties workbookProperties1 = new WorkbookProperties(){ DefaultThemeVersion = (UInt32Value)153222U };

            AlternateContent alternateContent1 = new AlternateContent();
            alternateContent1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");

            AlternateContentChoice alternateContentChoice1 = new AlternateContentChoice(){ Requires = "x15" };

            X15ac.AbsolutePath absolutePath1 = new X15ac.AbsolutePath(){ Url = "D:\\Users\\dito\\Desktop\\TestDocumentResaver\\OpenXmlApiConversion\\Slicer\\" };
            absolutePath1.AddNamespaceDeclaration("x15ac", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/ac");

            alternateContentChoice1.Append(absolutePath1);

            alternateContent1.Append(alternateContentChoice1);

            BookViews bookViews1 = new BookViews();
            WorkbookView workbookView1 = new WorkbookView(){ XWindow = 0, YWindow = 0, WindowWidth = (UInt32Value)26940U, WindowHeight = (UInt32Value)15120U };

            bookViews1.Append(workbookView1);

            Sheets sheets1 = new Sheets();
            Sheet sheet1 = new Sheet(){ Name = "Sheet1", SheetId = (UInt32Value)1U, Id = "rId1" };

            sheets1.Append(sheet1);

            DefinedNames definedNames1 = new DefinedNames();
            DefinedName definedName1 = new DefinedName(){ Name = "Slicer_Column1" };
            definedName1.Text = "#N/A";
            DefinedName definedName2 = new DefinedName(){ Name = "Slicer_Column2" };
            definedName2.Text = "#N/A";
            DefinedName definedName3 = new DefinedName(){ Name = "Slicer_Column3" };
            definedName3.Text = "#N/A";

            definedNames1.Append(definedName1);
            definedNames1.Append(definedName2);
            definedNames1.Append(definedName3);
            CalculationProperties calculationProperties1 = new CalculationProperties(){ CalculationId = (UInt32Value)152511U };

            WorkbookExtensionList workbookExtensionList1 = new WorkbookExtensionList();

            WorkbookExtension workbookExtension1 = new WorkbookExtension(){ Uri = "{79F54976-1DA5-4618-B147-4CDE4B953A38}" };
            workbookExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
            X14.WorkbookProperties workbookProperties2 = new X14.WorkbookProperties();

            workbookExtension1.Append(workbookProperties2);

            WorkbookExtension workbookExtension2 = new WorkbookExtension(){ Uri = "{46BE6895-7355-4a93-B00E-2C351335B9C9}" };
            workbookExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");

            X15.SlicerCaches slicerCaches1 = new X15.SlicerCaches();
            slicerCaches1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
            X14.SlicerCache slicerCache1 = new X14.SlicerCache(){ Id = "rId2" };
            X14.SlicerCache slicerCache2 = new X14.SlicerCache(){ Id = "rId3" };
            X14.SlicerCache slicerCache3 = new X14.SlicerCache(){ Id = "rId4" };

            slicerCaches1.Append(slicerCache1);
            slicerCaches1.Append(slicerCache2);
            slicerCaches1.Append(slicerCache3);

            workbookExtension2.Append(slicerCaches1);

            WorkbookExtension workbookExtension3 = new WorkbookExtension(){ Uri = "{140A7094-0E35-4892-8432-C4D2E57EDEB5}" };
            workbookExtension3.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
            X15.WorkbookProperties workbookProperties3 = new X15.WorkbookProperties(){ ChartTrackingReferenceBase = true };

            workbookExtension3.Append(workbookProperties3);

            workbookExtensionList1.Append(workbookExtension1);
            workbookExtensionList1.Append(workbookExtension2);
            workbookExtensionList1.Append(workbookExtension3);

            workbook1.Append(fileVersion1);
            workbook1.Append(workbookProperties1);
            workbook1.Append(alternateContent1);
            workbook1.Append(bookViews1);
            workbook1.Append(sheets1);
            workbook1.Append(definedNames1);
            workbook1.Append(calculationProperties1);
            workbook1.Append(workbookExtensionList1);

            workbookPart1.Workbook = workbook1;
        }
Exemplo n.º 48
0
        public FileMetadata SaveFile(FileDTO file)
        {
            var basePath = @"D:\";
            var chkSum = FileHelper.MD5File(file.FileStream);
            bool isAdd = true;
            var media = _fileMediaRepo.DbSet().Where(c => c.CheckSum == chkSum).FirstOrDefault();
            //复制相同文件重复上次
            if (media == null)
            {
                var relativePath = file.CreatedTime.ToString("yyyyMMdd") + @"\";
                var fullPath = basePath + relativePath + Guid.NewGuid();
                media = FileFactory.CreateFileMeida(file.FileStream, chkSum, fullPath, relativePath);
                _fileMediaRepo.Add(media);
            }
            var metaData = _fileMetadataRepo.DbSet().Where(c => c.Id == file.Id).FirstOrDefault();
            if (metaData == null)
            {
                var extension = file.ResourceName.Substring(file.ResourceName.LastIndexOf("."));
                metaData = FileFactory.CreateFile(
                    file.Id,
                    file.ResourceName,
                    file.CatalogUri,
                    file.CreatedTime,
                    extension,
                    media.Id,
                    file.CreatedTime,
                    file.Owner,
                    file.Owner,
                    file.ResourceSize,
                    file.Propertys
                    );
            }
            else
            {
                isAdd = false;
                metaData.Revision++;
                metaData.LastModifiedTime = file.CreatedTime;
                metaData.LastModifier = file.Owner;
                metaData.ResourceName = file.ResourceName;
                metaData.CatalogUri = file.CatalogUri;
                metaData.Extension = file.ResourceName.Substring(file.ResourceName.LastIndexOf("."));
            }

            var version = new FileVersion
            {
                Remark = "",
                Id = Guid.NewGuid().ToString().ToUpper(),
                ModifiedTime = metaData.LastModifiedTime,
                Modifier = metaData.LastModifier,
                Revision = metaData.Revision,
                FileMetadata = metaData,
                FileId = metaData.Id,
                FileInfor = JsonConvert.SerializeObject(metaData)
            };
            metaData.Versions.Add(version);

            if (isAdd)
            {
                _fileMetadataRepo.Add(metaData);
            }

            var i = _unitOfWork.Commit();

            return metaData;
        }
Exemplo n.º 49
0
        private static void BatchConvertResource(string sourcePath, string destinationPath, ResourceFormat inputFormat, ResourceFormat outputFormat, FileVersion fileVersion)
        {
            try
            {
                CommandLineLogger.LogDebug($"Using destination extension: {outputFormat}");

                ResourceUtils resourceUtils = new ResourceUtils();
                resourceUtils.ConvertResources(sourcePath, destinationPath, inputFormat, outputFormat, fileVersion);

                CommandLineLogger.LogInfo($"Wrote resources to: {destinationPath}");
            }
            catch (Exception e)
            {
                CommandLineLogger.LogFatal($"Failed to batch convert resources: {e.Message}", 2);
                CommandLineLogger.LogTrace($"{e.StackTrace}");
            }
        }
Exemplo n.º 50
0
        // Generates content of workbookPart1.
        private void GenerateWorkbookPart1Content(WorkbookPart workbookPart1)
        {
            Workbook workbook1 = new Workbook(){ MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "x15" }  };
            workbook1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            workbook1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            workbook1.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
            FileVersion fileVersion1 = new FileVersion(){ ApplicationName = "xl", LastEdited = "6", LowestEdited = "6", BuildVersion = "14420" };
            WorkbookProperties workbookProperties1 = new WorkbookProperties(){ DefaultThemeVersion = (UInt32Value)153222U };

            AlternateContent alternateContent1 = new AlternateContent();
            alternateContent1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");

            AlternateContentChoice alternateContentChoice1 = new AlternateContentChoice(){ Requires = "x15" };

            X15ac.AbsolutePath absolutePath1 = new X15ac.AbsolutePath(){ Url = "D:\\Users\\dito\\Desktop\\TestDocumentResaver\\OpenXmlApiConversion\\WorkBookPr\\" };
            absolutePath1.AddNamespaceDeclaration("x15ac", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/ac");

            alternateContentChoice1.Append(absolutePath1);

            alternateContent1.Append(alternateContentChoice1);

            BookViews bookViews1 = new BookViews();
            WorkbookView workbookView1 = new WorkbookView(){ XWindow = 0, YWindow = 0, WindowWidth = (UInt32Value)26940U, WindowHeight = (UInt32Value)15120U };

            bookViews1.Append(workbookView1);

            Sheets sheets1 = new Sheets();
            Sheet sheet1 = new Sheet(){ Name = "Sheet1", SheetId = (UInt32Value)1U, Id = "rId1" };

            sheets1.Append(sheet1);
            CalculationProperties calculationProperties1 = new CalculationProperties(){ CalculationId = (UInt32Value)152511U };

            WorkbookExtensionList workbookExtensionList1 = new WorkbookExtensionList();

            WorkbookExtension workbookExtension1 = new WorkbookExtension(){ Uri = "{140A7094-0E35-4892-8432-C4D2E57EDEB5}" };
            workbookExtension1.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
            X15.WorkbookProperties workbookProperties2 = new X15.WorkbookProperties(){ ChartTrackingReferenceBase = true };

            workbookExtension1.Append(workbookProperties2);

            workbookExtensionList1.Append(workbookExtension1);

            workbook1.Append(fileVersion1);
            workbook1.Append(workbookProperties1);
            workbook1.Append(alternateContent1);
            workbook1.Append(bookViews1);
            workbook1.Append(sheets1);
            workbook1.Append(calculationProperties1);
            workbook1.Append(workbookExtensionList1);

            workbookPart1.Workbook = workbook1;
        }
Exemplo n.º 51
0
 public LSFWriter(Stream stream, FileVersion version)
 {
     this.Stream  = stream;
     this.Version = (uint)version;
 }
        private List<SwatchColor> ReadSwatches(Stream stream, FileVersion version)
        {
            int colorCount;
            List<SwatchColor> results;

            results = new List<SwatchColor>();

            // read the number of colors, which also occupies two bytes
            colorCount = this.ReadInt16(stream);

            for (int i = 0; i < colorCount; i++)
            {
                ColorSpace colorSpace;
                int value1;
                int value2;
                int value3;
                int value4;
                string name = "color_" + i.ToString();

                // again, two bytes for the color space
                colorSpace = (ColorSpace)(this.ReadInt16(stream));

                value1 = this.ReadInt16(stream);
                value2 = this.ReadInt16(stream);
                value3 = this.ReadInt16(stream);
                value4 = this.ReadInt16(stream);

                if (version == FileVersion.Version2)
                {
                    int length;

                    // need to read the name even though currently our colour collection doesn't support names
                    length = ReadInt32(stream);
                    if (length > 0)
                    {
                        name = this.ReadString(stream, length);
                    }

                }

                switch (colorSpace)
                {
                    case ColorSpace.Rgb:
                        int red;
                        int green;
                        int blue;

                        // RGB.
                        // The first three values in the color data are red , green , and blue . They are full unsigned
                        //  16-bit values as in Apple's RGBColor data structure. Pure red = 65535, 0, 0.

                        red = value1 / 256; // 0-255
                        green = value2 / 256; // 0-255
                        blue = value3 / 256; // 0-255

                        results.Add(new SwatchColor() { Red = red, Blue = blue, Green = green, Name = name });
                        break;

                    case ColorSpace.Hsb:
                        double hue;
                        double saturation;
                        double brightness;

                        // HSB.
                        // The first three values in the color data are hue , saturation , and brightness . They are full 
                        // unsigned 16-bit values as in Apple's HSVColor data structure. Pure red = 0,65535, 65535.

                        hue = value1 / 182.04; // 0-359
                        saturation = value2 / 655.35; // 0-100
                        brightness = value3 / 655.35; // 0-100

                        throw new InvalidDataException(string.Format("Color space '{0}' not supported.", colorSpace));

                    case ColorSpace.Grayscale:

                        int gray;

                        // Grayscale.
                        // The first value in the color data is the gray value, from 0...10000.

                        gray = (int)(value1 / 39.0625); // 0-255

                        results.Add(new SwatchColor() { Red = gray, Blue = gray, Green = gray, Name = name });
                        break;

                    default:
                        throw new InvalidDataException(string.Format("Color space '{0}' not supported.", colorSpace));
                }
            }

            return results;
        }
Exemplo n.º 53
0
        public static void SaveResource(Resource resource, string outputPath, ResourceFormat format, FileVersion version = 0x0)
        {
            FileManager.TryToCreateDirectory(outputPath);

            using (var file = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
            {
                switch (format)
                {
                case ResourceFormat.LSX:
                {
                    var writer = new LSXWriter(file);
                    writer.PrettyPrint = true;
                    writer.Write(resource);
                    break;
                }

                case ResourceFormat.LSB:
                {
                    var writer = new LSBWriter(file);
                    writer.Write(resource);
                    break;
                }

                case ResourceFormat.LSF:
                {
                    // Write in V2 format for D:OS EE compatibility
                    FileVersion lsfVersion = version == 0x0 ? FileVersion.VerChunkedCompress : version;

                    var writer = new LSFWriter(file, lsfVersion);
                    writer.Write(resource);
                    break;
                }

                case ResourceFormat.LSJ:
                {
                    var writer = new LSJWriter(file);
                    writer.PrettyPrint = true;
                    writer.Write(resource);
                    break;
                }

                default:
                    throw new ArgumentException("Invalid resource format");
                }
            }
        }
Exemplo n.º 54
0
 public AstContext(NitraClient client, SolutionId solutionId, ProjectId projectId, FileId fileId, FileVersion fileVersion)
 {
   Client      = client;
   SolutionId  = solutionId;
   ProjectId   = projectId;
   FileId      = fileId;
   FileVersion = fileVersion;
 }
Exemplo n.º 55
0
 public static int UpdateFileVersion(FileVersion version) => _db.Update(version);
Exemplo n.º 56
0
        // Generates content of workbookPart1.
        private void GenerateWorkbookPart1Content(WorkbookPart workbookPart1)
        {
            Workbook workbook1 = new Workbook();
            workbook1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            FileVersion fileVersion1 = new FileVersion(){ ApplicationName = "xl", LastEdited = "4", LowestEdited = "4", BuildVersion = "4505" };
            WorkbookProperties workbookProperties1 = new WorkbookProperties(){ DefaultThemeVersion = (UInt32Value)124226U };

            BookViews bookViews1 = new BookViews();
            WorkbookView workbookView1 = new WorkbookView(){ XWindow = 240, YWindow = 45, WindowWidth = (UInt32Value)28320U, WindowHeight = (UInt32Value)12855U };

            bookViews1.Append(workbookView1);

            Sheets sheets1 = new Sheets();

            Sheet sheet1 = new Sheet(){ Name = "NOMBRE DE SOLAPA", SheetId = (UInt32Value)1U, Id = "rId1" };

            switch (_Estado.ToUpper())
            {
                case "ORDENADO":
                    {
                        sheet1.Name = "O" + _oCabecera.AnoMes + " " + _oCabecera.IdentifEspacio;
                        break;
                    }
                case "ESTIMADO":
                    {
                        sheet1.Name = "E" + _eCabecera.AnoMes + " V" + _eCabecera.Version + " " + _eCabecera.IdentifEspacio;
                        break;
                    }
                case "CERTIFICADO":
                    {
                        sheet1.Name = "C" + _cCabecera.AnoMes + " " + _cCabecera.IdentifEspacio + _cCabecera.IdentifOrigen;
                        break;
                    }
            }

            sheets1.Append(sheet1);
            CalculationProperties calculationProperties1 = new CalculationProperties(){ CalculationId = (UInt32Value)124519U };

            workbook1.Append(fileVersion1);
            workbook1.Append(workbookProperties1);
            workbook1.Append(bookViews1);
            workbook1.Append(sheets1);
            workbook1.Append(calculationProperties1);

            workbookPart1.Workbook = workbook1;
        }
Exemplo n.º 57
0
        //Main class function, export the mutationList to XLSX file, sets file name to testName.
        public static void saveXLS(String testName, List <Mutation> mutationList)
        {
            SpreadsheetDocument xl = null;
            string fullPath        = Properties.Settings.Default.ExportSavePath + @"\" + testName;

            fullPath += ".xlsx";
            try
            {
                xl = SpreadsheetDocument.Create(fullPath, SpreadsheetDocumentType.Workbook);
            }
            catch (IOException)
            {
                throw;
            }
            WorkbookPart  wbp = xl.AddWorkbookPart();
            WorksheetPart wsp = wbp.AddNewPart <WorksheetPart>();
            Workbook      wb  = new Workbook();
            FileVersion   fv  = new FileVersion();

            fv.ApplicationName = "Microsoft Office Excel";
            Worksheet          ws   = new Worksheet();
            SheetData          sd   = new SheetData();
            WorkbookStylesPart wbsp = wbp.AddNewPart <WorkbookStylesPart>();

            wbsp.Stylesheet = GenerateStyleSheet();
            wbsp.Stylesheet.Save();

            //save the longest width for each column.
            string[] longestWordPerColumn = new string[12];

            int k = 0;

            //create and add header row.
            Row headerRow = new Row();

            foreach (string s in Mutation.getHeaderForExport())
            {
                Cell cell = new Cell();
                cell.DataType   = CellValues.String;
                cell.CellValue  = new CellValue(s);
                cell.StyleIndex = 1;
                headerRow.AppendChild(cell);
                longestWordPerColumn[k] = s;
                k++;
            }
            sd.AppendChild(headerRow);

            //create and add rows for each mutation.
            foreach (Mutation m in mutationList)
            {
                Row      newRow     = new Row();
                string[] infoString = m.getInfoForExport();
                for (int i = 0; i < infoString.Length; i++)
                {
                    Cell cell1 = new Cell();
                    if (i == 1)
                    {
                        cell1.DataType = CellValues.Number;
                    }
                    else
                    {
                        cell1.DataType = CellValues.String;
                    }
                    cell1.CellValue = new CellValue(infoString[i]);
                    if (!m.CosmicName.Equals("-----"))
                    {
                        cell1.StyleIndex = 2;
                    }
                    else
                    {
                        cell1.StyleIndex = 3;
                    }
                    newRow.AppendChild(cell1);
                    if (longestWordPerColumn[i].Length < infoString[i].Length)
                    {
                        longestWordPerColumn[i] = infoString[i];
                    }
                }
                sd.AppendChild(newRow);
            }

            //Sets the column width to longest width for each column.
            Columns columns = new Columns();

            for (int i = 0; i < 12; i++)
            {
                columns.Append(CreateColumnData((UInt32)i + 1, (UInt32)i + 1, GetWidth("Calibri", 11, longestWordPerColumn[i])));
            }
            ws.Append(columns);


            ws.Append(sd);
            wsp.Worksheet = ws;
            wsp.Worksheet.Save();
            Sheets sheets = new Sheets();
            Sheet  sheet  = new Sheet();

            sheet.Name    = "Sheet1";
            sheet.SheetId = 1;
            sheet.Id      = wbp.GetIdOfPart(wsp);
            sheets.Append(sheet);
            wb.Append(fv);
            wb.Append(sheets);
            xl.WorkbookPart.Workbook = wb;
            xl.WorkbookPart.Workbook.Save();
            xl.Close();
        }
Exemplo n.º 58
0
 internal void FileAdded(ProjectId projectId, string path, FileId id, FileVersion version)
 {
   Client.Send(new ClientMessage.FileLoaded(projectId, path, id, version));
 }
Exemplo n.º 59
0
        public static Boolean RegisterProtocol(UserSession Session, String CardID, String TempFolder, Guid EmployeeId)
        {
            logger.Info("cardId='{0}'", CardID);
            logger.Info("tempName='{0}'", TempFolder);
            logger.Info("EmployeeId='{0}'", EmployeeId);
            using (new Impersonator(ServerExtension.Domain, ServerExtension.User, ServerExtension.SecurePassword))
            {
                Guid CardId = new Guid(CardID);
                switch (Session.CardManager.GetCardState(CardId))
                {
                case ObjectState.Existing:
                    DirectoryInfo TempDirectory = new DirectoryInfo(Path.Combine(ArchiveTempPath, TempFolder));
                    FileInfo[]    TempFiles     = TempDirectory.GetFiles();
                    logger.Info("В папке файлов: " + TempFiles.Length);
                    if (TempFiles.Length > 0)
                    {
                        logger.Info("Файлы: " + TempFiles.Select(file => file.Name).Aggregate((a, b) => a + "; " + b));
                        CardData Card = Session.CardManager.GetCardData(CardId);
                        Card.UnlockCard();
                        if (Card.InUpdate)
                        {
                            Card.CancelUpdate();
                        }
                        Card.PlaceLock();
                        Card.BeginUpdate();
                        foreach (Protocol Protocol in TempFiles.Select(fi => new Protocol(fi)))
                        {
                            if (Protocol.IsParsed)
                            {
                                RowData MainInfoRow   = Card.Sections[CardOrd.MainInfo.ID].FirstRow;
                                Guid    FilesID       = MainInfoRow.GetGuid(CardOrd.MainInfo.FilesID) ?? Guid.Empty;
                                Boolean FileListExist = !(FilesID.IsEmpty() && Card.Session.CardManager.GetCardState(FilesID) == ObjectState.Existing);
                                logger.Info("FileListExist = " + FileListExist);
                                CardData FileListCard;
                                if (FileListExist)
                                {
                                    FileListCard = Card.Session.CardManager.GetCardData(FilesID);
                                }
                                else
                                {
                                    FileListCard = Card.Session.CardManager.CreateCardData(FileList.ID);
                                    MainInfoRow.SetGuid(CardOrd.MainInfo.FilesID, FileListCard.Id);
                                }

                                SectionData FileReferencesSection = FileListCard.Sections[FileList.FileReferences.ID];
                                /* Проверка существования файла протокола в карточке */
                                if (!FileReferencesSection.Rows.Any(file => Protocol.PhysicalFile.Name.Contains(file.GetString(CardFile.MainInfo.FileName))))
                                {
                                    FileListCard.UnlockCard();

                                    VersionedFileCard FileCard        = (VersionedFileCard)Card.Session.CardManager.CreateCard(DocsVision.Platform.Cards.Constants.VersionedFileCard.ID);
                                    FileVersion       FileCardVersion = FileCard.Initialize(Protocol.PhysicalFile.FullName, Guid.Empty, false, true);
                                    CardData          FileData        = Card.Session.CardManager.CreateCardData(CardFile.ID);

                                    FileData.BeginUpdate();
                                    FileData.Description = "Файл: " + FileCard.Name;

                                    RowData FileMainInfoRow = FileData.Sections[CardFile.MainInfo.ID].Rows.AddNew();
                                    FileMainInfoRow.SetGuid(CardFile.MainInfo.FileID, FileCard.Id);
                                    FileMainInfoRow.SetString(CardFile.MainInfo.FileName, FileCardVersion.Name);
                                    FileMainInfoRow.SetGuid(CardFile.MainInfo.Author, FileCardVersion.AuthorId);
                                    FileMainInfoRow.SetInt32(CardFile.MainInfo.FileSize, FileCardVersion.Size);
                                    FileMainInfoRow.SetInt32(CardFile.MainInfo.VersioningType, 0);

                                    RowData FilePropertiesRow = FileData.Sections[CardFile.Properties.ID].Rows.AddNew();
                                    FilePropertiesRow.SetString(CardFile.Properties.Name, "Дата начала испытаний");
                                    FilePropertiesRow.SetInt32(CardFile.Properties.ParamType, (Int32)PropertieParamType.Date);
                                    FilePropertiesRow.SetString(CardFile.Properties.Value, Protocol.StringDate);
                                    FilePropertiesRow.SetString(CardFile.Properties.DisplayValue, Protocol.StringDate);

                                    FileData.Sections[CardFile.Categories.ID].Rows.AddNew().SetGuid(CardFile.Categories.CategoryID, MyHelper.RefCategory_CalibrationProtocol);

                                    FileData.EndUpdate();

                                    Int32 FilesCount = FileReferencesSection.Rows.Count;
                                    FileReferencesSection.Rows.AddNew().SetGuid(FileList.FileReferences.CardFileID, FileData.Id);
                                    FileListCard.Sections[FileList.MainInfo.ID].FirstRow.SetInt32(FileList.MainInfo.Count, FilesCount + 1);

                                    SectionData PropertiesSection = Card.Sections[CardOrd.Properties.ID];
                                    RowData     PropertyRow       = PropertiesSection.GetProperty("Дата");
                                    if (!PropertyRow.IsNull())
                                    {
                                        RowDataCollection SelectedValuesRows = PropertyRow.ChildSections[CardOrd.SelectedValues.ID].Rows;
                                        RowData           SelectedValuesRow  = SelectedValuesRows.AddNew();
                                        SelectedValuesRow.SetInt32(CardOrd.SelectedValues.Order, SelectedValuesRows.Count);
                                        SelectedValuesRow.SetDateTime(CardOrd.SelectedValues.SelectedValue, DateTime.Now);
                                    }
                                    PropertyRow = PropertiesSection.GetProperty("Действие");
                                    if (!PropertyRow.IsNull())
                                    {
                                        RowDataCollection SelectedValuesRows = PropertyRow.ChildSections[CardOrd.SelectedValues.ID].Rows;
                                        RowData           SelectedValuesRow  = SelectedValuesRows.AddNew();
                                        SelectedValuesRow.SetInt32(CardOrd.SelectedValues.Order, SelectedValuesRows.Count);
                                        SelectedValuesRow.SetString(CardOrd.SelectedValues.SelectedValue, "Прикреплен протокол калибровки");
                                    }
                                    PropertyRow = PropertiesSection.GetProperty("Участник");
                                    if (!PropertyRow.IsNull())
                                    {
                                        RowDataCollection SelectedValuesRows = PropertyRow.ChildSections[CardOrd.SelectedValues.ID].Rows;
                                        RowData           SelectedValuesRow  = SelectedValuesRows.AddNew();
                                        SelectedValuesRow.SetInt32(CardOrd.SelectedValues.Order, SelectedValuesRows.Count);
                                        SelectedValuesRow.SetGuid(CardOrd.SelectedValues.SelectedValue, EmployeeId);
                                    }
                                    PropertyRow = PropertiesSection.GetProperty("Комментарий");
                                    if (!PropertyRow.IsNull())
                                    {
                                        RowDataCollection SelectedValuesRows = PropertyRow.ChildSections[CardOrd.SelectedValues.ID].Rows;
                                        RowData           SelectedValuesRow  = SelectedValuesRows.AddNew();
                                        SelectedValuesRow.SetInt32(CardOrd.SelectedValues.Order, SelectedValuesRows.Count);
                                        SelectedValuesRow.SetString(CardOrd.SelectedValues.SelectedValue, "Автоматическое прикрепление протокола калибровки " + Protocol.PhysicalFile.Name);
                                    }
                                    PropertyRow = PropertiesSection.GetProperty("Ссылки");
                                    if (!PropertyRow.IsNull())
                                    {
                                        RowDataCollection SelectedValuesRows = PropertyRow.ChildSections[CardOrd.SelectedValues.ID].Rows;
                                        RowData           SelectedValuesRow  = SelectedValuesRows.AddNew();
                                        SelectedValuesRow.SetInt32(CardOrd.SelectedValues.Order, SelectedValuesRows.Count);
                                        SelectedValuesRow.SetString(CardOrd.SelectedValues.SelectedValue, null);
                                    }

                                    if (!FileListExist)
                                    {
                                        Card.Sections[CardOrd.MainInfo.ID].FirstRow.SetGuid(CardOrd.MainInfo.FilesID, FileListCard.Id);
                                    }
                                }
                            }
                            else
                            {
                                logger.Warn("Нераспознаный файл: " + Protocol.PhysicalFile.Name);
                            }
                        }

                        Card.EndUpdate();
                        Card.RemoveLock();

                        TempDirectory.Delete(true);
                        logger.Info("RegisterProtocol - выполнено.");
                    }
                    else
                    {
                        logger.Info("RegisterProtocol - не выполнено.");
                    }
                    return(true);

                default:
                    logger.Info("RegisterProtocol - не выполнено. Паспорт прибора не существует.");
                    return(false);
                }
            }
        }
Exemplo n.º 60
0
 internal void CaretPositionChanged(FileId fileId, int pos, FileVersion version)
 {
   Client.Send(new ClientMessage.SetCaretPos(fileId, version, pos));
 }