Пример #1
0
        static void Main(String[] args)
        {
            String  licenseKey          = null;
            String  targetDir           = null;
            String  printLogDir         = null;
            String  copyLogDir          = null;
            Boolean startInspector      = false;
            Boolean skipPapercutInstall = false;
            Boolean silentMode          = false;

            foreach (String argument in args)
            {
                if (argument.ToUpper().Contains("/K:"))
                {
                    licenseKey = ArgumentParser.GetValue(argument);                                     // informa a chave de produto
                }
                if (argument.ToUpper().Contains("/D:"))
                {
                    targetDir = ArgumentParser.GetValue(argument);                                     // informa o diretório de instalação
                }
                if (argument.ToUpper().Contains("/P"))
                {
                    printLogDir = ArgumentParser.GetValue(argument);                                     // informa o diretório de logs de impressão
                }
                if (argument.ToUpper().Contains("/C"))
                {
                    copyLogDir = ArgumentParser.GetValue(argument);                                     // informa o diretório de logs de cópia
                }
                if (argument.ToUpper().Contains("/I"))
                {
                    startInspector = true;                                     // inicia serviço de inspeção de impressoras
                }
                if (argument.ToUpper().Contains("/J"))
                {
                    skipPapercutInstall = true;                                     // pula o passo de instalação do papercut
                }
                if (argument.ToUpper().Contains("/S"))
                {
                    silentMode = true;                                     // executa em modo silencioso
                }
            }

            // Verifica se o instalador está sendo executado com permissões administrativas
            WindowsIdentity  windowsIdentity  = WindowsIdentity.GetCurrent();
            WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);
            Boolean          executingAsAdmin = windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);

            // Para debugar este programa execute o Visual Studio como administrador, caso contrário
            // o programa não vai parar nos "breakpoints" (isso se deve ao código de controle do UAC)
            Process process = Process.GetCurrentProcess();

            if ((process.ProcessName.ToUpper().Contains("VSHOST")) && (!executingAsAdmin))
            {
                String errorMessage = "Execute o Visual Studio com permissões administrativas para debugar!";
                MessageBox.Show(errorMessage, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Verifica se a caixa de dialogo do UAC (User Account Control) é necessária
            if (!executingAsAdmin)
            {
                // Pede elevação de privilégios (executa como administrador se o usuário concordar), o programa
                // atual é encerrado e uma nova instancia é executada com os privilégios concedidos
                ProcessStartInfo processInfo = new ProcessStartInfo();
                processInfo.Verb     = "runas";
                processInfo.FileName = Application.ExecutablePath;
                try { Process.Start(processInfo); } catch { }
                return;
            }

            // Executa a instalação em background, sem intervenção do usuário
            if ((silentMode) && (licenseKey != null) && (targetDir != null))
            {
                String installationFilesDirectory = Path.Combine(Path.GetTempPath(), "AccountingClientFiles");
                String loggerPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "PrintLogger");
                String version    = Assembly.GetExecutingAssembly().GetName().Version.ToString();

                TextReader       textReader       = new StreamReader(licenseKey);
                String           fileContent      = textReader.ReadToEnd();
                RegistrationInfo registrationInfo = LicenseKeyMaker.ReadKey(fileContent, null);
                InstallationInfo installationInfo = new InstallationInfo(targetDir, printLogDir, copyLogDir);

                InstallationHandler handler = new InstallationHandler(null);
                if (!handler.Uninstall())
                {
                    return;
                }
                if (!handler.ExtractInstallationFiles(installationFilesDirectory))
                {
                    return;
                }
                if (!handler.CopyInstallationFiles(installationFilesDirectory, targetDir))
                {
                    return;
                }
                if (!handler.InstallPapercut(installationFilesDirectory, loggerPath, skipPapercutInstall))
                {
                    return;
                }
                if (!handler.CreateConfigurationXML(registrationInfo, installationInfo, false))
                {
                    return;
                }
                if (!handler.StartWindowsServices(targetDir, false))
                {
                    return;
                }
                if (!handler.AddToWindowsRegistry(fileContent, version, installationInfo.PrintLogDirectories, installationInfo.CopyLogDirectory))
                {
                    return;
                }
                if (!handler.SetLicense(registrationInfo.ServiceUrl, registrationInfo.ConvertToLicense()))
                {
                    return;
                }

                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm(licenseKey, targetDir, startInspector, skipPapercutInstall));
        }
Пример #2
0
        private void btnInstall_Click(Object sender, EventArgs e)
        {
            this.btnInstall.Enabled = false;

            String installationFilesDirectory = Path.Combine(Path.GetTempPath(), "AccountingClientFiles");
            String loggerPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "PrintLogger");
            String version    = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            registrationInfo = null;
            EnrollmentForm enrollmentForm = new EnrollmentForm(licenseKey, this);

            enrollmentForm.ShowDialog();
            this.Refresh();
            // Se o usuário optou por não ativar o produto termina a instalação
            if (doNotRegister)
            {
                MessageBox.Show("Execução concluída. Encerrando instalador...");
                // Inicia o instalador do papercut e encerra este instalador
                Process.Start(Path.Combine(installationFilesDirectory, "papercut-print-logger.exe"));
                this.Close();
                return;
            }

            installationInfo = null;
            ConfigurationForm configurationForm = new ConfigurationForm(targetDirectory, this);

            configurationForm.ShowDialog();
            this.Refresh();
            if (installationInfo == null)
            {
                MessageBox.Show("Operação cancelada pelo usuário!");
                return;
            }

            InstallationHandler handler = new InstallationHandler(this);

            // Extrai os arquivos de instalação do pacote (zip)
            if (!handler.ExtractInstallationFiles(installationFilesDirectory))
            {
                return;
            }

            // Copia os arquivos extraídos para o diretório de destino
            if (!handler.CopyInstallationFiles(installationFilesDirectory, installationInfo.TargetDirectory))
            {
                return;
            }

            // Instala o Papercut Print Logger
            if (!handler.InstallPapercut(installationFilesDirectory, loggerPath, skipPapercutInstall))
            {
                return;
            }

            // Configura os parâmetros de execução no XML
            if (!handler.CreateConfigurationXML(registrationInfo, installationInfo, this.startInspector))
            {
                return;
            }

            // Inicia os serviços do windows
            if (!handler.StartWindowsServices(installationInfo.TargetDirectory, this.startInspector))
            {
                return;
            }

            // Adiciona dados do Addon ao registro do windows
            if (!handler.AddToWindowsRegistry(content, version, installationInfo.PrintLogDirectories, installationInfo.CopyLogDirectory))
            {
                return;
            }

            // Informa ao servidor que a licença está em uso por esta estação de trabalho
            if (!handler.SetLicense(registrationInfo.ServiceUrl, registrationInfo.ConvertToLicense()))
            {
                return;
            }

            MessageBox.Show("Execução concluída. Encerrando instalador...");
            this.Close();
        }
        private void btnSubmit_Click(Object sender, EventArgs e)
        {
            if (chkDoNotRegister.Checked)
            {
                // Envia notificação para o form principal
                if (listener != null)
                {
                    listener.NotifyObject(new DoNotRegisterNotification());
                }
                this.Close();
                return;
            }

            if (String.IsNullOrEmpty(txtLicenseKey.Text))
            {
                ShowWarning("É necessário fornecer a chave de ativação!");
                return;
            }

            if (!File.Exists(txtLicenseKey.Text))
            {
                ShowWarning("O arquivo " + txtLicenseKey.Text + " não existe.");
                return;
            }

            TextReader textReader  = new StreamReader(txtLicenseKey.Text);
            String     fileContent = textReader.ReadToEnd();

            registrationInfo = LicenseKeyMaker.ReadKey(fileContent, listener);
            if (registrationInfo == null)
            {
                ShowWarning("Licença inválida! Obtenha uma licença válida para o produto.");
                return;
            }

            AssemblyName assemblyName  = Assembly.GetExecutingAssembly().GetName();
            Version      clientVersion = assemblyName.Version;
            Version      serverVersion = new Version(registrationInfo.Version);

            if (clientVersion != serverVersion)
            {
                ShowWarning("Versão incompatível! Obtenha um executável atualizado para instalar o produto." +
                            Environment.NewLine + "Versão do Servidor: " + serverVersion.ToString());
                return;
            }

            if (DateTime.Now > registrationInfo.ExpirationDate)
            {
                ShowWarning("Chave de produto expirada! Obtenha outra chave.");
                return;
            }

            // Checa a licença junto ao servidor, para verificar se ela está disponível para uso
            RequestHandler requestHandler  = new RequestHandler(registrationInfo.ServiceUrl, 16000, listener);
            Boolean        requestSucceded = requestHandler.StartRequest("LicenseIsAvailable", registrationInfo.ConvertToLicense());

            if (!requestSucceded)
            {
                ShowWarning("Não foi possível verificar a licença junto ao servidor!");
                return;
            }

            Boolean isAvailable = false;

            try
            {
                isAvailable = (Boolean)requestHandler.ParseResponse(typeof(Boolean));
            }
            catch
            {
                ShowWarning("Não foi possível verificar a licença junto ao servidor!");
                ShowWarning("Resultado da requisição: " + Environment.NewLine + requestHandler.GetRawResponse());
                return;
            }

            if (!isAvailable)
            {
                ShowWarning("Esta licença já está em uso por outra estação de trabalho! Obtenha outra licença.");
                return;
            }

            if (listener != null)
            {
                listener.NotifyObject(new ContentNotification(fileContent));
            }

            // Repassa as informações para o form principal
            if (listener != null)
            {
                listener.NotifyObject(registrationInfo);
            }

            // Fecha a janela
            this.Close();
        }