示例#1
0
        /// <summary>
        /// <see cref="IProvider{TTSingle,TMultiple,TPrimaryKey}.Post(TMultiple, string[], string[])">Post</see>
        /// </summary>
        public virtual IHttpActionResult Post(TMultiple obj, [MatrixParameter] string[] zoneId = null, [MatrixParameter] string[] contextId = null)
        {
            string sessionToken;

            if (!authenticationService.VerifyAuthenticationHeader(Request.Headers, out sessionToken))
            {
                return(Unauthorized());
            }

            // Check ACLs and return StatusCode(HttpStatusCode.Forbidden) if appropriate.
            if (!authorisationService.IsAuthorised(Request.Headers, sessionToken, $"{TypeName}s", RightType.CREATE))
            {
                return(StatusCode(HttpStatusCode.Forbidden));
            }

            if ((zoneId != null && zoneId.Length != 1) || (contextId != null && contextId.Length != 1))
            {
                return(BadRequest("Request failed for object " + typeof(TSingle).Name + " as Zone and/or Context are invalid."));
            }

            bool?mustUseAdvisory = HttpUtils.GetMustUseAdvisory(Request.Headers);
            MultipleCreateResponse multipleCreateResponse =
                ((IProviderService <TSingle, TMultiple>)service).Create(obj, mustUseAdvisory, zoneId: (zoneId == null ? null : zoneId[0]), contextId: (contextId == null ? null : contextId[0]));
            createResponseType createResponse = MapperFactory.CreateInstance <MultipleCreateResponse, createResponseType>(multipleCreateResponse);
            IHttpActionResult  result         = Ok(createResponse);

            return(result);
        }
        /// <summary>
        /// <see cref="IProvider{TTSingle,TMultiple,TPrimaryKey}.Post(TMultiple, string[], string[])">Post</see>
        /// </summary>
        public override IHttpActionResult Post(
            TMultiple obj,
            [MatrixParameter] string[] zoneId    = null,
            [MatrixParameter] string[] contextId = null)
        {
            if (!AuthenticationService.VerifyAuthenticationHeader(Request.Headers, out string sessionToken))
            {
                return(Unauthorized());
            }

            // Check ACLs and return StatusCode(HttpStatusCode.Forbidden) if appropriate.
            if (!AuthorisationService.IsAuthorised(Request.Headers, sessionToken, $"{TypeName}s", RightType.CREATE))
            {
                return(StatusCode(HttpStatusCode.Forbidden));
            }

            if ((zoneId != null && zoneId.Length != 1) || (contextId != null && contextId.Length != 1))
            {
                return(BadRequest($"Request failed for object {TypeName} as Zone and/or Context are invalid."));
            }

            bool?mustUseAdvisory = HttpUtils.GetMustUseAdvisory(Request.Headers);

            RequestParameter[]     requestParameters      = GetQueryParameters(Request);
            MultipleCreateResponse multipleCreateResponse = service.Create(
                obj,
                mustUseAdvisory,
                zoneId?[0],
                contextId?[0],
                requestParameters);
            createResponseType createResponse =
                MapperFactory.CreateInstance <MultipleCreateResponse, createResponseType>(multipleCreateResponse);

            return(Ok(createResponse));
        }
        /// <summary>
        /// Create a multiple Jobs with the defaults provided, and persist it to the data store
        /// </summary>
        /// <param name="jobs">Job objects with defaults to use when creating the Jobs</param>
        /// <param name="zoneId">The zone in which to create the Jobs</param>
        /// <param name="contextId">The context in which to create the Jobs</param>
        /// <returns>A MultipleCreateResponse object</returns>
        public virtual MultipleCreateResponse Create(List <Job> jobs, string zoneId = null, string contextId = null)
        {
            checkRegistered();

            string jobName = checkJobs(jobs, RightType.CREATE, zoneId);

            string url  = GetURLPrefix(jobName) + HttpUtils.MatrixParameters(zoneId, contextId);
            string body = SerialiseMultiple(jobs);
            string xml  = HttpUtils.PostRequest(
                url,
                RegistrationService.AuthorisationToken,
                body,
                ConsumerSettings.CompressPayload,
                ServiceType.FUNCTIONAL);

            if (log.IsDebugEnabled)
            {
                log.Debug("XML from POST request ...");
            }
            if (log.IsDebugEnabled)
            {
                log.Debug(xml);
            }
            createResponseType     createResponseType = SerialiserFactory.GetXmlSerialiser <createResponseType>().Deserialise(xml);
            MultipleCreateResponse createResponse     = MapperFactory.CreateInstance <createResponseType, MultipleCreateResponse>(createResponseType);

            return(createResponse);
        }
示例#4
0
        /// <summary>
        /// Convenience method that processes a MultipleCreateResponse message and fetches all successfully created
        /// jobs. It does this by issuing multiple individual query requests for any create status codes that start
        /// with a "2" (OK, Created, etc.).
        /// </summary>
        /// <param name="creates">A MultipleCreateResponse object to parse</param>
        /// <param name="jobName">The job name (singular) that the MultipleCreateResponse refers to</param>
        /// <param name="zoneId">The zone in which to fetch the Jobs</param>
        /// <param name="contextId">The context in which to fetch the Jobs</param>
        /// <returns>The created Job objects</returns>
        public virtual IList <Job> GetCreated(
            MultipleCreateResponse creates,
            string jobName,
            string zoneId    = null,
            string contextId = null)
        {
            if (creates == null)
            {
                throw new ArgumentNullException(nameof(creates));
            }

            IList <Job> fetched = new List <Job>();
            IList <Job> toFetch = (from CreateStatus s in creates.StatusRecords
                                   where s.StatusCode.StartsWith("2")
                                   select new Job()
            {
                Id = Guid.Parse(s.Id),
                Name = jobName
            }).ToList();

            foreach (Job job in toFetch)
            {
                fetched.Add(Query(job, zoneId, contextId));
            }

            return(fetched);
        }
示例#5
0
        /// <summary>
        /// <see cref="IConsumer{TSingle,TMultiple,TPrimaryKey}.Create(TMultiple, bool?, string, string, RequestParameter[])">Create</see>
        /// </summary>
        public virtual MultipleCreateResponse Create(
            TMultiple obj,
            bool?mustUseAdvisory = null,
            string zoneId        = null,
            string contextId     = null,
            params RequestParameter[] requestParameters)
        {
            if (!RegistrationService.Registered)
            {
                throw new InvalidOperationException("Consumer has not registered.");
            }

            var url = new StringBuilder(EnvironmentUtils.ParseServiceUrl(EnvironmentTemplate))
                      .Append($"/{TypeName}s")
                      .Append(HttpUtils.MatrixParameters(zoneId, contextId))
                      .Append(GenerateQueryParameterString(requestParameters))
                      .ToString();
            string requestBody  = SerialiseMultiple(obj);
            string responseBody = HttpUtils.PostRequest(
                url,
                RegistrationService.AuthorisationToken,
                requestBody,
                ConsumerSettings.CompressPayload,
                contentTypeOverride: ContentType.ToDescription(),
                acceptOverride: Accept.ToDescription(),
                mustUseAdvisory: mustUseAdvisory);

            if (log.IsDebugEnabled)
            {
                log.Debug("Response from POST request ...");
            }
            if (log.IsDebugEnabled)
            {
                log.Debug(responseBody);
            }

            createResponseType createResponseType =
                SerialiserFactory.GetSerialiser <createResponseType>(Accept).Deserialise(responseBody);
            MultipleCreateResponse createResponse =
                MapperFactory.CreateInstance <createResponseType, MultipleCreateResponse>(createResponseType);

            return(createResponse);
        }
        private static IList <Guid> ProcessCreates(MultipleCreateResponse creates)
        {
            if (creates == null)
            {
                throw new ArgumentNullException("creates");
            }

            List <Guid> ids = new List <Guid>();

            foreach (CreateStatus s in creates.StatusRecords)
            {
                if (s.StatusCode.StartsWith("2"))
                {
                    log.Info("Created a job with id " + s.Id + " (" + s.StatusCode + ").");
                    ids.Add(Guid.Parse(s.Id));
                }
                else
                {
                    log.Info("Failed to create a job with id " + s.Id + " (" + s.StatusCode + "/" + s.Error.Code + ").\nDescription: " + s.Error.Description + "\nMessage: " + s.Error.Message);
                }
            }
            return(ids);
        }
示例#7
0
        /// <summary>
        /// <see cref="IConsumer{TSingle,TMultiple,TPrimaryKey}.Create(TMultiple, string, string)">Create</see>
        /// </summary>
        public virtual MultipleCreateResponse Create(TMultiple obj, string zoneId = null, string contextId = null)
        {
            if (!RegistrationService.Registered)
            {
                throw new InvalidOperationException("Consumer has not registered.");
            }

            string url  = EnvironmentUtils.ParseServiceUrl(EnvironmentTemplate) + "/" + TypeName + "s" + HttpUtils.MatrixParameters(zoneId, contextId);
            string body = SerialiseMultiple(obj);
            string xml  = HttpUtils.PostRequest(url, RegistrationService.AuthorisationToken, body);

            if (log.IsDebugEnabled)
            {
                log.Debug("XML from POST request ...");
            }
            if (log.IsDebugEnabled)
            {
                log.Debug(xml);
            }
            createResponseType     createResponseType = SerialiserFactory.GetXmlSerialiser <createResponseType>().Deserialise(xml);
            MultipleCreateResponse createResponse     = MapperFactory.CreateInstance <createResponseType, MultipleCreateResponse>(createResponseType);

            return(createResponse);
        }
        void RunSchoolInfoConsumer()
        {
            SchoolInfoConsumer schoolInfoConsumer = new SchoolInfoConsumer(SettingsManager.ConsumerSettings.ApplicationKey, SettingsManager.ConsumerSettings.InstanceId, SettingsManager.ConsumerSettings.UserToken, SettingsManager.ConsumerSettings.SolutionId);

            schoolInfoConsumer.Register();

            try
            {
                // Query all schools.
                IEnumerable <SchoolInfo> allSchools = schoolInfoConsumer.Query();

                foreach (SchoolInfo school in allSchools)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("School " + school.SchoolName + " has a RefId of " + school.RefId + ".");
                    }
                }

                if (log.IsInfoEnabled)
                {
                    log.Info("School count is " + allSchools.Count());
                }

                // Create multiple schools.
                MultipleCreateResponse createResponse = schoolInfoConsumer.Create(CreateSchools());

                foreach (CreateStatus status in createResponse.StatusRecords)
                {
                    SchoolInfo school = schoolInfoConsumer.Query(status.Id);
                    if (log.IsInfoEnabled)
                    {
                        log.Info("New school " + school.SchoolName + " has a RefId of " + school.RefId + ".");
                    }
                }

                // Update multiple schools.
                List <SchoolInfo> schoolsToUpdate = new List <SchoolInfo>();

                foreach (CreateStatus status in createResponse.StatusRecords)
                {
                    SchoolInfo school = schoolInfoConsumer.Query(status.Id);
                    school.SchoolName += "x";
                    schoolsToUpdate.Add(school);
                }

                MultipleUpdateResponse updateResponse = schoolInfoConsumer.Update(schoolsToUpdate);

                foreach (UpdateStatus status in updateResponse.StatusRecords)
                {
                    SchoolInfo school = schoolInfoConsumer.Query(status.Id);
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Updated school " + school.SchoolName + " has a RefId of " + school.RefId + ".");
                    }
                }

                // Delete multiple schools.
                ICollection <string> schoolsToDelete = new List <string>();

                foreach (CreateStatus status in createResponse.StatusRecords)
                {
                    schoolsToDelete.Add(status.Id);
                }

                MultipleDeleteResponse deleteResponse = schoolInfoConsumer.Delete(schoolsToDelete);

                foreach (DeleteStatus status in deleteResponse.StatusRecords)
                {
                    SchoolInfo school = schoolInfoConsumer.Query(status.Id);

                    if (school == null)
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info("School with RefId of " + status.Id + " has been deleted.");
                        }
                    }
                    else
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info("School " + school.SchoolName + " with RefId of " + school.RefId + " FAILED deletion.");
                        }
                    }
                }
            }
            finally
            {
                schoolInfoConsumer.Unregister();
            }
        }
        public void ExplicitResponseMapperTest()
        {
            // Error.
            ResponseError srcError = new ResponseError {
                Code = 123, Description = "Err desc", Id = "42", Message = "Error occurred", Scope = "request"
            };
            errorType destError = MapperFactory.CreateInstance <ResponseError, errorType>(srcError);

            // Create.
            CreateStatus srcCreateStatus = new CreateStatus {
                AdvisoryId = "src456", Error = srcError, Id = "cr8", StatusCode = "200"
            };
            createType             destCreateStatus  = MapperFactory.CreateInstance <CreateStatus, createType>(srcCreateStatus);
            MultipleCreateResponse srcCreateResponse = new MultipleCreateResponse {
                StatusRecords = new List <CreateStatus> {
                    srcCreateStatus
                }
            };
            createResponseType destCreateResponse = MapperFactory.CreateInstance <MultipleCreateResponse, createResponseType>(srcCreateResponse);
            int index = 0;

            // Assert that the mapping was successful.
            foreach (CreateStatus record in srcCreateResponse.StatusRecords)
            {
                Assert.AreEqual(record.AdvisoryId, destCreateResponse.creates[index].advisoryId);
                Assert.AreEqual(record.Error.Code, destCreateResponse.creates[index].error.code);
                Assert.AreEqual(record.Error.Description, destCreateResponse.creates[index].error.description);
                Assert.AreEqual(record.Error.Id, destCreateResponse.creates[index].error.id);
                Assert.AreEqual(record.Error.Message, destCreateResponse.creates[index].error.message);
                Assert.AreEqual(record.Error.Scope, destCreateResponse.creates[index].error.scope);
                Assert.AreEqual(record.Id, destCreateResponse.creates[index].id);
                Assert.AreEqual(record.StatusCode, destCreateResponse.creates[index].statusCode);
                index++;
            }

            // Delete.
            DeleteStatus srcDeleteStatus = new DeleteStatus {
                Error = srcError, Id = "del8", StatusCode = "300"
            };
            deleteStatus           destDeleteStatus  = MapperFactory.CreateInstance <DeleteStatus, deleteStatus>(srcDeleteStatus);
            MultipleDeleteResponse srcDeleteResponse = new MultipleDeleteResponse {
                StatusRecords = new List <DeleteStatus> {
                    srcDeleteStatus
                }
            };
            deleteResponseType destDeleteResponse = MapperFactory.CreateInstance <MultipleDeleteResponse, deleteResponseType>(srcDeleteResponse);

            index = 0;

            // Assert that the mapping was successful.
            foreach (DeleteStatus record in srcDeleteResponse.StatusRecords)
            {
                Assert.AreEqual(record.Error.Code, destDeleteResponse.deletes[index].error.code);
                Assert.AreEqual(record.Error.Description, destDeleteResponse.deletes[index].error.description);
                Assert.AreEqual(record.Error.Id, destDeleteResponse.deletes[index].error.id);
                Assert.AreEqual(record.Error.Message, destDeleteResponse.deletes[index].error.message);
                Assert.AreEqual(record.Error.Scope, destDeleteResponse.deletes[index].error.scope);
                Assert.AreEqual(record.Id, destDeleteResponse.deletes[index].id);
                Assert.AreEqual(record.StatusCode, destDeleteResponse.deletes[index].statusCode);
                index++;
            }

            // Update.
            UpdateStatus srcUpdateStatus = new UpdateStatus {
                Error = srcError, Id = "up8", StatusCode = "400"
            };
            updateType             destUpdateStatus  = MapperFactory.CreateInstance <UpdateStatus, updateType>(srcUpdateStatus);
            MultipleUpdateResponse srcUpdateResponse = new MultipleUpdateResponse {
                StatusRecords = new List <UpdateStatus> {
                    srcUpdateStatus
                }
            };
            updateResponseType destUpdateResponse = MapperFactory.CreateInstance <MultipleUpdateResponse, updateResponseType>(srcUpdateResponse);

            index = 0;

            // Assert that the mapping was successful.
            foreach (UpdateStatus record in srcUpdateResponse.StatusRecords)
            {
                Assert.AreEqual(record.Error.Code, destUpdateResponse.updates[index].error.code);
                Assert.AreEqual(record.Error.Description, destUpdateResponse.updates[index].error.description);
                Assert.AreEqual(record.Error.Id, destUpdateResponse.updates[index].error.id);
                Assert.AreEqual(record.Error.Message, destUpdateResponse.updates[index].error.message);
                Assert.AreEqual(record.Error.Scope, destUpdateResponse.updates[index].error.scope);
                Assert.AreEqual(record.Id, destUpdateResponse.updates[index].id);
                Assert.AreEqual(record.StatusCode, destUpdateResponse.updates[index].statusCode);
                index++;
            }
        }
        void RunPayloadConsumer()
        {
            FunctionalServiceConsumer consumer = new FunctionalServiceConsumer(SettingsManager.ConsumerSettings.ApplicationKey);

            consumer.Register();
            if (log.IsInfoEnabled)
            {
                log.Info("Registered the Consumer.");
            }

            try
            {
                // Create a new payload job.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Create a job.");
                }
                Job job = consumer.Create(new Job("Payload", "Testing"));
                if (log.IsInfoEnabled)
                {
                    log.Info("Created new job " + job.Name + " (" + job.Id + ")");
                }

                // Query phase "default".
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Check state of phase 'default', expecting NOTSTARTED.");
                }
                job = consumer.Query(job);
                PhaseState state = job.Phases["default"].GetCurrentState();
                if (state.Type == PhaseStateType.NOTSTARTED)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Got EXPECTED result, last modified at " + state.LastModified);
                    }
                }
                else
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Got UNEXPECTED result " + state.Type + ", last modified at " + state.LastModified);
                    }
                }

                // Execute CREATE to phase "default".
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Executing CREATE to phase 'default'.");
                }
                consumer.CreateToPhase(job, "default", "Sending CREATE", contentTypeOverride: "text/plain", acceptOverride: "text/plain");

                // Query phase "default".
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Check state of phase 'default', expecting INPROGRESS.");
                }
                job   = consumer.Query(job);
                state = job.Phases["default"].GetCurrentState();
                if (state.Type == PhaseStateType.INPROGRESS)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Got EXPECTED result, last modified at " + state.LastModified);
                    }
                }
                else
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Got UNEXPECTED result " + state.Type + ", last modified at " + state.LastModified);
                    }
                }

                // Execute UPDATE to phase "default".
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Executing UPDATE to phase 'default'.");
                }
                consumer.UpdateToPhase(job, "default", "Sending UPDATE", contentTypeOverride: "text/plain", acceptOverride: "text/plain");

                // Query phase "default".
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Check state of phase 'default', expecting COMPLETE.");
                }
                job   = consumer.Query(job);
                state = job.Phases["default"].GetCurrentState();
                if (state.Type == PhaseStateType.COMPLETED)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Got EXPECTED result, last modified at " + state.LastModified);
                    }
                }
                else
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Got UNEXPECTED result " + state.Type + ", last modified at " + state.LastModified);
                    }
                }

                // Execute DELETE to phase "default".
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Executing DELETE to phase 'default'.");
                }
                try {
                    consumer.DeleteToPhase(job, "default", "Sending DELETE", contentTypeOverride: "text/plain", acceptOverride: "text/plain");
                } catch (Exception e)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("EXPECTED exception due to access rights: " + e.Message);
                    }
                }

                // Execute UPDATE to phase "xml".
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Executing UPDATE to phase 'xml'.");
                }
                string xml = "";
                try
                {
                    xml = SerialiserFactory.GetXmlSerialiser <LearnerPersonal>().Serialise(CreateBruceWayne());
                } catch (Exception e)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.Error("***** Error serializing to xml: " + e.Message, e);
                    }
                }
                consumer.UpdateToPhase(job, "xml", xml, contentTypeOverride: "application/xml", acceptOverride: "text/plain");

                // Execute UPDATE to phase "json".
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Executing UPDATE to phase 'json'.");
                }
                string json = "";
                try
                {
                    json = JsonConvert.SerializeObject(CreateBruceWayne());
                } catch (Exception e)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.Error("***** Error serializing to json: " + e.Message, e);
                    }
                }

                consumer.UpdateToPhase(job, "json", json, contentTypeOverride: "application/json", acceptOverride: "text/plain");

                // Change state of phase "json".
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Executing CREATE to the state of phase 'json'.");
                }
                state = consumer.CreateToState(job, "json", new PhaseState(PhaseStateType.FAILED, "Because I want it to"));
                if (state.Type == PhaseStateType.FAILED)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Got EXPECTED result, last modified at " + state.LastModified);
                    }
                }
                else
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Got UNEXPECTED result " + state.Type + ", last modified at " + state.LastModified);
                    }
                }

                // Query phase "json".
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Check state of phase 'json', expecting FAILED.");
                }
                job   = consumer.Query(job);
                state = job.Phases["json"].GetCurrentState();
                if (state.Type == PhaseStateType.FAILED)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Got EXPECTED result, last modified at " + state.LastModified);
                    }
                }
                else
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Got UNEXPECTED result " + state.Type + ", last modified at " + state.LastModified);
                    }
                }

                // Delete the job.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Delete a job.");
                }
                consumer.Delete(job);
                try {
                    Job deleted = consumer.Query(job);

                    if (log.IsInfoEnabled)
                    {
                        log.Info("Shouldn't get here, provider should have caused an expection. Retrieving job with " + job.Id + " returned " + (job == null ? "null value" : "job object with ID " + deleted.Id) + ".");
                    }
                }
                catch (Exception e)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Job " + job.Id + " was successfully deleted. Provider responded with " + e.Message);
                    }
                }

                /*------------------------------------------*/
                /* Check multiple job creation and deletion */
                /*------------------------------------------*/
                List <Job> jobs = new List <Job>();
                for (int i = 0; i < 5; i++)
                {
                    jobs.Add(new Job("Payload"));
                }
                MultipleCreateResponse creates = consumer.Create(jobs);

                IList <Guid> ids = ProcessCreates(creates);
                jobs.Clear();
                foreach (Guid id in ids)
                {
                    jobs.Add(new Job("Payload")
                    {
                        Id = id
                    });
                }

                // Change a random job's id, whihc will result in:
                // 1) The missing job will be removed by the timeout
                // 2) We expect a single job to have an error when being removed
                jobs.ElementAt(random.Next(0, jobs.Count)).Id = Guid.NewGuid();

                MultipleDeleteResponse deletes = consumer.Delete(jobs);
            }
            catch (Exception e)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error(e.StackTrace);
                }
                throw new Exception(this.GetType().FullName, e);
            }
            finally
            {
                consumer.Unregister();
                if (log.IsInfoEnabled)
                {
                    log.Info("Unregistered the Consumer.");
                }
            }
        }
        void RunLearnerPersonalConsumer()
        {
            LearnerPersonalConsumer learnerPersonalConsumer = new LearnerPersonalConsumer(SettingsManager.ConsumerSettings.ApplicationKey);

            learnerPersonalConsumer.Register();
            if (log.IsInfoEnabled)
            {
                log.Info("Registered the Consumer.");
            }

            try
            {
                // Retrieve Bart Simpson using QBE.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Retrieve Bart Simpson using QBE.");
                }
                LearnerPersonal exampleLearner = new LearnerPersonal {
                    PersonalInformation = new PersonalInformationType
                    {
                        Name = new NameType
                        {
                            FamilyName = "Simpson",
                            GivenName  = "Bart"
                        }
                    }
                };
                IEnumerable <LearnerPersonal> filteredLearners = learnerPersonalConsumer.QueryByExample(exampleLearner);

                foreach (LearnerPersonal learner in filteredLearners)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Filtered learner name is " + learner.PersonalInformation.Name.GivenName + " " + learner.PersonalInformation.Name.FamilyName);
                    }
                }

                // Create a new learner.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Create a new learner.");
                }
                LearnerPersonal newLearner          = ConsumerApp.CreateBruceWayne();
                LearnerPersonal retrievedNewLearner = learnerPersonalConsumer.Create(newLearner);
                if (log.IsInfoEnabled)
                {
                    log.Info("Created new learner " + newLearner.PersonalInformation.Name.GivenName + " " + newLearner.PersonalInformation.Name.FamilyName);
                }

                // Create multiple new learners.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Create multiple new learners.");
                }
                List <LearnerPersonal> newLearners            = CreateLearners(5);
                MultipleCreateResponse multipleCreateResponse = learnerPersonalConsumer.Create(newLearners);
                int count = 0;

                foreach (CreateStatus status in multipleCreateResponse.StatusRecords)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Create status code is " + status.StatusCode);
                    }
                    newLearners[count++].RefId = status.Id;
                }

                // Update multiple learners.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Update multiple learners.");
                }
                foreach (LearnerPersonal learner in newLearners)
                {
                    learner.PersonalInformation.Name.GivenName += "o";
                }

                MultipleUpdateResponse multipleUpdateResponse = learnerPersonalConsumer.Update(newLearners);

                foreach (UpdateStatus status in multipleUpdateResponse.StatusRecords)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Update status code is " + status.StatusCode);
                    }
                }

                // Delete multiple learners.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Delete multiple learners.");
                }
                ICollection <string> refIds = new List <string>();

                foreach (CreateStatus status in multipleCreateResponse.StatusRecords)
                {
                    refIds.Add(status.Id);
                }

                MultipleDeleteResponse multipleDeleteResponse = learnerPersonalConsumer.Delete(refIds);

                foreach (DeleteStatus status in multipleDeleteResponse.StatusRecords)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Delete status code is " + status.StatusCode);
                    }
                }

                // Retrieve all learners from zone "Gov" and context "Curr".
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Retrieve all learners from zone \"Gov\" and context \"Curr\".");
                }
                IEnumerable <LearnerPersonal> learners = learnerPersonalConsumer.Query(zoneId: "Gov", contextId: "Curr");

                foreach (LearnerPersonal learner in learners)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Learner name is " + learner.PersonalInformation.Name.GivenName + " " + learner.PersonalInformation.Name.FamilyName);
                    }
                }

                if (learners.Count() > 1)
                {
                    // Retrieve a single learner.
                    if (log.IsInfoEnabled)
                    {
                        log.Info("*** Retrieve a single learner.");
                    }
                    string          learnerId     = learners.ElementAt(1).RefId;
                    LearnerPersonal secondLearner = learnerPersonalConsumer.Query(learnerId);
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Name of second learner is " + secondLearner.PersonalInformation.Name.GivenName + " " + secondLearner.PersonalInformation.Name.FamilyName);
                    }

                    // Update that learner and confirm.
                    if (log.IsInfoEnabled)
                    {
                        log.Info("*** Update that learner and confirm.");
                    }
                    secondLearner.PersonalInformation.Name.GivenName  = "Homer";
                    secondLearner.PersonalInformation.Name.FamilyName = "Simpson";
                    learnerPersonalConsumer.Update(secondLearner);
                    secondLearner = learnerPersonalConsumer.Query(learnerId);
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Name of second learner has been changed to " + secondLearner.PersonalInformation.Name.GivenName + " " + secondLearner.PersonalInformation.Name.FamilyName);
                    }

                    // Delete that learner and confirm.
                    if (log.IsInfoEnabled)
                    {
                        log.Info("*** Delete that learner and confirm.");
                    }
                    learnerPersonalConsumer.Delete(learnerId);
                    LearnerPersonal deletedLearner = learnerPersonalConsumer.Query(learnerId);
                    bool            learnerDeleted = (deletedLearner == null ? true : false);

                    if (learnerDeleted)
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info("Learner " + secondLearner.PersonalInformation.Name.GivenName + " " + secondLearner.PersonalInformation.Name.FamilyName + " was successfully deleted.");
                        }
                    }
                    else
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info("Learner " + secondLearner.PersonalInformation.Name.GivenName + " " + secondLearner.PersonalInformation.Name.FamilyName + " was NOT deleted.");
                        }
                    }
                }

                // Retrieve learners based on Teaching Group using Service Paths.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Retrieve learners based on Teaching Group using Service Paths.");
                }
                EqualCondition condition = new EqualCondition()
                {
                    Left = "TeachingGroups", Right = "597ad3fe-47e7-4b2c-b919-a93c564d19d0"
                };
                IList <EqualCondition> conditions = new List <EqualCondition>();
                conditions.Add(condition);
                IEnumerable <LearnerPersonal> teachingGroupLearners = learnerPersonalConsumer.QueryByServicePath(conditions);

                foreach (LearnerPersonal learner in teachingGroupLearners)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Learner name is " + learner.PersonalInformation.Name.GivenName + " " + learner.PersonalInformation.Name.FamilyName);
                    }
                }
            }
            catch (Exception e)
            {
                //if (log.IsInfoEnabled) log.Fatal(e.StackTrace);
                throw new Exception(this.GetType().FullName, e);
            }
            finally
            {
                learnerPersonalConsumer.Unregister();
                if (log.IsInfoEnabled)
                {
                    log.Info("Unregistered the Consumer.");
                }
            }
        }
        private void RunStudentPersonalConsumer()
        {
            StudentPersonalConsumer studentPersonalConsumer = new StudentPersonalConsumer(
                SettingsManager.ConsumerSettings.ApplicationKey,
                SettingsManager.ConsumerSettings.InstanceId,
                SettingsManager.ConsumerSettings.UserToken,
                SettingsManager.ConsumerSettings.SolutionId);

            studentPersonalConsumer.Register();
            if (log.IsInfoEnabled)
            {
                log.Info("Registered the Consumer.");
            }

            try
            {
                IEnumerable <StudentPersonal> queriedStudents = studentPersonalConsumer.DynamicQuery("[@id=1234]");

                foreach (StudentPersonal student in queriedStudents)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Queried student name is " + student.PersonInfo.Name.GivenName + " " + student.PersonInfo.Name.FamilyName);
                    }
                }

                // Retrieve Bart Simpson using QBE.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Retrieve Bart Simpson using QBE.");
                }
                NameOfRecordType name = new NameOfRecordType {
                    FamilyName = "Simpson", GivenName = "Bart"
                };
                PersonInfoType personInfo = new PersonInfoType {
                    Name = name
                };
                StudentPersonal studentPersonal = new StudentPersonal {
                    PersonInfo = personInfo
                };
                IEnumerable <StudentPersonal> filteredStudents = studentPersonalConsumer.QueryByExample(studentPersonal);

                foreach (StudentPersonal student in filteredStudents)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Filtered student name is " + student.PersonInfo.Name.GivenName + " " + student.PersonInfo.Name.FamilyName);
                    }
                }

                // Create a new student.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Create a new student.");
                }
                string[] text = new string[]
                {
                    @"
                        <MedicalCondition>
                            <ConditionID>Unique Medical Condition ID</ConditionID>
                            <Condition>Condition</Condition>
                            <Severity>Condition Severity</Severity>
                            <Details>Condition Details</Details>
                        </MedicalCondition>
                    "
                };
                SIF_ExtendedElementsTypeSIF_ExtendedElement extendedElement = new SIF_ExtendedElementsTypeSIF_ExtendedElement {
                    Name = "MedicalConditions", Text = text
                };
                SIF_ExtendedElementsTypeSIF_ExtendedElement[] extendedElements = new SIF_ExtendedElementsTypeSIF_ExtendedElement[] { extendedElement };
                NameOfRecordType newStudentName = new NameOfRecordType {
                    FamilyName = "Wayne", GivenName = "Bruce", Type = NameOfRecordTypeType.LGL
                };
                PersonInfoType newStudentInfo = new PersonInfoType {
                    Name = newStudentName
                };
                string          studentID  = Guid.NewGuid().ToString();
                StudentPersonal newStudent = new StudentPersonal {
                    RefId = studentID, LocalId = "555", PersonInfo = newStudentInfo, SIF_ExtendedElements = extendedElements
                };

                try
                {
                    StudentPersonal retrievedNewStudent = studentPersonalConsumer.Create(newStudent, true);
                    if (log.IsInfoEnabled)
                    {
                        log.Info($"Created new student {newStudent.PersonInfo.Name.GivenName} {newStudent.PersonInfo.Name.FamilyName} with ID of {studentID}.");
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info($"Access to create a new student is rejected.");
                    }
                }

                // Create multiple new students.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Create multiple new students.");
                }
                List <StudentPersonal> newStudents = CreateStudents(5);

                try
                {
                    MultipleCreateResponse multipleCreateResponse = studentPersonalConsumer.Create(newStudents);
                    int count = 0;

                    foreach (CreateStatus status in multipleCreateResponse.StatusRecords)
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info("Create status code is " + status.StatusCode);
                        }
                        newStudents[count++].RefId = status.Id;
                    }

                    // Update multiple students.
                    if (log.IsInfoEnabled)
                    {
                        log.Info("*** Update multiple students.");
                    }
                    foreach (StudentPersonal student in newStudents)
                    {
                        student.PersonInfo.Name.GivenName += "o";
                    }

                    try
                    {
                        MultipleUpdateResponse multipleUpdateResponse = studentPersonalConsumer.Update(newStudents);

                        foreach (UpdateStatus status in multipleUpdateResponse.StatusRecords)
                        {
                            if (log.IsInfoEnabled)
                            {
                                log.Info("Update status code is " + status.StatusCode);
                            }
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info($"Access to update multiple students is rejected.");
                        }
                    }

                    // Delete multiple students.
                    if (log.IsInfoEnabled)
                    {
                        log.Info("*** Delete multiple students.");
                    }
                    ICollection <string> refIds = new List <string>();

                    foreach (CreateStatus status in multipleCreateResponse.StatusRecords)
                    {
                        refIds.Add(status.Id);
                    }

                    try
                    {
                        MultipleDeleteResponse multipleDeleteResponse = studentPersonalConsumer.Delete(refIds);

                        foreach (DeleteStatus status in multipleDeleteResponse.StatusRecords)
                        {
                            if (log.IsInfoEnabled)
                            {
                                log.Info("Delete status code is " + status.StatusCode);
                            }
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info($"Access to delete multiple students is rejected.");
                        }
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info($"Access to create multiple new students is rejected.");
                    }
                }

                // Retrieve all students from zone "Gov" and context "Curr".
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Retrieve all students from zone \"Gov\" and context \"Curr\".");
                }
                IEnumerable <StudentPersonal> students = studentPersonalConsumer.Query(zoneId: "Gov", contextId: "Curr");

                foreach (StudentPersonal student in students)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Student name is " + student.PersonInfo.Name.GivenName + " " + student.PersonInfo.Name.FamilyName);
                    }
                }

                if (students.Count() > 1)
                {
                    // Retrieve a single student.
                    if (log.IsInfoEnabled)
                    {
                        log.Info("*** Retrieve a single student.");
                    }
                    string          studentId     = students.ElementAt(1).RefId;
                    StudentPersonal secondStudent = studentPersonalConsumer.Query(studentId);
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Name of second student is " + secondStudent.PersonInfo.Name.GivenName + " " + secondStudent.PersonInfo.Name.FamilyName);
                    }

                    // Update that student and confirm.
                    if (log.IsInfoEnabled)
                    {
                        log.Info("*** Update that student and confirm.");
                    }
                    secondStudent.PersonInfo.Name.GivenName  = "Homer";
                    secondStudent.PersonInfo.Name.FamilyName = "Simpson";

                    try
                    {
                        studentPersonalConsumer.Update(secondStudent);
                        secondStudent = studentPersonalConsumer.Query(studentId);
                        if (log.IsInfoEnabled)
                        {
                            log.Info("Name of second student has been changed to " + secondStudent.PersonInfo.Name.GivenName + " " + secondStudent.PersonInfo.Name.FamilyName);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info($"Access to update a student is rejected.");
                        }
                    }

                    // Delete that student and confirm.
                    if (log.IsInfoEnabled)
                    {
                        log.Info("*** Delete that student and confirm.");
                    }

                    try
                    {
                        studentPersonalConsumer.Delete(studentId);
                        StudentPersonal deletedStudent = studentPersonalConsumer.Query(studentId);
                        bool            studentDeleted = (deletedStudent == null ? true : false);

                        if (studentDeleted)
                        {
                            if (log.IsInfoEnabled)
                            {
                                log.Info("Student " + secondStudent.PersonInfo.Name.GivenName + " " + secondStudent.PersonInfo.Name.FamilyName + " was successfully deleted.");
                            }
                        }
                        else
                        {
                            if (log.IsInfoEnabled)
                            {
                                log.Info("Student " + secondStudent.PersonInfo.Name.GivenName + " " + secondStudent.PersonInfo.Name.FamilyName + " was NOT deleted.");
                            }
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info($"Access to delete a student is rejected.");
                        }
                    }
                }

                // Retrieve students based on Teaching Group using Service Paths.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Retrieve students based on Teaching Group using Service Paths.");
                }
                EqualCondition condition = new EqualCondition()
                {
                    Left = "TeachingGroups", Right = "597ad3fe-47e7-4b2c-b919-a93c564d19d0"
                };
                IList <EqualCondition> conditions = new List <EqualCondition>
                {
                    condition
                };

                try
                {
                    IEnumerable <StudentPersonal> teachingGroupStudents = studentPersonalConsumer.QueryByServicePath(conditions);

                    foreach (StudentPersonal student in teachingGroupStudents)
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info("Student name is " + student.PersonInfo.Name.GivenName + " " + student.PersonInfo.Name.FamilyName);
                        }

                        if (student.SIF_ExtendedElements != null && student.SIF_ExtendedElements.Length > 0)
                        {
                            foreach (SIF_ExtendedElementsTypeSIF_ExtendedElement element in student.SIF_ExtendedElements)
                            {
                                foreach (string content in element.Text)
                                {
                                    if (log.IsInfoEnabled)
                                    {
                                        log.Info("Extended element text is ...\n" + content);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Access to query students by Service Path TeachingGroups/{}/StudentPersonals is rejected.");
                    }
                }

                // Retrieve student changes since a particular point as defined by the Changes Since marker.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Retrieve student changes since a particular point as defined by the Changes Since marker.");
                }
                string changesSinceMarker = studentPersonalConsumer.GetChangesSinceMarker();
                IEnumerable <StudentPersonal> changedStudents = studentPersonalConsumer.QueryChangesSince(changesSinceMarker, out string nextChangesSinceMarker);
                if (log.IsInfoEnabled)
                {
                    log.Info("Iteration 1 - Student changes based on Changes Since marker - " + changesSinceMarker);
                }

                if (changedStudents == null || changedStudents.Count() == 0)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("No student changes");
                    }
                }
                else
                {
                    foreach (StudentPersonal student in changedStudents)
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info("Student name is " + student.PersonInfo.Name.GivenName + " " + student.PersonInfo.Name.FamilyName);
                        }
                    }
                }

                changesSinceMarker     = nextChangesSinceMarker;
                nextChangesSinceMarker = null;
                changedStudents        = studentPersonalConsumer.QueryChangesSince(changesSinceMarker, out nextChangesSinceMarker);
                if (log.IsInfoEnabled)
                {
                    log.Info("Iteration 2 - Student changes based on Changes Since marker - " + changesSinceMarker);
                }

                if (changedStudents == null || changedStudents.Count() == 0)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("No student changes");
                    }
                }
                else
                {
                    foreach (StudentPersonal student in changedStudents)
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info("Student name is " + student.PersonInfo.Name.GivenName + " " + student.PersonInfo.Name.FamilyName);
                        }
                    }
                }

                changesSinceMarker     = nextChangesSinceMarker;
                nextChangesSinceMarker = null;
                changedStudents        = studentPersonalConsumer.QueryChangesSince(changesSinceMarker, out nextChangesSinceMarker);
                if (log.IsInfoEnabled)
                {
                    log.Info("Iteration 3 - Student changes based on Changes Since marker - " + changesSinceMarker);
                }

                if (changedStudents == null || changedStudents.Count() == 0)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("No student changes");
                    }
                }
                else
                {
                    foreach (StudentPersonal student in changedStudents)
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info("Student name is " + student.PersonInfo.Name.GivenName + " " + student.PersonInfo.Name.FamilyName);
                        }
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                if (log.IsInfoEnabled)
                {
                    log.Info($"Access to query students is rejected.");
                }
            }
            catch (Exception e)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("Error running the StudentPersonal Consumer.\n" + ExceptionUtils.InferErrorResponseMessage(e), e);
                }
            }
            finally
            {
                studentPersonalConsumer.Unregister();
                if (log.IsInfoEnabled)
                {
                    log.Info("Unregistered the Consumer.");
                }
            }
        }
示例#13
0
        void RunSchoolInfoConsumer()
        {
            SchoolInfoConsumer schoolInfoConsumer = new SchoolInfoConsumer("HITS", null, "0EE41AE6-C43F-11E3-9050-E0F4DBD909AB", "HITS");

            schoolInfoConsumer.Register();

            try
            {
                // Query all schools.
                IEnumerable <SchoolInfo> allSchools = schoolInfoConsumer.Query();

                foreach (SchoolInfo school in allSchools)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("School " + school.SchoolName + " has a RefId of " + school.RefId + ".");
                    }
                }

                if (log.IsInfoEnabled)
                {
                    log.Info("School count is " + allSchools.Count());
                }

                // Create multiple schools.
                MultipleCreateResponse createResponse = schoolInfoConsumer.Create(CreateSchools());

                foreach (CreateStatus status in createResponse.StatusRecords)
                {
                    SchoolInfo school = schoolInfoConsumer.Query(status.Id);
                    if (log.IsInfoEnabled)
                    {
                        log.Info("New school " + school.SchoolName + " has a RefId of " + school.RefId + ".");
                    }
                }

                // Update multiple schools.
                List <SchoolInfo> schoolsToUpdate = new List <SchoolInfo>();

                foreach (CreateStatus status in createResponse.StatusRecords)
                {
                    SchoolInfo school = schoolInfoConsumer.Query(status.Id);
                    school.SchoolName += "x";
                    schoolsToUpdate.Add(school);
                }

                MultipleUpdateResponse updateResponse = schoolInfoConsumer.Update(schoolsToUpdate);

                foreach (UpdateStatus status in updateResponse.StatusRecords)
                {
                    SchoolInfo school = schoolInfoConsumer.Query(status.Id);
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Updated school " + school.SchoolName + " has a RefId of " + school.RefId + ".");
                    }
                }

                // Delete multiple schools.
                ICollection <string> schoolsToDelete = new List <string>();

                foreach (CreateStatus status in createResponse.StatusRecords)
                {
                    schoolsToDelete.Add(status.Id);
                }

                MultipleDeleteResponse deleteResponse = schoolInfoConsumer.Delete(schoolsToDelete);

                foreach (DeleteStatus status in deleteResponse.StatusRecords)
                {
                    SchoolInfo school = schoolInfoConsumer.Query(status.Id);

                    if (school == null)
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info("School with RefId of " + status.Id + " has been deleted.");
                        }
                    }
                    else
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info("School " + school.SchoolName + " with RefId of " + school.RefId + " FAILED deletion.");
                        }
                    }
                }
            }
            finally
            {
                schoolInfoConsumer.Unregister();
            }
        }
示例#14
0
        void RunStudentPersonalConsumer()
        {
            StudentPersonalConsumer studentPersonalConsumer = new StudentPersonalConsumer("Sif3DemoApp");

            studentPersonalConsumer.Register();
            if (log.IsInfoEnabled)
            {
                log.Info("Registered the Consumer.");
            }

            try
            {
                // Retrieve Bart Simpson using QBE.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Retrieve Bart Simpson using QBE.");
                }
                NameOfRecordType name = new NameOfRecordType {
                    FamilyName = "Simpson", GivenName = "Bart"
                };
                PersonInfoType personInfo = new PersonInfoType {
                    Name = name
                };
                StudentPersonal studentPersonal = new StudentPersonal {
                    PersonInfo = personInfo
                };
                IEnumerable <StudentPersonal> filteredStudents = studentPersonalConsumer.QueryByExample(studentPersonal);

                foreach (StudentPersonal student in filteredStudents)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Filtered student name is " + student.PersonInfo.Name.GivenName + " " + student.PersonInfo.Name.FamilyName);
                    }
                }

                // Create a new student.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Create a new student.");
                }
                string[] text = new string[]
                {
                    @"
                        <MedicalCondition>
                            <ConditionID>Unique Medical Condition ID</ConditionID>
                            <Condition>Condition</Condition>
                            <Severity>Condition Severity</Severity>
                            <Details>Condition Details</Details>
                        </MedicalCondition>
                    "
                };
                SIF_ExtendedElementsTypeSIF_ExtendedElement extendedElement = new SIF_ExtendedElementsTypeSIF_ExtendedElement {
                    Name = "MedicalConditions", Text = text
                };
                SIF_ExtendedElementsTypeSIF_ExtendedElement[] extendedElements = new SIF_ExtendedElementsTypeSIF_ExtendedElement[] { extendedElement };
                NameOfRecordType newStudentName = new NameOfRecordType {
                    FamilyName = "Wayne", GivenName = "Bruce", Type = NameOfRecordTypeType.LGL
                };
                PersonInfoType newStudentInfo = new PersonInfoType {
                    Name = newStudentName
                };
                StudentPersonal newStudent = new StudentPersonal {
                    LocalId = "555", PersonInfo = newStudentInfo, SIF_ExtendedElements = extendedElements
                };
                StudentPersonal retrievedNewStudent = studentPersonalConsumer.Create(newStudent);
                if (log.IsInfoEnabled)
                {
                    log.Info("Created new student " + newStudent.PersonInfo.Name.GivenName + " " + newStudent.PersonInfo.Name.FamilyName);
                }

                // Create multiple new students.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Create multiple new students.");
                }
                List <StudentPersonal> newStudents            = CreateStudents(5);
                MultipleCreateResponse multipleCreateResponse = studentPersonalConsumer.Create(newStudents);
                int count = 0;

                foreach (CreateStatus status in multipleCreateResponse.StatusRecords)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Create status code is " + status.StatusCode);
                    }
                    newStudents[count++].RefId = status.Id;
                }

                // Update multiple students.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Update multiple students.");
                }
                foreach (StudentPersonal student in newStudents)
                {
                    student.PersonInfo.Name.GivenName += "o";
                }

                MultipleUpdateResponse multipleUpdateResponse = studentPersonalConsumer.Update(newStudents);

                foreach (UpdateStatus status in multipleUpdateResponse.StatusRecords)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Update status code is " + status.StatusCode);
                    }
                }

                // Delete multiple students.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Delete multiple students.");
                }
                ICollection <string> refIds = new List <string>();

                foreach (CreateStatus status in multipleCreateResponse.StatusRecords)
                {
                    refIds.Add(status.Id);
                }

                MultipleDeleteResponse multipleDeleteResponse = studentPersonalConsumer.Delete(refIds);

                foreach (DeleteStatus status in multipleDeleteResponse.StatusRecords)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Delete status code is " + status.StatusCode);
                    }
                }

                // Retrieve all students from zone "Gov" and context "Curr".
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Retrieve all students from zone \"Gov\" and context \"Curr\".");
                }
                IEnumerable <StudentPersonal> students = studentPersonalConsumer.Query(zone: "Gov", context: "Curr");

                foreach (StudentPersonal student in students)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Student name is " + student.PersonInfo.Name.GivenName + " " + student.PersonInfo.Name.FamilyName);
                    }
                }

                if (students.Count() > 1)
                {
                    // Retrieve a single student.
                    if (log.IsInfoEnabled)
                    {
                        log.Info("*** Retrieve a single student.");
                    }
                    string          studentId     = students.ElementAt(1).RefId;
                    StudentPersonal secondStudent = studentPersonalConsumer.Query(studentId);
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Name of second student is " + secondStudent.PersonInfo.Name.GivenName + " " + secondStudent.PersonInfo.Name.FamilyName);
                    }

                    // Update that student and confirm.
                    if (log.IsInfoEnabled)
                    {
                        log.Info("*** Update that student and confirm.");
                    }
                    secondStudent.PersonInfo.Name.GivenName  = "Homer";
                    secondStudent.PersonInfo.Name.FamilyName = "Simpson";
                    studentPersonalConsumer.Update(secondStudent);
                    secondStudent = studentPersonalConsumer.Query(studentId);
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Name of second student has been changed to " + secondStudent.PersonInfo.Name.GivenName + " " + secondStudent.PersonInfo.Name.FamilyName);
                    }

                    // Delete that student and confirm.
                    if (log.IsInfoEnabled)
                    {
                        log.Info("*** Delete that student and confirm.");
                    }
                    studentPersonalConsumer.Delete(studentId);
                    StudentPersonal deletedStudent = studentPersonalConsumer.Query(studentId);
                    bool            studentDeleted = (deletedStudent == null ? true : false);

                    if (studentDeleted)
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info("Student " + secondStudent.PersonInfo.Name.GivenName + " " + secondStudent.PersonInfo.Name.FamilyName + " was successfully deleted.");
                        }
                    }
                    else
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.Info("Student " + secondStudent.PersonInfo.Name.GivenName + " " + secondStudent.PersonInfo.Name.FamilyName + " was NOT deleted.");
                        }
                    }
                }

                // Retrieve students based on Teaching Group using Service Paths.
                if (log.IsInfoEnabled)
                {
                    log.Info("*** Retrieve students based on Teaching Group using Service Paths.");
                }
                EqualCondition condition = new EqualCondition()
                {
                    Left = "TeachingGroups", Right = "597ad3fe-47e7-4b2c-b919-a93c564d19d0"
                };
                IList <EqualCondition> conditions = new List <EqualCondition>();
                conditions.Add(condition);
                IEnumerable <StudentPersonal> teachingGroupStudents = studentPersonalConsumer.QueryByServicePath(conditions);

                foreach (StudentPersonal student in teachingGroupStudents)
                {
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Student name is " + student.PersonInfo.Name.GivenName + " " + student.PersonInfo.Name.FamilyName);
                    }

                    if (student.SIF_ExtendedElements != null && student.SIF_ExtendedElements.Length > 0)
                    {
                        foreach (SIF_ExtendedElementsTypeSIF_ExtendedElement element in student.SIF_ExtendedElements)
                        {
                            foreach (string content in element.Text)
                            {
                                if (log.IsInfoEnabled)
                                {
                                    log.Info("Extended element text is ...\n" + content);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                studentPersonalConsumer.Unregister();
                if (log.IsInfoEnabled)
                {
                    log.Info("Unregistered the Consumer.");
                }
            }
        }