Example #1
0
        private static bool GetOutlook()
        {
            try
            {
                // If GetObject throws an exception, then Outlook is
                // either not running or is not available.
                outlook = AutomationFactory.GetObject("Outlook.Application");
                return(true);
            }
            catch
            {
                try
                {
                    // Start Outlook and display the Inbox, but minimize
                    // it to avoid hiding the running application.

                    outlook = AutomationFactory.CreateObject("Outlook.Application");
                    outlook.Session.GetDefaultFolder(6).Display();
                    // 6 = Inbox
                    outlook.ActiveWindow.WindowState = 1;
                    // minimized
                    return(true);
                }
                catch
                {
                    // Outlook is unavailable.
                    return(false);
                }
            }
        }
        partial void CreateWordDocPrinter_Execute()
        {
            if (AutomationFactory.IsAvailable)
            {
                try
                {
                    //Copy the word template file to 'My Documents'
                    SaveTemplateToMyDocuments();
                    string path = Environment.GetFolderPath(
                        Environment.SpecialFolder.MyDocuments) + @"\LetterTemplate.dotx";

                    using (dynamic wordApp =
                               AutomationFactory.CreateObject("Word.Application"))
                    {
                        dynamic wordDoc = wordApp.Documents.Open(
                            path);
                        wordDoc.Bookmarks("DepartmentName").Range.InsertAfter(
                            Department.DepartmentName);
                        wordApp.PrintOut();
                        wordDoc.Close(0);
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("Failed to create letter.", ex);
                }
            }
        }
Example #3
0
        private void btnCreate_Click(object sender, RoutedEventArgs e)
        {
            // Code below will throw System.UnauthorizedAccessException
            //using (StreamWriter writer = File.CreateText("C:\\Temp.txt"))
            //{
            //    writer.WriteLine("Some text");
            //}

            if (AutomationFactory.IsAvailable)
            {
                // Interesting, I can simply try to dispose a dynamic object without checking whether it has implemented IDisposible:)
                using (dynamic fso = AutomationFactory.CreateObject("Scripting.FileSystemObject"))
                {
                    if (!fso.FolderExists(folderPath))
                    {
                        fso.CreateFolder(folderPath);
                    }
                    dynamic txtFile = fso.CreateTextFile(filePath);
                    txtFile.WriteLine("Some text...");
                    txtFile.close();
                }

                ShowManipulationResult(filePath + " was created..");
            }
        }
Example #4
0
        public static void OpenWindow(string url, int width = 1100, int height = 600)
        {
            string host = Application.Current.Host.Source.Host;
            int    port = Application.Current.Host.Source.Port;
            Uri    uri  = new Uri(String.Format("http://{0}:{1}/{2}", host, port, url));

            if (!Application.Current.IsRunningOutOfBrowser)
            {
                System.Windows.Browser.HtmlPopupWindowOptions options = new System.Windows.Browser.HtmlPopupWindowOptions();
                options.Resizeable  = true;
                options.Width       = width;
                options.Height      = height;
                options.Menubar     = true;
                options.Directories = true;
                options.Toolbar     = true;
                options.Status      = true;
                System.Windows.Browser.HtmlPage.PopupWindow(uri, "_blank", options);
                //System.Windows.Browser.HtmlPage.Window.Navigate(uri);
            }
            else
            {
                //WebBrowserBridge.OpenURL(uri, "_blank");
                using (var shell = AutomationFactory.CreateObject("WScript.Shell")) {
                    shell.Run("iexplore.exe " + uri.AbsoluteUri);
                }
            }
        }
 public static void EjecutaEXE(string ruta)
 {
     using (dynamic shell = AutomationFactory.CreateObject("WScript.shell"))
     {
         shell.Run(@ruta);
     }
 }
Example #6
0
        private void DownloadPDFScript()
        {
            WebClient a = new WebClient();

            a.OpenReadAsync(new Uri(DownloadPDFScriptFileNameString, UriKind.Relative));
            a.OpenReadCompleted += (object sender1, OpenReadCompletedEventArgs e1) =>
            {
                StreamReader reader      = new StreamReader(e1.Result);
                string       VBSContents = reader.ReadToEnd();
                reader.Close();

                if (AutomationFactory.IsAvailable)
                {
                    using (dynamic fso = AutomationFactory.CreateObject("Scripting.FileSystemObject"))
                    {
                        if (!fso.FolderExists(TempFolderPathString))
                        {
                            fso.CreateFolder(TempFolderPathString);
                        }
                        dynamic txtFile = fso.CreateTextFile(TempFolderPathString + DownloadPDFScriptFileNameString);
                        txtFile.WriteLine(VBSContents);
                        txtFile.close();
                    }
                }
            };
        }
        private void Init()
        {
            try
            {
                if (App.Current.InstallState != InstallState.Installed)
                {
                    updateDetailLogLabel("\nAlt-Click to install to local machine");
                }

                if (AutomationFactory.IsAvailable)
                {
                    using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
                    {
                        shell.Run("screenshot.jar -e", 0);
                    }
                }
                else
                {
                    updateDetailLogLabel("\nUnable to launch, please run java -jar screenshot.jar -d for device and java -jar screenshot.jar -e for emulator");
                }

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.RemoteEndPoint = remoteEndPoint;
                args.Completed     += new EventHandler <SocketAsyncEventArgs>(OnConnect);
                socket.ConnectAsync(args);
            }
            catch (Exception exp)
            {
                updateDetailLogLabel("\n" + exp.Message);
            }
        }
Example #8
0
 private void InitCardObj()
 {
     if (obj == null)
     {
         obj = AutomationFactory.CreateObject("HJIC.HJICCtrl.1");
     }
 }
Example #9
0
 public BJICCard(bool isInit)
 {
     if (isInit)
     {
         obj = AutomationFactory.CreateObject("YLIC.YLICCtrl.1");
     }
 }
Example #10
0
        private static string GetSLLauncherCommand()
        {
            var desktopPath      = string.Empty;
            var startMenuPath    = string.Empty;
            var slLauncherCmmand = string.Empty;

            using (dynamic wShell = AutomationFactory.CreateObject("WScript.Shell"))
            {
                desktopPath   = wShell.SpecialFolders("Desktop");
                startMenuPath = wShell.SpecialFolders("Programs");
            }

            using (dynamic shell = AutomationFactory.CreateObject("Shell.Application"))
            {
                dynamic desktopItems   = shell.NameSpace(desktopPath).Items();
                dynamic startMenuItems = shell.NameSpace(startMenuPath).Items();


                FindApplicationInFolder(ref slLauncherCmmand, desktopItems);

                if (string.IsNullOrEmpty(slLauncherCmmand))
                {
                    FindApplicationInFolder(ref slLauncherCmmand, startMenuItems);
                }
            }

            return(slLauncherCmmand);
        }
Example #11
0
        //Listing 11-9. Opening files in their default applications
        partial void OpenFileFromDatabase_Execute()
        {
            try
            {
                if ((AutomationFactory.IsAvailable))
                {
                    //this is where we'll save the file
                    string fullFilePath = System.IO.Path.Combine(
                        Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                        IssueDocument.DocumentName);

                    byte[] fileData = IssueDocument.IssueFile.ToArray();

                    if ((fileData != null))
                    {
                        using (FileStream fs =
                                   new FileStream(
                                       fullFilePath, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            fs.Write(fileData, 0, fileData.Length);
                            fs.Close();
                        }
                    }

                    dynamic shell = AutomationFactory.CreateObject("Shell.Application");
                    shell.ShellExecute(fullFilePath);
                }
            }
            catch (Exception ex)
            {
                this.ShowMessageBox(ex.ToString());
            }
        }
Example #12
0
 public void addKey(string key)
 {
     using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
     {
         shell.RegWrite(keyPath + "key", key, "REG_SZ");
     }
     registered = getRegKey().checkKey();
 }
Example #13
0
 public override void Open()
 {
     if (!string.IsNullOrEmpty(FileName))
     {
         using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
         {
             shell.Run(FileName);
         }
     }
 }
Example #14
0
 private void cmdRunProcess_Click(object sender, RoutedEventArgs e)
 {
     if (TestForComSupport())
     {
         using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
         {
             shell.Run("calc.exe");
         }
     }
 }
 void fe_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Enter)
     {
         using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
         {
             shell.SendKeys("{TAB}");
         }
     }
 }
Example #16
0
 private void btnClose_Click(object sender, RoutedEventArgs e)
 {
     if (AutomationFactory.IsAvailable)
     {
         using (var wScript = AutomationFactory.CreateObject("WScript.Shell"))
         {
             wScript.Run(@"cmd /k taskkill /IM sllauncher.exe & exit", 0);
         }
     }
 }
        private void btnExcel_Click(object sender, RoutedEventArgs e)
        {
            //Abrir o Excel

            dynamic excel;

            //Criando uma novo aplicação Excel
            excel = AutomationFactory.CreateObject("Excel.Application");
            //Deixando a aplicação visível
            excel.Visible = true;
            // Criando um novo arquivo para a aplicação
            // Lembrando que um workbook é um conjunto de planilhas
            dynamic workbook = excel.workbooks;

            workbook.Add();
            // Pega a planilha que acabamos de criar
            dynamic sheet = excel.ActiveSheet;

            // Criando o título
            sheet.Cells[1, 1].Value = "Exporta Cubo";
            // Fonte negrito
            sheet.Cells[1, 1].Font.Bold = true;
            // Mesclando as celulas
            sheet.Range("A1:C1").Merge();
            // Centralizando o alinhamento horizontal
            sheet.Range("A1:C1").HorizontalAlignment = -4108;
            // Criando as colunas (lembrando as celulas das planilhas começam com o índice 1
            for (int coluna = 1; coluna <= dgCliente.Columns.Count; coluna++)
            {
                sheet.Cells[3, coluna].Value     = dgCliente.Columns[coluna - 1].Header;
                sheet.Cells[3, coluna].Font.Bold = true;
                // Cor do Interior: Cinza
                sheet.Cells[3, coluna].Interior.Color = 14540253;
            }

            // Criando as linhas
            int linha = 4;

            foreach (AprReprCursoDisc apr in dgCliente.ItemsSource)
            {
                sheet.Cells[linha, 1].Value = apr.Curso;
                sheet.Cells[linha, 2].Value = apr.Disciplina;
                sheet.Cells[linha, 3].Value = apr.Ano;
                sheet.cells[linha, 4].value = apr.Aprovados;
                sheet.cells[linha, 5].value = apr.Reprovados;

                // Se o indice da linha for par, a cor será verde
                // caso contrário a cor será azul
                sheet.Cells[linha, 1].Interior.Color         =
                    sheet.Cells[linha, 2].Interior.Color     =
                        sheet.Cells[linha, 3].Interior.Color = (linha % 2 == 0) ? 13434828 : 16772300;

                linha++;
            }
        }
Example #18
0
 private void cmdReadRegistry_Click(object sender, RoutedEventArgs e)
 {
     if (TestForComSupport())
     {
         using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
         {
             string desktopPath = shell.RegRead(@"HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Desktop");
             MessageBox.Show("The desktop files on this machine are placed in: " + desktopPath);
         }
     }
 }
Example #19
0
 private void cmdTextToSpeech_Click(object sender, RoutedEventArgs e)
 {
     if (TestForComSupport())
     {
         using (dynamic speech = AutomationFactory.CreateObject("Sapi.SpVoice"))
         {
             speech.Volume = 100;
             speech.Speak("This is a test");
         }
     }
 }
Example #20
0
        private void btnPhonate_Click(object sender, RoutedEventArgs e)
        {
            if (AutomationFactory.IsAvailable)
            {
                using (dynamic speechApi = AutomationFactory.CreateObject("Sapi.SpVoice"))
                {
                    speechApi.Speak(this.txtPhonateSource.Text);
                }

                ShowManipulationResult("I am speaking: " + this.txtPhonateSource.Text);
            }
        }
Example #21
0
 private void UserControl_Loaded(object sender, RoutedEventArgs e)
 {
     if (AutomationFactory.IsAvailable)
     {
         MessageBox.Show("AutomationFactory: OK");
         this.wsh = AutomationFactory.CreateObject("WScript.Shell");
     }
     else
     {
         MessageBox.Show("AutomationFactory: NG");
     }
 }
Example #22
0
    public IEnumerable <AccountEntity> GetAccountsInFriendlyFormat()
    {
        List <AccountEntity> accounts = new List <AccountEntity>();

        using (dynamic WShell = AutomationFactory.CreateObject("WScript.Shell"))
        {
            for (int i = 1; i < 1000; i++)
            {
                try
                {
                    string classId = WShell.RegRead(String.Format(registryPath, i.ToString().PadLeft(8, '0'), constValueClsid));

                    if (StringComparer.InvariantCultureIgnoreCase.Compare(classId, constContentsAccountClsid_POP3) == 0)
                    {
                        accounts.Add(new AccountEntity
                        {
                            FriendlyName       = GetRegisterElementValue(WShell, i.ToString(), constAccountName),
                            IncomingMailServer = GetRegisterElementValue(WShell, i.ToString(), constPOP3Server),
                            Email    = GetRegisterElementValue(WShell, i.ToString(), constEmail),
                            UserName = GetRegisterElementValue(WShell, i.ToString(), constName)
                        });
                        continue;
                    }

                    if (StringComparer.InvariantCultureIgnoreCase.Compare(classId, constContentsAccountClsid_IMAP) == 0)
                    {
                        accounts.Add(new AccountEntity
                        {
                            FriendlyName       = GetRegisterElementValue(WShell, i.ToString(), constAccountName),
                            IncomingMailServer = GetRegisterElementValue(WShell, i.ToString(), constIMAPServer),
                            Email    = GetRegisterElementValue(WShell, i.ToString(), constEmail),
                            UserName = GetRegisterElementValue(WShell, i.ToString(), constName)
                        });
                        continue;
                    }

                    //it isn't POP3 either IMAP
                }
                catch (FileNotFoundException e)
                {
                    //classId isn't found - we can break iterations because we already iterate through all elements
                    break;
                }
                catch (Exception e)
                {
                    MessageBox.Show("Unknown exception");
                }
            }
        }

        return(accounts);
    }
Example #23
0
        /// <summary>
        /// Starts an process using the passed parameters.
        /// </summary>
        /// <param name="filename">The filename to execute.</param>
        /// <param name="arguments">The arguments to pass to the process. This parameter is optional.</param>
        /// <param name="workingDirectory">The workingdirectory of the process. This parameter is optional.</param>
        /// <param name="operation">The operation to be performed. This parameter is optional. By default, <see cref="ProcessVerb.Open"/> will be used.</param>
        /// <param name="visibility">A <see cref="ProcessVisibility"/>-value to determine how the new process will be shown. This parameter is optional. By default, <see cref="ProcessVisibility.Normal"/> will be used.</param>
        /// <param name="suppressErrors">A value determining if exception will be supressed or not.</param>
        /// <returns><code>true</code> if the operation succeeds, otherwise <code>false</code>.</returns>
        public static bool ShellExecute(string filename, string arguments = null, string workingDirectory = null, ProcessVerb operation = ProcessVerb.Open, ProcessVisibility visibility = ProcessVisibility.Normal, bool suppressErrors = true)
        {
            if (!AutomationFactory.IsAvailable)
            {
                throw new Exception("Automation unavailable due to insufficient rights.");
            }

            if (filename == null)
            {
                throw new ArgumentNullException("commandline");
            }

            if (String.IsNullOrWhiteSpace(filename))
            {
                throw new ArgumentException("Invalid commandline.", "commandline");
            }

            var args = arguments ?? "";
            var dir  = workingDirectory ?? "";
            var verb = operation.ToString().ToLowerInvariant();
            int mode = (int)visibility;

            dynamic shell = null;

            try
            {
                using (shell = AutomationFactory.CreateObject("Shell.Application"))
                {
                    shell.ShellExecute(filename, args, dir, verb, mode);
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.ToString());
#endif
                if (suppressErrors)
                {
                    return(false);
                }

                throw ex;
            }
            finally
            {
                shell = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            return(true);
        }
Example #24
0
        public static void CreateEmail(
            string toAddress, string subject, string body)
        {
            try
            {
                dynamic outlook = null;

                if (AutomationFactory.IsAvailable)
                {
                    try
                    {
                        //Get the reference to the open Outlook App
                        outlook =
                            AutomationFactory.GetObject("Outlook.Application");
                    }
                    catch (Exception ex)
                    {
                        //Outlook isn't open, therefore try and open it
                        outlook =
                            AutomationFactory.CreateObject("Outlook.Application");
                    }

                    if (outlook != null)
                    {
                        //Create the email
                        dynamic mail = outlook.CreateItem(olMailItem);
                        if (body.ToLower().Contains("<html>"))
                        {
                            mail.BodyFormat = olFormatHTML;
                            mail.HTMLBody   = body;
                        }
                        else
                        {
                            mail.BodyFormat = olFormatPlain;
                            mail.Body       = body;
                        }
                        mail.Recipients.Add(toAddress);
                        mail.Subject = subject;

                        mail.Save();
                        mail.Display();
                        //uncomment this code to send the email immediately
                        //mail.Send()
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(
                          "Failed to create email.", ex);
            }
        }
Example #25
0
        private void btnReadReg_Click(object sender, RoutedEventArgs e)
        {
            if (AutomationFactory.IsAvailable)
            {
                using (dynamic wScript = AutomationFactory.CreateObject("WScript.Shell"))
                {
                    string dotNetRoot =
                        wScript.RegRead(@"HKLM\SOFTWARE\Microsoft\.NETFramework\InstallRoot");

                    ShowManipulationResult("Successfully read value from HKLM! .NET InstallRoot is: " + dotNetRoot);
                }
            }
        }
Example #26
0
 // Use this method to explicity create a new instance of Word
 public bool CreateWord()
 {
     try
     {
         // If CreateObject throws an exception, then Word is not available.
         _word = AutomationFactory.CreateObject("Word.Application");
         return(true);
     }
     catch
     {
         return(false);
     }
 }
 public void ExecuteCommandSync(object command)
 {
     try
     {
         using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
         {
             shell.Run((string)command);
         }
     }
     catch (Exception objException)
     {
     }
 }
Example #28
0
        //Listing 17-4. Microsoft Excel automation code
        partial void ExportToExcel_Execute()
        {
            if (AutomationFactory.IsAvailable)
            {
                try
                {
                    using (dynamic excelApp =
                               AutomationFactory.CreateObject("Excel.Application"))
                    {
                        var excelWorkbook  = excelApp.Workbooks.Add();
                        var excelWorksheet = excelWorkbook.ActiveSheet;

                        // Set the title text, set the style to bold and font size 16
                        excelWorksheet.Cells(1, 1).Value     = this.Issue.Subject;
                        excelWorksheet.Cells(1, 1).Font.Bold = true;
                        excelWorksheet.Cells(1, 1).Font.Size = 16;

                        // Set the issue header details.
                        excelWorksheet.Cells(1, 3).Value = "Issue Date:";
                        excelWorksheet.Cells(1, 4).Value =
                            this.Issue.CreateDateTime.ToShortDateString();
                        excelWorksheet.Cells(2, 3).Value = "Assigned Engineer:";
                        excelWorksheet.Cells(2, 4).Value = this.Issue.Engineer.Fullname;

                        // Set the response header.
                        excelWorksheet.Cells(1, 6).Value = "Response Date:";
                        excelWorksheet.Cells(2, 6).Value = "Response Text:";

                        // Start showing the responses from row 7
                        int currentRow = 7;
                        foreach (IssueResponse response in this.Issue.IssueResponses)
                        {
                            excelWorksheet.Cells(1, currentRow).Value =
                                response.ResponseDateTime.ToString();
                            excelWorksheet.Cells(2, currentRow).Value =
                                response.ResponseText;
                            currentRow++;
                        }

                        excelApp.Visible = true;
                    }
                }

                catch (Exception ex)
                {
                    throw new InvalidOperationException(
                              "Failed to create spreadsheet.", ex);
                }
            }
        }
Example #29
0
        private void btnWriteReg_Click(object sender, RoutedEventArgs e)
        {
            if (AutomationFactory.IsAvailable)
            {
                using (dynamic wScript = AutomationFactory.CreateObject("WScript.Shell"))
                {
                    // Only has write permissin to HKCU
                    wScript.RegWrite(@"HKCU\Software\WayneTestRegValue",
                                     "SomeStrValue", "REG_SZ");

                    ShowManipulationResult("Successfully wrote value to registry HKCU!");
                }
            }
        }
Example #30
0
        private void btnRunExe_Click(object sender, RoutedEventArgs e)
        {
            if (AutomationFactory.IsAvailable)
            {
                using (dynamic wScript = AutomationFactory.CreateObject("WScript.Shell"))
                {
                    //Refer WScript.Run at: http://msdn.microsoft.com/en-us/library/d5fk67ky(v=VS.85).aspx
                    //wScript.Run("iexplore http://wayneye.com", 1, true);
                    wScript.Run("C:\\Users\\yewei\\desktop\\Demo.js", 1, true);
                }

                ShowManipulationResult("Successfully launched IE and opened http://wayneye.com");
            }
        }