Ejemplo n.º 1
0
        public void WriteToFile(string FileName, bool Overwrite = true)
        {
            IFileSystemImageResult Res = ISO.CreateResultImage();
            IStream ImgStream          = (IStream)Res.ImageStream;

            if (ImgStream != null)
            {
                STATSTG Stat;
                ImgStream.Stat(out Stat, 0x1);

                if (File.Exists(FileName))
                {
                    if (Overwrite)
                    {
                        File.Delete(FileName);
                    }
                    else
                    {
                        throw new Exception("File already exists: " + FileName);
                    }
                }

                IStream OutStream;
                SHCreateStreamOnFile(FileName, 0x1001, out OutStream);

                ImgStream.CopyTo(OutStream, Stat.cbSize, IntPtr.Zero, IntPtr.Zero);
                OutStream.Commit(0);
            }
        }
Ejemplo n.º 2
0
        private void GetDataFileContents(ref FORMATETC format, ref STGMEDIUM medium)
        {
            if (format.lindex == -1)
            {
                return;
            }

            try
            {
                if (streams.Count == 0)
                {
                    try
                    {
                        Guid token = storedFiles.RequestTokenMethod(storedFiles.OperationId).Result;
                        foreach (var file in storedFiles.AllFiles)
                        {
                            streams.Add(new ManagedRemoteIStream(file, storedFiles, token));
                        }
                    }
                    catch (Exception ex)
                    {
                        ISLogger.Write("Failed to get access token for clipboard operation: " + ex.Message);
                        return;
                    }
                }

                medium.tymed = TYMED.TYMED_ISTREAM;
                IStream o = streams[format.lindex];
                medium.unionmember = Marshal.GetComInterfaceForObject(o, typeof(IStream));
            }catch (Exception ex)
            {
                ISLogger.Write("Failed to transfer file contents to shell: " + ex.Message);
            }
        }
 private static unsafe bool ExtractManifestContent(System.Deployment.Internal.Isolation.Manifest.ICMS cms, out MemoryStream ms)
 {
     ms = new MemoryStream();
     try
     {
         System.Runtime.InteropServices.ComTypes.IStream stream = cms as System.Runtime.InteropServices.ComTypes.IStream;
         if (stream == null)
         {
             return(false);
         }
         byte[] pv = new byte[0x1000];
         int    cb = 0x1000;
         do
         {
             stream.Read(pv, cb, new IntPtr((void *)&cb));
             ms.Write(pv, 0, cb);
         }while (cb == 0x1000);
         ms.Position = 0L;
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Ejemplo n.º 4
0
 public ComAdapterStream(com.IStream source)
 {
     if (source == null)
     {
         throw new ArgumentNullException("source");
     }
     this.source = source;
 }
Ejemplo n.º 5
0
 public ComStream(ComTypes.IStream baseStream)
 {
     if (baseStream == null)
     {
         throw new ArgumentNullException();
     }
     _baseStream = baseStream;
 }
Ejemplo n.º 6
0
 public override void Close()
 {
     base.Close();
     if (_baseStream != null)
     {
         Marshal.ReleaseComObject(_baseStream);
         _baseStream = null;
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Enumerates an Interop.IStorage object and creates the internal file object collection
        /// </summary>
        /// <param name="stgEnum">Interop.IStorage to enumerate</param>
        /// <param name="BasePath">Sets the base url for the storage files</param>
        protected void EnumIStorageObject(Interop.IStorage stgEnum, string BasePath)
        {
            Interop.IEnumSTATSTG iEnumSTATSTG;

            STATSTG sTATSTG;

            int i;

            stgEnum.EnumElements(0, IntPtr.Zero, 0, out iEnumSTATSTG);
            iEnumSTATSTG.Reset();
            while (iEnumSTATSTG.Next(1, out sTATSTG, out i) == (int)Interop.S_OK)
            {
                if (i == 0)
                {
                    break;
                }

                FileObject newFileObj = new FileObject();
                newFileObj.FileType = sTATSTG.type;
                switch (sTATSTG.type)
                {
                case 1:
                    Interop.IStorage iStorage = stgEnum.OpenStorage(sTATSTG.pwcsName, IntPtr.Zero, 16, IntPtr.Zero, 0);
                    if (iStorage != null)
                    {
                        string str = String.Concat(BasePath, sTATSTG.pwcsName.ToString());
                        newFileObj.FileStorage = iStorage;
                        newFileObj.FilePath    = BasePath;
                        newFileObj.FileName    = sTATSTG.pwcsName.ToString();
                        foCollection.Add(newFileObj);
                        EnumIStorageObject(iStorage, str);
                    }
                    break;

                case 2:
                    UCOMIStream uCOMIStream = stgEnum.OpenStream(sTATSTG.pwcsName, IntPtr.Zero, 16, 0);
                    newFileObj.FilePath   = BasePath;
                    newFileObj.FileName   = sTATSTG.pwcsName.ToString();
                    newFileObj.FileStream = uCOMIStream;
                    foCollection.Add(newFileObj);
                    break;

                case 4:
                    Debug.WriteLine("Ignoring IProperty type ...");
                    break;

                case 3:
                    Debug.WriteLine("Ignoring ILockBytes type ...");
                    break;

                default:
                    Debug.WriteLine("Unknown object type ...");
                    break;
                }
            }
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Closes the storage stream
 /// </summary>
 public override void Close()
 {
     if (fileStream != null)
     {
         fileStream.Commit(0);
         Marshal.ReleaseComObject(fileStream);
         fileStream = null;
         GC.SuppressFinalize(this);
     }
 }
Ejemplo n.º 9
0
        public static void CopyTo(this Stream source, com.IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten)
        {
            if (!source.CanRead)
            {
                throw new NotSupportedException("Source stream doesn't support reading.");
            }
            using (var destination = new ComAdapterStream(pstm))
            {
                if (!destination.CanWrite)
                {
                    throw new NotSupportedException("Destination stream doesn't support writing.");
                }
                var buffer            = new byte[4096];
                var totalBytesRead    = 0L;
                var totalBytesWritten = 0L;
                var chunkLength       = buffer.Length;
                if (cb < chunkLength)
                {
                    chunkLength = (int)cb;
                }
                while (totalBytesWritten < cb)
                {
                    // Read
                    var bytesRead = source.Read(buffer, 0, chunkLength);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    totalBytesRead += bytesRead;
                    // Write
                    var previousPosition = destination.Position;
                    destination.Write(buffer, 0, bytesRead);
                    var bytesWritten = destination.Position - previousPosition;
                    if (bytesWritten == 0)
                    {
                        break;
                    }
                    totalBytesWritten += bytesWritten;

                    if (bytesRead != bytesWritten)
                    {
                        break;
                    }
                }
                if (pcbRead != IntPtr.Zero)
                {
                    iop.Marshal.WriteInt64(pcbRead, totalBytesRead);
                }
                if (pcbWritten != IntPtr.Zero)
                {
                    iop.Marshal.WriteInt64(pcbWritten, totalBytesWritten);
                }
            }
        }
Ejemplo n.º 10
0
 Stream Wrap(com.IStream comStream)
 {
     if (comStream != null)
     {
         var netStream = comStream as Stream;
         if (netStream != null)
         {
             return(netStream);
         }
         return(new ComAdapterStream(comStream));
     }
     return(Stream.Null);
 }
Ejemplo n.º 11
0
        void IDiscFormat2Data.Write(COMTypes.IStream data)
        {
            Cancel = false;
            var hasupdate = Update != null && Update.GetInvocationList().Length > 0;

            if (hasupdate)
            {
                CreateProgressISOFile(data);
            }
            else
            {
                CreateISOFile(data);
            }
        }
Ejemplo n.º 12
0
        internal void CreateISOFile(COMTypes.IStream imagestream)
        {
            if (Cancel)
            {
                return;
            }
            COMTypes.IStream newStream;
            newStream = CreateCOMStreamFromFile(OutputFileName);

            COMTypes.STATSTG stat;
#if DEBUG
            var tm = new Stopwatch();
            tm.Start();
#endif
            imagestream.Stat(out stat, 0x0);

            var inBytes  = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(ulong)));
            var outBytes = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(ulong)));

            try
            {
                imagestream.CopyTo(newStream, stat.cbSize, inBytes, outBytes);
                newStream.Commit(0);
            }
            catch (Exception r)
            {
                Debug.WriteLine(r.ToString());
                throw;
            }
            finally
            {
                if (newStream != null)
                {
                    Marshal.FinalReleaseComObject(newStream);
                }
                newStream = null;
                Marshal.FreeHGlobal(inBytes);
                Marshal.FreeHGlobal(outBytes);
#if DEBUG
                tm.Stop();
                Debug.WriteLine(string.Format("Time spent in CreateISOFile: {0} ms",
                                              tm.Elapsed.TotalMilliseconds.ToString("#,#")));
#endif
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Opens an UCOMIStream and returns the associated file object
        /// </summary>
        /// <param name="parentStorage">storage used to open the stream</param>
        /// <param name="fileName">filename of the stream</param>
        /// <returns>A <see cref="FileObject">FileObject</see> instance if the file was found, otherwise null.</returns>
        public FileObject OpenUCOMStream(Interop.IStorage parentStorage, string fileName)
        {
            if (parentStorage == null)
            {
                parentStorage = storage;
            }

            FileObject retObject = null;

            STATSTG sTATSTG;

            sTATSTG.pwcsName = fileName;
            sTATSTG.type     = 2;

            try
            {
                retObject = new FileObject();

                UCOMIStream uCOMIStream = parentStorage.OpenStream(sTATSTG.pwcsName, IntPtr.Zero, 16, 0);

                if (uCOMIStream != null)
                {
                    retObject.FileType   = sTATSTG.type;
                    retObject.FilePath   = "";
                    retObject.FileName   = sTATSTG.pwcsName.ToString();
                    retObject.FileStream = uCOMIStream;
                }
                else
                {
                    retObject = null;
                }
            }
            catch (Exception ex)
            {
                retObject = null;

                Debug.WriteLine("ITStorageWrapper.OpenUCOMStream() - Failed for file '" + fileName + "'");
                Debug.Indent();
                Debug.WriteLine("Exception: " + ex.Message);
                Debug.Unindent();
            }

            return(retObject);
        }
Ejemplo n.º 14
0
        /// <summary>
        ///     Create the optical disk image.
        /// </summary>
        /// <returns></returns>
        public COMTypes.IStream CreateImageStream(IFileSystemImageResult fsres)
        {
            var ppos = IntPtr.Zero;

            COMTypes.IStream imagestream = null;
            try
            {
                _fsres      = fsres;
                imagestream = fsres.ImageStream;
                ppos        = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(long)));
                imagestream.Seek(0, 0, ppos);
                if (Marshal.ReadInt64(ppos) != 0)
                {
                    throw new IOException("Can't reset the stream position");
                }

                //IDiscFormat2Data idf = this as IDiscFormat2Data;
                //idf.Write(imagestream);
            }
            catch (Exception exc)
            {
                if (!string.IsNullOrEmpty(OutputFileName))
                {
                    File.Delete(OutputFileName);
                }
                Debug.WriteLine(exc.ToString());
            }
            finally
            {
                if (ppos != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(ppos);
                }
            }
            return(imagestream);
        }
Ejemplo n.º 15
0
        private void CreateFSIFile(FileInfo file, IFsiDirectoryItem diritem)
        {
            var realpath = UniqueListFileSystemInfo.GetPhysicalPath(file.FullName);
            var index    = realpath.IndexOf(":\\") + 1;

            if (_sysImage.Exists(realpath.Substring(index)) == FsiItemType.FsiItemNotFound)
            {
                var crtdiritem = diritem;
                var name       = Path.GetFileName(realpath);
                if (string.Compare(diritem.FullPath, Path.GetDirectoryName(realpath).Substring(index), true) != 0)
                {
                    var fsipath = Path.GetDirectoryName(realpath).Substring(index + 1 + diritem.FullPath.Length);
                    var dirs    = fsipath.Split('\\');

                    var dInfo   = new DirectoryInfo(CaptureDirectory);
                    var subdirs = dInfo.FullName.Split('\\');
                    //MessageBox.Show(subdirs.Length.ToString());
                    //create the subdirs one by one
                    foreach (var dir in dirs.Skip(subdirs.Length - 1))
                    {
                        if (dir.Length == 0)
                        {
                            continue; //in the root like C:\
                        }
                        try
                        {
                            var newpath = string.Format("{0}\\{1}", crtdiritem.FullPath, dir);
                            if (_sysImage.Exists(newpath) != FsiItemType.FsiItemDirectory)
                            {
                                crtdiritem.AddDirectory(dir);
                            }
                        }
                        catch
                        {
                            Cancel = true;
                            throw;
                        }
                        crtdiritem = crtdiritem[dir] as IFsiDirectoryItem;
                    }
                }

                COMTypes.IStream newStream = null;

                try
                {
                    newStream = LoadCOMStream(realpath);
                    crtdiritem.AddFile(name, newStream);
                }
                finally
                {
                    Marshal.FinalReleaseComObject(newStream);
                }

                ActualSize += file.Length;
                if (Update != null && Update.GetInvocationList().Length > 0)
                {
                    Update(file.FullName, file.Length);
                }
            }
            else
            {
                throw new ApplicationException(realpath.Substring(index) +
                                               " occurs in multiple source folders with the same name.");
            }
        }
Ejemplo n.º 16
0
 public static extern HRESULT CreateStreamOnHGlobal(IntPtr hGlobal, [MarshalAs(UnmanagedType.Bool)] bool fDeleteOnRelease, out IStream ppstm);
Ejemplo n.º 17
0
 static extern void SHCreateStreamOnFile(string fileName, uint grfMode, out System.Runtime.InteropServices.ComTypes.IStream stream);
Ejemplo n.º 18
0
 public void CopyTo(System.Runtime.InteropServices.ComTypes.IStream pstm,
                    long cb, System.IntPtr pcbRead, System.IntPtr pcbWritten)
 {
 }
Ejemplo n.º 19
0
 public void Clone(out System.Runtime.InteropServices.ComTypes.IStream ppstm)
 {
     ppstm = null;
 }
Ejemplo n.º 20
0
 [System.Runtime.InteropServices.DllImport("OLE32.DLL", EntryPoint = "CreateStreamOnHGlobal")] // Create a COM stream from a pointer in unmanaged memory
 public extern static int CreateStreamOnHGlobal(IntPtr ptr, bool delete, out System.Runtime.InteropServices.ComTypes.IStream pOutStm);
Ejemplo n.º 21
0
 public void CopyTo(com.IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten) => this.source.CopyTo(pstm, cb, pcbRead, pcbWritten);
Ejemplo n.º 22
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="iStream">an Istream to encapsulate</param>
 public StreamWrapperForIStream(IStream istream)
 {
     m_cachedIstream = istream;
 }
 public static extern HRESULT CreateStreamOnHGlobal(IntPtr hGlobal, bool fDeleteOnRelease, out IStream ppstm);
Ejemplo n.º 24
0
 public static extern int CreateStreamOnHGlobal(IntPtr hGlobal, bool fDeleteOnRelease, [MarshalAs(UnmanagedType.Interface)] out System.Runtime.InteropServices.ComTypes.IStream ppstm);
Ejemplo n.º 25
0
        private void CreateProgressISOFile(COMTypes.IStream imagestream)
        {
            COMTypes.STATSTG stat;

            var  bloksize    = _fsres.BlockSize;
            long totalblocks = _fsres.TotalBlocks;

#if DEBUG
            var tm = new Stopwatch();
            tm.Start();
#endif
            imagestream.Stat(out stat, 0x01);

            if (stat.cbSize == totalblocks * bloksize)
            {
                var buff    = new byte[bloksize];
                var bw      = new BinaryWriter(new FileStream(OutputFileName, FileMode.Create));
                var pcbRead = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(uint)));
                var prg     = _fsres.ProgressItems;
                var enm     = prg.GetEnumerator();
                enm.MoveNext();
                var crtitem = enm.Current as IProgressItem;
                try
                {
                    Marshal.WriteInt32(pcbRead, 0);
                    for (float i = 0; i < totalblocks; i++)
                    {
                        imagestream.Read(buff, bloksize, pcbRead);
                        if (Marshal.ReadInt32(pcbRead) != bloksize)
                        {
                            var err = string.Format(
                                "Failed because Marshal.ReadInt32(pcbRead) = {0} != bloksize = {1}",
                                Marshal.ReadInt32(pcbRead), bloksize);
                            Debug.WriteLine(err);
                            throw new ApplicationException(err);
                        }
                        bw.Write(buff);
                        if (crtitem.LastBlock <= i)
                        {
                            if (enm.MoveNext())
                            {
                                crtitem = enm.Current as IProgressItem;
                            }
                            if (Cancel)
                            {
                                return;
                            }
                        }
                        if (Update != null)
                        {
                            Update(crtitem, i / totalblocks);
                        }

                        if (Cancel)
                        {
                            return;
                        }
                    }

                    if (Update != null)
                    {
                        Update(crtitem, 1);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(string.Format("Exception in : CreateProgressISOFile {0}", ex.Message));

                    throw;
                }
                finally
                {
                    bw.Flush();
                    bw.Close();
                    Marshal.FreeHGlobal(pcbRead);
#if DEBUG
                    tm.Stop();
                    Debug.WriteLine(string.Format("Time spent in CreateProgressISOFile: {0} ms",
                                                  tm.Elapsed.TotalMilliseconds.ToString("#,#")));
#endif
                }
            }
            Debug.WriteLine("failed because stat.cbSize({0}) != totalblocks({1}) * bloksize({2}) ", stat.cbSize,
                            totalblocks, bloksize);
        }
Ejemplo n.º 26
0
 public static extern int GetHGlobalFromStream(ComTypes.IStream pstm, out IntPtr phglobal);
Ejemplo n.º 27
0
 public static extern int CreateStreamOnHGlobal(IntPtr hGlobal, bool fDeleteOnRelease, out System.Runtime.InteropServices.ComTypes.IStream ppstm);
Ejemplo n.º 28
0
 static extern void SHCreateStreamOnFile(string pszFile, uint grfMode, out IStream ppstm);
Ejemplo n.º 29
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="iStream">an Istream to encapsulate</param>
 public StreamWrapperForIStream(IStream istream)
 {
     m_cachedIstream = istream;
 }
Ejemplo n.º 30
0
 public void Clone(out com.IStream ppstm)
 {
     ppstm = new AdapterComStream(this.source);
 }
Ejemplo n.º 31
0
 public StreamWrapper(ComTypes.IStream stm)
 {
     _stm = stm;
 }
Ejemplo n.º 32
0
 internal static extern uint SHCreateStreamOnFile(string pszFile, uint grfMode, out COMTypes.IStream ppstm);
 public static extern Status GdipCreateBitmapFromStream(IStream stream, out IntPtr bitmap);
Ejemplo n.º 34
0
        public void CreateISO()
        {
            Extraction.WriteResource(Resources.BIOS, Directories.TempPath + "Files\\BIOS.com");
            _repository.BootableImageFile = Directories.TempPath + "Files\\BIOS.com";
            Application.DoEvents();
            OnPropertyChanged("0|Enumerating files...");
            var directory = new DirectoryInfo(_path);
            var files     = directory.GetFiles("*", SearchOption.AllDirectories);

            var filtered = files.Select(f => f)
                           .Where(f => (f.Attributes & FileAttributes.Directory) != FileAttributes.Directory);

            foreach (var file in filtered)
            {
                _repository.AddNewFile(file.FullName);
            }

            IFileSystemImageResult imageResult = null;

            COMTypes.IStream imagestream = null;
            try
            {
                var ifsi = InitRepository();
                Application.DoEvents();
                ifsi.CaptureDirectory = _path;
                imageResult           = ifsi.CreateResultImage();

                if (imageResult == null)
                {
                }

                formatter = new ISOFormatter(_output);


                DiscFormat2Data_Events ev = formatter;
                // if (_ckUseUIReport.Checked)
                ev.Update += FormattingEvent;

                imagestream = formatter.CreateImageStream(imageResult);
                IDiscFormat2Data idf = formatter;

                try
                {
                    idf.Write(imagestream);
                }
                catch (ApplicationException)
                {
                    throw;
                }
                catch (IOException)
                {
                    //WaitForSelection(_output);
                    //if (_backgroundISOWorker.CancellationPending)
                    //    throw;
                    idf.Write(imagestream);
                }
                catch (COMException ex)
                {
                    if (ex.ErrorCode == -2147024864)
                    {
                        //WaitForSelection(_output);
                        //if (_backgroundISOWorker.CancellationPending)
                        //    throw;
                        idf.Write(imagestream);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            catch (COMException ex)
            {
                //Console.Beep();
                //if (ex.ErrorCode == -1062555360)
                //{
                //    _lblUpdate.Text = "On UI Thread: Media size could be too small for the amount of data";
                //}
                //else
                //    _lblUpdate.Text = "On UI Thread: " + ex.Message;
                if (ex.ErrorCode != -2147024864 && File.Exists(_output))
                {
                    File.Delete(_output);
                }
            }
            catch (Exception ex)
            {
                //if (!this.IsDisposed)
                //{
                //    if (_repository.Cancel)
                //        _lblUpdate.Text = "Canceled on UI thread";
                //    else
                //    {
                //        Console.Beep();
                //        _lblUpdate.Text = "Failed on UI thread: " + ex.Message;
                //    }
                //}
                if (!(ex is IOException) && File.Exists(_output))
                {
                    File.Delete(_output);
                }
            }
            finally
            {
                if (imagestream != null)
                {
                    Marshal.FinalReleaseComObject(imagestream);
                    imagestream = null;
                }
                if (_repository.Cancel && !string.IsNullOrEmpty(_output))
                {
                    File.Delete(_output);
                }
                //else if (!_ckWorker.Checked)
                //    _lblFileImage.Text = _output;
                //if (!_ckWorker.Checked)
                //    RestoreUI(formatter);
                FileHandling.DeleteFile(Directories.TempPath + "Files\\BIOS.com");
            }
        }