2011-12-08 20 views
12

第一件事:我沒有經驗的面向對象編程,無論如何。我在學校創建了我的VB腳本和一些Java腳本,但就是這樣。所以我的問題很可能在那裏。但是,儘管如此,在過去的幾天裏,我一直在嘗試讓一些小應用程序一起使用,以便我掃描,選擇和安裝Windows更新。到目前爲止,我已經能夠理解大多數參考文獻,並且在互聯網上發佈了幾篇文章的幫助,現在我可以選擇並下載更新。C#和WUAPI:BeginDownload函數

到目前爲止,我已經能夠下載使用下面的代碼更新的集合:

UpdateCollection CurrentInstallCollection = (UpdateCollection)e.Argument; 
UpdateDownloader CurrentDownloader = CurrentSession.CreateUpdateDownloader(); 
CurrentDownloader.Updates = CurrentInstallCollection; 

這是在後臺工作,並返回運行一次下載完成。它工作得很好,我可以看到更新在文件系統上下載,但沒有真正的方法來顯示應用程序內的進度。要做這樣的事情,有IDownloadJob接口,允許我使用下載器(UpdateSession.CreateUpdateDownloader)的.BeginDownload方法...我想,至少。 :D然後問題出現了:我現在已經嘗試了大約6個小時以使代碼正常工作,但無論我嘗試什麼都沒有成功。此外,沒有太多的信息,各地有關.BeginDownload方法在互聯網上(或者至少看起來是這樣),但我的方法的調用不起作用:

IDownloadJob CurrentDownloadJob = CurrentDownloader.BeginDownload(); 

我不知道是什麼提供參數...我嘗試過方法,對象...無濟於事。代碼的完整塊看起來是這樣的:

UpdateCollection CurrentInstallCollection = (UpdateCollection)e.Argument; 
UpdateDownloader CurrentDownloader = CurrentSession.CreateUpdateDownloader(); 
CurrentDownloader.Updates = CurrentInstallCollection; 
IDownloadJob CurrentDownloadJob = CurrentDownloader.BeginDownload(); 
IDownloadProgress CurrentJobProgess = CurrentDownloadJob.GetProgress(); 
tbStatus.Text = Convert.ToString(CurrentJobProgess.PercentComplete); 

我發現一個來源,與.BeginDownload(this,this,this)調用該方法的互聯網,這並不在代碼編輯器報告任何錯誤,但可能不會與報表上的幫助因爲我的理解是,所提供的參數是所描述事件發生時調用的方法(進度已更改或下載完成)。

我也試過,但它沒有工作,要麼:

http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/636a8399-2bc1-46ff-94df-a58cebfe688c

的BeginDownload方法的詳細說明:

http://msdn.microsoft.com/en-us/library/aa386132(v=VS.85).aspx

WUAPI參考:

不幸的是,我不允許發佈該鏈接,但是到BeginDownload方法的鏈接仍然存在到同一個地方。 :)

我知道,這是相當多的要求,但如果有人能指出我在正確的方向(如哪些參數傳遞和如何),這將非常感激! :)

回答

1

增加提及WUApiLib

public UpdateSession updateSession; 
public ISearchResult searchResult; 

private void Form1_Load(object sender, EventArgs e) 
    { 
     //check for updates 
     updateSession = new UpdateSession(); 
     searchResult = updateSession.CreateUpdateSearcher().Search("IsInstalled=0 and Type='Software' and IsHidden=0"); 


     //download updates 
     UpdateDownloader downloader = updateSession.CreateUpdateDownloader(); 
     downloader.Updates = searchResult.Updates; 
     downloader.Download(); 

     //collect all downloaded updates 
     UpdateCollection updatesToInstall = new UpdateCollection(); 
     foreach (IUpdate update in searchResult.Updates) 
     { 
      if (update.IsDownloaded) 
      { 
       updatesToInstall.Add(update); 
      } 
     } 

     //install downloaded updates 
     IUpdateInstaller installer = updateSession.CreateUpdateInstaller(); 
     installer.Updates = updatesToInstall; 
     IInstallationResult installationRes = installer.Install(); 
    } 
+0

任何人都知道如何設置獲取更新的語言? w/.Search(「IsInstalled = 0 AND IsPresent = 0」);我得到所有的語言,我幾乎去了拉脫維亞,但能夠取消。 – DukeDidntNukeEm

3

Windows更新API(WU API庫(WUApiLib))是不是在我看來,有據可查。搜索,下載和安裝的所有任務的異步「開始」如下所示。它很難掌握,不幸的是微軟在這個階段還沒有給出任何C#代碼示例。我希望我可以幫助我的小應用程序。守則可以稍微整理一下,它只是在這個階段一起入侵,但它符合其目的。您將需要一個Windows窗體上面有四個組成部分:

private System.Windows.Forms.TextBox textBox1; 
private System.ComponentModel.BackgroundWorker EnableServicesWorker; 
private System.Windows.Forms.Label toolStripStatusLabel2; 
private System.Windows.Forms.Label toolStripStatusLabel1; 

我的代碼impliments所有過程的異步性的從微軟的網站搜索,下載和安裝更新(對不起它的長):

using System; 
using WUApiLib; 
using System.Data; 
using System.Linq; 
using System.Text; 
using System.Drawing; 
using System.Windows.Forms; 
using System.ComponentModel; 
using System.ServiceProcess; 
using System.Collections.Generic; 

namespace Windows_Update_Automation 
{ 
public partial class Form1 : Form 
{ 
public UpdateSession UpdateSession; 

#region <------- Search Section -------> 

public IUpdateSearcher iUpdateSearcher; 

public ISearchJob iSearchJob; 

public UpdateCollection NewUpdatesCollection; 

public ISearchResult NewUpdatesSearchResult; 

#endregion <------- Search Section -------> 

#region <------- Downloader Section -------> 

public IUpdateDownloader iUpdateDownloader; 

public IDownloadJob iDownloadJob; 

public IDownloadResult iDownloadResult; 

#endregion <------- Downloader Section -------> 

#region <------- Installer Section -------> 

public IUpdateInstaller iUpdateInstaller; 

public IInstallationJob iInstallationJob; 

public IInstallationResult iInstallationResult; 

#endregion <------- Installer Section -------> 

// Declare a Delegate Type for Message Notification... 
public delegate void SendNotification(); 

// Create an Instance of Delegate Type... 
public SendNotification sendNotification; 

private int count = 0; 

public int Count 
{ 
get { return count; } 
set { count = value; } 
} 

public Form1() 
{ 
InitializeComponent(); 
} 

private void Form1_Load(object sender, EventArgs e) 
{ 
// Show - or Hide... 
this.Show(); 

// Encapsulate the setTextBox1 Method in Delegate SendNotification... 
sendNotification = new SendNotification(setTextBox1); 

// Set Text Box Value... 
this.toolStripStatusLabel1.Text = "Enabling Update Services..."; 

// Set Text Box Value... 
this.toolStripStatusLabel2.Text = ""; 

// Lets check Windows is up to that task... 
EnableServicesWorker.RunWorkerAsync(); 
} 

private void EnableServicesWorker_DoWork(object sender, DoWorkEventArgs e) 
{ 
// Get Services Collection... 
ServiceController[] serviceController; 
serviceController = ServiceController.GetServices(); 

// Loop through and check for a particular Service... 
foreach (ServiceController scTemp in serviceController) 
{ 
switch (scTemp.DisplayName) 
{ 
case "Windows Update": 
RestartService(scTemp.DisplayName, 5000); 
break; 
case "Automatic Updates": 
RestartService(scTemp.DisplayName, 5000); 
break; 
default: 
break; 
} 
} 

// Check for iAutomaticUpdates.ServiceEnabled... 
IAutomaticUpdates iAutomaticUpdates = new AutomaticUpdates(); 
if (!iAutomaticUpdates.ServiceEnabled) 
{ 
iAutomaticUpdates.EnableService(); 
} 
} 

private void EnableServicesWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
{ 
this.toolStripStatusLabel1.Text = "Searching for updates..."; 

iUpdateSearch(); 
} 

public static void RestartService(string serviceName, int timeoutMilliseconds) 
{ 
ServiceController serviceController = new ServiceController(serviceName); 
try 
{ 
int millisec1 = Environment.TickCount; 
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); 

serviceController.Stop(); 
serviceController.WaitForStatus(ServiceControllerStatus.Stopped, timeout); 

// count the rest of the timeout 
int millisec2 = Environment.TickCount; 
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1)); 

serviceController.Start(); 
serviceController.WaitForStatus(ServiceControllerStatus.Running, timeout); 
} 
catch 
{ 
// ... 
} 
} 

#region <------- Search Methods -------> 

private void iUpdateSearch() 
{ 
UpdateSession = new UpdateSession(); 
iUpdateSearcher = UpdateSession.CreateUpdateSearcher(); 

// Only Check Online.. 
iUpdateSearcher.Online = true; 

// Begin Asynchronous IUpdateSearcher... 
iSearchJob = iUpdateSearcher.BeginSearch("IsInstalled=0 AND IsPresent=0", new iUpdateSearcher_onCompleted(this), new iUpdateSearcher_state(this)); 
} 

private void iUpdateSearchComplete(Form1 mainform) 
{ 
Form1 formRef = mainform; 

// Declare a new UpdateCollection and populate the result... 
NewUpdatesCollection = new UpdateCollection(); 
NewUpdatesSearchResult = iUpdateSearcher.EndSearch(iSearchJob); 

Count = NewUpdatesSearchResult.Updates.Count; 
formRef.Invoke(formRef.sendNotification); 

// Accept Eula code for each update 
for (int i = 0; i < NewUpdatesSearchResult.Updates.Count; i++) 
{ 
IUpdate iUpdate = NewUpdatesSearchResult.Updates[i]; 

if (iUpdate.EulaAccepted == false) 
{ 
iUpdate.AcceptEula(); 
} 

NewUpdatesCollection.Add(iUpdate); 
} 

foreach (IUpdate update in NewUpdatesSearchResult.Updates) 
{ 
textBox1.AppendText(update.Title + Environment.NewLine); 
} 

if (NewUpdatesSearchResult.Updates.Count > 0) 
{ 
iUpdateDownload(); 
} 
} 

#endregion <------- Search Methods -------> 

#region <------- Downloader Methods -------> 

private void iUpdateDownload() 
{ 
UpdateSession = new UpdateSession(); 
iUpdateDownloader = UpdateSession.CreateUpdateDownloader(); 

iUpdateDownloader.Updates = NewUpdatesCollection; 
iUpdateDownloader.Priority = DownloadPriority.dpHigh; 
iDownloadJob = iUpdateDownloader.BeginDownload(new iUpdateDownloader_onProgressChanged(this), new iUpdateDownloader_onCompleted(this), new iUpdateDownloader_state(this)); 
} 

public void iDownloadComplete() 
{ 
iDownloadResult = iUpdateDownloader.EndDownload(iDownloadJob); 
if (iDownloadResult.ResultCode == OperationResultCode.orcSucceeded) 
{ 
this.toolStripStatusLabel1.Text = "Installing Updates..."; 

iInstallation(); 
} 
else 
{ 
string message = "The Download has failed: " + iDownloadResult.ResultCode + ". Please check your  internet connection then Re-Start the application."; 
string caption = "Download Failed!"; 
MessageBoxButtons buttons = MessageBoxButtons.OK; 
MessageBoxIcon icon = MessageBoxIcon.Error; 
MessageBox.Show(message, caption, buttons, icon); 

Application.Exit(); 
} 
} 

#endregion <------- Downloader Methods -------> 

#region <------- Installation Methods -------> 

public void iInstallation() 
{ 
iUpdateInstaller = UpdateSession.CreateUpdateInstaller() as IUpdateInstaller; 
iUpdateInstaller.Updates = this.NewUpdatesCollection; 

iInstallationJob = iUpdateInstaller.BeginInstall(new iUpdateInstaller_onProgressChanged(this), new iUpdateInstaller_onCompleted(this), new iUpdateInstaller_state(this)); 
} 

public void iInstallationComplete() 
{ 
iInstallationResult = iUpdateInstaller.EndInstall(iInstallationJob); 
if (iInstallationResult.ResultCode == OperationResultCode.orcSucceeded) 
{ 
this.toolStripStatusLabel1.Text = "Installation Complete..."; 
} 
else 
{ 
string message = "The Installation has failed: " + iInstallationResult.ResultCode + "."; 
string caption = "DownInstallationload Failed!"; 
MessageBoxButtons buttons = MessageBoxButtons.OK; 
MessageBoxIcon icon = MessageBoxIcon.Error; 
MessageBox.Show(message, caption, buttons, icon); 

Application.Exit(); 
} 
} 

#endregion <------- Installation Methods -------> 

#region <------- Notification Methods -------> 

public void setTextBox1() 
{ 
toolStripStatusLabel1.Text = Count + " Updates found..."; 
} 

public void setTextBox1Notification(string txt) 
{ 
toolStripStatusLabel1.Text = txt; 
} 

public void setTextBox2Notification(string txt) 
{ 
toolStripStatusLabel2.Text = txt; 
} 

#endregion <------- Notification Methods -------> 

#region <------- iUpdateSearcher.BeginDownload Object Abstract Class's -------> 
// onCompleted [in] 
// An ISearchCompletedCallback interface that is called when an asynchronous search operation is complete. 
public class iUpdateSearcher_onCompleted : ISearchCompletedCallback 
{ 
private Form1 form1; 

public iUpdateSearcher_onCompleted(Form1 mainForm) 
{ 
this.form1 = mainForm; 
} 

// Implementation of IDownloadCompletedCallback interface... 
public void Invoke(ISearchJob searchJob, ISearchCompletedCallbackArgs e) 
{ 
form1.iUpdateSearchComplete(this.form1); 
} 
} 

// state [in] 
// The caller-specific state that is returned by the AsyncState property of the ISearchJob interface. 
public class iUpdateSearcher_state 
{ 
private Form1 form1; 

// Implementation of state interface... 
public iUpdateSearcher_state(Form1 mainForm) 
{ 
this.form1 = mainForm; 

form1.setTextBox2Notification("State: Search Started..."); 
} 
} 

#endregion <------- iUpdateSearcher.BeginDownload Object Abstract Class's -------> 

#region <------- iUpdateDownloader.BeginDownload Object Abstract Class's -------> 
// onProgressChanged [in] 
// An IDownloadProgressChangedCallback interface that is called periodically for download progress changes before download is complete. 
public class iUpdateDownloader_onProgressChanged : IDownloadProgressChangedCallback 
{ 
private Form1 form1; 

public iUpdateDownloader_onProgressChanged(Form1 mainForm) 
{ 
this.form1 = mainForm; 
} 

// Implementation of IDownloadProgressChangedCallback interface... 
public void Invoke(IDownloadJob downloadJob, IDownloadProgressChangedCallbackArgs e) 
{ 

decimal bDownloaded = ((e.Progress.TotalBytesDownloaded/1024)/1024); 
decimal bToDownloaded = ((e.Progress.TotalBytesToDownload/1024)/1024); 
bDownloaded = decimal.Round(bDownloaded, 2); 
bToDownloaded = decimal.Round(bToDownloaded, 2); 

form1.setTextBox1Notification("Downloading Update: " 
+ e.Progress.CurrentUpdateIndex 
+ "/" 
+ downloadJob.Updates.Count 
+ " - " 
+ bDownloaded + "Mb" 
+ "/" 
+ bToDownloaded + "Mb"); 
} 
} 

// onCompleted [in] 
// An IDownloadCompletedCallback interface (C++/COM) that is called when an asynchronous download operation is complete. 
public class iUpdateDownloader_onCompleted : IDownloadCompletedCallback 
{ 
private Form1 form1; 

public iUpdateDownloader_onCompleted(Form1 mainForm) 
{ 
this.form1 = mainForm; 
} 

// Implementation of IDownloadCompletedCallback interface... 
public void Invoke(IDownloadJob downloadJob, IDownloadCompletedCallbackArgs e) 
{ 
form1.iDownloadComplete(); 
} 
} 

// state [in] 
// The caller-specific state that the AsyncState property of the IDownloadJob interface returns. 
// A caller may use this parameter to attach a value to the download job object. 
// This allows the caller to retrieve custom information about that download job object at a later time. 
public class iUpdateDownloader_state 
{ 
private Form1 form1; 

// Implementation of state interface... 
public iUpdateDownloader_state(Form1 mainForm) 
{ 
this.form1 = mainForm; 

form1.setTextBox2Notification("State: Download Started..."); 
} 
} 

#endregion <------- iUpdateDownloader.BeginDownload Objects -------> 

#region <------- iUpdateInstaller.BeginInstall Object Abstract Class's -------> 
// onProgressChanged [in] 
// An IDownloadProgressChangedCallback interface that is called periodically for download progress changes before download is complete. 
public class iUpdateInstaller_onProgressChanged : IInstallationProgressChangedCallback 
{ 
private Form1 form1; 

public iUpdateInstaller_onProgressChanged(Form1 mainForm) 
{ 
this.form1 = mainForm; 
} 

// Implementation of IDownloadProgressChangedCallback interface... 
public void Invoke(IInstallationJob iInstallationJob, IInstallationProgressChangedCallbackArgs e) 
{ 
form1.setTextBox1Notification("Installing Update: " 
+ e.Progress.CurrentUpdateIndex 
+ "/" 
+ iInstallationJob.Updates.Count 
+ " - " 
+ e.Progress.CurrentUpdatePercentComplete + "% Complete"); 
} 
} 

// onCompleted [in] 
// An IDownloadCompletedCallback interface (C++/COM) that is called when an asynchronous download operation is complete. 
public class iUpdateInstaller_onCompleted : IInstallationCompletedCallback 
{ 
private Form1 form1; 

public iUpdateInstaller_onCompleted(Form1 mainForm) 
{ 
this.form1 = mainForm; 
} 

// Implementation of IDownloadCompletedCallback interface... 
public void Invoke(IInstallationJob iInstallationJob, IInstallationCompletedCallbackArgs e) 
{ 
form1.iInstallationComplete(); 
} 
} 

// state [in] 
// The caller-specific state that the AsyncState property of the IDownloadJob interface returns. 
// A caller may use this parameter to attach a value to the download job object. 
// This allows the caller to retrieve custom information about that download job object at a later time. 
public class iUpdateInstaller_state 
{ 
private Form1 form1; 

// Implementation of state interface... 
public iUpdateInstaller_state(Form1 mainForm) 
{ 
this.form1 = mainForm; 

form1.setTextBox2Notification("State: Installation Started..."); 
} 
} 

#endregion <------- iUpdateInstaller.BeginInstall Objects -------> 

} 
}