Esempio n. 1
0
        public async Task UnboundPoolCommitAndRefreshWorks()
        {
            using (BatchClient batchClient = ClientUnitTestCommon.CreateDummyClient())
            {
                const string id          = "Bar";
                const string displayName = "Baz";
                var          startTask   = new Protocol.Models.StartTask("cmd /c dir");
                var          protoPool   = new Protocol.Models.CloudPool(
                    id: id,
                    displayName: displayName,
                    startTask: startTask);

                CloudPool pool = batchClient.PoolOperations.CreatePool(id, "Woo", new CloudServiceConfiguration("4"));

                await pool.CommitAsync(additionalBehaviors : InterceptorFactory.CreateAddPoolRequestInterceptor());

                await pool.RefreshAsync(additionalBehaviors : InterceptorFactory.CreateGetPoolRequestInterceptor(protoPool));

                Assert.Equal(id, pool.Id);
                Assert.Equal(displayName, pool.DisplayName);
                Assert.Null(pool.CloudServiceConfiguration);
                Assert.NotNull(pool.StartTask);
                Assert.Equal(startTask.CommandLine, pool.StartTask.CommandLine);
            }
        }
Esempio n. 2
0
        public async Task UnboundJobCommitAndRefreshWorks()
        {
            using (BatchClient batchClient = ClientUnitTestCommon.CreateDummyClient())
            {
                const string id          = "Bar";
                const string displayName = "Baz";
                var          prepTask    = new Protocol.Models.JobPreparationTask(id);

                Protocol.Models.CloudJob protoJob = new Protocol.Models.CloudJob(
                    id: id,
                    displayName: displayName,
                    jobPreparationTask: prepTask);

                CloudJob job = batchClient.JobOperations.CreateJob(id, new PoolInformation()
                {
                    PoolId = "Foo"
                });

                await job.CommitAsync(additionalBehaviors : InterceptorFactory.CreateAddJobRequestInterceptor());

                await job.RefreshAsync(additionalBehaviors : InterceptorFactory.CreateGetJobRequestInterceptor(protoJob));

                Assert.Equal(id, job.Id);
                Assert.Equal(displayName, job.DisplayName);
                Assert.Null(job.PoolInformation);
                Assert.NotNull(job.JobPreparationTask);
                Assert.Equal(prepTask.Id, job.JobPreparationTask.Id);
            }
        }
        public void CloudJobSchedule_WhenSendingToTheServer_HasExpectedUnboundProperties()
        {
            const string jobScheduleId = "id-123";
            const string displayName   = "DisplayNameFoo";
            MetadataItem metadataItem  = new MetadataItem("foo", "bar");

            BatchSharedKeyCredentials credentials = ClientUnitTestCommon.CreateDummySharedKeyCredential();

            using (BatchClient client = BatchClient.Open(credentials))
            {
                CloudJobSchedule jobSchedule = client.JobScheduleOperations.CreateJobSchedule();
                jobSchedule.Id          = jobScheduleId;
                jobSchedule.DisplayName = displayName;
                jobSchedule.Metadata    = new List <MetadataItem> {
                    metadataItem
                };

                Assert.Equal(jobSchedule.Id, jobScheduleId); // can set an unbound object
                Assert.Equal(jobSchedule.Metadata.First().Name, metadataItem.Name);
                Assert.Equal(jobSchedule.Metadata.First().Value, metadataItem.Value);

                jobSchedule.Commit(additionalBehaviors: InterceptorFactory.CreateAddJobScheduleRequestInterceptor());

                // writing isn't allowed for a jobSchedule that is in an read only state.
                Assert.Throws <InvalidOperationException>(() => jobSchedule.Id          = "cannot-change-id");
                Assert.Throws <InvalidOperationException>(() => jobSchedule.DisplayName = "cannot-change-display-name");

                //Can still read though
                Assert.Equal(jobScheduleId, jobSchedule.Id);
                Assert.Equal(displayName, jobSchedule.DisplayName);
            }
        }
Esempio n. 4
0
        public async Task UnboundJobScheduleCommitAndRefreshWorks()
        {
            using (BatchClient batchClient = ClientUnitTestCommon.CreateDummyClient())
            {
                const string id               = "Bar";
                const string displayName      = "Baz";
                var          jobSpecification = new Protocol.Models.JobSpecification()
                {
                    DisplayName = displayName
                };
                var protoJobSchedule = new Protocol.Models.CloudJobSchedule(
                    id: id,
                    displayName: displayName,
                    jobSpecification: jobSpecification);

                CloudJobSchedule jobSchedule = batchClient.JobScheduleOperations.CreateJobSchedule(id, new Schedule(), null);

                await jobSchedule.CommitAsync(additionalBehaviors : InterceptorFactory.CreateAddJobScheduleRequestInterceptor());

                await jobSchedule.RefreshAsync(additionalBehaviors : InterceptorFactory.CreateGetJobScheduleRequestInterceptor(protoJobSchedule));

                Assert.Equal(id, jobSchedule.Id);
                Assert.Equal(displayName, jobSchedule.DisplayName);
                Assert.Null(jobSchedule.Schedule);
                Assert.NotNull(jobSchedule.JobSpecification);
                Assert.Equal(jobSpecification.DisplayName, jobSchedule.JobSpecification.DisplayName);
            }
        }
Esempio n. 5
0
        private void InterceptMessage(T message)
        {
            Interceptor <T> intercepter = null;

            try
            {
                intercepter = InterceptorFactory.GetInterceptor(message);

                T forward = intercepter.OnSend(message);

                // NOTE that if the output channel is not a synchronous channel, the intercepter will not
                // control the context of that channel and the processing of the message
                _output.Send(forward);

                intercepter.OnComplete();
            }
            catch (Exception ex)
            {
                if (intercepter != null)
                {
                    intercepter.OnException(ex);
                }
                throw;
            }
        }
Esempio n. 6
0
 public void TestDefaultValueWithError()
 {
     // Used to be:
     //var ex = Assert.Throws<InvalidCastException>(() => ProxyBuilder.CreateProxy<IDefaultValueWithErrorTest>());
     // Now it should run without error
     InterceptorFactory.New <IDefaultValueWithErrorTest>();
 }
Esempio n. 7
0
        public void TestCreateType_2x()
        {
            // Create via factory
            InterceptorFactory.New <ISimpleTypeTest>();

            var testInterfaceType = typeof(ISimpleTypeTest);

            var typeName = testInterfaceType.Name + "Impl";

            // Remove "I" at the start
            if (typeName.StartsWith("I"))
            {
                typeName = typeName.Substring(1);
            }

            var fqTypeName = testInterfaceType.FullName.Replace(testInterfaceType.Name, typeName);

            var baseType = typeof(ExtensibleInterceptorImpl <>);

            // Make sure we have a non generic type, by filling in the "blanks"
            if (baseType.IsGenericType)
            {
                baseType = baseType.MakeGenericType(testInterfaceType);
            }

            // Create self
            var typeBuilder = IlTypeBuilder.CreateOrGet();

            typeBuilder.CreateType(fqTypeName, new[] { testInterfaceType }, baseType);
        }
Esempio n. 8
0
        public void GetJobManagerTaskWithApplicationPackageReferences()
        {
            const string jobId         = "id-123";
            const string applicationId = "foo";
            const string version       = "beta";

            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                Models.CloudJob protoJob = new Models.CloudJob
                {
                    Id             = jobId,
                    JobManagerTask = new Models.JobManagerTask
                    {
                        ApplicationPackageReferences = new List <Models.ApplicationPackageReference>
                        {
                            new Models.ApplicationPackageReference
                            {
                                Version = version, ApplicationId = applicationId
                            }
                        }
                    }
                };

                var job = client.JobOperations.GetJob(jobId, additionalBehaviors: InterceptorFactory.CreateGetJobRequestInterceptor(protoJob));
                Assert.Equal(applicationId, job.JobManagerTask.ApplicationPackageReferences.First().ApplicationId);
                Assert.Equal(version, job.JobManagerTask.ApplicationPackageReferences.First().Version);
            }
        }
Esempio n. 9
0
        public async Task UnboundCertificateCommitAndRefreshWorks()
        {
            using (BatchClient batchClient = ClientUnitTestCommon.CreateDummyClient())
            {
                string pfxFilePath = TestCommon.GetTemporaryCertificateFilePath("unboundcertificateunittest.pfx");
                try
                {
                    CertificateBuilder.CreateSelfSignedInFile("test", pfxFilePath, CommonResources.CertificatePassword);

                    const string expectedThumbprint = "ABC";
                    var          protoCertificate   = new Protocol.Models.Certificate(thumbprint: expectedThumbprint);
                    Certificate  certificate        = batchClient.CertificateOperations.CreateCertificate(
                        pfxFilePath,
                        CommonResources.CertificatePassword);

                    Assert.NotNull(certificate.ThumbprintAlgorithm);

                    await certificate.CommitAsync(additionalBehaviors : InterceptorFactory.CreateAddCertificateRequestInterceptor());

                    await certificate.RefreshAsync(additionalBehaviors : InterceptorFactory.CreateGetCertificateRequestInterceptor(protoCertificate));

                    Assert.Equal(expectedThumbprint, certificate.Thumbprint);
                    Assert.Null(certificate.ThumbprintAlgorithm);
                }
                finally
                {
                    File.Delete(pfxFilePath);
                }
            }
        }
        public void CloudTask_WhenReturnedFromServer_HasExpectedBoundProperties()
        {
            const string jobId              = "id-123";
            const string taskId             = "id-123";
            const int    exitCode           = 1;
            const int    exitCodeRangeStart = 0;
            const int    exitCodeRangeEnd   = 4;

            Models.ExitOptions terminateExitOption = new Models.ExitOptions()
            {
                JobAction = Models.JobAction.Terminate
            };
            Models.ExitOptions disableExitOption = new Models.ExitOptions()
            {
                JobAction        = Models.JobAction.Disable,
                DependencyAction = Models.DependencyAction.Satisfy
            };

            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                Models.CloudTask cloudTask = new Models.CloudTask()
                {
                    Id             = jobId,
                    ExitConditions = new Models.ExitConditions()
                    {
                        DefaultProperty = disableExitOption,
                        ExitCodeRanges  = new List <Models.ExitCodeRangeMapping>()
                        {
                            new Models.ExitCodeRangeMapping(exitCodeRangeStart, exitCodeRangeEnd, terminateExitOption)
                        },
                        ExitCodes = new List <Models.ExitCodeMapping>()
                        {
                            new Models.ExitCodeMapping(exitCode, terminateExitOption)
                        },
                        PreProcessingError = terminateExitOption,
                        FileUploadError    = disableExitOption
                    }
                };

                CloudTask boundTask = client.JobOperations.GetTask(
                    jobId,
                    taskId,
                    additionalBehaviors: InterceptorFactory.CreateGetTaskRequestInterceptor(cloudTask));

                Assert.Equal(taskId, boundTask.Id); // reading is allowed from a task that is returned from the server.
                // These need to be compared as strings because they are different types but we are interested in the values being the same.
                Assert.Equal(disableExitOption.JobAction.ToString(), boundTask.ExitConditions.Default.JobAction.ToString());
                Assert.Equal(DependencyAction.Satisfy, boundTask.ExitConditions.Default.DependencyAction);
                Assert.Equal(DependencyAction.Satisfy, boundTask.ExitConditions.FileUploadError.DependencyAction);
                Assert.Throws <InvalidOperationException>(() => boundTask.ExitConditions         = new ExitConditions());
                Assert.Throws <InvalidOperationException>(() => boundTask.DependsOn              = new TaskDependencies(new List <string>(), new List <TaskIdRange>()));
                Assert.Throws <InvalidOperationException>(() => boundTask.UserIdentity           = new UserIdentity("abc"));
                Assert.Throws <InvalidOperationException>(() => boundTask.CommandLine            = "Cannot change command line");
                Assert.Throws <InvalidOperationException>(() => boundTask.ExitConditions.Default = new ExitOptions()
                {
                    JobAction = JobAction.Terminate
                });
            }
        }
        public void CloudJob_WhenSendingToTheServer_HasExpectedUnboundProperties()
        {
            const string jobId              = "id-123";
            const string displayName        = "DisplayNameFoo";
            MetadataItem metadataItem       = new MetadataItem("foo", "bar");
            const int    priority           = 0;
            const string applicationId      = "testApp";
            const string applicationVersion = "beta";

            using BatchClient client = ClientUnitTestCommon.CreateDummyClient();
            CloudJob cloudJob = client.JobOperations.CreateJob(jobId, new PoolInformation {
                AutoPoolSpecification = new AutoPoolSpecification {
                    KeepAlive = false
                }
            });

            cloudJob.Id          = jobId;
            cloudJob.DisplayName = displayName;
            cloudJob.Metadata    = new List <MetadataItem> {
                metadataItem
            };
            cloudJob.Priority       = priority;
            cloudJob.JobManagerTask = new JobManagerTask
            {
                ApplicationPackageReferences = new List <ApplicationPackageReference>
                {
                    new ApplicationPackageReference {
                        ApplicationId = applicationId, Version = applicationVersion
                    }
                },
                AuthenticationTokenSettings = new AuthenticationTokenSettings()
                {
                    Access = AccessScope.Job
                }
            };

            cloudJob.OnAllTasksComplete = OnAllTasksComplete.NoAction;
            cloudJob.OnTaskFailure      = OnTaskFailure.NoAction;


            Assert.Throws <InvalidOperationException>(() => cloudJob.Url); // cannot read a Url since it's unbound at this point.
            Assert.Equal(cloudJob.Id, jobId);                              // can set an unbound object
            Assert.Equal(cloudJob.Metadata.First().Name, metadataItem.Name);
            Assert.Equal(cloudJob.Metadata.First().Value, metadataItem.Value);
            Assert.Equal(OnAllTasksComplete.NoAction, cloudJob.OnAllTasksComplete);
            Assert.Equal(OnTaskFailure.NoAction, cloudJob.OnTaskFailure);

            cloudJob.Commit(additionalBehaviors: InterceptorFactory.CreateAddJobRequestInterceptor());

            // writing isn't allowed for a job that is in an invalid state.
            Assert.Throws <InvalidOperationException>(() => cloudJob.Id          = "cannot-change-id");
            Assert.Throws <InvalidOperationException>(() => cloudJob.DisplayName = "cannot-change-display-name");

            AuthenticationTokenSettings authenticationTokenSettings = new AuthenticationTokenSettings {
                Access = AccessScope.Job
            };

            Assert.Throws <InvalidOperationException>(() => { cloudJob.JobManagerTask.AuthenticationTokenSettings = authenticationTokenSettings; });
        }
        public void CloudTask_WhenReturnedFromServer_HasExpectedBoundProperties()
        {
            const string jobId              = "id-123";
            const string taskId             = "id-123";
            const int    exitCode           = 1;
            const int    exitCodeRangeStart = 0;
            const int    exitCodeRangeEnd   = 4;

            Models.ExitOptions terminateExitOption = new Models.ExitOptions()
            {
                JobAction = Models.JobAction.Terminate
            };
            Models.ExitOptions disableExitOption = new Models.ExitOptions()
            {
                JobAction = Models.JobAction.Disable
            };

            BatchSharedKeyCredentials credentials = ClientUnitTestCommon.CreateDummySharedKeyCredential();

            using (BatchClient client = BatchClient.Open(credentials))
            {
                Models.CloudTask cloudTask = new Models.CloudTask()
                {
                    Id             = jobId,
                    ExitConditions = new Models.ExitConditions()
                    {
                        DefaultProperty = disableExitOption,
                        ExitCodeRanges  = new List <Models.ExitCodeRangeMapping>()
                        {
                            new Models.ExitCodeRangeMapping(exitCodeRangeStart, exitCodeRangeEnd, terminateExitOption)
                        },
                        ExitCodes = new List <Models.ExitCodeMapping>()
                        {
                            new Models.ExitCodeMapping(exitCode, terminateExitOption)
                        },
                        SchedulingError = terminateExitOption,
                    }
                };

                CloudTask boundTask = client.JobOperations.GetTask(
                    jobId,
                    taskId,
                    additionalBehaviors: InterceptorFactory.CreateGetTaskRequestInterceptor(cloudTask));


                Assert.Equal(taskId, boundTask.Id); // reading is allowed from a task that is returned from the server.
                Assert.Equal(disableExitOption.JobAction.ToString(), boundTask.ExitConditions.Default.JobAction.ToString());
                Assert.Throws <InvalidOperationException>(() => boundTask.ExitConditions         = new ExitConditions());
                Assert.Throws <InvalidOperationException>(() => boundTask.DependsOn              = new TaskDependencies(new List <string>(), new List <TaskIdRange>()));
                Assert.Throws <InvalidOperationException>(() => boundTask.RunElevated            = true);
                Assert.Throws <InvalidOperationException>(() => boundTask.CommandLine            = "Cannot change command line");
                Assert.Throws <InvalidOperationException>(() => boundTask.ExitConditions.Default = new ExitOptions()
                {
                    JobAction = JobAction.Terminate
                });
            }
        }
        public void CloudJobSchedule_WhenReturnedFromServer_HasExpectedBoundProperties()
        {
            const string jobScheduleId = "id-123";
            const string displayName   = "DisplayNameFoo";
            MetadataItem metadataItem  = new MetadataItem("foo", "bar");

            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                DateTime creationTime = DateTime.Now;

                var cloudJobSchedule = new Models.CloudJobSchedule
                {
                    Id          = jobScheduleId,
                    DisplayName = displayName,
                    Metadata    = new[]
                    {
                        new Models.MetadataItem {
                            Name = metadataItem.Name, Value = metadataItem.Value
                        }
                    },
                    CreationTime     = creationTime,
                    JobSpecification = new Models.JobSpecification
                    {
                        OnAllTasksComplete = Models.OnAllTasksComplete.TerminateJob,
                        OnTaskFailure      = Models.OnTaskFailure.PerformExitOptionsJobAction
                    }
                };

                CloudJobSchedule boundJobSchedule = client.JobScheduleOperations.GetJobSchedule(
                    jobScheduleId,
                    additionalBehaviors: InterceptorFactory.CreateGetJobScheduleRequestInterceptor(cloudJobSchedule));

                Assert.Equal(jobScheduleId, boundJobSchedule.Id); // reading is allowed from a jobSchedule that is returned from the server.
                Assert.Equal(creationTime, boundJobSchedule.CreationTime);
                Assert.Equal(displayName, boundJobSchedule.DisplayName);
                Assert.Equal(OnAllTasksComplete.TerminateJob, boundJobSchedule.JobSpecification.OnAllTasksComplete);
                Assert.Equal(OnTaskFailure.PerformExitOptionsJobAction, boundJobSchedule.JobSpecification.OnTaskFailure);

                Assert.Throws <InvalidOperationException>(() => boundJobSchedule.DisplayName = "cannot-change-display-name");
                Assert.Throws <InvalidOperationException>(() => boundJobSchedule.Id          = "cannot-change-id");

                boundJobSchedule.JobSpecification.OnAllTasksComplete = OnAllTasksComplete.TerminateJob;
                boundJobSchedule.JobSpecification.OnTaskFailure      = OnTaskFailure.NoAction;

                Assert.Equal(OnAllTasksComplete.TerminateJob, boundJobSchedule.JobSpecification.OnAllTasksComplete);
                Assert.Equal(OnTaskFailure.NoAction, boundJobSchedule.JobSpecification.OnTaskFailure);
            }
        }
        public void CloudJobSchedule_WhenSendingToTheServer_HasExpectedUnboundProperties()
        {
            const string jobScheduleId = "id-123";
            const string displayName   = "DisplayNameFoo";
            MetadataItem metadataItem  = new MetadataItem("foo", "bar");

            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                CloudJobSchedule jobSchedule = client.JobScheduleOperations.CreateJobSchedule();
                jobSchedule.Id          = jobScheduleId;
                jobSchedule.DisplayName = displayName;
                jobSchedule.Metadata    = new List <MetadataItem> {
                    metadataItem
                };
                jobSchedule.JobSpecification = new JobSpecification
                {
                    OnAllTasksComplete = OnAllTasksComplete.TerminateJob,
                    OnTaskFailure      = OnTaskFailure.PerformExitOptionsJobAction
                };

                Assert.Equal(jobSchedule.Id, jobScheduleId); // can set an unbound object
                Assert.Equal(jobSchedule.Metadata.First().Name, metadataItem.Name);
                Assert.Equal(jobSchedule.Metadata.First().Value, metadataItem.Value);
                Assert.Equal(OnAllTasksComplete.TerminateJob, jobSchedule.JobSpecification.OnAllTasksComplete);
                Assert.Equal(OnTaskFailure.PerformExitOptionsJobAction, jobSchedule.JobSpecification.OnTaskFailure);

                jobSchedule.Commit(additionalBehaviors: InterceptorFactory.CreateAddJobScheduleRequestInterceptor());

                // writing isn't allowed for a jobSchedule that is in an read only state.
                Assert.Throws <InvalidOperationException>(() => jobSchedule.Id          = "cannot-change-id");
                Assert.Throws <InvalidOperationException>(() => jobSchedule.DisplayName = "cannot-change-display-name");

                //Can still read though
                Assert.Equal(jobScheduleId, jobSchedule.Id);
                Assert.Equal(displayName, jobSchedule.DisplayName);

                jobSchedule.Refresh(additionalBehaviors:
                                    InterceptorFactory.CreateGetJobScheduleRequestInterceptor(
                                        new Models.CloudJobSchedule()
                {
                    JobSpecification = new Models.JobSpecification()
                }));

                jobSchedule.JobSpecification.OnAllTasksComplete = OnAllTasksComplete.NoAction;
                jobSchedule.JobSpecification.OnTaskFailure      = OnTaskFailure.NoAction;
            }
        }
Esempio n. 15
0
        public async Task ExceptionOnClientError_ResultingExceptionContainsDetails()
        {
            const string expectedCode  = "badness";
            const string failingTaskId = "baz";

            using (BatchClient batchCli = BatchClient.Open(ClientUnitTestCommon.CreateDummySharedKeyCredential()))
            {
                var tasksToAdd = new List <CloudTask>
                {
                    new CloudTask("foo", "bar"),
                    new CloudTask(failingTaskId, "qux")
                };

                var results = new List <Protocol.Models.TaskAddResult>
                {
                    new Protocol.Models.TaskAddResult(Protocol.Models.TaskAddStatus.Success, "foo"),
                    new Protocol.Models.TaskAddResult(
                        Protocol.Models.TaskAddStatus.Clienterror,
                        failingTaskId,
                        error: new Protocol.Models.BatchError(
                            expectedCode,
                            new Protocol.Models.ErrorMessage(value: "Test value"),
                            new List <Protocol.Models.BatchErrorDetail>
                    {
                        new Protocol.Models.BatchErrorDetail("key", "value")
                    }))
                };

                ParallelOperationsException parallelOperationsException = await Assert.ThrowsAsync <ParallelOperationsException>(
                    () => batchCli.JobOperations.AddTaskAsync(
                        "dummy",
                        tasksToAdd,
                        additionalBehaviors: InterceptorFactory.CreateAddTaskCollectionInterceptor(results)));

                Assert.Equal(1, parallelOperationsException.InnerExceptions.Count);

                var exception = parallelOperationsException.InnerException as AddTaskCollectionTerminatedException;

                Assert.NotNull(exception);
                Assert.NotNull(exception.AddTaskResult);
                Assert.Equal(failingTaskId, exception.AddTaskResult.TaskId);
                Assert.Equal(AddTaskStatus.ClientError, exception.AddTaskResult.Status);
                Assert.Equal(expectedCode, exception.AddTaskResult.Error.Code);
                Assert.Equal("Addition of a task failed with unexpected status code. Details: TaskId=baz, Status=ClientError, Error.Code=badness, Error.Message=Test value, Error.Values=[key=value]",
                             exception.Message);
            }
        }
Esempio n. 16
0
        protected override Expression VisitMethodCall(MethodCallExpression mExpr)
        {
            var interceptor = InterceptorFactory.FindInterceptor(mExpr);

            if (interceptor != null)
            {
                interceptor.Intercept(Result, mExpr, (expr) => Visit(expr));
            }
            else
            {
                var compiled           = Expression.Lambda(mExpr).Compile();
                var constantExpression = Expression.Constant(compiled.DynamicInvoke(), mExpr.Type);
                Visit(constantExpression);
            }

            return(mExpr);
        }
        public void Pool_WhenReturnedFromServer_HasExpectedUnboundProperties()
        {
            const string cloudPoolId          = "id-123";
            const string osFamily             = "2";
            const string virtualMachineSize   = "4";
            const string cloudPoolDisplayName = "pool-display-name-test";
            MetadataItem metadataItem         = new MetadataItem("foo", "bar");

            BatchSharedKeyCredentials credentials = ClientUnitTestCommon.CreateDummySharedKeyCredential();

            using (BatchClient client = BatchClient.Open(credentials))
            {
                CloudPool cloudPool = client.PoolOperations.CreatePool(cloudPoolId, virtualMachineSize, new CloudServiceConfiguration(osFamily));
                cloudPool.DisplayName = cloudPoolDisplayName;
                cloudPool.Metadata    = new List <MetadataItem> {
                    metadataItem
                };

                Assert.Equal(cloudPoolId, cloudPool.Id); // can set an unbound object
                Assert.Equal(cloudPool.Metadata.First().Name, metadataItem.Name);
                Assert.Equal(cloudPool.Metadata.First().Value, metadataItem.Value);

                cloudPool.Commit(additionalBehaviors: InterceptorFactory.CreateAddPoolRequestInterceptor());

                // writing isn't allowed for a cloudPool that is in an readonly state.
                Assert.Throws <InvalidOperationException>(() => cloudPool.AutoScaleFormula          = "Foo");
                Assert.Throws <InvalidOperationException>(() => cloudPool.DisplayName               = "Foo");
                Assert.Throws <InvalidOperationException>(() => cloudPool.CloudServiceConfiguration = null);
                Assert.Throws <InvalidOperationException>(() => cloudPool.ResizeTimeout             = TimeSpan.FromSeconds(10));
                Assert.Throws <InvalidOperationException>(() => cloudPool.Metadata                    = null);
                Assert.Throws <InvalidOperationException>(() => cloudPool.TargetDedicated             = 5);
                Assert.Throws <InvalidOperationException>(() => cloudPool.VirtualMachineConfiguration = null);
                Assert.Throws <InvalidOperationException>(() => cloudPool.VirtualMachineSize          = "small");

                //read is allowed though
                Assert.Null(cloudPool.AutoScaleFormula);
                Assert.Equal(cloudPoolDisplayName, cloudPool.DisplayName);
                Assert.NotNull(cloudPool.CloudServiceConfiguration);
                Assert.Null(cloudPool.ResizeTimeout);
                Assert.Equal(1, cloudPool.Metadata.Count);
                Assert.Null(cloudPool.TargetDedicated);
                Assert.Null(cloudPool.VirtualMachineConfiguration);
                Assert.Equal(virtualMachineSize, cloudPool.VirtualMachineSize);
            }
        }
        public void TestComputeNodeCertificateReferencesAreReadOnly()
        {
            using (BatchClient batchClient = ClientUnitTestCommon.CreateDummyClient())
            {
                var protoComputeNode = new Protocol.Models.ComputeNode()
                {
                    CertificateReferences = new List <Protocol.Models.CertificateReference>
                    {
                        new Protocol.Models.CertificateReference(
                            thumbprint: "1234",
                            thumbprintAlgorithm: "SHA1",
                            storeLocation: Protocol.Models.CertificateStoreLocation.CurrentUser,
                            storeName: "My",
                            visibility: new List <Protocol.Models.CertificateVisibility>
                        {
                            Protocol.Models.CertificateVisibility.Task
                        })
                    }
                };

                ComputeNode computeNode = batchClient.PoolOperations.GetComputeNode(
                    "dummy",
                    "dummy",
                    additionalBehaviors: InterceptorFactory.CreateGetComputeNodeRequestInterceptor(protoComputeNode));

                CertificateReference computeNodeCertificateReference = computeNode.CertificateReferences.First();

                // reads are allowed
                this.testOutputHelper.WriteLine("{0}", computeNodeCertificateReference.StoreLocation);
                this.testOutputHelper.WriteLine("{0}", computeNodeCertificateReference.StoreName);
                this.testOutputHelper.WriteLine("{0}", computeNodeCertificateReference.Thumbprint);
                this.testOutputHelper.WriteLine("{0}", computeNodeCertificateReference.ThumbprintAlgorithm);
                this.testOutputHelper.WriteLine("{0}", computeNodeCertificateReference.Visibility);

                // writes are foribdden
                Assert.Throws <InvalidOperationException>(() => { computeNodeCertificateReference.StoreLocation = CertStoreLocation.CurrentUser; });
                Assert.Throws <InvalidOperationException>(() => { computeNodeCertificateReference.StoreName = "x"; });
                Assert.Throws <InvalidOperationException>(() => { computeNodeCertificateReference.Thumbprint = "y"; });
                Assert.Throws <InvalidOperationException>(() => { computeNodeCertificateReference.ThumbprintAlgorithm = "z"; });
                Assert.Throws <InvalidOperationException>(() => { computeNodeCertificateReference.Visibility = CertificateVisibility.None; });
            }
        }
Esempio n. 19
0
        public async Task UnboundCertificateCommitAndRefreshWorks()
        {
            using BatchClient batchClient = ClientUnitTestCommon.CreateDummyClient();
            const string expectedThumbprint = "ABC";
            var          protoCertificate   = new Protocol.Models.Certificate(thumbprint: expectedThumbprint);
            Certificate  certificate        = new Certificate(
                batchClient,
                null,
                string.Empty,
                expectedThumbprint,
                "SHA1");

            Assert.NotNull(certificate.ThumbprintAlgorithm);

            await certificate.CommitAsync(additionalBehaviors : InterceptorFactory.CreateAddCertificateRequestInterceptor());

            await certificate.RefreshAsync(additionalBehaviors : InterceptorFactory.CreateGetCertificateRequestInterceptor(protoCertificate));

            Assert.Equal(expectedThumbprint, certificate.Thumbprint);
            Assert.Null(certificate.ThumbprintAlgorithm);
        }
Esempio n. 20
0
        private static void CommonPatchPoolTest(
            Protocol.Models.CloudPool startEntity,
            Action <CloudPool> modificationFunction,
            Action <Protocol.Models.PoolPatchParameter> assertAction)
        {
            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                CloudPool pool = client.PoolOperations.GetPool(
                    string.Empty,
                    additionalBehaviors: InterceptorFactory.CreateGetPoolRequestInterceptor(startEntity));

                modificationFunction(pool);

                var patchInterceptor = ShimPatchPool(assertAction);
                pool.CommitChanges(additionalBehaviors: new[] { patchInterceptor });

                //Ensure that the job is in readable but unmodifiable state
                var id = pool.Id;
                Assert.Throws <InvalidOperationException>(() => pool.Metadata = null);
            }
        }
Esempio n. 21
0
        public virtual MethodInvokerEntry Get(MethodDescriptor methodDescriptor)
        {
            var result = InterceptorFactory.GetAllInterceptors(methodDescriptor, _services);

            if (!_caches.TryGetValue(methodDescriptor, out var cache))
            {
                cache = new MethodInvokerEntry
                {
                    Client                   = _goClient,
                    Codec                    = methodDescriptor.Codec,
                    Interceptors             = result.Interceptors,
                    KeyValueFormatterFactory = _keyValueFormatterFactory,
                    TemplateParser           = _templateParser,
                    UrlTemplate              = new UrlDescriptor(methodDescriptor.UrlTemplate.Template)
                };

                _caches[methodDescriptor] = cache;
            }
            cache.Interceptors = result.Interceptors;

            return(cache);
        }
Esempio n. 22
0
        private static void CommonPatchJobTest(
            Protocol.Models.CloudJob startEntity,
            Action <CloudJob> modificationFunction,
            Action <Protocol.Models.JobPatchParameter> assertAction)
        {
            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                CloudJob job = client.JobOperations.GetJob(
                    string.Empty,
                    additionalBehaviors: InterceptorFactory.CreateGetJobRequestInterceptor(startEntity));

                modificationFunction(job);

                var patchInterceptor = ShimPatchJob(assertAction);
                job.CommitChanges(additionalBehaviors: new[] { patchInterceptor });

                //Ensure that the job is in readable but unmodifiable state
                var id       = job.Id;
                var priority = job.Priority;

                Assert.Throws <InvalidOperationException>(() => job.Priority = 5);
            }
        }
        public void CloudJobSchedule_WhenReturnedFromServer_HasExpectedBoundProperties()
        {
            const string jobScheduleId = "id-123";
            const string displayName   = "DisplayNameFoo";
            MetadataItem metadataItem  = new MetadataItem("foo", "bar");

            BatchSharedKeyCredentials credentials = ClientUnitTestCommon.CreateDummySharedKeyCredential();

            using (BatchClient client = BatchClient.Open(credentials))
            {
                DateTime creationTime = DateTime.Now;

                var cloudJobSchedule = new Models.CloudJobSchedule
                {
                    Id          = jobScheduleId,
                    DisplayName = displayName,
                    Metadata    = new[]
                    {
                        new Models.MetadataItem {
                            Name = metadataItem.Name, Value = metadataItem.Value
                        }
                    },
                    CreationTime = creationTime
                };

                CloudJobSchedule boundJobSchedule = client.JobScheduleOperations.GetJobSchedule(
                    jobScheduleId,
                    additionalBehaviors: InterceptorFactory.CreateGetJobScheduleRequestInterceptor(cloudJobSchedule));

                Assert.Equal(jobScheduleId, boundJobSchedule.Id); // reading is allowed from a jobSchedule that is returned from the server.
                Assert.Equal(creationTime, boundJobSchedule.CreationTime);
                Assert.Equal(displayName, boundJobSchedule.DisplayName);

                Assert.Throws <InvalidOperationException>(() => boundJobSchedule.DisplayName = "cannot-change-display-name");
                Assert.Throws <InvalidOperationException>(() => boundJobSchedule.Id          = "cannot-change-id");
            }
        }
Esempio n. 24
0
        protected override InterceptorFactory <T> Visitor <T>(InterceptorFactory <T> factory)
        {
            Trace.WriteLine("InterceptorFactory<{0}>".FormatWith(typeof(T).Name));

            return(base.Visitor(factory));
        }
Esempio n. 25
0
        public virtual InterceptorFactory <T> Visit <T>(InterceptorFactory <T> factory)
        {
            InterceptorFactory <T> result = this.FastInvoke <ChannelVisitor, InterceptorFactory <T> >("Visitor", factory);

            return(result);
        }
Esempio n. 26
0
 protected virtual InterceptorFactory <T> Visitor <T>(InterceptorFactory <T> factory)
 {
     return(factory);
 }
Esempio n. 27
0
 /// <summary>
 /// Register a Func to run against any object of this PluginType immediately after it is created,
 /// but before the new object is passed back to the caller.  Unlike OnCreationForAll(),
 /// DecorateAllWith() gives the the ability to return a different object.  Use this method for runtime AOP
 /// scenarios or to return a decorator.
 /// </summary>
 /// <param name="description">Descriptive text for diagnostics</param>
 /// <param name="handler">Function that will create a decorator for the plugin type</param>
 /// <param name="filter"></param>
 public CreatePluginFamilyExpression <TPluginType> DecorateAllWith(string description,
                                                                   Func <IContext, TPluginType, TPluginType> handler, Func <Instance, bool> filter = null)
 {
     return(InterceptWith(InterceptorFactory.ForFunc(description, handler), filter));
 }
Esempio n. 28
0
 /// <summary>
 ///  Register an Action to run against any object of this PluginType immediately after
 ///  it is created, but before the new object is passed back to the caller
 ///  </summary>
 ///  <param name="description">Descriptive text for diagnostics</param>
 /// <param name="handler"></param>
 /// <param name="filter">If specified, limits the applicability of this activation interception</param>
 public CreatePluginFamilyExpression <TPluginType> OnCreationForAll(string description,
                                                                    Action <TPluginType> handler, Func <Instance, bool> filter = null)
 {
     return(InterceptWith(InterceptorFactory.ForAction(description, handler), filter));
 }
        public void Pool_WhenReturnedFromServer_HasExpectedBoundProperties()
        {
            const string cloudPoolId          = "id-123";
            const string cloudPoolDisplayName = "pool-display-name-test";
            MetadataItem metadataItem         = new MetadataItem("foo", "bar");

            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                Models.CloudPool protoPool = new Models.CloudPool(id: cloudPoolId, displayName: cloudPoolDisplayName, metadata: new[]
                {
                    new Models.MetadataItem
                    {
                        Name  = metadataItem.Name,
                        Value = metadataItem.Value
                    }
                });

                CloudPool boundPool = client.PoolOperations.GetPool(string.Empty, additionalBehaviors: InterceptorFactory.CreateGetPoolRequestInterceptor(protoPool));

                // Cannot change these bound properties.
                Assert.Throws <InvalidOperationException>(() => boundPool.DisplayName = "cannot-change-display-name");
                Assert.Throws <InvalidOperationException>(() => boundPool.Id          = "cannot-change-id");
                Assert.Throws <InvalidOperationException>(() => boundPool.TargetDedicatedComputeNodes = 1);
                Assert.Throws <InvalidOperationException>(() => boundPool.VirtualMachineSize          = "cannot-change-1");


                // Swap the value with the name and the name with the value.
                boundPool.Metadata = new[] { new MetadataItem(metadataItem.Value, metadataItem.Name) };
                Assert.Equal(metadataItem.Name, boundPool.Metadata.First().Value);
                Assert.Equal(metadataItem.Value, boundPool.Metadata.First().Name);
            }
        }
        public void CloudJob_WhenReturnedFromServer_HasExpectedBoundProperties()
        {
            const string jobId              = "id-123";
            const string displayName        = "DisplayNameFoo";
            string       applicationVersion = "beta";
            string       applicationId      = "test";

            MetadataItem metadataItem       = new MetadataItem("foo", "bar");
            const int    priority           = 0;
            var          onAllTasksComplete = OnAllTasksComplete.TerminateJob;

            using (BatchClient client = ClientUnitTestCommon.CreateDummyClient())
            {
                DateTime creationTime = DateTime.Now;

                Models.CloudJob protoJob = new Models.CloudJob(
                    jobId,
                    displayName,
                    jobManagerTask: new Models.JobManagerTask()
                {
                    ApplicationPackageReferences = new [] { new Models.ApplicationPackageReference()
                                                            {
                                                                ApplicationId = applicationId, Version = applicationVersion
                                                            } }
                },
                    metadata: new[] { new Models.MetadataItem {
                                          Name = metadataItem.Name, Value = metadataItem.Value
                                      } },
                    creationTime: creationTime,
                    priority: priority,
                    url: ClientUnitTestCommon.DummyBaseUrl,
                    onAllTasksComplete: Models.OnAllTasksComplete.NoAction);

                CloudJob boundJob = client.JobOperations.GetJob(jobId, additionalBehaviors: InterceptorFactory.CreateGetJobRequestInterceptor(protoJob));

                Assert.Equal(jobId, boundJob.Id); // reading is allowed from a job that is returned from the server.
                Assert.Equal(creationTime, boundJob.CreationTime);
                Assert.Equal(displayName, boundJob.DisplayName);
                Assert.Equal(applicationId, boundJob.JobManagerTask.ApplicationPackageReferences.First().ApplicationId);
                Assert.Equal(applicationVersion, boundJob.JobManagerTask.ApplicationPackageReferences.First().Version);

                AssertPatchableJobPropertiesCanBeWritten(boundJob, priority, metadataItem, onAllTasksComplete);

                // Can only read a url from a returned object.
                Assert.Equal(ClientUnitTestCommon.DummyBaseUrl, boundJob.Url);

                // Cannot change a bound displayName, Id and any property on a JobManagerTask.
                Assert.Throws <InvalidOperationException>(() => boundJob.DisplayName = "cannot-change-display-name");
                Assert.Throws <InvalidOperationException>(() => boundJob.Id          = "cannot-change-id");
                Assert.Throws <InvalidOperationException>(() => boundJob.JobManagerTask.ApplicationPackageReferences = new List <ApplicationPackageReference>());
                Assert.Throws <InvalidOperationException>(() => boundJob.JobManagerTask = new JobManagerTask());
            }
        }