Ejemplo n.º 1
0
        private void BitsAction(Action <IBackgroundCopyJob> action)
        {
            IBackgroundCopyManager bitsManager = null;
            IBackgroundCopyJob     bitsJob     = null;

            try {
                bitsManager = (IBackgroundCopyManager) new BackgroundCopyManager();
                bitsManager.GetJob(ref id, out bitsJob);
                if (bitsJob != null)
                {
                    action(bitsJob);
                }
            } catch (COMException cex) {
                string error;
                bitsManager.GetErrorDescription(cex.ErrorCode, 1033, out error);
                throw new InvalidOperationException(error, cex);
            } finally {
                if (bitsJob != null)
                {
                    Marshal.ReleaseComObject(bitsJob);
                }
                if (bitsManager != null)
                {
                    Marshal.ReleaseComObject(bitsManager);
                }
            }
        }
        /// <summary>
        /// Attemps to find the job with the given identifier.
        /// </summary>
        /// <param name="id">The job's identifier.</param>
        /// <returns>
        /// The job or <see langword="null" /> if not found.
        /// </returns>
        /// <exception cref="System.InvalidOperationException">An unexpected exception occurred trying to find the given job.</exception>
        public IDownloadJob FindJob(Guid id)
        {
            IBackgroundCopyManager bitsManager = null;
            IBackgroundCopyJob     bitsJob     = null;

            try {
                bitsManager = (IBackgroundCopyManager) new BackgroundCopyManager();
                bitsManager.GetJob(ref id, out bitsJob);

                if (bitsJob != null)
                {
                    return(new DownloadJob(id, bitsJob));
                }

                return(null);
            } catch (COMException cex) {
                if ((uint)cex.ErrorCode == (uint)BG_RESULT.BG_E_NOT_FOUND)
                {
                    return(null);
                }

                string error;
                bitsManager.GetErrorDescription(cex.ErrorCode, 1033, out error);
                throw new InvalidOperationException(error, cex);
            } finally {
                if (bitsJob != null)
                {
                    Marshal.ReleaseComObject(bitsJob);
                }
                if (bitsManager != null)
                {
                    Marshal.ReleaseComObject(bitsManager);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Verifies if the task has a download job assigned, meaning this is a retry.
        /// If a transferred job is detected, the job is completed and the event
        /// OnDownloadCompleted is raised.
        /// </summary>
        /// <param name="copyManager">The BITS background copy manager to use</param>
        /// <param name="task">The DownloadTask to get the data from</param>
        /// <param name="copyJob">If an in progress BITS job is found for this task, this job is returned on this parameter</param>
        /// <returns>A Boolean value indicating whether the job is completed or not.
        /// A True value means that the job has been completed by BITS while a False value
        /// means that the job doesn't exists or can be resumed.
        /// </returns>
        private bool CheckForResumeAndProceed(IBackgroundCopyManager copyManager, DownloadTask task,
                                              out IBackgroundCopyJob copyJob)
        {
            copyJob = null;
            if (task.JobId != null && task.DownloadErrorResumeCount < BackgroundDownloadManager.MaxDownloadErrorResumes)
            {
                Guid jobId = task.JobId.Value;

                try
                {
                    copyManager.GetJob(ref jobId, out copyJob);
                    if (copyJob != null)
                    {
                        BG_JOB_STATE jobState;
                        copyJob.GetState(out jobState);
                        if (jobState == BG_JOB_STATE.BG_JOB_STATE_TRANSFERRED)
                        {
                            OnJobTransferred(task, copyJob);
                            return(true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(
                        new DownloaderException(
                            String.Format(
                                "The BITSDownloader cannot connect to the job '{0}' for the task '{1}' so a new BITS job will be created.",
                                jobId, task.TaskId), ex));
                }
            }
            return(false);
        }
Ejemplo n.º 4
0
 public UpdateJob FindJob(System.Guid jobId)
 {
     try
     {
         IBackgroundCopyJob foundJob;
         GUID guid = UpdateUtility.ConvertToBitsGuid(jobId);
         copyManager.GetJob(ref guid, out foundJob);
         return(new UpdateJob(foundJob));
     }
     catch (COMException ex)
     {
         throw new Exception(String.Format("Error finding job ({0}).", ex.Message));
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Cancels an asynhronous download operation.
        /// </summary>
        /// <param name="task">The <see cref="DownloadTask"/> for the operation.</param>
        /// <returns>Indicates whether the operation was canceled.</returns>
        public bool CancelDownload(DownloadTask task)
        {
            IBackgroundCopyManager copyManager = null;
            IBackgroundCopyJob     pJob        = null;

            if (task.JobId != null)
            {
                try
                {
                    Guid jobID = task.JobId.Value;
                    copyManager = (IBackgroundCopyManager) new BackgroundCopyManager();
                    copyManager.GetJob(ref jobID, out pJob);

                    if (pJob != null)
                    {
                        pJob.Cancel();
                    }
                }
                catch (COMException)
                {
                    /* we may come up empty when trying to get the job */
                }
                finally
                {
                    if (copyManager != null)
                    {
                        Marshal.ReleaseComObject(copyManager);
                    }

                    if (pJob != null)
                    {
                        Marshal.ReleaseComObject(pJob);
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 检查/启动/结束传输作业进程,参数文件节点为空的取当前文件节点
        /// </summary>
        /// <param name="nodeFile">要管理的传输文件节点</param>
        static private void HandleBits(Object o)
        {
            IBackgroundCopyManager bcm = null;
            IBackgroundCopyJob     job = null;
            XmlNode nodeFile           = null;

            nodeFile = BitsFileList.GetCurrentFile();
            if (null == nodeFile)
            {
                return;
            }
            ((XmlElement)nodeFile).SetAttribute("state", "doing");
            try
            {
                // Create BITS object
                bcm = (IBackgroundCopyManager) new BackgroundCopyManager();
                Guid jobID = Guid.Empty;
                if (null != nodeFile.Attributes["jobguid"] && !string.IsNullOrEmpty(nodeFile.Attributes["jobguid"].Value))
                { // Do we already have a job in place?
                    jobID = new Guid(nodeFile.Attributes["jobguid"].Value);
                    BG_JOB_STATE state;
                    try
                    {
                        bcm.GetJob(ref jobID, out job); // Get the BITS job object
                        job.GetState(out state);        // check its state
                        switch (state)
                        {
                        case BG_JOB_STATE.BG_JOB_STATE_ERROR:     // If it is an error, re-poll
                            job.Complete();
                            nodeFile.Attributes.RemoveNamedItem("jobguid");
                            Marshal.ReleaseComObject(job);
                            job = null;
                            break;

                        case BG_JOB_STATE.BG_JOB_STATE_CANCELLED:
                        case BG_JOB_STATE.BG_JOB_STATE_TRANSFERRED:     // If we got the job
                            job.Complete();                             // then complete it
                            nodeFile.ParentNode.RemoveChild(nodeFile);
                            Marshal.ReleaseComObject(job);
                            Marshal.ReleaseComObject(bcm);
                            return;

                        default:
                            Marshal.ReleaseComObject(bcm);
                            return;
                        }
                    }
                    catch (Exception e)
                    {
                        NameValueCollection errInfo = new NameValueCollection();
                        errInfo["文件类别"]   = nodeFile.Attributes["doctype"].Value;
                        errInfo["远程文件"]   = nodeFile.Attributes["srcurl"].Value;
                        errInfo["作业Guid"] = nodeFile.Attributes["jobguid"].Value;
                        ExceptionManager.Publish(e, errInfo);
                        if (null != (e as UnauthorizedAccessException))
                        {
                            if (job != null)
                            {
                                Marshal.ReleaseComObject(job);
                            }
                            if (bcm != null)
                            {
                                Marshal.ReleaseComObject(bcm);
                            }
                            return;
                        }
                        COMException exCOM = e as COMException;
                        if (null != exCOM && exCOM.ErrorCode == unchecked ((Int32)0x80200001))
                        {
                            nodeFile.Attributes.RemoveNamedItem("jobguid");
                        }
                        else
                        {
                            return;
                        }
                    }
                }

                // Create a bits job to download the next expected update
                if (null != nodeFile && (null == nodeFile.Attributes["jobguid"] || string.IsNullOrEmpty(nodeFile.Attributes["jobguid"].Value)))
                {
                    bcm.CreateJob("下载远程文件",
                                  BG_JOB_TYPE.BG_JOB_TYPE_DOWNLOAD, out jobID, out job);
                    string doctype = nodeFile.Attributes["doctype"].Value;
                    string srcurl  = nodeFile.Attributes["srcurl"].Value;
                    string dest    = nodeFile.Attributes["localname"].Value;

                    job.SetDescription("下载文件位置: " + doctype);
                    job.AddFile(srcurl, dest);
                    job.Resume(); // start the job in action
                    ((XmlElement)nodeFile).SetAttribute("jobguid", jobID.ToString());
                }
                if (bcm != null)
                {
                    Marshal.ReleaseComObject(bcm);
                }
                return;
            }
            catch { }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// returns a job status enum for a particular job identified by its GUID
        /// </summary>
        /// <param name="jobId">a guid for the job requested</param>
        /// <returns>a JobStatus describing the state of the job</returns>
        JobStatus IDownloader.GetJobStatus(Guid jobId)
        {
            IBackgroundCopyManager backGroundCopyManager = null;
            IBackgroundCopyJob     backGroundCopyJob     = null;
            BG_JOB_STATE           state;
            string errMessage = "";
            string jobName    = "";
            string jobDesc    = "";
            string error      = "";

            try
            {
                backGroundCopyManager = (IBackgroundCopyManager) new BackgroundCopyManager();
                backGroundCopyManager.GetJob(ref jobId, out backGroundCopyJob);

                //  get job name
                backGroundCopyJob.GetDisplayName(out jobName);
                //  get job desc
                backGroundCopyJob.GetDescription(out jobDesc);
                //  get job state enum value
                backGroundCopyJob.GetState(out state);

                switch (state)
                {
                case BG_JOB_STATE.BG_JOB_STATE_ERROR:
                {
                    //  use utility method to handle error:
                    HandleDownloadErrorCancelJob(backGroundCopyJob, ref errMessage);

                    //  return status as error
                    return(JobStatus.Error);
                }

                case BG_JOB_STATE.BG_JOB_STATE_TRANSIENT_ERROR:
                {
                    //    NOTE:  if transient, just treat as full error.  During testing about 90% of transients
                    //				resulted in full failure.  Cleanup.
                    //  use utility method to handle error:
                    HandleDownloadErrorCancelJob(backGroundCopyJob, ref errMessage);

                    //  return status as error
                    return(JobStatus.Error);
                }

                case BG_JOB_STATE.BG_JOB_STATE_TRANSFERRED:
                {
                    //  tell BITS to transfer to us and stop thinking about the job
                    backGroundCopyJob.Complete();
                    // remove job from collection to be Dispose()ed
                    RemoveCopyJobEntry(jobId);
                    return(JobStatus.Ready);
                }

                case BG_JOB_STATE.BG_JOB_STATE_CANCELLED:
                {
                    //  use utility method to handle error:
                    HandleDownloadErrorCancelJob(backGroundCopyJob, ref errMessage);

                    //  return status as cancelled
                    return(JobStatus.Cancelled);
                }

                default:
                    return(JobStatus.Downloading);
                }
            }
            catch (ThreadInterruptedException tie)
            {
                //  if interrupted, clean up job
                HandleDownloadErrorCancelJob(backGroundCopyJob, ref errMessage);
                ApplicationUpdateManager.TraceWrite(tie, "[BITSDownloader.Download]", "RES_TIEInBITS", "N/A");
                throw tie;
            }
            catch (Exception e)
            {
                //  use utility method to handle error:
                HandleDownloadErrorCancelJob(backGroundCopyJob, ref errMessage);
                //  bad to catch all exceptions, but OK because we adorn it with necessary additional info then pass it up as innerException
                error = ApplicationUpdateManager.TraceWrite(e, "[BITSDownloader.GetJobStatus]", "RES_EXCEPTION_BITSOtherError", jobId, jobName, jobDesc);
                //  publish
                Exception newE = new Exception(error, e);
                ExceptionManager.Publish(newE);
                //  rethrow;
                throw newE;
            }
            finally
            {
                if (backGroundCopyManager != null)
                {
                    Marshal.ReleaseComObject(backGroundCopyManager);
                }
                if (backGroundCopyJob != null)
                {
                    Marshal.ReleaseComObject(backGroundCopyJob);
                }
            }
        }