public void UpdateSoftwareProduct()
        {
            RegistryKey parentKey   = Registry.LocalMachine.OpenSubKey("SOFTWARE", true);
            RegistryKey chlidKey    = parentKey.OpenSubKey("Accounting", true);
            String      productKey  = (String)chlidKey.GetValue("DownloadedKey");
            String      thisVersion = (String)chlidKey.GetValue("InstallerVersion");
            String      printLogDir = (String)chlidKey.GetValue("LogDirectories");
            String      copyLogDir  = (String)chlidKey.GetValue("CopyLogDir");

            RegistrationInfo registrationInfo = LicenseKeyMaker.ReadKey(productKey, null);

            updateUrl     = registrationInfo.ServiceUrl;
            updateExe     = FileResource.MapDesktopResource("ClientSetup.EXE");
            updateData    = FileResource.MapDesktopResource("ProductKey.BIN");
            execParams    = new String[3];
            execParams[0] = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            execParams[1] = printLogDir;
            execParams[2] = copyLogDir;

            RequestHandler requestHandler = new RequestHandler(updateUrl, 90000, null);
            String         requestData    = Convert.ToBase64String(Encoding.Default.GetBytes("ClientSetup.EXE"));

            requestHandler.StartRequest("GetVersionNumber", requestData);
            String currentVersion = (String)requestHandler.ParseResponse(typeof(String));

            if (thisVersion != currentVersion)
            {
                // Salva em disco a chave
                FileStream   fileStream   = new FileStream(updateData, FileMode.Create);
                StreamWriter streamWriter = new StreamWriter(fileStream);
                streamWriter.WriteLine(productKey);
                streamWriter.Close();

                // Baixa o EXE do servidor
                Uri       downloadUrl = new Uri(updateUrl + "?action=DownloadCurrentVersion");
                WebClient webClient   = new WebClient();
                webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(FileDownloaded);
                webClient.DownloadFileAsync(downloadUrl, updateExe);
            }
        }
예제 #2
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));
        }
        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();
        }