protected void Page_Load(Object sender, EventArgs e)
        {
            if (!Authentication.IsAuthenticated(Session))
            {
                Response.Redirect("LoginPage.aspx");
            }

            Tenant tenant = (Tenant)Session["tenant"];

            if (tenant == null)
            {
                EmbedClientScript.ShowErrorMessage(this, "Sessão inválida.", true);
                return;
            }

            int     licenseId;
            Boolean isNumeric = int.TryParse(Request.QueryString["licenseId"], out licenseId);

            if (!isNumeric)
            {
                EmbedClientScript.ShowErrorMessage(this, "Os parâmetros passados para a página não estão em um formato válido.", true);
                return;
            }

            // Abre a conexão com o banco
            DataAccess dataAccess = DataAccess.Instance;

            dataAccess.MountConnection(FileResource.MapWebResource(this.Page.Server, "DataAccess.xml"), DatabaseEnum.PrintAccounting);
            dataAccess.OpenConnection();

            ApplicationParamDAO appParamDAO = new ApplicationParamDAO(dataAccess.GetConnection());
            ApplicationParam    urlParam    = appParamDAO.GetParam("url", "webAccounting");

            // Fecha a conexão com o banco
            dataAccess.CloseConnection();
            dataAccess = null;

            if (urlParam == null)
            {
                EmbedClientScript.ShowErrorMessage(this, "Falha ao buscar url do sistema no banco.", true);
                return;
            }

            String serviceUrl = urlParam.value + "/JobRoutingService.aspx";

            DateTime oneYearFromNow = DateTime.Now.AddYears(1);
            DateTime expirationDate = new DateTime(oneYearFromNow.Year, oneYearFromNow.Month, oneYearFromNow.Day, 0, 0, 0);


            this.Response.Clear();
            this.Response.ContentType = "application/octet-stream";
            this.Response.AddHeader("content-disposition", "attachment; filename=ProductKey.bin");

            String licenseKey = LicenseKeyMaker.GenerateKey(serviceUrl, tenant.id, licenseId, expirationDate);

            Response.Write(licenseKey);

            this.Response.End();
        }
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            int      randomId       = 5; // utiliza um id qualquer
            DateTime selectedDate   = expirationDatePicker.Value;
            DateTime expirationDate = new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day, 0, 0, 0);

            infoBox.Text = LicenseKeyMaker.GenerateKey(txtServiceUrl.Text, int.Parse(txtTenantId.Text), randomId, expirationDate);
        }
        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);
            }
        }
Example #4
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();
        }