Ejemplo n.º 1
0
        /// <summary>
        /// Saves the Document to the given Stream with the default and given headers, and
        /// using the given IO completion callback.
        /// </summary>
        /// <param name="stream">The Stream to serialize the Document to.</param>
        /// <param name="callback">
        /// This can be used to keep track of the number of uncompressed bytes that are written. The
        /// values reported through the IOEventArgs.Count+Offset will vary from 1 to approximately
        /// Layers.Count*Width*Height*sizeof(ColorBgra). The final number will actually be higher
        /// because of hierarchical overhead, so make sure to cap any progress reports to 100%. This
        /// callback will be wired to the IOFinished event of a SiphonStream. Events may be raised
        /// from any thread. May be null.
        /// </param>
        public void SaveToStream(Stream stream, IOEventHandler callback)
        {
            PrepareHeader();
            string headerText = this.HeaderXml.OuterXml;

            // Write the header
            byte[] magicBytes = Document.MagicBytes;
            stream.Write(magicBytes, 0, magicBytes.Length);
            byte[] headerBytes = Encoding.UTF8.GetBytes(headerText);
            stream.WriteByte((byte)(headerBytes.Length & 0xff));
            stream.WriteByte((byte)((headerBytes.Length & 0xff00) >> 8));
            stream.WriteByte((byte)((headerBytes.Length & 0xff0000) >> 16));
            stream.Write(headerBytes, 0, headerBytes.Length);
            stream.Flush();

            // Copy version info
            this.savedWith = PdnInfo.GetVersion();

            // Write 0x00, 0x01 to indicate normal .NET serialized data
            stream.WriteByte(0x00);
            stream.WriteByte(0x01);

            // Write the remainder of the file (gzip compressed)
            SiphonStream      siphonStream = new SiphonStream(stream);
            BinaryFormatter   formatter    = new BinaryFormatter();
            DeferredFormatter deferred     = new DeferredFormatter(true, null);
            SaveProgressRelay relay        = new SaveProgressRelay(deferred, callback);

            formatter.Context = new StreamingContext(formatter.Context.State, deferred);
            formatter.Serialize(siphonStream, this);
            deferred.FinishSerialization(siphonStream);

            stream.Flush();
        }
        public void SendPacket(StreamBuffer buffer, PacketPredicate predicate, IOEventHandler dispatcher, Action <StreamBuffer> onSent = null)
        {
            if (predicate == null || dispatcher == null)
            {
                throw new AegisException(AegisResult.InvalidArgument, "The argument predicate and dispatcher cannot be null.");
            }


            try
            {
                lock (_session)
                {
                    if (_session.Socket == null)
                    {
                        return;
                    }

                    //  ReadIndex가 OnSocket_Send에서 사용되므로 ReadIndex를 초기화해야 한다.
                    buffer.ResetReadIndex();


                    SocketAsyncEventArgs saea = new SocketAsyncEventArgs();
                    saea.Completed += SendComplete;
                    saea.SetBuffer(buffer.Buffer, 0, buffer.WrittenBytes);
                    if (onSent != null)
                    {
                        saea.UserToken = new NetworkSendToken(buffer, onSent);
                    }

                    _responseSelector.Add(predicate, dispatcher);

                    if (_session.Socket.SendAsync(saea) == false)
                    {
                        ReceiveComplete(null, saea);
                    }
                }
            }
            catch (SocketException)
            {
            }
            catch (Exception e)
            {
                Logger.Err(LogMask.Aegis, e.ToString());
            }
        }
Ejemplo n.º 3
0
        public void SendPacket(StreamBuffer buffer, PacketPredicate predicate, IOEventHandler dispatcher, Action <StreamBuffer> onSent = null)
        {
            if (predicate == null || dispatcher == null)
            {
                throw new AegisException(AegisResult.InvalidArgument, "The argument predicate and dispatcher cannot be null.");
            }

            try
            {
                lock (_session)
                {
                    _responseSelector.Add(predicate, dispatcher);
                    if (_session.Socket != null)
                    {
                        //  ReadIndex가 OnSocket_Send에서 사용되므로 ReadIndex를 초기화해야 한다.
                        buffer.ResetReadIndex();

                        if (onSent == null)
                        {
                            _session.Socket.BeginSend(buffer.Buffer, 0, buffer.WrittenBytes, SocketFlags.None, Socket_Send, null);
                        }
                        else
                        {
                            _session.Socket.BeginSend(buffer.Buffer, 0, buffer.WrittenBytes, SocketFlags.None, Socket_Send,
                                                      new NetworkSendToken(buffer, onSent));
                        }
                    }
                }
            }
            catch (SocketException)
            {
            }
            catch (Exception e)
            {
                Logger.Err(LogMask.Aegis, e.ToString());
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Saves the Document to the given Stream with the default and given headers, and
        /// using the given IO completion callback.
        /// </summary>
        /// <param name="stream">The Stream to serialize the Document to.</param>
        /// <param name="callback">
        /// This can be used to keep track of the number of uncompressed bytes that are written. The 
        /// values reported through the IOEventArgs.Count+Offset will vary from 1 to approximately 
        /// Layers.Count*Width*Height*sizeof(ColorBgra). The final number will actually be higher 
        /// because of hierarchical overhead, so make sure to cap any progress reports to 100%. This
        /// callback will be wired to the IOFinished event of a SiphonStream. Events may be raised
        /// from any thread. May be null.
        /// </param>
        public void SaveToStream(Stream stream, IOEventHandler callback)
        {
            InitializeDpu();

            PrepareHeader();
            string headerText = this.HeaderXml.OuterXml;

            // Write the header
            byte[] magicBytes = Document.MagicBytes;
            stream.Write(magicBytes, 0, magicBytes.Length);
            byte[] headerBytes = Encoding.UTF8.GetBytes(headerText);
            stream.WriteByte((byte)(headerBytes.Length & 0xff));
            stream.WriteByte((byte)((headerBytes.Length & 0xff00) >> 8));
            stream.WriteByte((byte)((headerBytes.Length & 0xff0000) >> 16));
            stream.Write(headerBytes, 0, headerBytes.Length);
            stream.Flush();

            // Copy version info
            this.savedWith = PdnInfo.GetVersion();

            // Write 0x00, 0x01 to indicate normal .NET serialized data
            stream.WriteByte(0x00);
            stream.WriteByte(0x01);

            // Write the remainder of the file (gzip compressed)
            SiphonStream siphonStream = new SiphonStream(stream);
            BinaryFormatter formatter = new BinaryFormatter();
            DeferredFormatter deferred = new DeferredFormatter(true, null);
            SaveProgressRelay relay = new SaveProgressRelay(deferred, callback);
            formatter.Context = new StreamingContext(formatter.Context.State, deferred);
            formatter.Serialize(siphonStream, this);
            deferred.FinishSerialization(siphonStream);

            stream.Flush();
        }
Ejemplo n.º 5
0
        public void OnEnteredStateImpl()
        {
            FileStream zipFileRead  = new FileStream(this.extractMe, FileMode.Open, FileAccess.Read, FileShare.Read);
            FileStream exeFileWrite = null;

            try
            {
                ICSharpCode.SharpZipLib.Zip.ZipInputStream zipStream =
                    new ICSharpCode.SharpZipLib.Zip.ZipInputStream(zipFileRead);

                // Search for the first .msi file in the exe, and extract it
                ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry;
                bool foundExe = false;

                while (true)
                {
                    zipEntry = zipStream.GetNextEntry();

                    if (zipEntry == null)
                    {
                        break;
                    }

                    if (!zipEntry.IsDirectory &&
                        string.Compare(".exe", Path.GetExtension(zipEntry.Name), true, CultureInfo.InvariantCulture) == 0)
                    {
                        foundExe = true;
                        break;
                    }
                }

                if (!foundExe)
                {
                    this.exception = new FileNotFoundException();
                    StateMachine.QueueInput(PrivateInput.GoToError);
                }
                else
                {
                    int maxBytes   = (int)zipEntry.Size;
                    int bytesSoFar = 0;

                    this.installerPath = Path.Combine(Path.GetDirectoryName(this.extractMe), zipEntry.Name);
                    exeFileWrite       = new FileStream(this.installerPath, FileMode.Create, FileAccess.Write, FileShare.Read);
                    SiphonStream siphonStream2 = new SiphonStream(exeFileWrite, 4096);

                    this.abortMeStream = siphonStream2;

                    IOEventHandler ioFinishedDelegate =
                        delegate(object sender, IOEventArgs e)
                    {
                        bytesSoFar += e.Count;
                        double percent = 100.0 * ((double)bytesSoFar / (double)maxBytes);
                        OnProgress(percent);
                    };

                    OnProgress(0.0);

                    if (maxBytes > 0)
                    {
                        siphonStream2.IOFinished += ioFinishedDelegate;
                    }

                    Utility.CopyStream(zipStream, siphonStream2);

                    if (maxBytes > 0)
                    {
                        siphonStream2.IOFinished -= ioFinishedDelegate;
                    }

                    this.abortMeStream = null;
                    siphonStream2      = null;
                    exeFileWrite.Close();
                    exeFileWrite = null;
                    zipStream.Close();
                    zipStream = null;

                    StateMachine.QueueInput(PrivateInput.GoToReadyToInstall);
                }
            }

            catch (Exception ex)
            {
                if (this.AbortRequested)
                {
                    StateMachine.QueueInput(PrivateInput.GoToAborted);
                }
                else
                {
                    this.exception = ex;
                    StateMachine.QueueInput(PrivateInput.GoToError);
                }
            }

            finally
            {
                if (exeFileWrite != null)
                {
                    exeFileWrite.Close();
                    exeFileWrite = null;
                }

                if (zipFileRead != null)
                {
                    zipFileRead.Close();
                    zipFileRead = null;
                }

                if (this.exception != null || this.AbortRequested)
                {
                    if (this.installerPath != null)
                    {
                        bool result = FileSystem.TryDeleteFile(this.installerPath);
                    }
                }

                if (this.extractMe != null)
                {
                    bool result = FileSystem.TryDeleteFile(this.extractMe);
                }
            }
        }
        public void SendPacket(StreamBuffer buffer, PacketPredicate predicate, IOEventHandler dispatcher, Action<StreamBuffer> onSent = null)
        {
            if (predicate == null || dispatcher == null)
                throw new AegisException(AegisResult.InvalidArgument, "The argument predicate and dispatcher cannot be null.");

            try
            {
                lock (_session)
                {
                    if (_session.Socket == null)
                        return;

                    //  ReadIndex가 OnSocket_Send에서 사용되므로 ReadIndex를 초기화해야 한다.
                    buffer.ResetReadIndex();

                    SocketAsyncEventArgs saea = new SocketAsyncEventArgs();
                    saea.Completed += SendComplete;
                    saea.SetBuffer(buffer.Buffer, 0, buffer.WrittenBytes);
                    if (onSent != null)
                        saea.UserToken = new NetworkSendToken(buffer, onSent);

                    _responseSelector.Add(predicate, dispatcher);

                    if (_session.Socket.SendAsync(saea) == false)
                        ReceiveComplete(null, saea);
                }
            }
            catch (SocketException)
            {
            }
            catch (Exception e)
            {
                Logger.Err(LogMask.Aegis, e.ToString());
            }
        }
Ejemplo n.º 7
0
 public Data(PacketPredicate predicate, IOEventHandler dispatcher)
 {
     Predicate = predicate;
     Dispatcher = dispatcher;
 }
Ejemplo n.º 8
0
 public void Add(PacketPredicate predicate, IOEventHandler dispatcher)
 {
     lock (_listResponseAction)
         _listResponseAction.Add(new Data(predicate, dispatcher));
 }
Ejemplo n.º 9
0
 public SaveProgressRelay(DeferredFormatter formatter, IOEventHandler ioCallback)
 {
     this.formatter  = formatter;
     this.ioCallback = ioCallback;
     this.formatter.ReportedBytesChanged += new EventHandler(Formatter_ReportedBytesChanged);
 }
Ejemplo n.º 10
0
 /// <summary>
 /// 패킷을 전송하고, 특정 패킷이 수신될 경우 dispatcher에 지정된 핸들러를 실행합니다.
 /// 이 기능은 AwaitableMethod보다는 빠르지만, 동시에 많이 호출될 경우 성능이 저하될 수 있습니다.
 /// </summary>
 /// <param name="buffer">전송할 데이터가 담긴 StreamBuffer</param>
 /// <param name="predicate">dispatcher에 지정된 핸들러를 호출할 것인지 여부를 판단하는 함수를 지정합니다.</param>
 /// <param name="dispatcher">실행될 함수를 지정합니다.</param>
 /// <param name="onSent">패킷 전송이 완료된 후 호출할 Action</param>
 public virtual void SendPacket(StreamBuffer buffer, PacketPredicate predicate, IOEventHandler dispatcher, Action <StreamBuffer> onSent = null)
 {
     _method.SendPacket(buffer, predicate, dispatcher, onSent);
 }
Ejemplo n.º 11
0
 /// <summary>
 /// 패킷을 전송하고, 특정 패킷이 수신될 경우 dispatcher에 지정된 핸들러를 실행합니다.
 /// 이 기능은 AwaitableMethod보다는 빠르지만, 동시에 많이 호출될 경우 성능이 저하될 수 있습니다.
 /// </summary>
 /// <param name="buffer">전송할 데이터가 담긴 StreamBuffer</param>
 /// <param name="predicate">dispatcher에 지정된 핸들러를 호출할 것인지 여부를 판단하는 함수를 지정합니다.</param>
 /// <param name="dispatcher">실행될 함수를 지정합니다.</param>
 /// <param name="onSent">패킷 전송이 완료된 후 호출할 Action</param>
 public virtual void SendPacket(StreamBuffer buffer, PacketPredicate predicate, IOEventHandler dispatcher, Action<StreamBuffer> onSent = null)
 {
     _method.SendPacket(buffer, predicate, dispatcher, onSent);
 }
Ejemplo n.º 12
0
        public void OnEnteredStateImpl()
        {
            FileStream stream           = new FileStream(this.extractMe, FileMode.Open, FileAccess.Read, FileShare.Read);
            FileStream underlyingStream = null;

            try
            {
                using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read, true))
                {
                    ZipArchiveEntry entry = archive.Entries.FirstOrDefault <ZipArchiveEntry>(ze => string.Compare(".exe", Path.GetExtension(ze.Name), true, CultureInfo.InvariantCulture) == 0);
                    if (entry == null)
                    {
                        this.exception = new FileNotFoundException();
                        base.StateMachine.QueueInput(PrivateInput.GoToError);
                    }
                    else
                    {
                        int maxBytes   = (int)entry.Length;
                        int bytesSoFar = 0;
                        this.installerPath = Path.Combine(Path.GetDirectoryName(this.extractMe), entry.Name);
                        underlyingStream   = new FileStream(this.installerPath, FileMode.Create, FileAccess.Write, FileShare.Read);
                        SiphonStream output = new SiphonStream(underlyingStream, 0x1000);
                        this.abortMeStream = output;
                        IOEventHandler handler = delegate(object sender, IOEventArgs e) {
                            bytesSoFar += e.Count;
                            double percent = 100.0 * (((double)bytesSoFar) / ((double)maxBytes));
                            this.OnProgress(percent);
                        };
                        base.OnProgress(0.0);
                        if (maxBytes > 0)
                        {
                            output.IOFinished += handler;
                        }
                        using (Stream stream4 = entry.Open())
                        {
                            StreamUtil.CopyStream(stream4, output);
                        }
                        if (maxBytes > 0)
                        {
                            output.IOFinished -= handler;
                        }
                        this.abortMeStream = null;
                        output             = null;
                        underlyingStream.Close();
                        underlyingStream = null;
                        base.StateMachine.QueueInput(PrivateInput.GoToReadyToInstall);
                    }
                }
            }
            catch (Exception exception)
            {
                if (base.AbortRequested)
                {
                    base.StateMachine.QueueInput(PrivateInput.GoToAborted);
                }
                else
                {
                    this.exception = exception;
                    base.StateMachine.QueueInput(PrivateInput.GoToError);
                }
            }
            finally
            {
                if (underlyingStream != null)
                {
                    underlyingStream.Close();
                    underlyingStream = null;
                }
                if (stream != null)
                {
                    stream.Close();
                    stream = null;
                }
                if (((this.exception != null) || base.AbortRequested) && (this.installerPath != null))
                {
                    bool flag = FileSystem.TryDeleteFile(this.installerPath);
                }
                if (this.extractMe != null)
                {
                    bool flag2 = FileSystem.TryDeleteFile(this.extractMe);
                }
            }
        }
Ejemplo n.º 13
0
 public void Add(PacketPredicate predicate, IOEventHandler dispatcher)
 {
     lock (_listResponseAction)
         _listResponseAction.Add(new Data(predicate, dispatcher));
 }
Ejemplo n.º 14
0
 public Data(PacketPredicate predicate, IOEventHandler dispatcher)
 {
     Predicate  = predicate;
     Dispatcher = dispatcher;
 }
Ejemplo n.º 15
0
 public SaveProgressRelay(DeferredFormatter formatter, IOEventHandler ioCallback)
 {
     this.formatter = formatter;
     this.ioCallback = ioCallback;
     this.formatter.ReportedBytesChanged += new EventHandler(Formatter_ReportedBytesChanged);
 }
Ejemplo n.º 16
0
        public static Document LoadDocument(Control owner, string fileName, out FileType fileTypeResult, ProgressEventHandler progressCallback)
        {
            fileTypeResult = null;

            try
            {
                var fileTypes = FileTypes.GetFileTypes();
                var extName   = Path.GetExtension(fileName);
                if (extName == null)
                {
                    //Todo: Get file real type.
                    throw new Exception("Get file real type.");
                }
                extName        = extName.Replace(".", "");
                fileTypeResult = fileTypes.First(x => x.Extensions.Any(ext => ext == extName));
            }

            catch (ArgumentException)
            {
                string format = PdnResources.GetString("LoadImage.Error.InvalidFileName.Format");
                string error  = string.Format(format, fileName);
                Utility.ErrorBox(owner, error);
                return(null);
            }

            Document document = null;

            using (new WaitCursorChanger(owner))
            {
                Utility.GCFullCollect();
                Stream stream = null;

                try
                {
                    try
                    {
                        stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                        long totalBytes = 0;

                        var siphonStream = new SiphonStream(stream);

                        IOEventHandler ioEventHandler = null;
                        ioEventHandler =
                            delegate(object sender, IOEventArgs e)
                        {
                            if (progressCallback != null)
                            {
                                totalBytes += (long)e.Count;
                                double percent = Utility.Clamp(100.0 * ((double)totalBytes / (double)siphonStream.Length), 0, 100);
                                progressCallback(null, new ProgressEventArgs(percent));
                            }
                        };

                        siphonStream.IOFinished += ioEventHandler;

                        using (new WaitCursorChanger(owner))
                        {
                            document = fileTypeResult.Load(siphonStream);

                            if (progressCallback != null)
                            {
                                progressCallback(null, new ProgressEventArgs(100.0));
                            }
                        }

                        siphonStream.IOFinished -= ioEventHandler;
                        siphonStream.Close();
                    }

                    catch (WorkerThreadException ex)
                    {
                        Type            innerExType = ex.InnerException.GetType();
                        ConstructorInfo ci          = innerExType.GetConstructor(new Type[] { typeof(string), typeof(Exception) });

                        if (ci == null)
                        {
                            throw;
                        }
                        else
                        {
                            var ex2 = (Exception)ci.Invoke(new object[] { "Worker thread threw an exception of this type", ex.InnerException });
                            throw ex2;
                        }
                    }
                }

                catch (ArgumentException)
                {
                    if (fileName.Length == 0)
                    {
                        Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.BlankFileName"));
                    }
                    else
                    {
                        Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.ArgumentException"));
                    }
                }

                catch (UnauthorizedAccessException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.UnauthorizedAccessException"));
                }

                catch (SecurityException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SecurityException"));
                }

                catch (FileNotFoundException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.FileNotFoundException"));
                }

                catch (DirectoryNotFoundException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.DirectoryNotFoundException"));
                }

                catch (PathTooLongException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.PathTooLongException"));
                }

                catch (IOException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.IOException"));
                }

                catch (SerializationException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SerializationException"));
                }

                catch (OutOfMemoryException)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.OutOfMemoryException"));
                }

                catch (Exception)
                {
                    Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.Exception"));
                }

                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                        stream = null;
                    }
                }
            }

            return(document);
        }
        public void SendPacket(StreamBuffer buffer, PacketPredicate predicate, IOEventHandler dispatcher, Action<StreamBuffer> onSent = null)
        {
            if (predicate == null || dispatcher == null)
                throw new AegisException(AegisResult.InvalidArgument, "The argument predicate and dispatcher cannot be null.");

            try
            {
                lock (_session)
                {
                    _responseSelector.Add(predicate, dispatcher);
                    if (_session.Socket != null)
                    {
                        //  ReadIndex가 OnSocket_Send에서 사용되므로 ReadIndex를 초기화해야 한다.
                        buffer.ResetReadIndex();

                        if (onSent == null)
                            _session.Socket.BeginSend(buffer.Buffer, 0, buffer.WrittenBytes, SocketFlags.None, Socket_Send, null);
                        else
                            _session.Socket.BeginSend(buffer.Buffer, 0, buffer.WrittenBytes, SocketFlags.None, Socket_Send,
                                             new NetworkSendToken(buffer, onSent));
                    }
                }
            }
            catch (SocketException)
            {
            }
            catch (Exception e)
            {
                Logger.Err(LogMask.Aegis, e.ToString());
            }
        }