/// <summary> /// Handles the FormClosing event of the UpdateDownloadForm control. /// </summary> /// <param name="e">The <see cref="FormClosingEventArgs"/> instance containing the event data.</param> protected override void OnFormClosing(FormClosingEventArgs e) { base.OnFormClosing(e); if (!Visible || (e.CloseReason != CloseReason.ApplicationExitCall && e.CloseReason != CloseReason.TaskManagerClosing && e.CloseReason != CloseReason.WindowsShutDown)) { return; } m_client?.CancelAsync(); }
private void kryptonButtonDownload_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(downloadingAddress)) { downloadingClient?.CancelAsync(); downloadingPackageName = ""; downloadingAddress = ""; //downloadingDestinationPath = ""; downloadProgress = 0; downloadingClient = null; return; } if (selectedPackage != null && (!string.IsNullOrEmpty(selectedPackage.Download) /* || selectedPackage.OnlyPro && EngineApp.IsProPlan && selectedPackage.SecureDownload*/)) { downloadingPackageName = selectedPackage.Name; if (!string.IsNullOrEmpty(selectedPackage.Download)) { downloadingAddress = selectedPackage.Download; downloadingDestinationPath = Path.Combine(PackageManager.PackagesFolder, Path.GetFileName(downloadingAddress)); } //else if( selectedPackage.OnlyPro && EngineApp.IsProPlan && selectedPackage.SecureDownload ) //{ // if( !LoginUtility.GetCurrentLicense( out var email, out var hash ) ) // return; // var item = selectedPackage.Name.Replace( ' ', '_' ); // var version = selectedPackage.Version; // var email64 = Convert.ToBase64String( Encoding.UTF8.GetBytes( email.ToLower() ) ).Replace( "=", "" ); // var hash64 = Convert.ToBase64String( Encoding.UTF8.GetBytes( hash ) ).Replace( "=", "" ); // var item64 = Convert.ToBase64String( Encoding.UTF8.GetBytes( item ) ).Replace( "=", "" ); // var version64 = Convert.ToBase64String( Encoding.UTF8.GetBytes( version ) ).Replace( "=", "" ); // downloadingAddress = $@"https://www.neoaxis.com/api/secure_download?email={email64}&hash={hash64}&item={item64}&version={version64}"; // var fileName = $"{item}-{version}.neoaxispackage"; // downloadingDestinationPath = Path.Combine( PackageManager.PackagesFolder, fileName ); //} downloadProgress = 0; Thread thread1 = new Thread(ThreadDownload); thread1.Start(); UpdatePackageControls(); } }
/// <summary> /// Stop download /// </summary> public void CancelDownload() { lock (_locker) { _fileDownloaderWebClient?.CancelAsync(); } }
/// <summary> /// Cancels a pending asynchronous transfer. /// </summary> public void CancelAsync() { if (IsBusy) { _webClient?.CancelAsync(); } }
public override void StopDownload() { _downloadThread?.Abort(); _webClient?.CancelAsync(); _webClient?.Dispose(); OnDownloadItemDownloadCompleted(new DownloadCompletedEventArgs(true, true)); }
private void kryptonButtonDownload_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(downloadingAddress)) { downloadingClient?.CancelAsync(); downloadingPackageIdentifier = ""; downloadingAddress = ""; //downloadingDestinationPath = ""; downloadProgress = 0; downloadingInstallAfterDownload = false; downloadingClient = null; needUpdatePackageControls = true; return; } TryStartDownload(false); }
/// <summary> /// Throws ArgumentException when host name is invalid /// </summary> internal HttpClient(string host, string token, CancellationTokenSource cts) { Client = new WebClient { BaseAddress = host, Encoding = Encoding.UTF8 }; Client.Headers.Add("Content-Type", "application/json"); Client.Headers.Add("Accept", "application/json"); Client.Headers.Add("Private-Token", token); CancellationTokenSource = cts; CancellationTokenSource.Token.Register(() => Client?.CancelAsync()); }
private void OnUpdateProgress(object sender, DownloadProgressChangedEventArgs ea) { bool isCanceled = true; waitDialog?.UpdateProgress( dialogDesc?.WaitMessage, dialogDesc?.ProgressText, dialogDesc?.StatusBarText, ea.ProgressPercentage, 100, false, out isCanceled); if (isCanceled && !IsCanceledByUser) { IsCanceledByUser = isCanceled; webClient?.CancelAsync(); } }
private void CancelOperation() { // Stop any async action taking place. if (downloader != null) { downloader.CancelAsync(); // The coroutine should resume and clean up. return; } if (coroutine != null) { this.StopCoroutine(coroutine.routine); } if (progress > 0) { EditorUtility.ClearProgressBar(); } coroutine = null; downloader = null; progress = 0; }
private XmlDocument GetIndexFile(string url, bool useCache) { XmlDocument result; try { if (useCache && Downloader.mIndexCached != null) { result = Downloader.mIndexCached; } else { WebClient webClient = new WebClient(); webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.Downloader_DownloadFileCompleted); string tempFileName = Path.GetTempFileName(); webClient.DownloadFileAsync(new Uri(url), tempFileName); while (webClient.IsBusy) { if (Downloader.mStopFlag) { webClient.CancelAsync(); result = null; return(result); } Thread.Sleep(100); } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(tempFileName); Downloader.mIndexCached = xmlDocument; result = xmlDocument; } } catch (Exception ex) { MessageBox.Show("GetIndexFile Exception: " + ex.ToString()); result = null; } return(result); }
public async Task Downloanding(Uri url, string filename) { using (WebClient client = new WebClient()) { try { client.DownloadFileAsync(url, filename); ctsForDownload = new CancellationTokenSource(); ctsForDownload.Token.Register(() => { client.CancelAsync(); }); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); client.DownloadFileCompleted += Client_DownloadFileCompleted; } catch (UriFormatException ex) { MessageBox.Show(ex.Message); } catch (WebException ex) { MessageBox.Show(ex.Message); } catch (InvalidOperationException ex) { MessageBox.Show(ex.Message); } catch (Exception) { throw; } finally { ButtonDownloader.IsEnabled = true; TxtUrl.IsEnabled = true; } } }
private async Task <string> RetreiveSDKFile(CancellationToken ct, string sdkName, string sdkUri, string zipPath) { var tries = 3; while (--tries > 0) { try { var uri = new Uri(sdkUri); if (!uri.IsFile) { var client = new WebClient(); var wp = WebRequest.DefaultWebProxy; wp.Credentials = CredentialCache.DefaultCredentials; client.Proxy = wp; Log.LogMessage(Microsoft.Build.Framework.MessageImportance.High, $"Downloading {sdkName} to {zipPath}"); using (ct.Register(() => client.CancelAsync())) { await client.DownloadFileTaskAsync(sdkUri, zipPath); } return(zipPath); } else { return(uri.LocalPath); } } catch (Exception e) { Log.LogWarning($"Failed to download Downloading {sdkName} to {zipPath}. Retrying... ({e.Message})"); } } throw new Exception($"Failed to download {sdkName} to {zipPath}"); }
public void ExampleCancellationToken() { var print = PrintStateMessage("ExampleCancellationToken"); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationToken token = cancellationTokenSource.Token; Task.Run(async() => { var client = new WebClient(); token.Register(() => { print("cancel"); client.CancelAsync(); }); var data = await client.DownloadDataTaskAsync("www.amazon.com"); }, token); print("begin"); Thread.Sleep(100); cancellationTokenSource.Cancel(); print("end"); }
private void DownloadFile() { WebClient client = new WebClient(); //register download events client.DownloadProgressChanged += client_DownloadProgressChanged; client.DownloadFileCompleted += client_DownloadFileCompleted; //start the download client.DownloadFileAsync(address, outFileName); patchDownloadState = DownloadState.InProgress; bool patchDownloadCancelling = false; //wait for the file to be downloaded while (patchDownloadState == DownloadState.InProgress) { if (!patchDownloadCancelling && (Cancelling || Cancelled)) { Description = Messages.DOWNLOAD_AND_EXTRACT_ACTION_DOWNLOAD_CANCELLED_DESC; client.CancelAsync(); patchDownloadCancelling = true; } Thread.Sleep(SLEEP_TIME); } //deregister download events client.DownloadProgressChanged -= client_DownloadProgressChanged; client.DownloadFileCompleted -= client_DownloadFileCompleted; if (patchDownloadState == DownloadState.Cancelled) { throw new CancelledException(); } if (patchDownloadState == DownloadState.Error) { MarkCompleted(patchDownloadError ?? new Exception(Messages.ERROR_UNKNOWN)); } }
public override async Task Request(CancellationToken ct, IProgress <int> progress = null) { using (var client = new WebClient()) { using (ct.Register(() => client.CancelAsync(), useSynchronizationContext: false)) { try { client.DownloadProgressChanged += (s, e) => { progress?.Report(e.ProgressPercentage); }; await client.DownloadFileTaskAsync(Url, TargetLocation); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.RequestCanceled) { throw new OperationCanceledException(); } else { throw ex; } } } } }
void cancelDownload(object sender, System.EventArgs ea) { Console.WriteLine("Cancel clicked!"); if (webClient != null) { webClient.CancelAsync(); } webClient.DownloadProgressChanged -= HandleDownloadProgressChanged; this.downloadButton.TouchUpInside -= cancelDownload; this.downloadButton.TouchUpInside += downloadAsync; this.downloadButton.SetTitle("Download", UIControlState.Normal); this.downloadProgress.Progress = 0.0f; new UIAlertView("Canceled" , "Download has been canceled." , null , "OK" , null).Show(); infoLabel.Text = "Click Dowload button to download the image"; }
/// <summary> /// метод скачивания телеграмма /// </summary> /// <returns></returns> private async Task DownLoad() { cancelTokenSource = new CancellationTokenSource(); var token = cancelTokenSource.Token; await Task.Run( () => { var url = new Uri(@"https://telegram.org/dl/desktop/win64"); using (var client = new WebClient()) { client.DownloadProgressChanged += (s, ee) => { if (token.IsCancellationRequested) { client.CancelAsync(); Dispatcher.StatusName = "Операция отменена"; Dispatcher.ProgressValue = 0; return; } var sizeDownloaded = (ee.BytesReceived / 1048576).ToString("#.# МБ"); Dispatcher.StatusName = $"Идет загрузка: {ee.ProgressPercentage.ToString()}% ({sizeDownloaded})"; Dispatcher.ProgressValue = ee.ProgressPercentage; if (Dispatcher.ProgressValue == 100) { Dispatcher.StatusName = "Загрузка завершена\nПроверьте рабочий стол"; } }; client.DownloadFileAsync( url, $@"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}\Установщик телеги.exe"); } }); }
public void downloadPatchFileCompleted(object sender, AsyncCompletedEventArgs e) { form.downloadStatusLabel.Text = "Status: Download complete"; form.progressBar.Value = 0; PatchMover.moveActive(serverToDownload); List <Patch> patches = patchFilesToPatch(PatchReader.readPatches("patchfile.dat")); if (patches.Count > 0) { downloadPatches(patches); } form.playButton.Enabled = true; form.playButton.Text = "Play"; ApplicationStatus.downloading = false; WebClient client = (WebClient)sender; client.CancelAsync(); client.Dispose(); }
public Update(String _LatestLink) { InitializeComponent(); // Initialization Client = new WebClient(); Timer = new DispatcherTimer(); LatestLink = _LatestLink; #region Buttons events InstallBtn.Click += delegate { // Force install Install(); }; CancelBtn.Click += delegate { Client.CancelAsync(); Utils.RestartApplication(); }; #endregion }
private void BtnExit_Click(object sender, EventArgs e) { if (client != null) { client.CancelAsync(); } if (MessageBox.Show("Do you want to abort update?", "EZBlocker 2", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes) { labelMessage.Text = "Restarting download..."; client.DownloadFileAsync(address, updateFullFile); } else { try { DeleteFile(updateFullFile); } catch { } Close(); } }
void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { if (e.Cancelled) { this.clsWebClient_Status = e.Cancelled.ToString(); } else if (e.Error != null) { this.clsWebClient_Status = e.Error.ToString(); } else { string strMessage = string.Format("{0} Completed", GetFileNameFromLocalPath(m_strLocalPath)); this.clsWebClient_Status = strMessage; } WebClientStatus(); swTime.Reset(); webClient.CancelAsync(); webClient.Dispose(); }
/// <summary> /// Downloads a file asynchronously /// </summary> /// <param name="address">The Uri of the file to download</param> /// <param name="path">The path to download the file to, including the name of /// the file, e.g "C:\Users\Trevor\Downloads\example.txt"</param> /// <exception cref="ToolExecutionException">Thrown if the user cancels the download /// using the instances' LongWaitBroker</exception> /// <returns>True if the downlaod was successful, otherwise false</returns> public bool DownloadFileAsync(Uri address, string path) { // reset download status DownloadComplete = false; DownloadSucceeded = false; Match file = Regex.Match(address.AbsolutePath, @"[^/]*$"); _longWaitBroker.Message = string.Format(Resources.MultiFileAsynchronousDownloadClient_DownloadFileAsync_Downloading__0_, file); _webClient.DownloadFileAsync(address, path); // while downloading, check to see if the user has canceled the operation while (!DownloadComplete) { if (_longWaitBroker.IsCanceled) { _webClient.CancelAsync(); throw new ToolExecutionException( Resources.MultiFileAsynchronousDownloadClient_DownloadFileAsyncWithBroker_Download_canceled_); } } return(DownloadSucceeded); }
private WebClient GetWebClient(CancellationToken cancelToken, IProgress <DownloadProgressChangedEventArgs> progress) { var wc = new WebClient { BaseAddress = BaseAddress, CachePolicy = CachePolicy, UseDefaultCredentials = UseDefaultCredentials, Credentials = Credentials, Headers = Headers, Proxy = Proxy }; if (cancelToken != CancellationToken.None) { cancelToken.Register(() => wc.CancelAsync()); } if (progress != null) { wc.DownloadProgressChanged += (sender, args) => progress.Report(args); } return(wc); }
/// <summary> /// 停止下载(释放资源) /// </summary> public void Dispose() { try { if (client != null) { //取消异步挂起 client.CancelAsync(); //释放页面请求资源 client.Dispose(); client = null; } if (_thread != null) { //结束当前线程 _thread.Abort(); _thread = null; } } catch (Exception) { } }
private void OnCancelButtonClick(object sender, RoutedEventArgs e) { try { switch (int.Parse(btnCancel.Tag.ToString())) { case 0: _webClient.CancelAsync(); break; case 1: Process.Start(_fileName); Close(); break; case 2: Close(); break; } } catch (Exception ex) { _log.ErrorFormat(ex.Message); } }
private async void simpleButton1_Click(object sender, EventArgs e) { if (simpleButton1.Text == "Stop") // Si bouton "Stop" Cliquez faire le code ci-dessous { webClient.CancelAsync(); labelControl2.Text = "Le téléchargement à était arréter"; lblSize.Visible = false; lblSpeed.Visible = false; simpleButton1.Text = "Relancer le téléchargement"; await Task.Delay(3000); File.Delete(location); } else // Si le bouton n'a pas "Stop" comme texte assigné faire le code ci-dessous { DownloadFile(); labelControl2.Text = "Téléchargement du pilotes en cours..."; labelControl2.Visible = true; lblSize.Visible = true; lblSpeed.Visible = true; simpleButton1.Text = "Stop"; } }
private void Download() { if (this.downloadQueue.Any() && !this.downloading) { this.downloading = true; var model = this.downloadQueue.Dequeue(); if (model.DownloadComplete) { return; } model.FileName = GetUniqueFileName(Folder, model.Title); WebClient client = new WebClient(); EventHandler modelCanceled = (s, e) => { if (client.IsBusy) { client.CancelAsync(); } }; model.CancelRequested += modelCanceled; client.DownloadFileCompleted += (s, e) => { DownloadCount--; this.downloading = false; model.CancelRequested -= modelCanceled; model.DownloadComplete = true; Download(); }; client.DownloadProgressChanged += (s, e) => { model.DownloadProgress = e.ProgressPercentage; }; client.DownloadFileAsync(model.Url, model.FileName); } }
IEnumerator DoDownloadCallback() { while (!m_IsComplete) { yield return(0); if (_OnDownloadProgressChanged != null) { _OnDownloadProgressChanged(m_CurrentRelativeUrl, m_DownloadedBytes, m_TotalDownloadBytes); } if (m_PreDownloadedBytes != m_DownloadedBytes) { m_PreDownloadedBytes = m_DownloadedBytes; m_CurConnectTime = 0; } else { m_CurConnectTime += Time.deltaTime; if (m_CurConnectTime > TimeOut) { if (m_client != null) { m_client.CancelAsync(); } } } } if (_OnDownloadCompleted != null) { _OnDownloadCompleted(m_ResultConfig, m_Error); } m_IsComplete = false; m_Error = null; }
private static void CheckForRunningWebServer() { var completedSignal = new ManualResetEventSlim(false); using (var wc = new WebClient()) { Exception fetchError = null; string fetchResult = null; wc.DownloadStringCompleted += (s, e) => { try { fetchResult = e.Result; } catch (Exception exc) { fetchError = exc; } completedSignal.Set(); }; wc.DownloadStringAsync(new Uri(LocalHost)); completedSignal.Wait(2500); if (!completedSignal.IsSet) { try { wc.CancelAsync(); } catch (Exception exc) { fetchError = fetchError ?? exc; } } if (fetchResult == null) { throw new Exception("Failed to connect to local web server at " + LocalHost, fetchError); } } }
public void letsTellToGithubThatWeWannaUseGithubUpdateWayNow() { var client3 = new WebClient(); Uri StringToUri2 = new Uri("https://api.github.com/repos/SoapboxRaceWorld/GameLauncher_NFSW/releases/latest"); client3.Headers.Add("user-agent", "GameLauncherUpdater " + Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)"); client3.CancelAsync(); client3.DownloadStringAsync(StringToUri2); client3.DownloadStringCompleted += (sender3, e3) => { try { ReleaseModel json = new JavaScriptSerializer().Deserialize <ReleaseModel>(e3.Result); if (version != json.tag_name) { Thread thread = new Thread(() => { WebClient client4 = new WebClient(); client4.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Client_DownloadProgressChanged); client4.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted); client4.DownloadFileAsync(new Uri("http://github.com/SoapboxRaceWorld/GameLauncher_NFSW/releases/download/" + json.tag_name + "/Release_" + json.tag_name + ".zip"), tempNameZip); }); thread.Start(); } else { Process.Start(@"GameLauncher.exe"); error("Starting GameLauncher.exe"); } } catch (Exception ex) { error("Failed to update.\n" + ex.Message); } }; }
public override System.Collections.IEnumerator Execute(UTContext context) { if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebPlayer || EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebPlayerStreamed) { Debug.LogWarning("You have currently set the build target to 'Web Player'. This may cause interference with actions that access the internet. If you get an error message about cross domain policy from this action, switch the target to 'PC and Mac Standalone' and try again."); } var theNexusUrl = nexusUrl.EvaluateIn (context); if (string.IsNullOrEmpty (theNexusUrl)) { throw new UTFailBuildException ("You need to specify the nexus URL", this); } var theRepoId = repositoryId.EvaluateIn (context); if (string.IsNullOrEmpty (theRepoId)) { throw new UTFailBuildException ("You need to specify the repository id.", this); } var theUserName = userName.EvaluateIn (context); var thePassword = password.EvaluateIn (context); var theGroupId = groupId.EvaluateIn (context); if (string.IsNullOrEmpty (theGroupId)) { throw new UTFailBuildException ("You need to specify the group id.", this); } var theArtifactId = artifactId.EvaluateIn (context); if (string.IsNullOrEmpty (theArtifactId)) { throw new UTFailBuildException ("You need to specify the artifact id.", this); } var theVersion = version.EvaluateIn (context); if (string.IsNullOrEmpty (theVersion)) { throw new UTFailBuildException ("You need to specify the version.", this); } var thePackaging = packaging.EvaluateIn(context); if (string.IsNullOrEmpty (thePackaging)) { throw new UTFailBuildException ("You need to specify the packaging.", this); } var theExtension = extension.EvaluateIn(context); var theClassifier = classifier.EvaluateIn(context); var theOutputFileName = outputFileName.EvaluateIn (context); if (string.IsNullOrEmpty (theOutputFileName)) { throw new UTFailBuildException ("You need to specify the output file name.", this); } if (Directory.Exists (theOutputFileName)) { throw new UTFailBuildException ("The specified output file " + theOutputFileName + " is a directory.", this); } UTFileUtils.EnsureParentFolderExists (theOutputFileName); // TODO: ignore SSL certs if required using (var wc = new WebClient()) { if (!string.IsNullOrEmpty (theUserName)) { wc.Credentials = new NetworkCredential (theUserName, thePassword); } Uri uri = new Uri (theNexusUrl + "/service/local/artifact/maven/content?" + "g=" + Uri.EscapeUriString (theGroupId) + "&a=" + Uri.EscapeUriString (theArtifactId) + "&v=" + Uri.EscapeUriString (theVersion) + "&r=" + Uri.EscapeUriString (theRepoId) + "&p=" + Uri.EscapeUriString(thePackaging) + (!string.IsNullOrEmpty(theClassifier) ? "&c=" + Uri.EscapeUriString(theClassifier) : "") + (!string.IsNullOrEmpty(theExtension) ? "&e=" + Uri.EscapeUriString(theExtension) : "")); downloadFinished = false; error = false; wc.DownloadFileCompleted += delegate( object sender, AsyncCompletedEventArgs e) { downloadFinished = true; error = e.Error != null; if (error) { Debug.LogError ("An error occured while downloading. " + e.Error.Message, this); } }; wc.DownloadFileAsync (uri, theOutputFileName); do { yield return ""; if (context.CancelRequested) { wc.CancelAsync (); } } while(!downloadFinished); if (!error && !context.CancelRequested) { Debug.Log ("Successfully downloaded artifact to " + theOutputFileName + ".", this); } if (context.CancelRequested) { File.Delete(theOutputFileName); } } }
protected void OnTestButtonClicked(object sender, EventArgs e) { testButton.State = Gtk.StateType.Insensitive; speedStatus.Text = "Testing... "; WebClient japan = new WebClient (); japan.Proxy = new WebProxy ("127.0.0.1:13370"); japan.DownloadDataAsync (new Uri ("http://ipv4.download.thinkbroadband.com:8080/5MB.zip")); Stopwatch tmr = new Stopwatch (); tmr.Start (); double jSpeed; japan.DownloadDataCompleted += delegate(object sdr, DownloadDataCompletedEventArgs E) { if (true) { speedStatus.Text = ""; jSpeed = (5000000 / 1024.0) / (tmr.ElapsedMilliseconds / 1000); GLib.Timeout.Add (200, updateStatus); theSpeed = jSpeed.ToString ().Substring (0, 6); theSpeed = "Result: " + Math.Round (jSpeed).ToString () + " KiB/s"; tmr.Reset (); tmr.Stop (); japan.CancelAsync (); japan.CancelAsync (); japan.CancelAsync (); testButton.Sensitive = true; } }; }
public override System.Collections.IEnumerator Execute(UTContext context) { if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebPlayer || EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebPlayerStreamed) { Debug.LogWarning("You have currently set the build target to 'Web Player'. This may cause interference with actions that access the internet. If you get an error message about cross domain policy from this action, switch the target to 'PC and Mac Standalone' and try again."); } var theNexusUrl = nexusUrl.EvaluateIn (context); if (string.IsNullOrEmpty (theNexusUrl)) { throw new UTFailBuildException ("You need to specify the nexus URL", this); } var theRepoId = repositoryId.EvaluateIn (context); if (string.IsNullOrEmpty (theRepoId)) { throw new UTFailBuildException ("You need to specify the repository id.", this); } var theUserName = userName.EvaluateIn (context); var thePassword = password.EvaluateIn (context); var theGroupId = groupId.EvaluateIn (context); if (string.IsNullOrEmpty (theGroupId)) { throw new UTFailBuildException ("You need to specify the group id.", this); } var theArtifactId = artifactId.EvaluateIn (context); if (string.IsNullOrEmpty (theArtifactId)) { throw new UTFailBuildException ("You need to specify the artifact id.", this); } var theVersion = version.EvaluateIn (context); if (string.IsNullOrEmpty (theVersion)) { throw new UTFailBuildException ("You need to specify the version.", this); } var thePackaging = packaging.EvaluateIn (context); if (string.IsNullOrEmpty (thePackaging)) { throw new UTFailBuildException ("You need to specify the packaging.", this); } var theExtension = extension.EvaluateIn (context); var theClassifier = classifier.EvaluateIn (context); var theInputFileName = inputFileName.EvaluateIn (context); if (string.IsNullOrEmpty (theInputFileName)) { throw new UTFailBuildException ("You need to specify the input file name.", this); } if (Directory.Exists (theInputFileName)) { throw new UTFailBuildException ("The specified input file " + theInputFileName + " is a directory.", this); } if (!File.Exists (theInputFileName)) { throw new UTFailBuildException ("The specified input file " + theInputFileName + " does not exist.", this); } WWWForm form = new WWWForm (); form.AddField ("r", theRepoId); form.AddField ("g", theGroupId); form.AddField ("a", theArtifactId); form.AddField ("v", theVersion); if (!string.IsNullOrEmpty (thePackaging)) { form.AddField ("p", thePackaging); } if (!string.IsNullOrEmpty (theClassifier)) { form.AddField ("c", theClassifier); } if (!string.IsNullOrEmpty (theExtension)) { form.AddField ("e", theExtension); } var bytes = File.ReadAllBytes (theInputFileName); form.AddBinaryData ("file", bytes, new FileInfo (theInputFileName).Name); var hash = UTils.ComputeHash (bytes); if (UTPreferences.DebugMode) { Debug.Log ("SHA1-Hash of file to upload: " + hash); } string authString = theUserName + ":" + thePassword; var authBytes = System.Text.UTF8Encoding.UTF8.GetBytes (authString); var headers = new Hashtable (); foreach (var key in form.headers.Keys) { headers.Add (key, form.headers [key]); } headers.Add ("Authorization", "Basic " + System.Convert.ToBase64String (authBytes)); var url = UTils.BuildUrl (theNexusUrl, "/service/local/artifact/maven/content"); using (var www = new WWW (url, form.data, headers)) { do { yield return ""; } while(!www.isDone && !context.CancelRequested); if (UTPreferences.DebugMode) { Debug.Log ("Server Response: " + www.text); } } if (!context.CancelRequested) { using (var wc = new WebClient()) { if (!string.IsNullOrEmpty (theUserName)) { Debug.Log("Setting credentials" ); wc.Credentials = new NetworkCredential (theUserName, thePassword); } Uri uri = new Uri (UTils.BuildUrl (theNexusUrl, "/service/local/artifact/maven/resolve?") + "g=" + Uri.EscapeUriString (theGroupId) + "&a=" + Uri.EscapeUriString (theArtifactId) + "&v=" + Uri.EscapeUriString (theVersion) + "&r=" + Uri.EscapeUriString (theRepoId) + "&p=" + Uri.EscapeUriString (thePackaging) + (!string.IsNullOrEmpty (theClassifier) ? "&c=" + Uri.EscapeUriString (theClassifier) : "") + (!string.IsNullOrEmpty (theExtension) ? "&e=" + Uri.EscapeUriString (theExtension) : "")); var downloadFinished = false; var error = false; string result = null; wc.DownloadStringCompleted += delegate( object sender, DownloadStringCompletedEventArgs e) { downloadFinished = true; error = e.Error != null; if (error) { Debug.LogError ("An error occured while downloading artifact information. " + e.Error.Message, this); } else { result = (string)e.Result; } }; wc.DownloadStringAsync (uri); do { yield return ""; if (context.CancelRequested) { wc.CancelAsync (); } } while(!downloadFinished); if (!context.CancelRequested) { if (!error) { if (UTPreferences.DebugMode) { Debug.Log ("Server Response: " + result); } if (result.Contains ("<sha1>" + hash + "</sha1>")) { Debug.Log ("Successfully uploaded artifact " + theInputFileName + ".", this); } else { throw new UTFailBuildException ("Upload failed. Checksums do not match.", this); } } else { throw new UTFailBuildException ("Artifact verification failed", this); } } } } }