Exemplo n.º 1
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            uniqueInstanceName = $"{Environment.MachineName}-{Handle}";
            client             = new XDMessagingClient().WithAmazonSettings(RegionEndPoint.EUWest1);
            if (!client.HasValidAmazonSettings())
            {
                MessageBox.Show("Azazon AWS crendentials not set. Enter your credentials in the app.config.",
                                "Missing AWS Crendentials",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);

                propagateCheck.CheckState = CheckState.Unchecked;
                propagateCheck.Enabled    = false;
                mailRadio.Enabled         = false;
            }

            var tooltips = new ToolTip();

            tooltips.SetToolTip(sendBtn, "Broadcast message on Channel 1\r\nand Channel2");
            tooltips.SetToolTip(groupBox1, "Choose which channels\r\nthis instance will\r\nlisten on");
            tooltips.SetToolTip(Mode, "Choose which mode\r\nto use for sending\r\nand receiving");

            UpdateDisplayText(
                "Launch multiple instances of this application to demo interprocess communication. Run multiple instances on different machines to demo network propogation.\r\n",
                Color.Gray);

            Text += $" - {uniqueInstanceName}";

            InitializeMode(XDTransportMode.HighPerformanceUI);

            var message = $"{uniqueInstanceName} has joined";

            broadcast.SendToChannel("Status", message);
        }
Exemplo n.º 2
0
        public Listeners(XDMessagingClient client, IocContainer container)
            : base(container)
        {
            Validate.That(client).IsNotNull();

            this.client = client;
        }
Exemplo n.º 3
0
        public Listeners(XDMessagingClient client, IocContainer container)
            : base(container)
        {
            Validate.That(client).IsNotNull();

            this.client = client;
        }
Exemplo n.º 4
0
        /// <summary>
        ///   Broadcast a message that the service has started.
        /// </summary>
        /// <param name = "args"></param>
        protected override void OnStart(string[] args)
        {
            isTraceEnabled = true;

            client = new XDMessagingClient().WithAmazonSettings(RegionEndPoint.EUWest1);

            listener = client.Listeners.GetListenerForMode(XDTransportMode.Compatibility);
            listener.MessageReceived += OnMessageReceived;
            listener.RegisterChannel("BinaryChannel1");
            listener.RegisterChannel("BinaryChannel2");

            //only the following mode is supported in windows services
            broadcast = client.Broadcasters.GetBroadcasterForMode(XDTransportMode.Compatibility);

            broadcast.SendToChannel("Status", "Test Service has started: Send STOP on Channel 1/2 to halt timer. Send START to Channel 1/2 to restart.");
            cancelToken = new CancellationTokenSource();
            Task.Factory.StartNew(() =>
            {
                while (!cancelToken.IsCancellationRequested)
                {
                    if (isTraceEnabled)
                    {
                        broadcast.SendToChannel("Status",
                                                "The time is: " + DateTime.Now.ToString("f"));
                        Thread.Sleep(5000);
                    }
                }
            });
        }
Exemplo n.º 5
0
        public Broadcasters(XDMessagingClient messagingClient, IocContainer container)
            : base(container)
        {
            Validate.That(messagingClient).IsNotNull();

            this.messagingClient = messagingClient;
        }
Exemplo n.º 6
0
        private void SendButton_Click(object sender, RoutedEventArgs e)
        {
            var client      = new XDMessagingClient();
            var broadcaster = client.Broadcasters.GetBroadcasterForMode(XDTransportMode.Compatibility);

            broadcaster.SendToChannel(Constants.ChannelName, TextBox.Text);
        }
Exemplo n.º 7
0
        public Broadcasters(XDMessagingClient messagingClient, IocContainer container)
            : base(container)
        {
            Validate.That(messagingClient).IsNotNull();

            this.messagingClient = messagingClient;
        }
Exemplo n.º 8
0
        internal Listeners(XDMessagingClient client, ISerializer serializer)
        {
            client.Requires("client").IsNotNull();
            serializer.Requires("serializer").IsNotNull();

            this.serializer = serializer;
        }
Exemplo n.º 9
0
        internal Listeners(XDMessagingClient client, ISerializer serializer)
        {
            client.Requires("client").IsNotNull();
            serializer.Requires("serializer").IsNotNull();

            this.serializer = serializer;
        }
Exemplo n.º 10
0
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var client   = new XDMessagingClient();
            var listener = client.Listeners.GetListenerForMode(XDTransportMode.Compatibility);

            listener.MessageReceived += Listener_MessageReceived;
            listener.RegisterChannel(Constants.ChannelName);
        }
Exemplo n.º 11
0
        public void GivenAmazonBroadcastImplThenShouldResolveSuccess()
        {
            // arrange
            var client = new XDMessagingClient();

            // act
            var instance = client.Broadcasters.GetAmazonBroadcaster();

            // assert
            Assert.That(instance, Is.Not.Null);
        }
Exemplo n.º 12
0
        public void GivenWindowsMessagingListenerImplThenShouldResolveInstanceSuccess()
        {
            // arrange
            var client = new XDMessagingClient();

            // act
            var instance = client.Listeners.GetWindowsMessagingListener();

            // assert
            Assert.That(instance, Is.Not.Null);
        }
        public void GivenCompatibilityModeThenShouldResolveSuccess()
        {
            // arrange
            var client = new XDMessagingClient();

            // act
            var instance = client.Broadcasters.GetBroadcasterForMode(XDTransportMode.Compatibility);

            // assert
            Assert.That(instance, Is.Not.Null);
        }
        public void GivenWindowsMessagingListenerImplThenShouldResolveInstanceSuccess()
        {
            // arrange
            var client = new XDMessagingClient();

            // act
            var instance = client.Listeners.GetWindowsMessagingListener();

            // assert
            Assert.That(instance, Is.Not.Null);
        }
        public void GivenCompatibilityModeThenShouldResolveSuccess()
        {
            // arrange
            var client = new XDMessagingClient();

            // act
            var instance = client.Broadcasters.GetBroadcasterForMode(XDTransportMode.Compatibility);

            // assert
            Assert.That(instance, Is.Not.Null);
        }
        public void GivenHighPerformanceUiModeBroadcastImplThenShouldResolveSuccess()
        {
            // arrange
            var client = new XDMessagingClient();

            // act
            var instance = client.Broadcasters.GetBroadcasterForMode(XDTransportMode.HighPerformanceUI);

            // assert
            Assert.That(instance, Is.Not.Null);
        }
        public void GivenAmazonBroadcastImplThenShouldResolveSuccess()
        {
            // arrange
            var client = new XDMessagingClient();

            // act
            var instance = client.Broadcasters.GetAmazonBroadcaster();

            // assert
            Assert.That(instance, Is.Not.Null);
        }
        public void GivenRemoteNetworkModeImplThenShouldResolveSuccess()
        {
            // arrange
            var client = new XDMessagingClient();

            // act
            var instance = client.Broadcasters.GetBroadcasterForMode(XDTransportMode.RemoteNetwork);

            // assert
            Assert.That(instance, Is.Not.Null);
        }
        public void GivenRemoteNetworkModeImplThenShouldResolveSuccess()
        {
            // arrange
            var client = new XDMessagingClient();

            // act
            var instance = client.Broadcasters.GetBroadcasterForMode(XDTransportMode.RemoteNetwork);

            // assert
            Assert.That(instance, Is.Not.Null);
        }
        public void GivenHighPerformanceUiModeBroadcastImplThenShouldResolveSuccess()
        {
            // arrange
            var client = new XDMessagingClient();

            // act
            var instance = client.Broadcasters.GetBroadcasterForMode(XDTransportMode.HighPerformanceUI);

            // assert
            Assert.That(instance, Is.Not.Null);
        }
Exemplo n.º 21
0
        public ExplorerMonitorAdapter(SynchronizationContext synchronizationContext)
        {
            this.synchronizationContext = synchronizationContext ?? throw new ArgumentNullException(nameof(synchronizationContext));

            messageClient = new XDMessagingClient();
            broadcaster   = messageClient.Broadcasters.GetBroadcasterForMode(XDTransportMode.HighPerformanceUI);

            sink = messageClient.Listeners.GetListenerForMode(XDTransportMode.HighPerformanceUI);
            sink.RegisterChannel("SelectionOfExplorerWindowChanged");

            sink.MessageReceived += Sink_MessageReceived;
        }
        public void GivenAmazonSettingsThenShouldResolveSuccess()
        {
            // arrange
            var client = new XDMessagingClient().WithAmazonSettings("xx", "xx");

            // act
            var accessKey = AmazonAccountSettings.GetInstance().AccessKey;
            var accessKey2 = client.Broadcasters.Container.Resolve<AmazonAccountSettings>().AccessKey;


            // assert
            Assert.That(accessKey, Is.EqualTo("xx"));
            Assert.That(accessKey2, Is.EqualTo("xx"));
        }
Exemplo n.º 23
0
        public void GivenAmazonSettingsThenShouldResolveSuccess()
        {
            // arrange
            var client = new XDMessagingClient().WithAmazonSettings("xx", "xx");

            // act
            var accessKey  = AmazonAccountSettings.GetInstance().AccessKey;
            var accessKey2 = client.Broadcasters.Container.Resolve <AmazonAccountSettings>().AccessKey;


            // assert
            Assert.That(accessKey, Is.EqualTo("xx"));
            Assert.That(accessKey2, Is.EqualTo("xx"));
        }
Exemplo n.º 24
0
        public LoadingForm()
        {
            InitializeComponent();

            string[] args = Environment.GetCommandLineArgs();
            if (args.Contains("-packing") || args.Contains("packing"))
            {
                labPacking.Visible = true;
            }
            else if (args.Contains("-unpacking") || args.Contains("unpacking"))
            {
                labUnpacking.Visible = true;
            }

            // Setup XDMessagingClient listener to receive progress updates
            XDMessagingClient client = new XDMessagingClient();

            listener = client.Listeners.GetListenerForMode(XDTransportMode.HighPerformanceUI);
            listener.RegisterChannel("AppackerProgress");

            // Attach event handler for incoming messages
            listener.MessageReceived += (o, ea) =>
            {
                if (ea.DataGram.Channel == "AppackerProgress")
                {
                    // 'Done' is sent when packing/unpacking is finished => close this splash
                    if (ea.DataGram.Message == "Done")
                    {
                        progressBar.Value = progressBar.Maximum;
                        Exit();
                    }
                    // Other messages are progress updates
                    else
                    {
                        string[] tokens = ea.DataGram.Message.Split(' ');
                        progressBar.Maximum = int.Parse(tokens[1]);
                        progressBar.Value   = int.Parse(tokens[0]);
                    }
                }
            };
        }
Exemplo n.º 25
0
        public MonitorApplicationContext(CommandlineOptions commandline)
        {
            messageClient = new XDMessagingClient();
            broadcaster   = messageClient.Broadcasters.GetBroadcasterForMode(XDTransportMode.HighPerformanceUI);

            sink = messageClient.Listeners.GetListenerForMode(XDTransportMode.HighPerformanceUI);
            sink.RegisterChannel("ExplorerObserverCommand");

            sink.MessageReceived += Sink_MessageReceived;

            observer = new ExplorerMonitor();
            observer.ExplorerSelectionChanged += Observer_ExplorerSelectionChanged;
            observer.ExplorerWindowGotFocus   += Observer_ExplorerWindowGotFocus;

            WatchParentProcessExit(commandline.ParentProcessId);

            observer.Start();

            if (commandline.ShowDebugForm)
            {
                this.MainForm = new DebugForm();
                this.MainForm.Show();
            }
        }
Exemplo n.º 26
0
        internal Broadcasters(XDMessagingClient client, ISerializer serializer)
        {
            serializer.Requires("serializer").IsNotNull();

            this.serializer = serializer;
        }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
#if DEBUG
            Console.WriteLine("Unpacker is running in Debug");
            Console.WriteLine("Attach to process now and press Enter...");
            Console.ReadLine();
            Console.WriteLine("Resuming");
#endif

            // Hide console window if stdout is not redirected
            // If it is => keep window and later redirect I/O of the unpacked app too
            bool stdoutRedirected = Console.IsOutputRedirected;
            if (!stdoutRedirected)
#if DEBUG
            { Console.WriteLine($"Output redirected: {stdoutRedirected}"); }
            Console.WriteLine("I'm hidden");
#else
            { ShowWindow(GetConsoleWindow(), SW_HIDE); }
#endif

            // After self-repacking, packer.exe can't delete itself from the temp dir, so it calls repacked app to kill it
            // Command is "unpacker.exe -killme <path to packer.exe>"
            // The whole folder where packer.exe is gets deleted (cuz there should also be temp unpacker.exe from repacking process)
            if (args.Length > 0 &&
                (args[0] == "-killme" || args[0] == "killme"))
            {
                if (args.Length > 1)
                {
                    if (WaitForFileAccess(args[1], WAIT_FOR_FILE_ACCESS_TIMEOUT) == true)
                    {
                        DeleteDirectory(Path.GetDirectoryName(args[1]));
                    }
                }

                // Don't unpack anything. Just close the app now
                return;
            }


            // Subscribe for exit event to delete tempDir
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(Unpacker_ProcessExit);

            // Open self exe file as byte stream and unpack data that is appended to the end of exe
            string selfExePath = System.Reflection.Assembly.GetEntryAssembly().Location;
            using (var me = new BinaryReader(File.OpenRead(selfExePath)))
            {
                // Find the end of the actual unpacker.exe
                byte[] pattern = Encoding.UTF8.GetBytes("<SerGreen>");
                long   pos     = FindPatternPosition(me.BaseStream, pattern);
                me.BaseStream.Seek(pos + pattern.Length, SeekOrigin.Begin);

                // Create temp directory to store tools
                while (repackerTempDir == null || Directory.Exists(repackerTempDir))
                {
                    repackerTempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
                }
                Directory.CreateDirectory(repackerTempDir);

                // Start extracting appended data
                isSelfRepackable = me.ReadBoolean();
                if (isSelfRepackable)
                {
                    // For repacking we also need the unpacker.exe itself
                    // So return to the beginning of the file and save the unpacker.exe part
                    me.BaseStream.Seek(0, SeekOrigin.Begin);
                    File.WriteAllBytes(Path.Combine(repackerTempDir, "unpacker.exe"), me.ReadBytes((int)pos));
                    // Skip <SerGreen> keyword and 1 byte of isSelfRepackable flag
                    me.ReadBytes(pattern.Length + 1);
                    // Save the packer.exe
                    int packerDataLength = me.ReadInt32();
                    File.WriteAllBytes(Path.Combine(repackerTempDir, "packer.exe"), me.ReadBytes(packerDataLength));
                }

                // Extract splash screen tool if present
                isProgressBarSplashExePresent = me.ReadBoolean();
                if (isProgressBarSplashExePresent)
                {
                    int splashDataLength = me.ReadInt32();
                    File.WriteAllBytes(Path.Combine(repackerTempDir, "ProgressBarSplash.exe"), me.ReadBytes(splashDataLength));
                }

                // Unpack directory loading
                openUnpackedDir        = me.ReadBoolean();
                unpackingDirectoryType = me.ReadInt32();

                // Decode actual path
                // Desktop
                if (unpackingDirectoryType == 1)
                {
                    unpackingDirectoryPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                }
                // Directory where this exe is located
                else if (unpackingDirectoryType == 2)
                {
                    unpackingDirectoryPath = AppDomain.CurrentDomain.BaseDirectory;
                }
                // Ask user for a folder
                else if (unpackingDirectoryType == 3)
                {
                    FolderBrowserDialog fbd = new FolderBrowserDialog {
                        Description = "Select a folder in which to extract files"
                    };
                    if (fbd.ShowDialog() == DialogResult.OK)
                    {
                        unpackingDirectoryPath = fbd.SelectedPath;
                    }
                    else
                    {
                        unpackingDirectoryPath = Path.GetTempPath();
                    }
                }
                // Default is %TEMP%
                else
                {
                    unpackingDirectoryPath = Path.GetTempPath();
                }

                // Create temp directory to store unpacked files
                while (tempDir == null || Directory.Exists(tempDir))
                {
                    tempDir = Path.Combine(unpackingDirectoryPath, Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location) + "_" + Guid.NewGuid().ToString());
                }
                Directory.CreateDirectory(tempDir);

                // Load relative path to the main exe
                pathToMainExe = me.ReadString();

                // Load launch arguments for main exe
                launchArguments = me.ReadString();

                timer.Start();
                Process splashProgressBarProc = null;

                // Keep extracting files until the end of the stream
                while (me.BaseStream.Position < me.BaseStream.Length)
                {
                    // If unpacking process takes too long, display splash screen with progress bar
                    if (isProgressBarSplashExePresent && broadcaster == null && timer.ElapsedMilliseconds > SPLASH_POPUP_DELAY)
                    {
                        // Create XDMessagingClient broadcaster to report progress
                        XDMessagingClient client = new XDMessagingClient();
                        broadcaster = client.Broadcasters.GetBroadcasterForMode(XDTransportMode.HighPerformanceUI);

                        splashProgressBarProc = Process.Start(Path.Combine(repackerTempDir, "ProgressBarSplash.exe"), "-unpacking");
                        timer.Stop();
                    }

                    // Report progress to the Splash screen with progress bar
                    broadcaster?.SendToChannel("AppackerProgress", $"{me.BaseStream.Position} {me.BaseStream.Length}");

                    targetAppFilesCount++;
                    string path   = me.ReadString();
                    int    length = me.ReadInt32();
                    byte[] data   = me.ReadBytes(length);

                    // Create subdirectory if necessary
                    string dir = Path.GetDirectoryName(path);
                    if (!string.IsNullOrWhiteSpace(dir) && !Directory.Exists(Path.Combine(tempDir, dir)))
                    {
                        Directory.CreateDirectory(Path.Combine(tempDir, dir));
                    }

                    File.WriteAllBytes(Path.Combine(tempDir, path), data);
                }

                unpackingDoneTimestamp = DateTime.Now;
                splashProgressBarProc?.Kill();
            }

            // Open tempDir in Explorer if corresponding flag is set
            if (openUnpackedDir)
            {
                Process.Start(new ProcessStartInfo()
                {
                    FileName        = "explorer.exe",
                    Arguments       = tempDir,
                    UseShellExecute = true,
                    Verb            = "open"
                });
            }

            // Launch unpacked app
            ProcessStartInfo procInfo = new ProcessStartInfo()
            {
                FileName         = Path.Combine(tempDir, pathToMainExe),
                Arguments        = launchArguments + " " + string.Join(" ", args.Select(x => $"\"{x}\"")),
                WorkingDirectory = tempDir,
                UseShellExecute  = !stdoutRedirected    // if stdout is redirected, then redirect i/o of the target app too
            };
            Process proc = Process.Start(procInfo);

            // Wait until app exits to delete its files from temp directory
            proc.WaitForExit();
        }
Exemplo n.º 28
0
        internal Broadcasters(XDMessagingClient client, ISerializer serializer)
        {
            serializer.Requires("serializer").IsNotNull();

            this.serializer = serializer;
        }
Exemplo n.º 29
0
        private const int SPLASH_POPUP_DELAY    = 1000; // ms

        //string unpackerExePath, string pathToPackedApp, string localPathToMainExe, string pathToFolderWithApp
        static int Main(string[] args)
        {
#if DEBUG
            Console.WriteLine("Packer.exe is running in Debug");
            Console.WriteLine("Attach to process now and press Enter...");
            Console.ReadLine();
            Console.WriteLine("Resuming");
#endif

            string unpackerExePath, pathToPackedApp, localPathToMainExe, pathToFolderWithApp;
            bool   isSelfRepackable, isRepacking, openUnpackedDir;
            bool   isNoGui = false; // determines the type of XDMessaging mode
            int    unpackDirectory; // Temp = 0, Desktop = 1, SameAsPackedExe = 2 or AskAtLaunch = 3

            try
            {
                #region == Arguments check and assignment ==
                if (args.Length < 4)
                {
                    Console.WriteLine("Arguments are missing. Usage:");
                    Console.WriteLine(USAGE);
                    return(1);
                }

                // UPD: i should have used arguments parser library... Mistakes were made and i don't want to refactor them now .__.
                // UPD2: what a shitty code. I hate myself.
                unpackerExePath     = args[0];
                pathToPackedApp     = args[1];
                localPathToMainExe  = args[2];
                pathToFolderWithApp = args[3];
                isSelfRepackable    = false;
                if (args.Length > 4)
                {
                    bool.TryParse(args[4], out isSelfRepackable);
                }
                if (args.Length > 5)
                {
                    bool.TryParse(args[5], out isNoGui);
                }
                openUnpackedDir = false;
                if (args.Length > 6)
                {
                    bool.TryParse(args[6], out openUnpackedDir);
                }
                unpackDirectory = 0;
                if (args.Length > 7)
                {
                    int.TryParse(args[7], out unpackDirectory);
                    if (unpackDirectory < 0 || unpackDirectory > 3)
                    {
                        unpackDirectory = 0;
                    }
                }
                isRepacking = false;
                if (args.Length > 8 && (args[8] == "-repack" || args[8] == "repack"))
                {
                    isRepacking = true;
                }

                // Create XDMessagingClient broadcaster to report progress
                // Creating it here so the broadcaster is initialized before any possible return => finally
                XDMessagingClient client = new XDMessagingClient();
                // For command line launch use Compatibility mode, for GUI use HighPerformanceUI
                broadcaster = client.Broadcasters.GetBroadcasterForMode(isNoGui ? XDTransportMode.Compatibility : XDTransportMode.HighPerformanceUI);

                if (!File.Exists(unpackerExePath))
                {
                    Console.WriteLine("Unpacker.exe is missing.");
                    return(2);
                }

                if (!Directory.Exists(pathToFolderWithApp))
                {
                    Console.WriteLine("Specified directory with application does not exist.");
                    return(3);
                }

                if (!File.Exists(Path.Combine(pathToFolderWithApp, localPathToMainExe)))
                {
                    Console.WriteLine("Main executable does not exist in app directory.");
                    return(4);
                }

                // Check if the provided path where we gonna save packed exe is valid
                FileStream testFile = null;
                try
                {
                    testFile = File.Create(pathToPackedApp + ".temp", 1, FileOptions.DeleteOnClose);
                }
                catch (Exception)
                {
                    Console.WriteLine("Invalid path to packed executable.");
                    return(5);
                }
                finally
                {
                    testFile?.Close();
                }
                #endregion

                // Get all files in the application folder (incl. sub-folders)
                List <string> filesToPack = GetFilesRecursively(pathToFolderWithApp);

                // Transform absolute paths into relative ones
                for (int i = 0; i < filesToPack.Count; i++)
                {
                    filesToPack[i] = filesToPack[i].Replace(pathToFolderWithApp, string.Empty).TrimStart('\\');
                }

                // If it's self-repacking process, then we should wait until packed app frees its .exe file
                if (isRepacking)
                {
                    if (WaitForFileAccess(pathToPackedApp, WAIT_FOR_FILE_ACCESS_TIMEOUT) == false)
                    {
                        Console.WriteLine($"Can't access file {pathToPackedApp}");
                        return(6);
                    }
                }

                timer.Start();

                // Do the packing
                try
                {
                    PackApp(unpackerExePath, pathToPackedApp, pathToFolderWithApp, localPathToMainExe, filesToPack, isSelfRepackable, isRepacking, openUnpackedDir, unpackDirectory);
                }
                catch (UnauthorizedAccessException)
                {
                    Console.WriteLine($"Unauthorized access to {pathToPackedApp}");
                    return(6);
                }
                catch (Exception)
                {
                    Console.WriteLine($"Oops! Something went wrong");
                    return(-1);
                }

                // If it was repack call, then packer.exe is the one who should remove the temp dir with the app after packing
                // Problem: packer.exe can't delete itself
                // Solution: launch just repacked app and tell it to kill this packer.exe
                if (isRepacking)
                {
                    if (Directory.Exists(pathToFolderWithApp))
                    {
                        Directory.Delete(pathToFolderWithApp, true);
                    }

                    Process.Start(pathToPackedApp, $@"-killme ""{System.Reflection.Assembly.GetEntryAssembly().Location}""");
                }

                return(0);
            }
            finally
            {
                broadcaster.SendToChannel("AppackerProgress", "Done");
            }
        }
Exemplo n.º 30
0
        private const int SPLASH_POPUP_DELAY    = 1000; // ms

        static void Main(string[] args)
        {
#if DEBUG
            Console.WriteLine("Unpacker is running in Debug");
            Console.WriteLine("Attach to process now and press Enter...");
            Console.ReadLine();
            Console.WriteLine("Resuming");
#endif

            // After self-repacking, packer.exe can't delete itself from the temp dir, so it calls repacked app to kill it
            // Command is "unpacker.exe -killme <path to packer.exe>"
            // The whole folder where packer.exe is gets deleted (cuz there should also be temp unpacker.exe from repacking process)
            if (args.Length > 0 &&
                (args[0] == "-killme" || args[0] == "killme"))
            {
                if (args.Length > 1)
                {
                    if (WaitForFileAccess(args[1], WAIT_FOR_FILE_ACCESS_TIMEOUT) == true)
                    {
                        DeleteDirectory(Path.GetDirectoryName(args[1]));
                    }
                }

                // Don't unpack anything. Just close the app now
                return;
            }

            // Subscribe for exit event to delete tempDir
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(Unpacker_ProcessExit);

            // Create temp directory to store unpacked files
            while (tempDir == null || Directory.Exists(tempDir))
            {
                tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            }
            Directory.CreateDirectory(tempDir);

            // Open self exe file as byte stream and unpack data that is appended to the end of exe
            string selfExePath = System.Reflection.Assembly.GetEntryAssembly().Location;
            using (var me = new BinaryReader(File.OpenRead(selfExePath)))
            {
                // Find the end of the actual unpacker.exe
                byte[] pattern = Encoding.UTF8.GetBytes("<SerGreen>");
                long   pos     = FindPatternPosition(me.BaseStream, pattern);
                me.BaseStream.Seek(pos + pattern.Length, SeekOrigin.Begin);

                // Create temp directory to store tools
                while (repackerTempDir == null || Directory.Exists(repackerTempDir))
                {
                    repackerTempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
                }
                Directory.CreateDirectory(repackerTempDir);

                // Start extracting appended data
                isSelfRepackable = me.ReadBoolean();
                if (isSelfRepackable)
                {
                    // For repacking we also need the unpacker.exe itself
                    // So return to the beginning of the file and save the unpacker.exe part
                    me.BaseStream.Seek(0, SeekOrigin.Begin);
                    File.WriteAllBytes(Path.Combine(repackerTempDir, "unpacker.exe"), me.ReadBytes((int)pos));
                    // Skip <SerGreen> keyword and 1 byte of isSelfRepackable flag
                    me.ReadBytes(pattern.Length + 1);
                    // Save the packer.exe
                    int packerDataLength = me.ReadInt32();
                    File.WriteAllBytes(Path.Combine(repackerTempDir, "packer.exe"), me.ReadBytes(packerDataLength));
                }

                // Extract splash screen tool if present
                isProgressBarSplashExePresent = me.ReadBoolean();
                if (isProgressBarSplashExePresent)
                {
                    int splashDataLength = me.ReadInt32();
                    File.WriteAllBytes(Path.Combine(repackerTempDir, "ProgressBarSplash.exe"), me.ReadBytes(splashDataLength));
                }

                pathToMainExe = me.ReadString();

                timer.Start();
                Process splashProgressBarProc = null;

                // Keep extracting files until the end of the stream
                while (me.BaseStream.Position < me.BaseStream.Length)
                {
                    // If unpacking process takes too long, display splash screen with progress bar
                    if (isProgressBarSplashExePresent && broadcaster == null && timer.ElapsedMilliseconds > SPLASH_POPUP_DELAY)
                    {
                        // Create XDMessagingClient broadcaster to report progress
                        XDMessagingClient client = new XDMessagingClient();
                        broadcaster = client.Broadcasters.GetBroadcasterForMode(XDTransportMode.HighPerformanceUI);

                        splashProgressBarProc = Process.Start(Path.Combine(repackerTempDir, "ProgressBarSplash.exe"), "-unpacking");
                        timer.Stop();
                    }

                    // Report progress to the Splash screen with progress bar
                    broadcaster?.SendToChannel("AppackerProgress", $"{me.BaseStream.Position} {me.BaseStream.Length}");

                    targetAppFilesCount++;
                    string path   = me.ReadString();
                    int    length = me.ReadInt32();
                    byte[] data   = me.ReadBytes(length);

                    // Create subdirectory if necessary
                    string dir = Path.GetDirectoryName(path);
                    if (!string.IsNullOrWhiteSpace(dir) && !Directory.Exists(Path.Combine(tempDir, dir)))
                    {
                        Directory.CreateDirectory(Path.Combine(tempDir, dir));
                    }

                    File.WriteAllBytes(Path.Combine(tempDir, path), data);
                }

                unpackingDoneTimestamp = DateTime.Now;
                splashProgressBarProc?.Kill();
            }

            // Launch unpacked app
            ProcessStartInfo procInfo = new ProcessStartInfo(Path.Combine(tempDir, pathToMainExe));
            procInfo.WorkingDirectory = tempDir;
            Process proc = Process.Start(procInfo);

            // Wait until app exits to delete its files from temp directory
            proc.WaitForExit();
        }
Exemplo n.º 31
0
        public FTDataSource(string config)
            : base(config)
        {
            LogAndMessage.LogSource = "FTDataSource";

            #region Context menu

            // main menu
            mReconnect  = new ToolStripMenuItem("Connect", null, new EventHandler(mReconnect_Click));
            mDisconnect = new ToolStripMenuItem("Disconnect", null, new EventHandler(mDisconnect_Click));
            ToolStripSeparator mSeparator1 = new ToolStripSeparator();
            mBackfill    = new ToolStripMenuItem("Backfill Current");
            mBackfillWL  = new ToolStripMenuItem("Backfill Watchlist");
            mBackfillAll = new ToolStripMenuItem("Backfill All");
            mCancel      = new ToolStripMenuItem("Cancel All Backfills", null, new EventHandler(mCancel_Click));
            ToolStripSeparator mSeparator2 = new ToolStripSeparator();
            mUpdateSymbolInfo = new ToolStripMenuItem("Update Symbol Data", null, mUpdateSymbolInfo_Click);
            mOpenIBContract   = new ToolStripMenuItem("Open IB Contract", null, new EventHandler(mOpenIBContract_Click));
            mFindIBContract   = new ToolStripMenuItem("Find IB Contract", null, new EventHandler(mFindIBContract_Click));
            ToolStripSeparator mSeparator3 = new ToolStripSeparator();
            mOpenLogFile = new ToolStripMenuItem("Open Log File", null, new EventHandler(mOpenLogFile_Click));

            // backfill submenu
            menu1Day    = new ToolStripMenuItem("1 Day", null, new EventHandler(mBackfill_Click));
            menu1Week   = new ToolStripMenuItem("1 Week", null, new EventHandler(mBackfill_Click));
            menu2Weeks  = new ToolStripMenuItem("2 Weeks", null, new EventHandler(mBackfill_Click));
            menu1Month  = new ToolStripMenuItem("1 Month", null, new EventHandler(mBackfill_Click));
            menu3Months = new ToolStripMenuItem("3 Months", null, new EventHandler(mBackfill_Click));
            menu6Months = new ToolStripMenuItem("6 Months", null, new EventHandler(mBackfill_Click));
            menu1Year   = new ToolStripMenuItem("1 Year", null, new EventHandler(mBackfill_Click));
            menuMax     = new ToolStripMenuItem("Maximum", null, new EventHandler(mBackfill_Click));

            // backfillWL submenu
            menu1DayWL    = new ToolStripMenuItem("1 Day", null, new EventHandler(mBackfillWL_Click));
            menu1WeekWL   = new ToolStripMenuItem("1 Week", null, new EventHandler(mBackfillWL_Click));
            menu2WeeksWL  = new ToolStripMenuItem("2 Weeks", null, new EventHandler(mBackfillWL_Click));
            menu1MonthWL  = new ToolStripMenuItem("1 Month", null, new EventHandler(mBackfillWL_Click));
            menu3MonthsWL = new ToolStripMenuItem("3 Months", null, new EventHandler(mBackfillWL_Click));
            menu6MonthsWL = new ToolStripMenuItem("6 Months", null, new EventHandler(mBackfillWL_Click));
            menu1YearWL   = new ToolStripMenuItem("1 Year", null, new EventHandler(mBackfillWL_Click));
            menuMaxWL     = new ToolStripMenuItem("Maximum", null, new EventHandler(mBackfillWL_Click));

            // backfillAll submenu
            menu1DayAll    = new ToolStripMenuItem("1 Day", null, new EventHandler(mBackfillAll_Click));
            menu1WeekAll   = new ToolStripMenuItem("1 Week", null, new EventHandler(mBackfillAll_Click));
            menu2WeeksAll  = new ToolStripMenuItem("2 Weeks", null, new EventHandler(mBackfillAll_Click));
            menu1MonthAll  = new ToolStripMenuItem("1 Month", null, new EventHandler(mBackfillAll_Click));
            menu3MonthsAll = new ToolStripMenuItem("3 Months", null, new EventHandler(mBackfillAll_Click));
            menu6MonthsAll = new ToolStripMenuItem("6 Months", null, new EventHandler(mBackfillAll_Click));
            menu1YearAll   = new ToolStripMenuItem("1 Year", null, new EventHandler(mBackfillAll_Click));
            menuMaxAll     = new ToolStripMenuItem("Maximum", null, new EventHandler(mBackfillAll_Click));

            // adding submenus
            mBackfill.DropDownItems.AddRange(new ToolStripItem[] { menu1Day, menu1Week, menu2Weeks, menu1Month, menu3Months, menu6Months, menu1Year, menuMax });
            mBackfillWL.DropDownItems.AddRange(new ToolStripItem[] { menu1DayWL, menu1WeekWL, menu2WeeksWL, menu1MonthWL, menu3MonthsWL, menu6MonthsWL, menu1YearWL, menuMaxWL });
            mBackfillAll.DropDownItems.AddRange(new ToolStripItem[] { menu1DayAll, menu1WeekAll, menu2WeeksAll, menu1MonthAll, menu3MonthsAll, menu6MonthsAll, menu1YearAll, menuMaxAll });

            mContextMenu = new ContextMenuStrip();
            mContextMenu.Items.AddRange(new ToolStripItem[] { mReconnect, mDisconnect, mSeparator1, mBackfill, mBackfillWL, mBackfillAll, mCancel, mSeparator2, mUpdateSymbolInfo, mOpenIBContract, mFindIBContract, mSeparator3, mOpenLogFile });

            SetContextMenuState();

            #endregion

            rtWindowTickersBck = new StringCollection();

            timer = new System.Threading.Timer(timer_Tick);
            timer.Change(TimerInterval, TimerInterval);

            XDMessagingClient client = new XDMessagingClient();
            // Create listener instance using HighPerformanceUI mode
            IXDListener listener = client.Listeners
                                   .GetListenerForMode(XDTransportMode.HighPerformanceUI);

            // Register channel to listen on
            listener.RegisterChannel("commands");
            listener.MessageReceived += Listener_MessageReceived;
        }