ApplicationDeployment Classe

Definição

Dá suporte a atualizações da implantação atual de forma programática e manipula o download sob demanda de arquivos.Supports updates of the current deployment programmatically, and handles on-demand downloading of files. Essa classe não pode ser herdada.This class cannot be inherited.

public ref class ApplicationDeployment sealed
public sealed class ApplicationDeployment
type ApplicationDeployment = class
Public NotInheritable Class ApplicationDeployment
Herança
ApplicationDeployment

Exemplos

O exemplo de código a seguir determina em tempo de carregamento do aplicativo se uma nova atualização está disponível; se uma atualização necessária estiver disponível, o exemplo de código instalará a atualização de forma assíncrona.The following code example determines at application load time whether a new update is available; if a required update is available, the code example installs the update asynchronously. Esse código deve ser adicionado a um formulário que contém um TextBox nome downloadStatus .This code should be added to a form that contains a TextBox named downloadStatus.

private:
    long sizeOfUpdate;


private:
    void Form1_Load(Object^ sender, System::EventArgs^ e)
    {
        DoUpdate();
    }

public:
    void DoUpdate()
    {
        if (ApplicationDeployment::IsNetworkDeployed)
        {
            ApplicationDeployment^ currentAppDeployment =
                ApplicationDeployment::CurrentDeployment;
            currentAppDeployment->CheckForUpdateCompleted +=
                gcnew CheckForUpdateCompletedEventHandler(
                this, &Form1::currentDeploy_CheckForUpdateCompleted);
            currentAppDeployment->CheckForUpdateAsync();
        }
    }

    // If update is available, fetch it.
    void currentDeploy_CheckForUpdateCompleted(Object^ sender,
        CheckForUpdateCompletedEventArgs^ e)
    {
        if (nullptr != e->Error)
        {
            // Log error.
            return;
        }

        if (e->UpdateAvailable)
        {
            sizeOfUpdate = (long) e->UpdateSizeBytes;
            if (!e->IsUpdateRequired)
            {
                System::Windows::Forms::DialogResult 
                    updateDialogueResult = MessageBox::Show(
                    "An update is available.Would you like to update the" +
                    " application now?", "Update Available",
                    MessageBoxButtons::OKCancel);
                if (System::Windows::Forms::DialogResult::OK == 
                    updateDialogueResult)
                {
                    BeginUpdate();
                }
            }
            else
            {
                BeginUpdate();
            }
        }
    }

    void BeginUpdate()
    {
        ApplicationDeployment^ ad = ApplicationDeployment::CurrentDeployment;
        ad->UpdateCompleted +=
            gcnew AsyncCompletedEventHandler(
            this, &Form1::CurrentDeployment_UpdateCompleted);

        // Indicate progress in the application's status bar.
        ad->UpdateProgressChanged +=
            gcnew DeploymentProgressChangedEventHandler(this, 
            &Form1::ad_ProgressChanged);

        ad->UpdateAsync();
    }

    void CurrentDeployment_UpdateCompleted(Object^ sender,
        AsyncCompletedEventArgs^ e)
    {
        if (!e->Cancelled)
        {
            if (nullptr != e->Error)
            {
                System::Windows::Forms::DialogResult 
                    restartDialogueResult = MessageBox::Show(
                    "The application has been updated. Restart?",
                    "Restart Application",
                    MessageBoxButtons::OKCancel);
                if (System::Windows::Forms::DialogResult::OK == 
                    restartDialogueResult)
                {
                    Application::Restart();
                }
            }
            else
            {
                // Replace with your own error reporting or logging.
                MessageBox::Show(
                    "The application encountered an error in downloading" +
                    " the latest update. Error: {0}",
                    e->Error->Message);
            }
        }
        else
        {
            // Replace with your own error reporting or logging.
            MessageBox::Show("The update of the application's latest" +
                " version was cancelled.");
        }
    }

    void ad_ProgressChanged(Object^ sender,
        DeploymentProgressChangedEventArgs^ e)
    {
        String^ progressText =
            String::Format(
            "{0:D}K out of {1:D}K downloaded - {2:D}% complete",
            e->BytesCompleted / 1024, e->BytesTotal / 1024,
            e->ProgressPercentage);
        statusStrip1->Text = progressText;
    }
long sizeOfUpdate = 0;

private void UpdateApplication()
{
    if (ApplicationDeployment.IsNetworkDeployed)
    {
        ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
        ad.CheckForUpdateCompleted += new CheckForUpdateCompletedEventHandler(ad_CheckForUpdateCompleted);
        ad.CheckForUpdateProgressChanged += new DeploymentProgressChangedEventHandler(ad_CheckForUpdateProgressChanged);

        ad.CheckForUpdateAsync();
    }
}

void  ad_CheckForUpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
{
    downloadStatus.Text = String.Format("Downloading: {0}. {1:D}K of {2:D}K downloaded.", GetProgressString(e.State), e.BytesCompleted/1024, e.BytesTotal/1024);   
}

string GetProgressString(DeploymentProgressState state)
{
    if (state == DeploymentProgressState.DownloadingApplicationFiles)
    {
        return "application files";
    } 
    else if (state == DeploymentProgressState.DownloadingApplicationInformation) 
    {
        return "application manifest";
    } 
    else 
    {
        return "deployment manifest";
    }
}

void ad_CheckForUpdateCompleted(object sender, CheckForUpdateCompletedEventArgs e)
{
    if (e.Error != null)
    {
        MessageBox.Show("ERROR: Could not retrieve new version of the application. Reason: \n" + e.Error.Message + "\nPlease report this error to the system administrator.");
        return;
    }
    else if (e.Cancelled == true)
    {
        MessageBox.Show("The update was cancelled.");
    }

    // Ask the user if they would like to update the application now.
    if (e.UpdateAvailable)
    {
        sizeOfUpdate = e.UpdateSizeBytes;

        if (!e.IsUpdateRequired)
        {
            DialogResult dr = MessageBox.Show("An update is available. Would you like to update the application now?\n\nEstimated Download Time: ", "Update Available", MessageBoxButtons.OKCancel);
            if (DialogResult.OK == dr)
            {
                BeginUpdate();
            }
        }
        else
        {
            MessageBox.Show("A mandatory update is available for your application. We will install the update now, after which we will save all of your in-progress data and restart your application.");
            BeginUpdate();
        }
    }
}

private void BeginUpdate()
{
    ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
    ad.UpdateCompleted += new AsyncCompletedEventHandler(ad_UpdateCompleted);

    // Indicate progress in the application's status bar.
    ad.UpdateProgressChanged += new DeploymentProgressChangedEventHandler(ad_UpdateProgressChanged);
    ad.UpdateAsync();
}

void ad_UpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
{
    String progressText = String.Format("{0:D}K out of {1:D}K downloaded - {2:D}% complete", e.BytesCompleted / 1024, e.BytesTotal / 1024, e.ProgressPercentage);
    downloadStatus.Text = progressText;
}

void ad_UpdateCompleted(object sender, AsyncCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        MessageBox.Show("The update of the application's latest version was cancelled.");
        return;
    }
    else if (e.Error != null)
    {
        MessageBox.Show("ERROR: Could not install the latest version of the application. Reason: \n" + e.Error.Message + "\nPlease report this error to the system administrator.");
        return;
    }

    DialogResult dr = MessageBox.Show("The application has been updated. Restart? (If you do not restart now, the new version will not take effect until after you quit and launch the application again.)", "Restart Application", MessageBoxButtons.OKCancel);
    if (DialogResult.OK == dr)
    {
        Application.Restart();
    }
}
Private sizeOfUpdate As Long = 0

Dim WithEvents ADUpdateAsync As ApplicationDeployment

Private Sub UpdateApplication()
    If (ApplicationDeployment.IsNetworkDeployed) Then
        ADUpdateAsync = ApplicationDeployment.CurrentDeployment

        ADUpdateAsync.CheckForUpdateAsync()
    End If
End Sub

Private Sub ADUpdateAsync_CheckForUpdateProgressChanged(ByVal sender As Object, ByVal e As DeploymentProgressChangedEventArgs) Handles ADUpdateAsync.CheckForUpdateProgressChanged
    DownloadStatus.Text = [String].Format("{0:D}K of {1:D}K downloaded.", e.BytesCompleted / 1024, e.BytesTotal / 1024)
End Sub


Private Sub ADUpdateAsync_CheckForUpdateCompleted(ByVal sender As Object, ByVal e As CheckForUpdateCompletedEventArgs) Handles ADUpdateAsync.CheckForUpdateCompleted
    If (e.Error IsNot Nothing) Then
        MessageBox.Show(("ERROR: Could not retrieve new version of the application. Reason: " + ControlChars.Lf + e.Error.Message + ControlChars.Lf + "Please report this error to the system administrator."))
        Return
    Else
        If (e.Cancelled = True) Then
            MessageBox.Show("The update was cancelled.")
        End If
    End If

    ' Ask the user if they would like to update the application now.
    If (e.UpdateAvailable) Then
        sizeOfUpdate = e.UpdateSizeBytes

        If (Not e.IsUpdateRequired) Then
            Dim dr As DialogResult = MessageBox.Show("An update is available. Would you like to update the application now?", "Update Available", MessageBoxButtons.OKCancel)
            If (System.Windows.Forms.DialogResult.OK = dr) Then
                BeginUpdate()
            End If
        Else
            MessageBox.Show("A mandatory update is available for your application. We will install the update now, after which we will save all of your in-progress data and restart your application.")
            BeginUpdate()
        End If
    End If
End Sub

Private Sub BeginUpdate()
    ADUpdateAsync = ApplicationDeployment.CurrentDeployment
    ADUpdateAsync.UpdateAsync()
End Sub


Private Sub ADUpdateAsync_UpdateProgressChanged(ByVal sender As Object, ByVal e As DeploymentProgressChangedEventArgs) Handles ADUpdateAsync.UpdateProgressChanged
    Dim progressText As String = String.Format("{0:D}K out of {1:D}K downloaded - {2:D}% complete", e.BytesCompleted / 1024, e.BytesTotal / 1024, e.ProgressPercentage)
    DownloadStatus.Text = progressText
End Sub


Private Sub ADUpdateAsync_UpdateCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs) Handles ADUpdateAsync.UpdateCompleted
    If (e.Cancelled) Then
        MessageBox.Show("The update of the application's latest version was cancelled.")
        Exit Sub
    Else
        If (e.Error IsNot Nothing) Then
            MessageBox.Show("ERROR: Could not install the latest version of the application. Reason: " + ControlChars.Lf + e.Error.Message + ControlChars.Lf + "Please report this error to the system administrator.")
            Exit Sub
        End If
    End If

    Dim dr As DialogResult = MessageBox.Show("The application has been updated. Restart? (If you do not restart now, the new version will not take effect until after you quit and launch the application again.)", "Restart Application", MessageBoxButtons.OKCancel)
    If (dr = System.Windows.Forms.DialogResult.OK) Then
        Application.Restart()
    End If
End Sub

Comentários

Você pode configurar seu aplicativo ClickOnce para verificar se há atualizações e instalá-las automaticamente por meio do subscription elemento do manifesto de implantação.You can configure your ClickOnce application to check for updates and install them automatically through the subscription element of the deployment manifest. Alguns aplicativos, no entanto, precisam de um controle mais preciso sobre suas atualizações.Some applications, however, need finer control over their updates. Talvez você queira instalar as atualizações necessárias programaticamente e solicitar que os usuários instalem atualizações opcionais em sua conveniência.You may want to install required updates programmatically, and prompt users to install optional updates at their convenience. Desativando as atualizações de assinatura no manifesto de implantação, você pode assumir o controle total das políticas de atualização do aplicativo.By turning off subscription updates in the deployment manifest, you can take complete control of your application's update policies. Como alternativa, você pode usar a assinatura automática em conjunto com ApplicationDeployment o, que permite que o ClickOnce atualize o aplicativo periodicamente, mas usa ApplicationDeployment para baixar atualizações críticas logo após a liberação.Alternatively, you can use automatic subscription in conjunction with ApplicationDeployment, which enables ClickOnce to update the application periodically, but uses ApplicationDeployment to download critical updates shortly after they are released.

Você pode testar se sua implantação tem uma atualização disponível usando o CheckForUpdate ou o CheckForUpdateAsync método; o último método gera o CheckForUpdateCompleted evento na conclusão bem-sucedida.You can test whether your deployment has an available update by using either the CheckForUpdate or the CheckForUpdateAsync method; the latter method raises the CheckForUpdateCompleted event on successful completion. CheckForDetailedUpdate Retorna informações importantes sobre a atualização, como seu número de versão e se é uma atualização necessária para os usuários atuais.CheckForDetailedUpdate returns important information about the update, such as its version number and whether it is a required update for current users. Se uma atualização estiver disponível, você poderá instalá-la usando Update ou UpdateAsync ; o último método gerará o UpdateCompleted evento depois que a instalação da atualização for concluída.If an update is available, you can install it by using Update or UpdateAsync; the latter method raises the UpdateCompleted event after installation of the update is complete. Para atualizações grandes, você pode receber notificações de progresso por meio dos CheckForUpdateProgressChanged eventos e e UpdateProgressChanged usar as informações em ProgressChangedEventArgs para notificar o usuário sobre o status de download.For large updates, you can receive progress notifications through the CheckForUpdateProgressChanged and UpdateProgressChanged events, and use the information in ProgressChangedEventArgs to notify the user of the download status.

Você também pode usar o ApplicationDeployment para baixar arquivos grandes e assemblies sob demanda.You can also use ApplicationDeployment to download large files and assemblies on demand. Esses arquivos devem ser marcados como "opcionais" no manifesto do aplicativo da implantação para que eles não sejam baixados durante a instalação.These files must be marked as "optional" within the deployment's application manifest so that they are not downloaded during installation. Você pode baixar os arquivos a qualquer momento durante a duração do aplicativo usando o DownloadFileGroup DownloadFileGroupAsync método ou.You can download the files at any point during the application's duration by using the DownloadFileGroup or the DownloadFileGroupAsync method. Você pode baixar assemblies antes que eles sejam carregados na memória, fornecendo um manipulador de eventos para o AssemblyResolve evento na AppDomain classe.You can download assemblies before they are loaded into memory by supplying an event handler for the AssemblyResolve event on the AppDomain class. Para obter mais informações, consulte Walkthrough: Downloading Assemblies on Demand with the ClickOnce Deployment API Using the Designer (Instruções passo a passo: baixando assemblies sob demanda com a API de implantação do ClickOnce usando o designer).For more information, see Walkthrough: Downloading Assemblies on Demand with the ClickOnce Deployment API Using the Designer.

Observação

Se você atualizar um aplicativo ClickOnce enquanto o aplicativo estiver em execução, o usuário não verá as atualizações até que você chame o Restart método do Application , que fechará a instância em execução no momento do aplicativo e a reiniciará imediatamente.If you update a ClickOnce application while the application is running, the user will not see the updates until you call the Restart method of the Application, which will close the current running instance of the application and immediately restart it.

ApplicationDeployment Não tem construtor público; Você obtém instâncias da classe dentro de um aplicativo ClickOnce por meio da CurrentDeployment propriedade.ApplicationDeployment has no public constructor; you obtain instances of the class within a ClickOnce application through the CurrentDeployment property. Você usa a IsNetworkDeployed propriedade para verificar se o aplicativo atual é um aplicativo ClickOnce.You use the IsNetworkDeployed property to verify that the current application is a ClickOnce application.

ApplicationDeployment dá suporte à verificação de atualizações e download de arquivos atualizados de forma assíncrona usando a nova visão geral de padrão assíncrono baseado em evento, que expõe os retornos de chamada de conclusão como eventos de classe.ApplicationDeployment supports checking for updates and downloading updated files asynchronously by using the new Event-based Asynchronous Pattern Overview, which exposes completion callbacks as class events. ApplicationDeployment inicia e gerencia os threads para você e chama seu aplicativo de volta no thread da interface do usuário correto.ApplicationDeployment starts and manages the threads for you, and calls your application back on the correct UI thread. Por meio dessa classe, você pode atualizar sem bloquear o aplicativo, para que o usuário possa continuar trabalhando enquanto a atualização é instalada.Through this class, you can update without locking up the application, so that the user can continue working while the update installs. Se o usuário precisar parar todo o trabalho enquanto ocorre uma atualização, considere usar os métodos síncronos.If the user must stop all work while an update takes place, consider using the synchronous methods instead.

Observação

A execução de atualizações assíncronas exige que seu aplicativo importe os System.Deployment.Application System.ComponentModel namespaces e.Performing asynchronous updates requires that your application import both the System.Deployment.Application and System.ComponentModel namespaces.

Propriedades

ActivationUri

Obtém a URL usada para iniciar o manifesto de implantação do aplicativo.Gets the URL used to launch the deployment manifest of the application.

CurrentDeployment

Retorna o ApplicationDeployment atual para essa implantação.Returns the current ApplicationDeployment for this deployment.

CurrentVersion

Obtém a versão da implantação para a instância em execução atual do aplicativo.Gets the version of the deployment for the current running instance of the application.

DataDirectory

Obtém o caminho para o diretório de dados do ClickOnce.Gets the path to the ClickOnce data directory.

IsFirstRun

Obtém um valor que indica se esta é a primeira vez que este aplicativo foi executado no computador cliente.Gets a value indicating whether this is the first time this application has run on the client computer.

IsNetworkDeployed

Obtém um valor que indica se o aplicativo atual é um aplicativo ClickOnce.Gets a value indicating whether the current application is a ClickOnce application.

TimeOfLastUpdateCheck

Obtém a data e a hora em que o ClickOnce foi verificado pela última vez em busca de uma atualização de aplicativo.Gets the date and the time ClickOnce last checked for an application update.

UpdatedApplicationFullName

Obtém o nome completo do aplicativo depois de ele ser atualizado.Gets the full name of the application after it has been updated.

UpdatedVersion

Obtém a versão da atualização baixada recentemente.Gets the version of the update that was recently downloaded.

UpdateLocation

Obtém o site ou o compartilhamento de arquivos no qual este aplicativo atualiza a si mesmo.Gets the Web site or file share from which this application updates itself.

Métodos

CheckForDetailedUpdate()

Executa a mesma operação que CheckForUpdate(), mas retorna informações estendidas sobre a atualização disponível.Performs the same operation as CheckForUpdate(), but returns extended information about the available update.

CheckForDetailedUpdate(Boolean)

Executa a mesma operação que CheckForUpdate(), mas retorna informações estendidas sobre a atualização disponível.Performs the same operation as CheckForUpdate(), but returns extended information about the available update.

CheckForUpdate()

Verifica UpdateLocation para determinar se uma nova atualização está disponível.Checks UpdateLocation to determine whether a new update is available.

CheckForUpdate(Boolean)

Verifica UpdateLocation para determinar se uma nova atualização está disponível.Checks UpdateLocation to determine whether a new update is available.

CheckForUpdateAsync()

Verifica UpdateLocation assincronamente para determinar se uma nova atualização está disponível.Checks UpdateLocation asynchronously to determine whether a new update is available.

CheckForUpdateAsyncCancel()

Cancela a verificação de atualização assíncrona.Cancels the asynchronous update check.

DownloadFileGroup(String)

Baixa um conjunto de arquivos opcionais sob demanda.Downloads a set of optional files on demand.

DownloadFileGroupAsync(String)

Baixa, sob demanda, um conjunto de arquivos opcionais em segundo plano.Downloads, on demand, a set of optional files in the background.

DownloadFileGroupAsync(String, Object)

Baixa, sob demanda, um conjunto de arquivos opcionais em segundo plano e transmite uma parte do estado do aplicativo para os retornos de chamada do evento.Downloads, on demand, a set of optional files in the background, and passes a piece of application state to the event callbacks.

DownloadFileGroupAsyncCancel(String)

Cancela um download de arquivo assíncrono.Cancels an asynchronous file download.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
IsFileGroupDownloaded(String)

Verifica se o grupo de arquivo nomeado já foi baixado para o computador cliente.Checks whether the named file group has already been downloaded to the client computer.

MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)
Update()

Inicia um download síncrono e a instalação da versão mais recente deste aplicativo.Starts a synchronous download and installation of the latest version of this application.

UpdateAsync()

Inicia um download assíncrono e a instalação da versão mais recente deste aplicativo.Starts an asynchronous download and installation of the latest version of this application.

UpdateAsyncCancel()

Cancela uma atualização assíncrona iniciada pelo UpdateAsync().Cancels an asynchronous update initiated by UpdateAsync().

Eventos

CheckForUpdateCompleted

Ocorre quando CheckForUpdateAsync() é concluído.Occurs when CheckForUpdateAsync() has completed.

CheckForUpdateProgressChanged

Ocorre quando uma atualização em andamento está disponível em uma chamada CheckForUpdateAsync().Occurs when a progress update is available on a CheckForUpdateAsync() call.

DownloadFileGroupCompleted

Ocorre no thread de aplicativo principal quando um download de arquivo é concluído.Occurs on the main application thread when a file download is complete.

DownloadFileGroupProgressChanged

Ocorre quando informações de status estão disponíveis em uma operação de download de arquivo iniciada por uma chamada a DownloadFileGroupAsync.Occurs when status information is available on a file download operation initiated by a call to DownloadFileGroupAsync.

UpdateCompleted

Ocorre quando o ClickOnce conclui a atualização do aplicativo como o resultado de uma chamada para UpdateAsync() .Occurs when ClickOnce has finished upgrading the application as the result of a call to UpdateAsync().

UpdateProgressChanged

Ocorre quando o ClickOnce tem novas informações de status para uma operação de atualização iniciada chamando o UpdateAsync() método.Occurs when ClickOnce has new status information for an update operation initiated by calling the UpdateAsync() method.

Aplica-se a