コード例 #1
0
        /// <summary>
        /// Runs the reducer task.
        /// </summary>
        public async Task RunAsync()
        {
            //Set up the Batch Service credentials used to authenticate with the Batch Service.
            BatchCredentials credentials = new BatchCredentials(
                this.configurationSettings.BatchAccountName,
                this.configurationSettings.BatchAccountKey);

            using (IBatchClient batchClient = BatchClient.Connect(this.configurationSettings.BatchServiceUrl, credentials))
            {
                using (IWorkItemManager workItemManager = batchClient.OpenWorkItemManager())
                {
                    //Gather each Mapper tasks output and write it to standard out.
                    for (int i = 0; i < this.configurationSettings.NumberOfMapperTasks; i++)
                    {
                        string mapperTaskName = Helpers.GetMapperTaskName(i);

                        //Download the standard out from each mapper task.
                        ITaskFile taskFile = await workItemManager.GetTaskFileAsync(
                            this.workItemName,
                            this.jobName,
                            mapperTaskName,
                            Microsoft.Azure.Batch.Constants.StandardOutFileName);

                        string taskFileString = await taskFile.ReadAsStringAsync();

                        Console.WriteLine(taskFileString);

                        Console.WriteLine();
                    }
                }
            }
        }
コード例 #2
0
        public void When_WorkItemExecuted_Expect_ShouldRaiseStausUpdateEvents()
        {
            IWorkItemManager workerManager = WorkItemManagerProvider.GetWorkItemManager();

            //Arrange
            var moqWorkItem = new Mock <IWorkItem>();

            moqWorkItem.Setup(c => c.Name).Returns("A");
            moqWorkItem.Setup(c => c.Duration).Returns(100);

            Mock <IAsyncRun> moqAsyncService = new Mock <IAsyncRun>();

            moqAsyncService.Setup(c => c.DoTask(It.IsAny <IWorkItem>()))
            .Callback <IWorkItem>((workItem) =>
            {
                moqWorkItem.Raise(x => x.WorkItemStatusUpdated += null,
                                  moqWorkItem.Object,
                                  new WorkItemStatusUpdatedEventArgs(WorkItemStatus.Completed));
            });
            workerManager.Service = (IAsyncRun)moqAsyncService.Object;

            //Act
            workerManager.AddWorkItem((IWorkItem)moqWorkItem.Object);

            //Assert
            moqAsyncService.Verify(c => c.DoTask(It.IsAny <IWorkItem>()), Times.Once);
        }
コード例 #3
0
 /// <summary>
 /// Returns a list of WorkItems
 /// </summary>
 /// <returns></returns>
 public IEnumerable <ICloudWorkItem> ListWorkItems(DetailLevel detailLevel = null)
 {
     using (IWorkItemManager wiManager = this.Client.OpenWorkItemManager())
     {
         return(wiManager.ListWorkItems(detailLevel));
     }
 }
コード例 #4
0
 public Task <ICloudTask> GetTaskAsync(string workItemName, string jobName, string taskName, DetailLevel detailLevel)
 {
     using (IWorkItemManager wiManager = this.Client.OpenWorkItemManager())
     {
         return(wiManager.GetTaskAsync(workItemName, jobName, taskName, detailLevel));
     }
 }
コード例 #5
0
 /// <summary>
 /// Adds a task.
 /// </summary>
 /// <param name="options">The options describing the task to add.</param>
 /// <returns></returns>
 public async Task AddTaskAsync(AddTaskOptions options)
 {
     using (IWorkItemManager workItemManager = this.Client.OpenWorkItemManager())
     {
         ICloudTask unboundTask = new CloudTask(options.TaskName, options.CommandLine);
         await workItemManager.AddTaskAsync(options.WorkItemName, options.JobName, unboundTask);
     }
 }
コード例 #6
0
        /// <summary>
        /// Lists the Tasks matching the specified filter options
        /// </summary>
        /// <param name="options">The options to use when querying for Tasks</param>
        /// <returns>The Tasks matching the specified filter options</returns>
        public IEnumerable <PSCloudTask> ListTasks(ListTaskOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if ((string.IsNullOrEmpty(options.WorkItemName) || string.IsNullOrEmpty(options.JobName)) && options.Job == null)
            {
                throw new ArgumentNullException(Resources.GBT_NoJob);
            }

            // Get the single Task matching the specified name
            if (!string.IsNullOrEmpty(options.TaskName))
            {
                WriteVerbose(string.Format(Resources.GBT_GetByName, options.TaskName, options.JobName, options.WorkItemName));
                using (IWorkItemManager wiManager = options.Context.BatchOMClient.OpenWorkItemManager())
                {
                    ICloudTask  task   = wiManager.GetTask(options.WorkItemName, options.JobName, options.TaskName, additionalBehaviors: options.AdditionalBehaviors);
                    PSCloudTask psTask = new PSCloudTask(task);
                    return(new PSCloudTask[] { psTask });
                }
            }
            // List Tasks using the specified filter
            else
            {
                if (options.MaxCount <= 0)
                {
                    options.MaxCount = Int32.MaxValue;
                }
                string           jName = options.Job == null ? options.JobName : options.Job.Name;
                ODATADetailLevel odata = null;
                if (!string.IsNullOrEmpty(options.Filter))
                {
                    WriteVerbose(string.Format(Resources.GBT_GetByOData, jName, options.MaxCount));
                    odata = new ODATADetailLevel(filterClause: options.Filter);
                }
                else
                {
                    WriteVerbose(string.Format(Resources.GBT_GetNoFilter, jName, options.MaxCount));
                }

                IEnumerableAsyncExtended <ICloudTask> tasks = null;
                if (options.Job != null)
                {
                    tasks = options.Job.omObject.ListTasks(odata, options.AdditionalBehaviors);
                }
                else
                {
                    using (IWorkItemManager wiManager = options.Context.BatchOMClient.OpenWorkItemManager())
                    {
                        tasks = wiManager.ListTasks(options.WorkItemName, options.JobName, odata, options.AdditionalBehaviors);
                    }
                }
                Func <ICloudTask, PSCloudTask> mappingFunction = t => { return(new PSCloudTask(t)); };
                return(new PSAsyncEnumerable <PSCloudTask, ICloudTask>(tasks, mappingFunction).Take(options.MaxCount));
            }
        }
コード例 #7
0
        public void When_GetTwoWorkItemManagerObjects_Expect_ShouldRefSameObject()
        {
            //Arrange
            IWorkItemManager workerManager1 = WorkItemManagerProvider.GetWorkItemManager();
            IWorkItemManager workerManager2 = WorkItemManagerProvider.GetWorkItemManager();

            //Assert
            Should.ReferenceEquals(workerManager1, workerManager2);
        }
コード例 #8
0
 public SpotlightImageLoader(IWorkItemManager workItemManager)
 {
     Source = new WallpaperSource
     {
         Name    = "Spotlight",
         BaseUri = new Uri("http://arc.msn.com/")
     };
     _workItemManager = workItemManager;
 }
コード例 #9
0
 public BingWallpaperLoader(IWorkItemManager workItemManager)
 {
     _workItemManager = workItemManager;
     Source           = new WallpaperSource
     {
         Name    = "Bing",
         BaseUri = new Uri(URI)
     };
 }
コード例 #10
0
        /// <summary>
        /// Downloads a Task file using the specified options.
        /// </summary>
        /// <param name="options">The download options</param>
        public void DownloadTaskFile(DownloadTaskFileOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if ((string.IsNullOrWhiteSpace(options.WorkItemName) || string.IsNullOrWhiteSpace(options.JobName) || string.IsNullOrWhiteSpace(options.TaskName) ||
                 string.IsNullOrWhiteSpace(options.TaskFileName)) && options.TaskFile == null)
            {
                throw new ArgumentNullException(Resources.GBTFC_NoTaskFileSpecified);
            }

            ITaskFile taskFile = null;

            if (options.TaskFile == null)
            {
                using (IWorkItemManager wiManager = options.Context.BatchOMClient.OpenWorkItemManager())
                {
                    taskFile = wiManager.GetTaskFile(options.WorkItemName, options.JobName, options.TaskName, options.TaskFileName, options.AdditionalBehaviors);
                }
            }
            else
            {
                taskFile = options.TaskFile.omObject;
            }

            string path = null;
            // The task file object's name is a relative path that includes directories.
            string fileName = Path.GetFileName(taskFile.Name);

            if (string.IsNullOrWhiteSpace(options.DestinationPath))
            {
                // If no destination is specified, just save the file to the local directory
                path = fileName;
            }
            else
            {
                path = Path.Combine(options.DestinationPath, fileName);
            }

            WriteVerbose(string.Format(Resources.GBTFC_Downloading, taskFile.Name, path));
            if (options.Stream != null)
            {
                // Used for testing.
                // Don't dispose supplied Stream
                taskFile.CopyToStream(options.Stream, options.AdditionalBehaviors);
            }
            else
            {
                using (FileStream fs = new FileStream(path, FileMode.Create))
                {
                    taskFile.CopyToStream(fs, options.AdditionalBehaviors);
                }
            }
        }
コード例 #11
0
        /// <summary>
        /// Lists the Task files matching the specified filter options
        /// </summary>
        /// <param name="options">The options to use when querying for Task files</param>
        /// <returns>The Task files matching the specified filter options</returns>
        public IEnumerable <PSTaskFile> ListTaskFiles(ListTaskFileOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if ((string.IsNullOrWhiteSpace(options.WorkItemName) || string.IsNullOrWhiteSpace(options.JobName) || string.IsNullOrWhiteSpace(options.TaskName)) &&
                options.Task == null)
            {
                throw new ArgumentNullException(Resources.GBTF_NoTaskSpecified);
            }

            // Get the single Task file matching the specified name
            if (!string.IsNullOrEmpty(options.TaskFileName))
            {
                WriteVerbose(string.Format(Resources.GBTF_GetByName, options.TaskFileName, options.TaskName));
                using (IWorkItemManager wiManager = options.Context.BatchOMClient.OpenWorkItemManager())
                {
                    ITaskFile  taskFile   = wiManager.GetTaskFile(options.WorkItemName, options.JobName, options.TaskName, options.TaskFileName, options.AdditionalBehaviors);
                    PSTaskFile psTaskFile = new PSTaskFile(taskFile);
                    return(new PSTaskFile[] { psTaskFile });
                }
            }
            // List Task files using the specified filter
            else
            {
                string           tName = options.Task == null ? options.TaskName : options.Task.Name;
                ODATADetailLevel odata = null;
                if (!string.IsNullOrEmpty(options.Filter))
                {
                    WriteVerbose(string.Format(Resources.GBTF_GetByOData, tName));
                    odata = new ODATADetailLevel(filterClause: options.Filter);
                }
                else
                {
                    WriteVerbose(string.Format(Resources.GBTF_NoFilter, tName));
                }

                IEnumerableAsyncExtended <ITaskFile> taskFiles = null;
                if (options.Task != null)
                {
                    taskFiles = options.Task.omObject.ListTaskFiles(options.Recursive, odata, options.AdditionalBehaviors);
                }
                else
                {
                    using (IWorkItemManager wiManager = options.Context.BatchOMClient.OpenWorkItemManager())
                    {
                        taskFiles = wiManager.ListTaskFiles(options.WorkItemName, options.JobName, options.TaskName, options.Recursive, odata, options.AdditionalBehaviors);
                    }
                }
                Func <ITaskFile, PSTaskFile> mappingFunction = f => { return(new PSTaskFile(f)); };
                return(PSAsyncEnumerable <PSTaskFile, ITaskFile> .CreateWithMaxCount(
                           taskFiles, mappingFunction, options.MaxCount, () => WriteVerbose(string.Format(Resources.MaxCount, options.MaxCount))));
            }
        }
コード例 #12
0
ファイル: SimpleBugStrategy.cs プロジェクト: strince/mail2bug
 public SimpleBugStrategy(Config.InstanceConfig config, IWorkItemManager workItemManager)
 {
     _config = config;
     _workItemManager = workItemManager;
     _ackEmailHandler = new AckEmailHandler(config);
     _messageToWorkItemMapper = new MessageToWorkItemMapper(
         _config.EmailSettings.AppendOnlyEmailTitleRegex,
         _config.EmailSettings.AppendOnlyEmailBodyRegex,
         _workItemManager.WorkItemsCache);
 }
コード例 #13
0
 /// <summary>
 /// Deletes a WorkItem used in a Scenario test.
 /// TODO: Replace with remove WorkItem client method when it exists.
 /// </summary>
 public static void DeleteWorkItem(BatchAccountContext context, string workItemName)
 {
     if (HttpMockServer.Mode == HttpRecorderMode.Record)
     {
         using (IWorkItemManager wiManager = context.BatchOMClient.OpenWorkItemManager())
         {
             wiManager.DeleteWorkItem(workItemName);
         }
     }
 }
コード例 #14
0
 public SimpleBugStrategy(Config.InstanceConfig config, IWorkItemManager workItemManager)
 {
     _config                  = config;
     _workItemManager         = workItemManager;
     _ackEmailHandler         = new AckEmailHandler(config);
     _messageToWorkItemMapper = new MessageToWorkItemMapper(
         _config.EmailSettings.AppendOnlyEmailTitleRegex,
         _config.EmailSettings.AppendOnlyEmailBodyRegex,
         _workItemManager.WorkItemsCache);
 }
コード例 #15
0
 /// <summary>
 /// Terminates a job
 /// TODO: Replace with terminate Job client method when it exists.
 /// </summary>
 public static void TerminateJob(BatchAccountContext context, string workItemName, string jobName)
 {
     if (HttpMockServer.Mode == HttpRecorderMode.Record)
     {
         using (IWorkItemManager wiManager = context.BatchOMClient.OpenWorkItemManager())
         {
             wiManager.TerminateJob(workItemName, jobName);
         }
     }
 }
コード例 #16
0
 public WallpaperJob(WallpaperLoaderHandler[] loaders,
                     IWallpaperManager wallpaperManager,
                     IWorkItemManager workItemManager,
                     ILogger logger)
 {
     _loaders          = loaders;
     _wallpaperManager = wallpaperManager;
     _workItemManager  = workItemManager;
     _logger           = logger;
 }
コード例 #17
0
        /// <summary>
        /// Builds a PSCloudWorkItem for testing
        /// </summary>
        public static PSCloudWorkItem CreatePSCloudWorkItem()
        {
            BatchAccountContext context = CreateBatchContextWithKeys();

            using (IWorkItemManager wiManager = context.BatchOMClient.OpenWorkItemManager())
            {
                ICloudWorkItem workItem = wiManager.CreateWorkItem("testWorkItem");
                return(new PSCloudWorkItem(workItem));
            }
        }
コード例 #18
0
 public WallpaperDeletedCleaner(ILogger logger,
                                IWallpaperManager wallpaperManager,
                                IWallpaperActionManager wallpaperActionManager,
                                IWorkItemManager workItemManager)
 {
     _logger                 = logger;
     _wallpaperManager       = wallpaperManager;
     _wallpaperActionManager = wallpaperActionManager;
     _workItemManager        = workItemManager;
 }
コード例 #19
0
        /// <summary>
        /// Creates a new task
        /// </summary>
        /// <param name="parameters">The parameters to use when creating the task</param>
        public void CreateTask(NewTaskParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            CloudTask task = new CloudTask(parameters.TaskName, parameters.CommandLine);

            task.RunElevated = parameters.RunElevated;

            if (parameters.EnvironmentSettings != null)
            {
                task.EnvironmentSettings = new List <IEnvironmentSetting>();
                foreach (DictionaryEntry d in parameters.EnvironmentSettings)
                {
                    EnvironmentSetting setting = new EnvironmentSetting(d.Key.ToString(), d.Value.ToString());
                    task.EnvironmentSettings.Add(setting);
                }
            }

            if (parameters.ResourceFiles != null)
            {
                task.ResourceFiles = new List <IResourceFile>();
                foreach (DictionaryEntry d in parameters.ResourceFiles)
                {
                    ResourceFile file = new ResourceFile(d.Value.ToString(), d.Key.ToString());
                    task.ResourceFiles.Add(file);
                }
            }

            if (parameters.AffinityInformation != null)
            {
                task.AffinityInformation = parameters.AffinityInformation.omObject;
            }

            if (parameters.TaskConstraints != null)
            {
                task.TaskConstraints = parameters.TaskConstraints.omObject;
            }

            WriteVerbose(string.Format(Resources.NBT_CreatingTask, parameters.TaskName));
            if (parameters.Job != null)
            {
                parameters.Job.omObject.AddTask(task, parameters.AdditionalBehaviors);
            }
            else
            {
                using (IWorkItemManager wiManager = parameters.Context.BatchOMClient.OpenWorkItemManager())
                {
                    wiManager.AddTask(parameters.WorkItemName, parameters.JobName, task, parameters.AdditionalBehaviors);
                }
            }
        }
コード例 #20
0
 public GoogleEarthImageLoader(IWorkItemManager workItemManager)
 {
     Source = new WallpaperSource
     {
         Name    = "Google-EarthView",
         BaseUri = new Uri("https://www.gstatic.com/prettyearth/assets/data/v3/")
     };
     _httpClient             = new HttpClient();
     _httpClient.BaseAddress = Source.BaseUri;
     _workItemManager        = workItemManager;
 }
コード例 #21
0
 /// <summary>
 /// Creates a test Task for use in Scenario tests.
 /// TODO: Replace with new Task client method when it exists.
 /// </summary>
 public static void CreateTestTask(BatchAccountContext context, string workItemName, string jobName, string taskName)
 {
     if (HttpMockServer.Mode == HttpRecorderMode.Record)
     {
         using (IWorkItemManager wiManager = context.BatchOMClient.OpenWorkItemManager())
         {
             ICloudTask task = new CloudTask(taskName, "cmd /c dir /s");
             wiManager.AddTask(workItemName, jobName, task);
         }
     }
 }
コード例 #22
0
 public static IWorkItemManager GetWorkItemManager()
 {
     lock (lockOjbect)
     {
         if (workerManager == null)
         {
             workerManager         = new WorkItemManager();
             workerManager.Service = new AsyncRun();
         }
     }
     return(workerManager);
 }
コード例 #23
0
        /// <summary>
        /// Deletes the specified WorkItem
        /// </summary>
        /// <param name="context">The account to use</param>
        /// <param name="workItemName">The name of the WorkItem to delete</param>
        /// <param name="additionBehaviors">Additional client behaviors to perform</param>
        public void DeleteWorkItem(BatchAccountContext context, string workItemName, IEnumerable <BatchClientBehavior> additionBehaviors = null)
        {
            if (string.IsNullOrWhiteSpace(workItemName))
            {
                throw new ArgumentNullException("workItemName");
            }

            using (IWorkItemManager wiManager = context.BatchOMClient.OpenWorkItemManager())
            {
                wiManager.DeleteWorkItem(workItemName, additionBehaviors);
            }
        }
コード例 #24
0
 private static void ListWorkItems(IBatchClient client)
 {
     // All Workitem, Job, and Task related operation start from WorkItemManager
     using (IWorkItemManager wm = client.OpenWorkItemManager())
     {
         Console.WriteLine("Listing Workitems\n=================");
         IEnumerable <ICloudWorkItem> wis = wm.ListWorkItems();
         foreach (var w in wis)
         {
             Console.WriteLine("Workitem: " + w.Name + " State:" + w.State);
         }
         Console.WriteLine();
     }
 }
コード例 #25
0
        /// <summary>
        /// Lists the Jobs matching the specified filter options
        /// </summary>
        /// <param name="options">The options to use when querying for Jobs</param>
        /// <returns>The Jobs matching the specified filter options</returns>
        public IEnumerable <PSCloudJob> ListJobs(ListJobOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (string.IsNullOrEmpty(options.WorkItemName) && options.WorkItem == null)
            {
                throw new ArgumentNullException(Resources.GBJ_NoWorkItem);
            }
            string wiName = options.WorkItem == null ? options.WorkItemName : options.WorkItem.Name;

            // Get the single Job matching the specified name
            if (!string.IsNullOrEmpty(options.JobName))
            {
                WriteVerbose(string.Format(Resources.GBJ_GetByName, options.JobName, wiName));
                using (IWorkItemManager wiManager = options.Context.BatchOMClient.OpenWorkItemManager())
                {
                    ICloudJob  job   = wiManager.GetJob(wiName, options.JobName, additionalBehaviors: options.AdditionalBehaviors);
                    PSCloudJob psJob = new PSCloudJob(job);
                    return(new PSCloudJob[] { psJob });
                }
            }
            // List Jobs using the specified filter
            else
            {
                if (options.MaxCount <= 0)
                {
                    options.MaxCount = Int32.MaxValue;
                }
                ODATADetailLevel odata = null;
                if (!string.IsNullOrEmpty(options.Filter))
                {
                    WriteVerbose(string.Format(Resources.GBJ_GetByOData, wiName, options.MaxCount));
                    odata = new ODATADetailLevel(filterClause: options.Filter);
                }
                else
                {
                    WriteVerbose(string.Format(Resources.GBJ_GetNoFilter, wiName, options.MaxCount));
                }

                using (IWorkItemManager wiManager = options.Context.BatchOMClient.OpenWorkItemManager())
                {
                    IEnumerableAsyncExtended <ICloudJob> jobs            = wiManager.ListJobs(wiName, odata, options.AdditionalBehaviors);
                    Func <ICloudJob, PSCloudJob>         mappingFunction = j => { return(new PSCloudJob(j)); };
                    return(new PSAsyncEnumerable <PSCloudJob, ICloudJob>(jobs, mappingFunction).Take(options.MaxCount));
                }
            }
        }
コード例 #26
0
        private static void AddWork(IBatchClient client)
        {
            using (IWorkItemManager wm = client.OpenWorkItemManager())
            {
                //The toolbox contains some helper mechanisms to ease submission and monitoring of tasks.
                IToolbox toolbox = client.OpenToolbox();

                // to submit a batch of tasks, the TaskSubmissionHelper is useful.
                ITaskSubmissionHelper taskSubmissionHelper = toolbox.CreateTaskSubmissionHelper(wm, Program.PoolName);

                // workitem is uniquely identified by its name so we will use a timestamp as suffix
                taskSubmissionHelper.WorkItemName = Environment.GetEnvironmentVariable("USERNAME") + DateTime.Now.ToString("yyyyMMdd-HHmmss");

                Console.WriteLine("Creating work item: {0}", taskSubmissionHelper.WorkItemName);

                // add 2 quick tasks. Tasks within a job must have unique names
                taskSubmissionHelper.AddTask(new CloudTask("task1", "hostname"));
                taskSubmissionHelper.AddTask(new CloudTask("task2", "cmd /c dir /s"));

                //Commit the tasks to the Batch Service
                IJobCommitUnboundArtifacts artifacts = taskSubmissionHelper.Commit() as IJobCommitUnboundArtifacts;

                // TaskSubmissionHelper commit artifacts returns the workitem and job name
                ICloudJob job = wm.GetJob(artifacts.WorkItemName, artifacts.JobName);

                Console.WriteLine("Waiting for all tasks to complete on work item: {0}, Job: {1} ...", artifacts.WorkItemName, artifacts.JobName);

                //We use the task state monitor to monitor the state of our tasks -- in this case we will wait for them all to complete.
                ITaskStateMonitor taskStateMonitor = toolbox.CreateTaskStateMonitor();

                // blocking wait on the list of tasks until all tasks reach completed state
                bool timedOut = taskStateMonitor.WaitAll(job.ListTasks(), TaskState.Completed, new TimeSpan(0, 20, 0));

                if (timedOut)
                {
                    throw new TimeoutException("Timed out waiting for tasks");
                }

                // dump task output
                foreach (var t in job.ListTasks())
                {
                    Console.WriteLine("Task " + t.Name + " says:\n" + t.GetTaskFile(Constants.StandardOutFileName).ReadAsString());
                }

                // remember to delete the workitem before exiting
                Console.WriteLine("Deleting work item: {0}", artifacts.WorkItemName);
                wm.DeleteWorkItem(artifacts.WorkItemName);
            }
        }
コード例 #27
0
        public void When_WorkItemsAdded_Expect_ItShouldRunInTheOrder()
        {
            IWorkItemManager workerManager = WorkItemManagerProvider.GetWorkItemManager();

            //Arrange
            string workItemNames = "";
            var    moqWorkItem1  = new Mock <IWorkItem>();

            moqWorkItem1.Setup(c => c.Name).Returns("A");
            moqWorkItem1.Setup(c => c.Duration).Returns(10);

            var moqWorkItem2 = new Mock <IWorkItem>();

            moqWorkItem2.Setup(c => c.Name).Returns("B");
            moqWorkItem2.Setup(c => c.Duration).Returns(10);

            Mock <IAsyncRun> moqAsyncService = new Mock <IAsyncRun>();

            moqAsyncService.Setup(c => c.DoTask(It.IsAny <IWorkItem>()))
            .Callback <IWorkItem>((workItem) =>
            {
                if (workItem.Equals(moqWorkItem1.Object))
                {
                    workItemNames += workItem.Name.ToString();
                    moqWorkItem1.Raise(x => x.WorkItemStatusUpdated += null,
                                       moqWorkItem1.Object,
                                       new WorkItemStatusUpdatedEventArgs(WorkItemStatus.Completed));
                }

                if (workItem.Equals(moqWorkItem2.Object))
                {
                    workItemNames += workItem.Name.ToString();
                    moqWorkItem2.Raise(x => x.WorkItemStatusUpdated += null,
                                       moqWorkItem2.Object,
                                       new WorkItemStatusUpdatedEventArgs(WorkItemStatus.Completed));
                }
            });
            workerManager.Service = (IAsyncRun)moqAsyncService.Object;

            //Act
            workerManager.AddWorkItem((IWorkItem)moqWorkItem1.Object);
            workerManager.AddWorkItem((IWorkItem)moqWorkItem2.Object);

            //Assert
            Assert.AreEqual("AB", workItemNames);
        }
コード例 #28
0
        /// <summary>
        /// Creates a new WorkItem
        /// </summary>
        /// <param name="parameters">The parameters to use when creating the WorkItem</param>
        public void CreateWorkItem(NewWorkItemParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (string.IsNullOrWhiteSpace(parameters.WorkItemName))
            {
                throw new ArgumentNullException("WorkItemName");
            }

            using (IWorkItemManager wiManager = parameters.Context.BatchOMClient.OpenWorkItemManager())
            {
                ICloudWorkItem workItem = wiManager.CreateWorkItem(parameters.WorkItemName);

                if (parameters.Schedule != null)
                {
                    workItem.Schedule = parameters.Schedule.omObject;
                }

                if (parameters.JobSpecification != null)
                {
                    Utils.Utils.JobSpecificationSyncCollections(parameters.JobSpecification);
                    workItem.JobSpecification = parameters.JobSpecification.omObject;
                }

                if (parameters.JobExecutionEnvironment != null)
                {
                    Utils.Utils.JobExecutionEnvironmentSyncCollections(parameters.JobExecutionEnvironment);
                    workItem.JobExecutionEnvironment = parameters.JobExecutionEnvironment.omObject;
                }

                if (parameters.Metadata != null)
                {
                    workItem.Metadata = new List <IMetadataItem>();
                    foreach (DictionaryEntry d in parameters.Metadata)
                    {
                        MetadataItem metadata = new MetadataItem(d.Key.ToString(), d.Value.ToString());
                        workItem.Metadata.Add(metadata);
                    }
                }
                WriteVerbose(string.Format(Resources.NBWI_CreatingWorkItem, parameters.WorkItemName));
                workItem.Commit(parameters.AdditionalBehaviors);
            }
        }
コード例 #29
0
 /// <summary>
 /// Creates a test WorkItem for use in Scenario tests.
 /// TODO: Replace with new WorkItem client method when it exists.
 /// </summary>
 public static void CreateTestWorkItem(BatchAccountContext context, string workItemName, TimeSpan?recurrenceInterval)
 {
     if (HttpMockServer.Mode == HttpRecorderMode.Record)
     {
         using (IWorkItemManager wiManager = context.BatchOMClient.OpenWorkItemManager())
         {
             ICloudWorkItem workItem = wiManager.CreateWorkItem(workItemName);
             workItem.JobExecutionEnvironment          = new Azure.Batch.JobExecutionEnvironment();
             workItem.JobExecutionEnvironment.PoolName = "testPool";
             if (recurrenceInterval != null)
             {
                 workItem.Schedule = new Azure.Batch.WorkItemSchedule();
                 workItem.Schedule.RecurrenceInterval = recurrenceInterval;
             }
             workItem.Commit();
         }
     }
 }
コード例 #30
0
        /// <summary>
        /// Lists the workitems matching the specified filter options
        /// </summary>
        /// <param name="options">The options to use when querying for workitems</param>
        /// <returns>The workitems matching the specified filter options</returns>
        public IEnumerable <PSCloudWorkItem> ListWorkItems(ListWorkItemOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            // Get the single WorkItem matching the specified name
            if (!string.IsNullOrWhiteSpace(options.WorkItemName))
            {
                WriteVerbose(string.Format(Resources.GBWI_GetByName, options.WorkItemName));
                using (IWorkItemManager wiManager = options.Context.BatchOMClient.OpenWorkItemManager())
                {
                    ICloudWorkItem  workItem   = wiManager.GetWorkItem(options.WorkItemName, additionalBehaviors: options.AdditionalBehaviors);
                    PSCloudWorkItem psWorkItem = new PSCloudWorkItem(workItem);
                    return(new PSCloudWorkItem[] { psWorkItem });
                }
            }
            // List WorkItems using the specified filter
            else
            {
                ODATADetailLevel odata            = null;
                string           verboseLogString = null;
                if (!string.IsNullOrEmpty(options.Filter))
                {
                    verboseLogString = Resources.GBWI_GetByOData;
                    odata            = new ODATADetailLevel(filterClause: options.Filter);
                }
                else
                {
                    verboseLogString = Resources.GBWI_NoFilter;
                }
                WriteVerbose(verboseLogString);

                using (IWorkItemManager wiManager = options.Context.BatchOMClient.OpenWorkItemManager())
                {
                    IEnumerableAsyncExtended <ICloudWorkItem> workItems       = wiManager.ListWorkItems(odata, options.AdditionalBehaviors);
                    Func <ICloudWorkItem, PSCloudWorkItem>    mappingFunction = w => { return(new PSCloudWorkItem(w)); };
                    return(PSAsyncEnumerable <PSCloudWorkItem, ICloudWorkItem> .CreateWithMaxCount(
                               workItems, mappingFunction, options.MaxCount, () => WriteVerbose(string.Format(Resources.MaxCount, options.MaxCount))));
                }
            }
        }
コード例 #31
0
        /// <summary>
        /// Deletes the specified task
        /// </summary>
        /// <param name="parameters">The parameters indicating which task to delete</param>
        public void DeleteTask(TaskOperationParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (parameters.Task != null)
            {
                parameters.Task.omObject.Delete(parameters.AdditionalBehaviors);
            }
            else
            {
                using (IWorkItemManager wiManager = parameters.Context.BatchOMClient.OpenWorkItemManager())
                {
                    wiManager.DeleteTask(parameters.WorkItemName, parameters.JobName, parameters.TaskName, parameters.AdditionalBehaviors);
                }
            }
        }