Пример #1
0
    public static void Main()
    {
        AppDomainSetup setup = new AppDomainSetup();

        setup.ApplicationBase = "commands";

        PermissionSet permissions = new PermissionSet(PermissionState.None);

        permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
        permissions.AddPermission(new UIPermission(PermissionState.Unrestricted));

        for (;;)
        {
            Console.Write("COMMAND: ");
            string cmd = Console.ReadLine();
            if (cmd.ToLower() == "quit")
            {
                break;
            }

            AppDomain sandbox = AppDomain.CreateDomain(cmd, null, setup, permissions);
            try
            {
                sandbox.ExecuteAssemblyByName(cmd);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: {0}", ex.Message);
            }
            AppDomain.Unload(sandbox);

            Console.WriteLine();
        }
    }
Пример #2
0
        static void Main(string[] args)
        {
            // Create the permission set to grant to other assemblies.
            // In this case we are granting the permissions found in the LocalIntranet zone.
            Evidence e = new Evidence();

            e.AddHostEvidence(new Zone(SecurityZone.Intranet));
            PermissionSet pset = SecurityManager.GetStandardSandbox(e);

            AppDomainSetup ads = new AppDomainSetup();

            // Identify the folder to use for the sandbox.
            ads.ApplicationBase = "C:\\Sandbox";
            // Copy the application to be executed to the sandbox.
            Directory.CreateDirectory("C:\\Sandbox");
            File.Copy("..\\..\\..\\HelloWorld\\bin\\debug\\HelloWorld.exe", "C:\\sandbox\\HelloWorld.exe", true);

            // Create the sandboxed domain.
            AppDomain sandbox = AppDomain.CreateDomain(
                "Sandboxed Domain",
                e,
                ads,
                pset,
                null);

            sandbox.ExecuteAssemblyByName("HelloWorld");
        }
Пример #3
0
        // Название исполняемого файла должно совпадать с именем сборки
        public Error Open(string path, Func <byte[], byte[]> Transform = null)
        {
            try
            {
                _file = File.ReadAllBytes(path);
                if (Transform != null)
                {
                    _file = Transform(_file);
                }

                _assembly = Assembly.Load(_file);
                var nameDomain = _assembly.GetName().Name;
                _domainInfo = new AppDomainSetup();
                _domainInfo.ApplicationBase = Path.GetDirectoryName(path);
                _domainInfo.ApplicationName = Path.GetFileName(path);
                _domain = AppDomain.CreateDomain(nameDomain, null, _domainInfo);
                _domain.ExecuteAssemblyByName(nameDomain);
                AppDomain.Unload(_domain);
            }
            catch (FileNotFoundException)
            {
                return(Error.Path);
            }
            catch (DirectoryNotFoundException)
            {
                return(Error.Path);
            }
            catch (FileLoadException)
            {
                return(Error.LoadingFile);
            }

            return(Error.No);
        }
Пример #4
0
        private static void LoadServices()
        {
            var directory = Path.GetDirectoryName(_executable);

            Watchers.Add(CreateWatcher(directory, "*.exe"));
            Watchers.Add(CreateWatcher(directory, "*.dll"));
            Watchers.Add(CreateWatcher(directory, "*.config"));

            var domainInfo = new AppDomainSetup
            {
                ConfigurationFile = Path.GetFileName(_executable) + ".config",
                ApplicationBase   = directory,
                ShadowCopyFiles   = "true",
                ApplicationName   = "OpenHomeServer",
            };

            _domain = AppDomain.CreateDomain("OpenHomeServer", null, domainInfo);
            var assemblyName = AssemblyName.GetAssemblyName(_executable);

            Task.Run(() =>
            {
                try
                {
                    _domain.ExecuteAssemblyByName(assemblyName);
                }catch (AppDomainUnloadedException) {}
            });
        }
Пример #5
0
        static void MakeNewDomain()
        {
            // Создадим новый домен приложения
            AppDomain newD         = AppDomain.CreateDomain("OrganizationCheckerDomain");
            var       assemblyName = AssemblyName.GetAssemblyName(@"D:\project\CNnet_Lab1\OrganizationChecker\bin\Debug\OrganizationChecker.exe");

            newD.Load(assemblyName);
            newD.ExecuteAssemblyByName(assemblyName);
            InfoDomainApp(newD);
            // Уничтожение домена приложения
            AppDomain.Unload(newD);
        }
Пример #6
0
        static void MakeNewDomain()
        {
            // Создадим новый домен приложения
            AppDomain newD         = AppDomain.CreateDomain("SPNETLAB1WebAppDomain");
            var       assemblyName = AssemblyName.GetAssemblyName(@"C:\Users\KramRul\source\repos\SPNET_LB1\SPNET_LB1\bin\Debug\SPNET_LB1.exe");

            newD.Load(assemblyName);
            newD.ExecuteAssemblyByName(assemblyName);
            InfoDomainApp(newD);
            // Уничтожение домена приложения
            AppDomain.Unload(newD);
        }
Пример #7
0
        private static void CreateAndRunAppDomain(string appName)
        {
            AppDomain domain = null;

            try
            {
                // Construct and initialize settings for a second AppDomain.
                AppDomainSetup ads = new AppDomainSetup();
                ads.ApplicationBase = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, appName);

                ads.DisallowBindingRedirects = false;
                ads.DisallowCodeDownload     = true;
                ads.ConfigurationFile        =
                    Path.Combine(ads.ApplicationBase, appName + ".exe.config");

                PermissionSet ps = new PermissionSet(PermissionState.Unrestricted);
                domain = System.AppDomain.CreateDomain(
                    appName,
                    System.AppDomain.CurrentDomain.Evidence,
                    ads,
                    ps);

                Console.WriteLine("**********************************************");
                Console.WriteLine($"Starting code execution in AppDomain {appName}");
                domain.ExecuteAssemblyByName(
                    appName,
                    new string[0]);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.ToString()}");
            }
            finally
            {
                Console.WriteLine($"Finished code execution in AppDomain {appName}");
                Console.WriteLine("**********************************************");
                Console.WriteLine();

                if (domain != null)
                {
                    // Wait for traces to be flushed, then unload the domain
                    Thread.Sleep(2000);
                    AppDomain.Unload(domain);
                }
            }
        }
Пример #8
0
        public void Run(Action <string[]> main, string[] args)
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;

            if (!currentDomain.IsDefaultAppDomain())
            {
                // Información de dominio.
                Debug.WriteLine(GetInfo(AppDomain.CurrentDomain));

                main(args);
                return;
            }

            // Información de dominio.
            Debug.WriteLine(GetInfo(currentDomain));

            this.ConfigurarPath3264();

            AppDomainSetup setup = new AppDomainSetup();

            setup.ApplicationName = this.applicationName;
            setup.ApplicationBase = currentDomain.BaseDirectory;
            setup.PrivateBinPath  = (Environment.Is64BitProcess ? WIN64 : WIN32);

            // Create a new application domain.
            AppDomain domain = AppDomain.CreateDomain(this.applicationName + ".Domain", currentDomain.Evidence, setup);

#if USO_INTERNO && !DISABLE_DOTTRACE
            domain.AssemblyResolve += MyResolveEventHandler;
            domain.ReflectionOnlyAssemblyResolve += MyReflectionOnlyAssemblyResolveEventHandler;
#endif

            // Información de dominio.
            Debug.WriteLine(GetInfo(domain));

            Assembly executingAssembly = Assembly.GetEntryAssembly();
            //domain.ExecuteAssemblyByName(typeof(BootStrap).Assembly.FullName);
            domain.ExecuteAssemblyByName(executingAssembly.GetName());
        }
    public static void Main()
    {
        var config = new AppDomainSetup();

        config.ApplicationBase = "commands";

        var policy = new PermissionSet(PermissionState.None);

        policy.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
        policy.AddPermission(new UIPermission(PermissionState.Unrestricted));

        Console.WriteLine("Welcome to our Shell");
        for (;;)
        {
            Console.Write("COMMAND: ");
            string cmd = Console.ReadLine();
            if (cmd.Length == 0)
            {
                continue;
            }
            if (cmd == "quit")
            {
                break;
            }
            AppDomain sandbox = AppDomain.CreateDomain(cmd, null, config, policy);
            try
            {
                sandbox.ExecuteAssemblyByName(cmd);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ERROR: {ex.Message}");
            }
            AppDomain.Unload(sandbox);
            Console.WriteLine();
        }
        Console.WriteLine("Goodbye from our Shell");
    }
Пример #10
0
        public static void Start(IEnumerable <CompilerResult> compiledScripts)
        {
            if (Running)
            {
                return;
            }

            Running = true;

            appDomain = AppDomain.CreateDomain("sharpyson");

            appDomain.AssemblyResolve += AppDomainOnAssemblyResolve;

            foreach (var compiledScript in compiledScripts)
            {
                var assemblyName = AssemblyName.GetAssemblyName(compiledScript.AssemblyPath);

                try
                {
                    if (compiledScript.AssemblyPath.EndsWith(".dll"))
                    {
                        appDomain.Load(assemblyName);
                    }
                    else
                    {
                        appDomain.ExecuteAssemblyByName(assemblyName);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }

                LoadedAssemblies.Add(assemblyName);
            }
        }
Пример #11
0
        static void Main(string[] args)
        {
            TaskDialog.ForceEmulationMode = true;
            Application.SetCompatibleTextRenderingDefault(false);
            Application.EnableVisualStyles();

            //register errorhandler as default unhandled exception handler
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            List <string> arguments = new List <string>(args);

            //check settings file before any other setting access occurs
            CheckSettings();

            #region Check for updates
            if (arguments.Contains("--no-autoupdate"))
            {
                arguments.Remove("--no-autoupdate");
                UpdateChecked = true;
            }
            else if (!Properties.Settings.Default.CheckForUpdates)
            {
                UpdateChecked = true;
            }
            else
            {
                try
                {
                    Thread updateChecker = new Thread(new ThreadStart(CheckForUpdate));
                    updateChecker.CurrentCulture   = Thread.CurrentThread.CurrentCulture;
                    updateChecker.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
                    updateChecker.IsBackground     = true;
                    updateChecker.Name             = "Check for Updates";
                    updateChecker.Priority         = ThreadPriority.BelowNormal;
                    updateChecker.Start();
                }
                catch (Exception e)
                {
                    Trace.WriteLine(e.ToString());
                }
            }
            #endregion

            Mutex splashMutex = new Mutex(false, "Local\\MLifterSplashMutex");

            #region Running from stick
            //execute the program in a new appdomain with shadow copying enabled
            if (Setup.RunningFromStick() && !AppDomain.CurrentDomain.ShadowCopyFiles)
            {
                SplashManager splashManager = new SplashManager(typeof(Splash));
                splashManager.InitialMessage = Resources.SPLASHSCREEN_PREPARING;
                splashManager.ShowSplash();

                AppDomainSetup setup = new AppDomainSetup();
                setup.ShadowCopyFiles       = "true";
                setup.ShadowCopyDirectories = null;                 //all files

                Evidence evidence = System.Reflection.Assembly.GetEntryAssembly().Evidence;

                AppDomain appdomain = AppDomain.CreateDomain("MLifter", evidence, setup);
                appdomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                AssemblyName entryassembly = System.Reflection.Assembly.GetEntryAssembly().GetName();

                appdomain.Load(entryassembly);

                //test the mutex every 100 ms and hide the splash screen if it cannot be taken anymore
                Thread mutexWatcherThread = new Thread(new ThreadStart(delegate
                {
                    TimeSpan wait = new TimeSpan(0, 0, 0, 0, 20);
                    try
                    {
                        while (true)
                        {
                            Thread.Sleep(100);
                            if (splashMutex.WaitOne(wait, false))
                            {
                                splashMutex.ReleaseMutex();
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    catch (AbandonedMutexException)
                    { }
                    finally
                    {
                        splashManager.HideSplash();
                    }
                }));
                mutexWatcherThread.Name         = "Splash Mutex Watcher Thread";
                mutexWatcherThread.IsBackground = true;
                mutexWatcherThread.Start();

                appdomain.ExecuteAssemblyByName(entryassembly, args);                 //evidence removed as second parameter to avoid compiler warning
                //let main function end
            }
            #endregion
            else
            {
                SplashManager splashManager = new SplashManager(typeof(Splash));
                splashManager.EnableFadingMainForm = true;

                #region Only one program instance
                //register IPC channel so that only one instance can be active
                GetIPCData(out UniqueChannelName, out UniqueChannelPortName, out ClientURL, out ServiceURL);

                //check if this is the first instance
                bool firstInstance = true;
                if (Settings.Default.AllowOnlyOneInstance)
                {
                    try
                    {
                        instanceMutex = new Mutex(false, "Local\\MLifterMutex", out firstInstance);
                    }
                    catch (Exception exp)
                    {
                        System.Diagnostics.Trace.WriteLine("Failed to create Mutex: " + exp.ToString());
                    }
                }

#if !DEBUG
                //show the splashscreen
                if (firstInstance || !Settings.Default.AllowOnlyOneInstance)
                {
                    splashManager.ShowSplash();
                }
#endif

                //begin preparing styles
                MLifter.Components.StyleHandler.BeginStylePreparation(System.IO.Path.Combine(Application.StartupPath, Properties.Settings.Default.AppDataFolderDesigns));

                try
                {
                    StartIPC();
                    SuspendIPC = true;                     //suspend IPC until ML is fully loaded
                }
                catch (Exception exp)
                {
                    System.Diagnostics.Trace.WriteLine("Failed to start IPC server: " + exp.ToString());
                }

                if (!firstInstance && Settings.Default.AllowOnlyOneInstance)
                {
                    try
                    {
                        if (arguments.Count > 0)
                        {
                            SendPathToIPC(arguments[0]);
                        }
                        else
                        {
                            BringMLifterToFront();
                        }
                        Environment.Exit(-1);
                    }
                    catch (Exception exp)
                    {
                        System.Diagnostics.Trace.WriteLine("Failed to SendPathToIPC/BringMLifterToFront with another instance active: "
                                                           + exp.ToString());
                    }
                }
                #endregion

                // Run Application
                Program.MainForm = new MainForm(arguments.ToArray());
#if !DEBUG
                splashManager.HideMainForm(Program.MainForm);                 //register MainForm to be automatically hidden and showed
#endif

                #region Running from stick (Mutex check)
                //take the mutex signal for 500 ms to trigger the hiding of the previous splash screen
                Thread mutexReleaseThread = new Thread(new ThreadStart(delegate
                {
                    TimeSpan wait = new TimeSpan(0, 0, 0, 0, 100);
                    try
                    {
                        if (splashMutex.WaitOne(wait, false))
                        {
                            Thread.Sleep(500);
                            splashMutex.ReleaseMutex();
                        }
                    }
                    catch (AbandonedMutexException)
                    { }
                }));
                mutexReleaseThread.Name         = "Splash Mutex Release Thread";
                mutexReleaseThread.IsBackground = true;
                mutexReleaseThread.Start();
                #endregion

                Application.Run(Program.MainForm);
            }
        }
Пример #12
0
        public static void Main()
        {
            if (!Environment.UserInteractive)
            {
                // In service mode we wipe out command line of startup config after we complete.
                // If somebody tries to restart the service then, we want to immediately shutdown.
                // They only way to launch is through the UI.
                // UI is intended mechanism to shutdown too, but if user shuts down service, we trigger stop of collection properly too.
                if (Environment.GetCommandLineArgs().Length == 3)
                {
                    if (Environment.GetCommandLineArgs()[1] == "/instance")
                    {
                        ProcessStartInfo p = new ProcessStartInfo("cmd.exe", "/c ping 1.1.1.1 -n 1 -w 1500 > nul & net stop SSASDiag_" + Environment.GetCommandLineArgs()[2]);
                        p.WindowStyle     = ProcessWindowStyle.Hidden;
                        p.UseShellExecute = true;
                        p.Verb            = "runas";
                        p.CreateNoWindow  = true;
                        Process.Start(p);
                        return;
                    }
                }
            }

            // Assign a unique Run ID used to anonymously track usage if user allows
            RunID = Guid.NewGuid();

            // Check for .NET 4.6.1 or later.
            object ReleaseVer = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "").OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full").GetValue("Release");

            if (ReleaseVer == null || Convert.ToInt32(ReleaseVer) <= 378389)
            {
                if (Environment.UserInteractive && MessageBox.Show("SSASDiag requires .NET 4.5 or later and will exit now.\r\nInstall the latest .NET release now?", ".NET Update Required", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {
                    Process.Start("https://download.microsoft.com/download/F/9/4/F942F07D-F26F-4F30-B4E3-EBD54FABA377/NDP462-KB3151800-x86-x64-AllOS-ENU.exe");
                }
                return;
            }

            // Setup private temp bin location...
            if (!AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                TempPath = AppDomain.CurrentDomain.GetData("tempbinlocation") as string;
            }
            else
            {
                TempPath = new DirectoryInfo(Environment.GetEnvironmentVariable("temp") + "\\SSASDiag\\").FullName;
            }

            // Setup custom app domain to launch real assembly from temp location, and act as singleton also...
            if (AppDomain.CurrentDomain.BaseDirectory != TempPath)
            {
                int ret = 0;

                // Extract all embedded file type (byte[]) resource assemblies and copy self into temp location
                ResourceManager       rm = Properties.Resources.ResourceManager;
                ResourceSet           rs = rm.GetResourceSet(System.Globalization.CultureInfo.CurrentCulture, true, true);
                IDictionaryEnumerator de = rs.GetEnumerator();
                Directory.CreateDirectory(TempPath);
                while (de.MoveNext() == true)
                {
                    if (de.Entry.Value is byte[])
                    {
                        try {
                            if (de.Key.ToString() == "ResourcesZip")
                            {
                                byte[] b = de.Entry.Value as byte[];
                                if (!File.Exists(TempPath + "Resources.zip") ||
                                    (File.Exists(TempPath + "Resources.zip") &&
                                     new FileInfo(TempPath + "Resources.zip").Length != b.Length)
                                    )
                                {
                                    File.WriteAllBytes(TempPath + "Resources.zip", b);
                                }
                                break;
                            }
                        } catch { } // may fail if file is in use, fine...
                    }
                }
                // Do non-immediately-essential out-of-proc exe resource extractions off thread to speed startup...
                de.Reset();
                new Thread(new ThreadStart(() =>
                {
                    while (de.MoveNext() == true)
                    {
                        if (de.Entry.Value is byte[] && de.Key.ToString() != "ResourcesZip")
                        {
                            File.WriteAllBytes(TempPath
                                               + de.Key.ToString().Replace('_', '.') + ".exe",
                                               de.Entry.Value as byte[]);
                        }
                    }
                })).Start();

                // Symbolic debugger binaries required for dump parsing.
                // Silent, 'impactless' (completely asynchronously off main thread), minimal subset of the standard debugging tools required for cdb.exe.
                // Copied simply into %Program Files%\CDB.
                InstallCDB();

                try {
                    if (!File.Exists(TempPath + "SSASDiag.exe") ||
                        (File.Exists(TempPath + "SSASDiag.exe") && new FileInfo(TempPath + "SSASDiag.exe").Length != new FileInfo(Application.ExecutablePath).Length) ||
                        Debugger.IsAttached ||
                        !Environment.UserInteractive)
                    {
                        File.Copy(Application.ExecutablePath, Environment.GetEnvironmentVariable("temp") + "\\SSASDiag\\SSASDiag.exe", true);
                    }
                } catch { }                                                                                                                               // may fail if file is in use, fine...

                // Now decompress any compressed files we include.  This lets us cram more dependencies in as we add features and still not excessively bloat!  :D
                // Although in our real compression work in assembling files for upload we will use the more flexible open source Ionic.Zip library included in our depenencies,
                // these may not be loaded initially when are launching the first time outside the sandbox.  So here we will use .NET built in compression, at least always there.
                foreach (string f in Directory.GetFiles(TempPath))
                {
                    if (f.EndsWith(".zip"))
                    {
                        try
                        {
                            // Extract any dependencies required for initial form display on main thread...
                            ZipArchive za = ZipFile.OpenRead(f);
                            if (!File.Exists(TempPath + za.GetEntry("FastColoredTextBox.dll").Name) ||
                                (File.Exists(TempPath + za.GetEntry("FastColoredTextBox.dll").Name) &&
                                 new FileInfo(TempPath + za.GetEntry("FastColoredTextBox.dll").Name).Length != za.GetEntry("FastColoredTextBox.dll").Length)
                                )
                            {
                                za.GetEntry("FastColoredTextBox.dll").ExtractToFile(TempPath + "FastColoredTextBox.dll", true);
                            }

                            // Extract remainig non-immediate depencies off main thread to improve startup time...
                            new Thread(new ThreadStart(() =>
                            {
                                foreach (ZipArchiveEntry ze in za.Entries)
                                {
                                    try
                                    {
                                        if (!File.Exists(TempPath + ze.Name) ||
                                            (File.Exists(TempPath + ze.Name) && new FileInfo(TempPath + ze.Name).Length != ze.Length)
                                            )
                                        {
                                            ze.ExtractToFile(TempPath + ze.Name, true);
                                        }
                                    }
                                    catch (Exception ex2)
                                    {
                                        Trace.WriteLine("Extraction Exception: " + ex2.Message);
                                    }
                                }
                            }
                                                       )).Start();
                        }
                        catch (Exception ex)
                        {
                            Trace.WriteLine("Extraction Exception: " + ex.Message);
                        }
                    }
                }
                try
                {
                    // Initialize the new app domain from temp location...
                    var currentAssembly = Assembly.GetExecutingAssembly();


                    AppDomainSetup ads = new AppDomainSetup();
                    ads.ApplicationBase = TempPath;
                    AppDomain tempDomain = AppDomain.CreateDomain("SSASDiagTempDomain", null, ads);
                    tempDomain.SetData("tempbinlocation", TempPath);

                    if (Properties.Settings.Default.AutoUpdate == "true" && Environment.UserInteractive)
                    {
                        CheckForUpdates(tempDomain);
                    }

                    tempDomain.SetData("originalbinlocation", currentAssembly.Location.Substring(0, currentAssembly.Location.LastIndexOf("\\")));
                    // Execute the domain.
                    ret = tempDomain.ExecuteAssemblyByName(currentAssembly.FullName);
                }
                catch (AppDomainUnloadedException ex)
                {
                    /* This happens normally if we terminate due to update process... */
                    Trace.WriteLine("Exception:\r\n" + ex.Message + "\r\n at stack:\r\n" + ex.StackTrace);
                }
                catch (Exception ex)
                {
                    // This is the generic exception handler from the top level default AppDomain,
                    // which catches any previously uncaught exceptions originating from the tempDomain.
                    // This should avoid any crashes of the app in theory, instead providing graceful error messaging.
                    //
                    Trace.WriteLine("Exception:\r\n" + ex.Message + "\r\n at stack:\r\n" + ex.StackTrace);
                    string msg = "There was an unexpected error in the SSAS Diagnostics Collector and the application will close.  "
                                 + "Details of the error are provided for debugging purposes, and copied on the clipboard.\r\n\r\n"
                                 + "An email will also be generated to the tool's author after you click OK.  Please paste the details there to report the issue.\r\n\r\n"
                                 + ex.Message + "\r\n at " + ex.TargetSite + ".";
                    if (ex.InnerException != null)
                    {
                        msg += "\r\n\r\n Inner Exception: " + ex.InnerException.Message + "\r\n  at " + ex.InnerException.TargetSite + ".";
                    }

                    if (Environment.UserInteractive)
                    {
                        MessageBox.Show(msg, "Unexpected error in SSAS Diagnostics Collection", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    if (Environment.UserInteractive)
                    {
                        Clipboard.SetData(DataFormats.StringFormat, "Error: " + ex.Message + " at " + ex.TargetSite + "\n"
                                          + ex.StackTrace
                                          + (ex.InnerException == null ? "" :
                                             "\n\n=====================\nInner Exception: " + ex.InnerException.Message + " at " + ex.InnerException.TargetSite + "\n"
                                             + ex.InnerException.StackTrace));
                    }

                    if (Environment.UserInteractive)
                    {
                        Process.Start("mailto:[email protected]?subject=" + WebUtility.UrlEncode("SSASDiag error at " + ex.TargetSite));
                    }
                }

                // After the inner app domain exits
                Environment.ExitCode = ret;
                return;
            }

            // Launch application normally then...
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
                MainForm = new frmSSASDiag();
                Application.ApplicationExit += Application_ApplicationExit;
                Application.Run(MainForm);
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Exception:\r\n" + ex.Message + "\r\n at stack:\r\n" + ex.StackTrace);
                if (Environment.UserInteractive)
                {
                    MessageBox.Show("SSASDiag encountered an unexpected exception:\n\t" + ex.Message + "\n\tat\n" + ex.StackTrace, "SSASDiag Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            System.Diagnostics.Trace.WriteLine("Exiting SSASDiag.");
        }
Пример #13
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.ApplicationExit += Application_ApplicationExit;


            List <string> arguments   = new List <string>(args);
            Mutex         splashMutex = new Mutex(false, "Local\\MLifterSplashMutex");

            if (!AppDomain.CurrentDomain.ShadowCopyFiles)
            {
                SplashManager splashManager = new SplashManager(typeof(Splash));
                splashManager.InitialMessage = Resources.SPLASHSCREEN_PREPARING;
                splashManager.ShowSplash();

                AppDomainSetup setup = new AppDomainSetup();
                setup.ShadowCopyFiles       = "true";
                setup.ShadowCopyDirectories = null; //all files

                Evidence  evidence  = System.Reflection.Assembly.GetEntryAssembly().Evidence;
                AppDomain appdomain = AppDomain.CreateDomain("MLifter", evidence, setup);
                appdomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                AssemblyName entryassembly = System.Reflection.Assembly.GetEntryAssembly().GetName();
                appdomain.Load(entryassembly);

                //test the mutex every 100 ms and hide the splash screen if it cannot be taken anymore
                Thread mutexWatcherThread = new Thread(new ThreadStart(delegate
                {
                    TimeSpan wait = new TimeSpan(0, 0, 0, 0, 20);
                    try
                    {
                        while (true)
                        {
                            Thread.Sleep(100);
                            if (splashMutex.WaitOne(wait, false))
                            {
                                splashMutex.ReleaseMutex();
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    catch (AbandonedMutexException)
                    { }
                    finally
                    {
                        splashManager.HideSplash();
                    }
                }));
                mutexWatcherThread.Name         = "Splash Mutex Watcher Thread";
                mutexWatcherThread.IsBackground = true;
                mutexWatcherThread.Start();

                appdomain.ExecuteAssemblyByName(entryassembly, args); //evidence removed as second parameter to avoid compiler warning
                                                                      //let main function end
            }
            else
            {
                SplashManager splashManager = new SplashManager(typeof(Splash));
                splashManager.EnableFadingMainForm = true;

                #region Only one program instance

                //register IPC channel so that only one instance can be active
                UniqueChannelName     = GetAssemblyGUID() + "/" + GetMd5Sum(GetAssemblyPath(false));
                UniqueChannelPortName = "MLifterIPCChannel";
                ClientURL             = "ipc://" + UniqueChannelPortName + "/" + UniqueChannelName;
                ServiceURL            = UniqueChannelName;

                //check if this is the first instance
                bool firstInstance = true;
                try
                {
                    instanceMutex = new Mutex(false, "Local\\MLifterMutex", out firstInstance);
                }
                catch (Exception exp)
                {
                    System.Diagnostics.Trace.WriteLine("Failed to create Mutex: " + exp.ToString());
                }

#if !DEBUG
                //show the splashscreen
                if (firstInstance || !Settings.Default.AllowOnlyOneInstance)
                {
                    splashManager.ShowSplash();
                }
#endif

                try
                {
                    StartIPC();
                    SuspendIPC = true; //suspend IPC until ML is fully loaded
                }
                catch (Exception exp)
                {
                    System.Diagnostics.Trace.WriteLine("Failed to start IPC server: " + exp.ToString());
                }

                if (!firstInstance)
                {
                    try
                    {
                        //System.Diagnostics.Debugger.Launch();

                        if (arguments.Count > 0)
                        {
                            SendPathToIPC(arguments[0]);
                        }
                        else
                        {
                            BringMLifterToFront();
                        }
                        Environment.Exit(-1);
                    }
                    catch (Exception exp)
                    {
                        System.Diagnostics.Trace.WriteLine("Failed to SendPathToIPC/BringMLifterToFront with another instance active: "
                                                           + exp.ToString());
                    }
                    Environment.Exit(-1);
                }
                #endregion

                // Run Application
                Program.MainForm = new MainForm(arguments.ToArray());
#if !DEBUG
                splashManager.HideMainForm(Program.MainForm);                 //register MainForm to be automatically hidden and showed
#endif

                #region Running from stick (Mutex check)
                //take the mutex signal for 500 ms to trigger the hiding of the previous splash screen
                Thread mutexReleaseThread = new Thread(new ThreadStart(delegate
                {
                    TimeSpan wait = new TimeSpan(0, 0, 0, 0, 100);
                    try
                    {
                        if (splashMutex.WaitOne(wait, false))
                        {
                            Thread.Sleep(500);
                            splashMutex.ReleaseMutex();
                        }
                    }
                    catch (AbandonedMutexException)
                    { }
                }));
                mutexReleaseThread.Name         = "Splash Mutex Release Thread";
                mutexReleaseThread.IsBackground = true;
                mutexReleaseThread.Start();
                #endregion
                Application.Run(Program.MainForm);
            }
        }