private void SingleWriteReadMatchingSTREAMED(int size) { MemoryStream ms = new MemoryStream(size); CompoundFile cf = new CompoundFile(); CFStorage st = cf.RootStorage.AddStorage("MyStorage"); CFStream sm = st.AddStream("MyStream"); byte[] b = Helpers.GetBuffer(size); sm.SetData(b); cf.Save(ms); cf.Close(); CompoundFile cf2 = new CompoundFile(ms); CFStorage st2 = cf2.RootStorage.GetStorage("MyStorage"); CFStream sm2 = st2.GetStream("MyStream"); Assert.IsNotNull(sm2); Assert.IsTrue(sm2.Size == size); Assert.IsTrue(Helpers.CompareBuffer(sm2.GetData(), b)); cf2.Close(); }
/// <summary> /// Creates this object and sets all its properties /// </summary> /// <param name="stream">The Compound File Storage Ole <see cref="CFStream" /></param> internal OleStream(CFStream stream) { using (var memoryStream = new MemoryStream(stream.GetData())) using (var binaryReader = new BinaryReader(memoryStream)) { Version = binaryReader.ReadUInt16(); // Flags (4 bytes): If this field is set to 0x00000001, the OLEStream structure MUST be for a linked object and // the CLSID field of the Compound File Directory Entry of the OLE Compound File Storage object MUST be set to // CLSID_StdOleLink ({00000300-0000-0000-C000-000000000046}). If this field is set to 0x00000000, then the OLEStream // structure MUST be for an embedded object and the CLSID field of the Compound File Directory Entry // of the OLE Compound File Storage object MUST be set to the object class GUID of the creating application. var flags = binaryReader.ReadUInt32(); switch (flags) { case 0x00000000: case 0x00001000: Format = OleFormat.File; break; case 0x00000001: case 0x00001001: Format = OleFormat.Link; break; } // LinkUpdateOption (4 bytes): This field contains an implementation-specific hint supplied by the application or by // a higher-level protocol that creates the data structure. The hint MAY be ignored on processing of this data structure LinkUpdateOptions = binaryReader.ReadUInt32(); //Reserved1 (4 bytes): This MUST be set to 0x00000000. Otherwise, the OLEStream structure is invalid binaryReader.ReadUInt32(); // ReservedMonikerStreamSize (4 bytes): This MUST be set to the size, in bytes, of the ReservedMonikerStream field. If this // field has a value 0x00000000, the ReservedMonikerStream field MUST NOT be present. var reservedMonikerStreamSize = (int)binaryReader.ReadUInt32(); // ReservedMonikerStream (variable): This MUST be a MONIKERSTREAM structure that can contain any arbitrary // value and MUST be ignored on processing. binaryReader.ReadBytes(reservedMonikerStreamSize); // Note The fields that follow MUST NOT be present if the OLEStream structure is for an embedded object. if (Format == OleFormat.Link) { // RelativeSourceMonikerStreamSize (4 bytes): This MUST be set to the size, in bytes, of the RelativeSourceMonikerStream field. // If this field has a value 0x00000000, the RelativeSourceMonikerStream field MUST NOT be present. var relativeSourceMonikerStreamSize = (int)binaryReader.ReadUInt32(); // RelativeSourceMonikerStream (variable): This MUST be a MONIKERSTREAM structure that specifies the relative // path to the linked object. if (relativeSourceMonikerStreamSize > 0) { RelativeSource = new MonikerStream(binaryReader, relativeSourceMonikerStreamSize); } // AbsoluteSourceMonikerStreamSize (4 bytes): This MUST be set to the size, in bytes, of the AbsoluteSourceMonikerStream field. // This field MUST NOT contain the value 0x00000000. var absoluteSourceMonikerStreamSize = (int)binaryReader.ReadUInt32(); // AbsoluteSourceMonikerStream (variable): This MUST be a MONIKERSTREAM structure that specifies the full path // to the linked object. if (absoluteSourceMonikerStreamSize > 0) { AbsoluteSource = new MonikerStream(binaryReader, absoluteSourceMonikerStreamSize); } // If the RelativeSourceMonikerStream field is present, it MUST be used by the container application instead of the // AbsoluteSourceMonikerStream. If the RelativeSourceMonikerStream field is not present, the AbsoluteSourceMonikerStream MUST be used // by the container application. // ClsidIndicator (4 bytes): This MUST be the LONG as specified in section value -1. Otherwise the OLEStream // structure is invalid. binaryReader.ReadUInt32(); // Clsid (16 bytes): This MUST be the CLSID (Packet) containing the object class GUID of the creating application. Clsid = new CLSID(binaryReader); // ReservedDisplayName (4 bytes): This MUST be a LengthPrefixedUnicodeString that can contain any arbitrary value // and MUST be ignored on processing. binaryReader.ReadUInt32(); // Reserved2 (4 bytes): This can contain any arbitrary value and MUST be ignored on processing. binaryReader.ReadUInt32(); // LocalUpdateTime (4 bytes): This MUST be a FILETIME (Packet) that contains the time when the container application // last updated the RemoteUpdateTime field. var localUpdateTime = binaryReader.ReadBytes(4).Reverse().ToArray(); LocalUpdateTime = DateTime.FromFileTime(BitConverter.ToInt32(localUpdateTime, 0)); // LocalCheckUpdateTime (4 bytes): This MUST be a FILETIME (Packet) that contains the time when the container application last // checked the update time of the linked object. var localCheckUpdateTime = binaryReader.ReadBytes(4).Reverse().ToArray(); LocalCheckUpdateTime = DateTime.FromFileTime(BitConverter.ToInt32(localCheckUpdateTime, 0)); // RemoteUpdateTime (4 bytes): This MUST be a FILETIME (Packet) that contains the time when the linked object was last updated. var remoteUpdateTime = binaryReader.ReadBytes(4).Reverse().ToArray(); RemoteUpdateTime = DateTime.FromFileTime(BitConverter.ToInt32(remoteUpdateTime, 0)); } } }
public void Test_FUNCTIONAL_BEHAVIOUR() { //System.Diagnostics.Trace.Listeners.Add(new ConsoleTraceListener()); const int N_FACTOR = 1; byte[] bA = Helpers.GetBuffer(20 * 1024 * N_FACTOR, 0x0A); byte[] bB = Helpers.GetBuffer(5 * 1024, 0x0B); byte[] bC = Helpers.GetBuffer(5 * 1024, 0x0C); byte[] bD = Helpers.GetBuffer(5 * 1024, 0x0D); byte[] bE = Helpers.GetBuffer(8 * 1024 * N_FACTOR + 1, 0x1A); byte[] bF = Helpers.GetBuffer(16 * 1024 * N_FACTOR, 0x1B); byte[] bG = Helpers.GetBuffer(14 * 1024 * N_FACTOR, 0x1C); byte[] bH = Helpers.GetBuffer(12 * 1024 * N_FACTOR, 0x1D); byte[] bE2 = Helpers.GetBuffer(8 * 1024 * N_FACTOR, 0x2A); byte[] bMini = Helpers.GetBuffer(1027, 0xEE); Stopwatch sw = new Stopwatch(); sw.Start(); //############ // Phase 1 var cf = new CompoundFile(CFSVersion.Ver_3, CFSConfiguration.SectorRecycle); cf.RootStorage.AddStream("A").SetData(bA); cf.Save("OneStream.cfs"); cf.Close(); // Test Phase 1 var cfTest = new CompoundFile("OneStream.cfs"); CFStream testSt = cfTest.RootStorage.GetStream("A"); Assert.IsNotNull(testSt); Assert.IsTrue(testSt.Size == bA.Length); Assert.IsTrue(Helpers.CompareBuffer(bA, testSt.GetData())); cfTest.Close(); //########### //Phase 2 cf = new CompoundFile("OneStream.cfs", CFSUpdateMode.ReadOnly, CFSConfiguration.SectorRecycle); cf.RootStorage.AddStream("B").SetData(bB); cf.RootStorage.AddStream("C").SetData(bC); cf.RootStorage.AddStream("D").SetData(bD); cf.RootStorage.AddStream("E").SetData(bE); cf.RootStorage.AddStream("F").SetData(bF); cf.RootStorage.AddStream("G").SetData(bG); cf.RootStorage.AddStream("H").SetData(bH); cf.Save("8_Streams.cfs"); cf.Close(); // Test Phase 2 cfTest = new CompoundFile("8_Streams.cfs"); testSt = cfTest.RootStorage.GetStream("B"); Assert.IsNotNull(testSt); Assert.IsTrue(testSt.Size == bB.Length); Assert.IsTrue(Helpers.CompareBuffer(bB, testSt.GetData())); testSt = cfTest.RootStorage.GetStream("C"); Assert.IsNotNull(testSt); Assert.IsTrue(testSt.Size == bC.Length); Assert.IsTrue(Helpers.CompareBuffer(bC, testSt.GetData())); testSt = cfTest.RootStorage.GetStream("D"); Assert.IsNotNull(testSt); Assert.IsTrue(testSt.Size == bD.Length); Assert.IsTrue(Helpers.CompareBuffer(bD, testSt.GetData())); testSt = cfTest.RootStorage.GetStream("E"); Assert.IsNotNull(testSt); Assert.IsTrue(testSt.Size == bE.Length); Assert.IsTrue(Helpers.CompareBuffer(bE, testSt.GetData())); testSt = cfTest.RootStorage.GetStream("F"); Assert.IsNotNull(testSt); Assert.IsTrue(testSt.Size == bF.Length); Assert.IsTrue(Helpers.CompareBuffer(bF, testSt.GetData())); testSt = cfTest.RootStorage.GetStream("G"); Assert.IsNotNull(testSt); Assert.IsTrue(testSt.Size == bG.Length); Assert.IsTrue(Helpers.CompareBuffer(bG, testSt.GetData())); testSt = cfTest.RootStorage.GetStream("H"); Assert.IsNotNull(testSt); Assert.IsTrue(testSt.Size == bH.Length); Assert.IsTrue(Helpers.CompareBuffer(bH, testSt.GetData())); cfTest.Close(); File.Copy("8_Streams.cfs", "6_Streams.cfs", true); File.Delete("8_Streams.cfs"); //########### // #if !NETCOREAPP2_0 Trace.Listeners.Add(new ConsoleTraceListener()); #endif // Phase 3 cf = new CompoundFile("6_Streams.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle | CFSConfiguration.EraseFreeSectors); cf.RootStorage.Delete("D"); cf.RootStorage.Delete("G"); cf.Commit(); cf.Close(); //Test Phase 3 cfTest = new CompoundFile("6_Streams.cfs"); bool catched = false; try { testSt = cfTest.RootStorage.GetStream("D"); } catch (Exception ex) { if (ex is CFItemNotFound) { catched = true; } } Assert.IsTrue(catched); catched = false; try { testSt = cfTest.RootStorage.GetStream("G"); } catch (Exception ex) { if (ex is CFItemNotFound) { catched = true; } } Assert.IsTrue(catched); cfTest.Close(); //########## // Phase 4 File.Copy("6_Streams.cfs", "6_Streams_Shrinked.cfs", true); CompoundFile.ShrinkCompoundFile("6_Streams_Shrinked.cfs"); // Test Phase 4 Assert.IsTrue(new FileInfo("6_Streams_Shrinked.cfs").Length < new FileInfo("6_Streams.cfs").Length); cfTest = new CompoundFile("6_Streams_Shrinked.cfs"); Action <CFItem> va = delegate(CFItem item) { if (item.IsStream) { CFStream ia = item as CFStream; Assert.IsNotNull(ia); Assert.IsTrue(ia.Size > 0); byte[] d = ia.GetData(); Assert.IsNotNull(d); Assert.IsTrue(d.Length > 0); Assert.IsTrue(d.Length == ia.Size); } }; cfTest.RootStorage.VisitEntries(va, true); cfTest.Close(); //########## //Phase 5 cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle); cf.RootStorage.AddStream("ZZZ").SetData(bF); cf.RootStorage.GetStream("E").Append(bE2); cf.Commit(); cf.Close(); cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle); cf.RootStorage.CLSID = new Guid("EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"); cf.Commit(); cf.Close(); cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle); cf.RootStorage.AddStorage("MyStorage").AddStream("ZIP").Append(bE); cf.Commit(); cf.Close(); cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle); cf.RootStorage.AddStorage("AnotherStorage").AddStream("ANS").Append(bE); cf.RootStorage.Delete("MyStorage"); cf.Commit(); cf.Close(); //Test Phase 5 //##### //Phase 6 cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle); CFStorage root = cf.RootStorage; root.AddStorage("MiniStorage").AddStream("miniSt").Append(bMini); cf.RootStorage.GetStorage("MiniStorage").AddStream("miniSt2").Append(bMini); cf.Commit(); cf.Close(); cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle); cf.RootStorage.GetStorage("MiniStorage").Delete("miniSt"); cf.RootStorage.GetStorage("MiniStorage").GetStream("miniSt2").Append(bE); cf.Commit(); cf.Close(); //Test Phase 6 cfTest = new CompoundFile("6_Streams_Shrinked.cfs"); byte[] d2 = cfTest.RootStorage.GetStorage("MiniStorage").GetStream("miniSt2").GetData(); Assert.IsTrue(d2.Length == (bE.Length + bMini.Length)); int cnt = 1; byte[] buf = new byte[cnt]; cnt = cfTest.RootStorage.GetStorage("MiniStorage").GetStream("miniSt2").Read(buf, bMini.Length, cnt); Assert.IsTrue(cnt == 1); Assert.IsTrue(buf[0] == 0x1A); cnt = 1; cnt = cfTest.RootStorage.GetStorage("MiniStorage").GetStream("miniSt2").Read(buf, bMini.Length - 1, cnt); Assert.IsTrue(cnt == 1); Assert.IsTrue(buf[0] == 0xEE); try { cfTest.RootStorage.GetStorage("MiniStorage").GetStream("miniSt"); } catch (Exception ex) { Assert.IsTrue(ex is CFItemNotFound); } cfTest.Close(); //############## //Phase 7 cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle); cf.RootStorage.GetStorage("MiniStorage").GetStream("miniSt2").SetData(bA); cf.Commit(); cf.Close(); //Test Phase 7 cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle); d2 = cf.RootStorage.GetStorage("MiniStorage").GetStream("miniSt2").GetData(); Assert.IsNotNull(d2); Assert.IsTrue(d2.Length == bA.Length); cf.Close(); //############## cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.ReadOnly, CFSConfiguration.SectorRecycle); var myStream = cf.RootStorage.GetStream("C"); var data = myStream.GetData(); Console.WriteLine(data[0] + " : " + data[data.Length - 1]); myStream = cf.RootStorage.GetStream("B"); data = myStream.GetData(); Console.WriteLine(data[0] + " : " + data[data.Length - 1]); cf.Close(); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); }
/// <summary> /// Creates this object and sets all its properties /// </summary> /// <param name="stream">The Compound File Storage CompObj <see cref="CFStream" /></param> internal CompObjStream(CFStream stream) { using (var memoryStream = new MemoryStream(stream.GetData())) using (var binaryReader = new BinaryReader(memoryStream)) { // Reserved1 (4 bytes): This can be set to any arbitrary value and MUST be ignored on processing. // Version (4 bytes): This can be set to any arbitrary value and MUST be ignored on processing. // Reserved2 (20 bytes): This can be set to any arbitrary value and MUST be ignored on processing. // Skip the first 28 bytes, this is the CompObjHeader binaryReader.ReadBytes(28); // This MUST be a LengthPrefixedAnsiString structure that contains a display name of the linked // object or embedded object. AnsiUserType = Strings.Read4ByteLengthPrefixedAnsiString(binaryReader); // MarkerOrLength (4 bytes): If this is set to 0x00000000, the FormatOrAnsiString field MUST NOT // be present. If this field is set to 0xFFFFFFFF or 0xFFFFFFFE, the FormatOrAnsiString field MUST // be 4 bytes in size and MUST contain a standard clipboard format identifier. // If this set to a value other than 0x00000000, the FormatOrAnsiString field MUST be set to a // null-terminated ANSI string containing the name of a registered clipboard format and the // MarkerOrLength field MUST be set to the number of ANSI characters in the FormatOrAnsiString field, // including the terminating null character. var markerOrLength = binaryReader.ReadUInt32(); switch (markerOrLength) { case 0x00000000: // Skip break; case 0xFFFFFFFF: case 0xFFFFFFFE: ClipboardFormat = (OleClipboardFormat)binaryReader.ReadUInt32(); break; default: binaryReader.BaseStream.Position -= 4; StringFormat = Strings.Read4ByteLengthPrefixedAnsiString(binaryReader); break; } // Reserved1 (variable): If present, this MUST be a LengthPrefixedAnsiString structure. If the Length // field of the LengthPrefixedAnsiString contains a value of 0 or a value that is greater than 0x00000028, // the remaining fields of the structure starting with the String field of the LengthPrefixedAnsiString // MUST be ignored on processing. var reserved1Length = binaryReader.ReadUInt32(); if (reserved1Length <= 0x00000028) { binaryReader.BaseStream.Position -= 4; // ReSharper disable once UnusedVariable var reserved1 = Strings.Read4ByteLengthPrefixedAnsiString(binaryReader); } // UnicodeMarker (variable): If this field is present and is NOT set to 0x71B239F4, the remaining fields // of the structure MUST be ignored on processing. var unicodeMarker = binaryReader.ReadUInt32(); if (unicodeMarker == 0x71B239F4) { markerOrLength = binaryReader.ReadUInt32(); switch (markerOrLength) { case 0x00000000: // Skip break; case 0xFFFFFFFF: case 0xFFFFFFFE: ClipboardFormat = (OleClipboardFormat)binaryReader.ReadUInt32(); break; default: binaryReader.BaseStream.Position -= 4; StringFormat = Strings.Read4ByteLengthPrefixedAnsiString(binaryReader); break; } } } }
private void exportDataToolStripMenuItem_Click(object sender, EventArgs e) { //No export if storage if (treeView1.SelectedNode == null || !((CFItem)treeView1.SelectedNode.Tag).IsStream) { MessageBox.Show("Only stream data can be exported", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } CFStream target = (CFStream)treeView1.SelectedNode.Tag; // A lot of stream and storage have only non-printable characters. // We need to sanitize filename. String sanitizedFileName = String.Empty; foreach (char c in target.Name) { if ( Char.GetUnicodeCategory(c) == UnicodeCategory.LetterNumber || Char.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter || Char.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter ) { sanitizedFileName += c; } } if (String.IsNullOrEmpty(sanitizedFileName)) { sanitizedFileName = "tempFileName"; } saveFileDialog1.FileName = sanitizedFileName + ".bin"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { FileStream fs = null; try { fs = new FileStream(saveFileDialog1.FileName, FileMode.CreateNew, FileAccess.ReadWrite); fs.Write(target.GetData(), 0, (int)target.Size); } catch (Exception ex) { treeView1.Nodes.Clear(); MessageBox.Show("Internal error: " + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (fs != null) { fs.Flush(); fs.Close(); fs = null; } } } }
public void Test_WRITE_MINISTREAM_READ_REWRITE_STREAM() { const int BIGGER_SIZE = 350; //const int SMALLER_SIZE = 290; const int MEGA_SIZE = 18000000; byte[] ba1 = Helpers.GetBuffer(BIGGER_SIZE, 1); byte[] ba2 = Helpers.GetBuffer(BIGGER_SIZE, 2); byte[] ba3 = Helpers.GetBuffer(BIGGER_SIZE, 3); byte[] ba4 = Helpers.GetBuffer(BIGGER_SIZE, 4); byte[] ba5 = Helpers.GetBuffer(BIGGER_SIZE, 5); //WRITE 5 (mini)streams in a compound file -- CompoundFile cfa = new CompoundFile(); CFStream myStream = cfa.RootStorage.AddStream("MyFirstStream"); Assert.IsNotNull(myStream); myStream.SetData(ba1); Assert.IsTrue(myStream.Size == BIGGER_SIZE); CFStream myStream2 = cfa.RootStorage.AddStream("MySecondStream"); Assert.IsNotNull(myStream2); myStream2.SetData(ba2); Assert.IsTrue(myStream2.Size == BIGGER_SIZE); CFStream myStream3 = cfa.RootStorage.AddStream("MyThirdStream"); Assert.IsNotNull(myStream3); myStream3.SetData(ba3); Assert.IsTrue(myStream3.Size == BIGGER_SIZE); CFStream myStream4 = cfa.RootStorage.AddStream("MyFourthStream"); Assert.IsNotNull(myStream4); myStream4.SetData(ba4); Assert.IsTrue(myStream4.Size == BIGGER_SIZE); CFStream myStream5 = cfa.RootStorage.AddStream("MyFifthStream"); Assert.IsNotNull(myStream5); myStream5.SetData(ba5); Assert.IsTrue(myStream5.Size == BIGGER_SIZE); cfa.Save("WRITE_MINISTREAM_READ_REWRITE_STREAM.cfs"); cfa.Close(); // Now get the second stream and rewrite it smaller byte[] bb = Helpers.GetBuffer(MEGA_SIZE); CompoundFile cfb = new CompoundFile("WRITE_MINISTREAM_READ_REWRITE_STREAM.cfs"); CFStream myStreamB = cfb.RootStorage.GetStream("MySecondStream"); Assert.IsNotNull(myStreamB); myStreamB.SetData(bb); Assert.IsTrue(myStreamB.Size == MEGA_SIZE); byte[] bufferB = myStreamB.GetData(); cfb.Save("WRITE_MINISTREAM_READ_REWRITE_STREAM_2ND.cfs"); cfb.Close(); CompoundFile cfc = new CompoundFile("WRITE_MINISTREAM_READ_REWRITE_STREAM_2ND.cfs"); CFStream myStreamC = cfc.RootStorage.GetStream("MySecondStream"); Assert.IsTrue(myStreamC.Size == MEGA_SIZE, "DATA SIZE FAILED"); byte[] bufferC = myStreamC.GetData(); Assert.IsTrue(Helpers.CompareBuffer(bufferB, bufferC), "DATA INTEGRITY FAILED"); cfc.Close(); if (File.Exists("WRITE_MINISTREAM_READ_REWRITE_STREAM.cfs")) { File.Delete("WRITE_MINISTREAM_READ_REWRITE_STREAM.cfs"); } if (File.Exists("WRITE_MINISTREAM_READ_REWRITE_STREAM_2ND.cfs")) { File.Delete("WRITE_MINISTREAM_READ_REWRITE_STREAM_2ND.cfs"); } }
public override WFState Run() { WFState retval = new WFState() { Value = "Success" }; OpenMcdf.CompoundFile cf = null; try { cf = new CompoundFile(this.FileToProcess); bool attachfound = false; int attachinc = 0; do { CFStorage cfstorage = this.GetStorage(cf.RootStorage, MakeAttachStorageName(attachinc)); if (cfstorage != null) { // check if attachment is embedded message - if so do not process if (this.GetStorage(cfstorage, nameOfEmbeddedMessageStream) == null) { string filename = string.Format("attachment{0}", attachinc); // first get filename CFStream cfstream = this.GetStream(cfstorage, MakeSubStorageStreamName(0x3001, 0x001F)); if (cfstream != null) { filename = System.Text.UnicodeEncoding.Unicode.GetString(cfstream.GetData()); } // second get filename cfstream = this.GetStream(cfstorage, MakeSubStorageStreamName(0x3701, 0x0102)); if (cfstream != null) { string filedir = string.Format("{0}\\{1}", this.ExportDirectory, WFUtilities.GetNextDirectoryNumber(this.ExportDirectory)); if (!Directory.Exists(filedir)) { Directory.CreateDirectory(filedir); } if (Directory.Exists(filedir)) { using (var bw = new BinaryWriter(File.OpenWrite(string.Format("{0}\\{1}", filedir, filename)))) { bw.Write(cfstream.GetData()); this.OutputFiles.Add(string.Format("{0}\\{1}", filedir, filename), "Success"); } } } } attachfound = true; } else { attachfound = false; } attachinc++; } while(attachfound); } catch (Exception) { retval.Value = "Fail"; } finally { if (cf != null) { cf.Close(); } } return(retval); }
/// <summary> /// Adds a CFStream and converts it into a property /// </summary> /// <param name="stream">The <see cref="CFStream" /></param> /// <exception cref="ArgumentOutOfRangeException"> /// Raised when the <paramref name="stream"/> does not start with /// "__substg1.0_" /// </exception> internal void AddProperty(CFStream stream) { if (!stream.Name.StartsWith("__substg1.0_")) { throw new ArgumentOutOfRangeException(nameof(stream), "The stream name needs to start with '__substg1.0_'"); } var id = stream.Name.Substring(12, 4); var type = stream.Name.Substring(16, 4); var uId = ushort.Parse(id, NumberStyles.AllowHexSpecifier); var uType = ushort.Parse(type, NumberStyles.AllowHexSpecifier); Add(new Property(uId, (PropertyType)uType, PropertyFlags.PROPATTR_READABLE, stream.GetData())); }
private void MainThreadInitialization(IVsUIShell shellService, bool isAsyncPath) { // Do operations requiring main thread utilizing passed in services if (isAsyncPath) { var solService = GetService(typeof(SVsSolution)) as IVsSolution; string dir = ""; string file = ""; string optsFile = ""; solService.GetSolutionInfo(out dir, out file, out optsFile); if (string.IsNullOrEmpty(optsFile)) { return; } try { FileStream fs = new FileStream( optsFile, FileMode.Open, FileAccess.ReadWrite ); CompoundFile cf = new CompoundFile(fs, CFSUpdateMode.Update, CFSConfiguration.SectorRecycle | CFSConfiguration.NoValidationException | CFSConfiguration.EraseFreeSectors); IList <CFItem> list = cf.GetAllNamedEntries(PersistSolutionProps._strSolutionUserOptionsKey); if (list != null && list.Count > 0) { // while checking the solution user options, get the port, // user, and workspace. This needs to be done here as ReadUserOptions // is no longer triggered on .sln load if Visual Studio is launched // by opening a .sln. CFStream foundStream = cf.RootStorage.GetStream(PersistSolutionProps._strSolutionUserOptionsKey); byte[] data = foundStream.GetData(); Stream stream = new MemoryStream(data); Hashtable hashProjectsUserData = new Hashtable(); if (stream.Length > 0) { BinaryFormatter formatter = new BinaryFormatter(); hashProjectsUserData = formatter.Deserialize(stream) as Hashtable; } P4VsProviderService P4VSService = (P4VsProviderService)GetService(typeof(P4VsProviderService)); if (hashProjectsUserData != null && (hashProjectsUserData.ContainsKey("Connect_State") && (hashProjectsUserData["Connect_State"] != null))) { if (hashProjectsUserData.ContainsKey("Connect_Port")) { P4VSService.port = hashProjectsUserData["Connect_Port"] as string; } if (hashProjectsUserData.ContainsKey("Connect_User")) { P4VSService.user = hashProjectsUserData["Connect_User"] as string; } if (hashProjectsUserData.ContainsKey("Connect_Workspace")) { P4VSService.workspace = hashProjectsUserData["Connect_Workspace"] as string; } if (string.IsNullOrEmpty(P4VSService.LoadingControlledSolutionLocation)) { P4VSService.LoadingControlledSolutionLocation = P4VSService.port; } } // check to see if the sln is tagged string sln = System.IO.File.ReadAllText(file); P4VSService._P4VsProvider.SolutionFileTagged = sln.Contains("GlobalSection(" + PersistSolutionProps._strSolutionPersistanceKey + ") = preSolution\r\n\t\t" + PersistSolutionProps._strSolutionControlledProperty + " = True\r\n\tEndGlobalSection"); P4VSService.AsyncLoad = true; P4VSService.OnAfterOpenSolution(null, 0); } cf.Close(); } catch { // If we are here, most likely the .suo file was not found, or could not // be opened, so just continue without attempting to get user settings. } } }
/// <summary> /// Store the CFB file in target format /// </summary> /// <param name="text"></param> /// <param name="filePath"></param> /// <param name="ignoreNotSupportedFiles"></param> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> private static string StoreTargetFileFromCfb(string text, string filePath, bool ignoreNotSupportedFiles, int start, int end) { // find object type of OLE Regex rxObjectType = new Regex(@"objclass\s+([^}]*)}"); Match match = rxObjectType.Match(text.Substring(0, 70)); string typeText = ""; string ext = ""; if (match.Success) { typeText = match.Groups[1].Value; } // DOORS file types supported and tested string[] lTypes = { "AcroExch." }; //,"Excel.", "Word."}; string[] lExtensions = { ".pdf" }; //, "xlsx", "docx" }; string[] lCompoundFileStreamName = { "CONTENTS" }; int j = 0; string componentFileStreamName = ""; foreach (var type in lTypes) { if (typeText.Contains(type)) { ext = lExtensions[j]; componentFileStreamName = lCompoundFileStreamName[j]; break; } j += 1; } if (ext == "") { string newFilePath = $@"{filePath}.notSupported"; if (!ignoreNotSupportedFiles) { MessageBox.Show($@"File: '{filePath}' File type not supported: '{typeText}' Supported ole types: '{String.Join(", ", lTypes)}' Copied to: {DirFiles.GetMessageFromFile(newFilePath)} ", @"Can't convert *.ole to file, not supported type!"); } DirFiles.FileMove(filePath, newFilePath); return(newFilePath); } string filePathNew = Path.Combine(Path.GetDirectoryName(filePath), $"{Path.GetFileNameWithoutExtension(filePath)}{ext}"); StoreAsAsciiFile(text, start, end, filePathNew); // By DOORS supported file type if (componentFileStreamName != "") { using (CompoundFile cf = new CompoundFile(filePathNew)) { CFStream foundStream = cf.RootStorage.GetStream("CONTENTS"); DirFiles.WriteAllBytes(filePathNew, foundStream.GetData().ToArray()); } } if (DirFiles.FileDelete(filePath)) { return(filePathNew); } else { return(""); } }
void CMConvert(CompoundFile cf) { IList <IDirectoryEntry> entries = cf.GetDirectories(); // extract Circuit maker files and then try and rename directories // to match .pcbdoc entries string CurrentDir = ""; foreach (var entry in entries) { if (false && entry.Name == "Root Entry") { DirectoryInfo Info = Directory.CreateDirectory(entry.Name); if (!Info.Exists) { // for some reason the create directory failed so try again Info = Directory.CreateDirectory(entry.Name); } Thread.Sleep(500); // TODO this is a frig sort out ClearFolder(entry.Name); Directory.SetCurrentDirectory(entry.Name); CurrentDir = entry.Name; } else { if (entry.StgType == StgType.StgStorage) { CurrentDir = entry.Name; // Directory.CreateDirectory(entry.Name); CFStorage storage = cf.RootStorage.TryGetStorage(entry.Name); CFStream datastream = storage.GetStream("Data"); // get file contents and write to file byte[] data = datastream.GetData(); if (data.Length == 0) { OutputString($"Deleted '{CurrentDir}' no data"); // remove empty directory // Directory.Delete(CurrentDir); } else { // create the file // File.WriteAllBytes(CurrentDir + "\\" + "Data.dat", data); // now try and determine which file it is by examining the contents TextFile textfile = ByteArrayToStructure <TextFile>(data); TypeBinary typebinary = ByteArrayToStructure <TypeBinary>(data); TextFile2 textfile2 = ByteArrayToStructure <TextFile2>(data); if (IsPads(data)) { RenameDirectory(CurrentDir, "Pads6", data); } else if (IsVias(data)) { RenameDirectory(CurrentDir, "Vias6", data); } else if (IsTracks(data)) { RenameDirectory(CurrentDir, "Tracks6", data); } else if (IsComponentBodies(data)) { RenameDirectory(CurrentDir, "ComponentBodies6", data); } else if (IsBoard6(data)) { RenameDirectory(CurrentDir, "Board6", data); } else if (IsPolygons6(data)) { RenameDirectory(CurrentDir, "Polygons6", data); } else if (IsShapeBasedComponentBodies6(data)) { RenameDirectory(CurrentDir, "ShapeBasedComponentBodies6", data); } else if (IsArcs6(data)) { RenameDirectory(CurrentDir, "Arcs6", data); } else if (IsTexts6(data)) { RenameDirectory(CurrentDir, "Texts6", data); } else if (IsDimensions6(data)) { RenameDirectory(CurrentDir, "Dimensions6", data); } else if (IsRules6(data)) { RenameDirectory(CurrentDir, "Rules6", data); } else if (IsModels6(data)) { RenameDirectory(CurrentDir, "Models", data); // now need to get all of the model files CFStream models; byte[] modeldata; int i = 0; while ((models = storage.TryGetStream($"{i}")) != null) { OutputString($"Creating {i}.dat model file"); // get file contents and write to file modeldata = models.GetData(); // uncompress the x.dat file to a .step file // step file is renamed to it's actual name later in the process // string Inflated = ZlibCodecDecompress(modeldata); // File.WriteAllText($"Models\\{i}.step", Inflated); i++; } } else if ((textfile2.type == 0x0001 && textfile2.Length < data.Length) || textfile.Length < data.Length) { // could be text file string str = Encoding.Default.GetString(data); if (str.Contains("ORIGINX")) { RenameDirectory(CurrentDir, "Board6", data); } else if (str.Contains("AdvancedPlacerOptions")) { RenameDirectory(CurrentDir, "Advanced Placer Options6", data); } else if (str.Contains("SUPERCLASS")) { RenameDirectory(CurrentDir, "Classes6", data); } else if (str.Contains("SOURCEFOOTPRINTLIBRARY")) { RenameDirectory(CurrentDir, "Components6", data); } else if (str.Contains("DesignRuleCheckerOptions")) { RenameDirectory(CurrentDir, "Design Rule Checker Options6", data); } else if (str.Contains("POSITIVENETNAME")) { RenameDirectory(CurrentDir, "DifferentialPairs6", data); } else if (str.Contains("FWDMSG")) { RenameDirectory(CurrentDir, "FileVersionInfo", data); } else if (str.Contains("LOOPREMOVAL=")) { RenameDirectory(CurrentDir, "Nets6", data); } else if (str.Contains("PinSwapOptions")) { RenameDirectory(CurrentDir, "Pin Swap Option6", data); } else if (str.Contains("REMOVEDEAD")) { RenameDirectory(CurrentDir, "Polygons6", data); } else { OutputError($"Failed to convert possible text file '{CurrentDir}'"); } } else if (typebinary.Next < data.Length) { if (typebinary.Type == 0x03) { RenameDirectory(CurrentDir, "Vias6", data); } else if (typebinary.Type == 0x04) { RenameDirectory(CurrentDir, "Tracks6", data); } else if (typebinary.Type == 0x0B) { RenameDirectory(CurrentDir, "Regions6", data); } else if (typebinary.Type == 0x06) { RenameDirectory(CurrentDir, "Fills6", data); } else { OutputError($"Failed to convert possible binary file '{CurrentDir}'"); } } } } /* * else * if (entry.StgType == StgType.StgStream) * { * CFStream stream = cf.RootStorage.TryGetStream(CurrentDir + "\\" + entry.Name); * if (stream != null && stream.Size != 0) * { * var data = new byte[stream.Size]; * stream.Read(data, 0, data.Length); * File.WriteAllBytes(CurrentDir + "\\" + entry.Name, data); * } * } */ } // cf.RootStorage..DirEntry.EntryName. //OutputString($"{entry.ToString()}"); } Directory.SetCurrentDirectory(".."); }
/// <summary> /// Creates this object and sets all its properties /// </summary> /// <param name="stream">The Compound File Storage CompObj <see cref="CFStream" /></param> internal ObjInfoStream(CFStream stream) { using (var memoryStream = new MemoryStream(stream.GetData())) using (var binaryReader = new BinaryReader(memoryStream)) { var bytes = binaryReader.ReadBytes(2); var bitArray = new BitArray(bytes); // A - reserved1 (1 bit): Undefined and MUST be ignored. // B - fDefHandler (1 bit): If this bit is 1, then the application MUST assume that this OLE object’s // class identifier (CLSID) is {00020907-0000-0000-C000-000000000046}. DefHandler = bitArray.Get(1); // C - reserved2 (1 bit): Undefined and MUST be ignored. // D - reserved3 (1 bit): Undefined and MUST be ignored. // E - fLink (1 bit): A bit that specifies whether this OLE object is a link. Link = bitArray.Get(4); // F - reserved4 (1 bit): Undefined and MUST be ignored. // G - fIcon (1 bit): A bit that specifies whether this OLE object is being represented by an icon. Icon = bitArray.Get(6); // H - fIsOle1 (1 bit): A bit that specifies whether this OLE object is only compatible with OLE 1. // If this bit is zero, then the object is compatible with OLE 2. IsOle1 = bitArray.Get(7); // I - fManual (1 bit): A bit that specifies whether the user has requested that this OLE object only // be updated in response to a user action. If fManual is zero, then the user has requested that // this OLE object update automatically. If fLink is zero, then fManual is undefined and MUST be ignored. Manual = bitArray.Get(8); // J - fRecomposeOnResize (1 bit): A bit that specifies whether this OLE object has requested to be notified // when it is resized by its container. RecomposeOnResize = bitArray.Get(9); // K - reserved5 (1 bit): MUST be zero and MUST be ignored. // L - reserved6 (1 bit): MUST be zero and MUST be ignored. // M - fOCX (1 bit): A bit that specifies whether this object is an OLE control. Ocx = bitArray.Get(12); // N - fStream (1 bit): If fOCX is zero, then this bit MUST be zero. If fOCX is 1, then fStream is a bit that // specifies whether this OLE control stores its data in a single stream instead of a storage. If fStream // is 1, then the data for the OLE control is in a stream called "\003OCXDATA" where \003 is the character // with value 0x0003, not the string literal "\003". Stream = bitArray.Get(13); // O - reserved7 (1 bit): Undefined and MUST be ignored. // P - fViewObject (1 bit): A bit that specifies whether this OLE object supports the IViewObject interface. ViewObject = bitArray.Get(15); try { Cf = (OleCf)binaryReader.ReadUInt16(); } catch (Exception) { Cf = OleCf.UnSpecified; } try { bytes = binaryReader.ReadBytes(2); bitArray = new BitArray(bytes); // A - fEMF(1 bit): A bit that specifies that the presentation of this OLE object in the document is in the // Enhanced Metafile format. This is different from fStoredAsEMF in the case of an object being represented // as an icon.For icons, the icon can be an Enhanced Metafile even if the OLE object does not support the // Enhanced Metafile format. Emf = bitArray.Get(1); // B - reserved1(1 bit): MUST be zero and MUST be ignored. // C - fQueriedEMF(1 bit): A bit that specifies whether the application that saved this Word Binary file had // queried this OLE object to determine whether it supported the Enhanced Metafile format. QueriedEmf = bitArray.Get(3); // D - fStoredAsEMF(1 bit): A bit that specifies that this OLE object supports the Enhanced Metafile format. StoredAsEmf = bitArray.Get(4); // E - reserved2(1 bit): Undefined and MUST be ignored. // F - reserved3(1 bit): Undefined and MUST be ignored. // reserved4(10 bits): Undefined and MUST be ignored. } catch (Exception) { // Ignore } } }
static void Main(string[] args) { bool updating = false; int index; string lang; string installDir; string bakfile; string file; string config = Path.GetFullPath("panyi.ini"); Console.WriteLine( @",-------------------------------------------------. | panyi 1.1 | | Copyright 2018 zeffy <https://github.com/zeffy> | | Simple Understanding Public License v1 (SUPL) | `+---------------------------------------------+-' | OpenMcdf 2.1 | | Copyright (c) 2010-2018, Federico Blaseotto | | Mozilla Public License 2.0 (MPL-2.0) | `---------------------------------------------' "); if (!File.Exists(config)) { Console.Write("panyi.ini is missing! Download the latest copy? [y/n] "); string input = Console.ReadLine().Trim().ToLowerInvariant(); if (!string.IsNullOrEmpty(input) && new[] { "yes", "y" }.Contains(input)) { updating = true; } else { Console.Write("\nCancelled by user! Press any key to exit... "); Console.ReadKey(true); return; } } else { updating = Array.IndexOf(args, "-update") != -1; } if (updating) { using (var wc = new WebClient()) { string part = config + ".part"; Console.Write("Downloading latest panyi.ini... "); try { wc.DownloadFile( "https://raw.githubusercontent.com/zeffy/panyi/master/panyi/panyi.ini", part); Console.WriteLine("Finished!\n"); } catch (WebException) { Console.WriteLine("Failed!\n\n" + "You can download it manually from https://git.io/fAdWN"); Console.Write("\nPress any key to exit... "); Console.ReadKey(true); return; } if (File.Exists(config)) { bakfile = config + DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss.bak"); File.Copy(config, bakfile); Console.WriteLine("Copied old panyi.ini to \"{0}\"", bakfile); } File.Move(part, config); Console.Write("\nDone! Press any key to exit... "); Console.ReadKey(true); return; } } if ((index = Array.IndexOf(args, "-lang")) != -1) { if (++index >= args.Length) { return; } lang = args[index]; } else { lang = "en"; } if ((index = Array.IndexOf(args, "-file")) != -1) { if (++index >= args.Length) { return; } file = args[index]; } else { installDir = Registry.GetValue( @"HKEY_CURRENT_USER\Software\Baidu\BaiduYunGuanjia", "installDir", null) as string; if (string.IsNullOrEmpty(installDir)) { return; } file = installDir + "\\resource.db"; } using (var fs = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) using (var cf = new CompoundFile(fs, CFSUpdateMode.Update, CFSConfiguration.SectorRecycle | CFSConfiguration.EraseFreeSectors)) { CFStream cfs = cf.RootStorage.GetStream("StringTable.xml"); XDocument xd = XDocument.Parse(Encoding.UTF8.GetString(cfs.GetData())); string id; if (Array.IndexOf(args, "-x") != -1) { Console.WriteLine("Extracting cn string table to panyi.ini..."); foreach (var element in xd.Root.Elements("String")) { if (!NativeMethods.WritePrivateProfileString("cn", (string)element.Attribute("id"), (string)element.Attribute("value"), config)) { Console.WriteLine("Failed to write string!"); } } } else { bakfile = file + DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss.bak"); File.Copy(file, bakfile); Console.WriteLine("Copied old resource.db to \"{0}\"", bakfile); Console.WriteLine("Translating string table to {0}...", lang); var sb = new StringBuilder(0x200); foreach (var element in xd.Root.Elements("String")) { id = (string)element.Attribute("id"); if (NativeMethods.GetPrivateProfileString(lang, id, "", sb, (uint)sb.MaxCapacity, config) > 0) { element.Attribute("value").SetValue(sb.ToString()); } } cfs.SetData(Encoding.UTF8.GetBytes(xd.ToString())); cf.Commit(true); } } Console.Write("\nDone! Press any key to exit... "); Console.ReadKey(true); return; }
/// <summary> /// Initializes a new instance of the DynamicByteProvider class. /// </summary> /// <param name="bytes"></param> public StreamDataProvider(CFStream modifiedStream) { _bytes = new ByteCollection(modifiedStream.GetData()); _modifiedStream = modifiedStream; }
private void AddStreamToStorage(CFStorage storage, CFStream stream) { CFStream cfStream = storage.AddStream(stream.Name); cfStream.SetData(stream.GetData()); }