public string TryGetMatcherDataOutputsCorrectMatcherData(string referenceName, int matcherIndex) { var sut = new ReferenceService(DefaultReferencedMatchersList, DefaultStatMatchersList); sut.TryGetMatcherData(referenceName, matcherIndex, out var matcherData); return(matcherData?.Regex); }
private static DigitalResource CreateNewResourceObject(ResourceModel.User owner, Stream fileStream, string originalName, ResourceType imageRT, ResourceType otherRT, string md5Sum) { DigitalResource resource = new ResourceModel.DigitalResource { Md5 = md5Sum, OriginalFileName = originalName, Size = fileStream.Length, Uploaded = DateTime.Now, Owners = new List <ResourceModel.User>() }; resource.Owners.Add(owner); if (ReferenceService.IsValidImage(fileStream)) { resource.Type = imageRT; //resource.Type = "Image"; resource.Date = ReferenceService.GetDateTakenFromImage(fileStream); } else { resource.Type = otherRT; resource.Date = null; } return(resource); }
internal DataErrorRoutingEngine(DataErrorService service) { dataErrorService = service; referenceRepository = new ReferenceRepository(); referenceService = new ReferenceService(); correctiveActionService = new CorrectiveActionService(); dataErrorRepository = service.repository; }
public void GetReferencesReturnsCorrectResultForStatMatchersName(string referenceName) { var sut = new ReferenceService(DefaultReferencedMatchersList, DefaultStatMatchersList); var expected = DefaultStatMatchersList .Where(r => r.ReferenceNames.Contains(referenceName)) .SelectMany(r => r.Select(d => d.Regex)); CollectionAssert.AreEqual(expected, sut.GetRegexes(referenceName)); }
public ErrorTypeDictionary() { IQueryable <ErrorType> errorTypes = new ReferenceService().RetrieveErrorTypes(); foreach (var errorType in errorTypes) { _errorTypes.Add(errorType.Id, errorType); } }
public EntityHandler(EventService eventService, ReferenceService referenceService, EntityType entity) : base(string.Empty, entity) { _eventService = eventService; _referenceService = referenceService; Entity = entity; SetEntityHandler(this); }
public void GetReferencesReturnsCorrectResultForReferencedMatchersName(string referenceName) { var sut = new ReferenceService(DefaultReferencedMatchersList, DefaultStatMatchersList); var expected = DefaultReferencedMatchersList .First(r => r.ReferenceName == referenceName).Data .Select(d => d.Regex); CollectionAssert.AreEqual(expected, sut.GetRegexes(referenceName)); }
/// <summary> /// Runs the code generation as configured using this instance's properties. /// </summary> /// <param name="progress">Optional handler of diagnostics provided by code generator.</param> /// <param name="cancellationToken">Cancellation token to interrupt async operations.</param> public void Generate(IProgress <Diagnostic> progress = null, CancellationToken cancellationToken = default) { Verify.Operation(SourcePathsToCompile != null, FormatVerifyOperationMessage(nameof(SourcePathsToCompile))); var compilation = CreateCompilation(cancellationToken); // TODO: TBD: we should have a pretty good idea whether an initial compilation would be successful... // TODO: TBD: as to whether any subsequent code generation would be justified... // TODO: TBD: and somehow capture/report those errors through caller channels... if (ReferenceService.TryLoad(out _)) { ReferenceService.PurgeNotExists(); } TryLoad(out _); PurgeRegistrySet(compilation, ReferenceService.AssembliesLastWrittenTimestamp); // TODO: TBD: need to pre-load the assemblies here ? // TODO: TBD: trim/shake the references if they do not exist at this moment ? cancellationToken.ThrowIfCancellationRequested(); foreach (var callback in new CodeGenerationFacilitationCallback[] { FacilitateAssemblyCodeGeneration, FacilitateDocumentCodeGeneration }) { callback.Invoke(compilation, progress, cancellationToken); } // Throw sooner if there were any file failures. if (FileFailures.Count > 0) { throw new AggregateException(FileFailures); } // Shake out the Compilation Set one last time; Remove is sufficient, no need to Purge anything. Registry.RemoveWhere(x => !x.GeneratedAssetKeys.Any()); // TODO: TBD: need to revisit these calls... // TODO: TBD: somewhere during the course of add references, etc, those should probably be registering with the service... ReferenceService.TrySave(); TrySave(); }
private IStringParser <IReadOnlyList <Modifier> > CreateParser() { var referenceService = new ReferenceService(_parsingData.ReferencedMatchers, _parsingData.StatMatchers); var regexGroupService = new RegexGroupService(_builderFactories.ValueBuilders); // The parsing pipeline using one IStatMatchers instance to parse a part of the stat. IStringParser <IIntermediateModifier> CreateInnerParser(IStatMatchers statMatchers) => new CachingStringParser <IIntermediateModifier>( new StatNormalizingParser <IIntermediateModifier>( new ResolvingParser( MatcherDataParser.Create( statMatchers.Data, new StatMatcherRegexExpander( referenceService, regexGroupService, statMatchers.MatchesWholeLineOnly).Expand), referenceService, new IntermediateModifierResolver(ModifierBuilder.Empty), regexGroupService ) ) ); Parallel.ForEach(_parsingData.StatMatchers, s => { _ = s.Data; }); var innerParserCache = _parsingData.StatMatchers.ToDictionary(Funcs.Identity, CreateInnerParser); // The steps define the order in which the inner parsers, and by extent the IStatMatchers, are executed. IStringParser <IIntermediateModifier> StepToParser(TStep step) => innerParserCache[_parsingData.SelectStatMatcher(step)]; // The full parsing pipeline. return (new ValidatingParser <IReadOnlyList <Modifier> >( new StatNormalizingParser <IReadOnlyList <Modifier> >( new ResultMappingParser <IReadOnlyList <IReadOnlyList <Modifier> >, IReadOnlyList <Modifier> >( new StatReplacingParser <IReadOnlyList <Modifier> >( new ResultMappingParser <IReadOnlyList <IIntermediateModifier>, IReadOnlyList <Modifier> >( new CompositeParser <IIntermediateModifier, TStep>(_parsingData.Stepper, StepToParser), AggregateAndBuild), _parsingData.StatReplacers ), (_, ls) => ls.Flatten().ToList() ) ) )); }
protected override async Task OnInitializedAsync() { await base.OnInitializedAsync(); if (ReferenceHandler.References == default) { IList <Reference> references = await ReferenceService.GetAsync(); ReferenceHandler.References = new ReadOnlyCollection <Reference>(references); } if (!string.IsNullOrEmpty(ReferenceName)) { Reference = ReferenceHandler.References.FirstOrDefault(r => r.RowKey == ReferenceName); ReferenceHandler.CurrentReference = Reference; } }
public void Get_One_Type_Many_times() { var refService = new ReferenceService(ConnectionString); for (var i = 0; i < 100000; i++) { var referenceItems = refService.GetAll(ReferenceType.ActionType); var enumerable = referenceItems as ReferenceItem[] ?? referenceItems.ToArray(); const string typeName = "ActionType"; Assert.True(referenceItems != null && enumerable.Any(), $"No results returned for type {typeName}"); Assert.True(!enumerable.Any(r => r.Id <= 0 && r.Id != -999999), $"Primary key has not been populated for type {typeName}"); Assert.True(!enumerable.Any(r => r.StartDate.Year <= 1750), $"Start date has not been populated for type {typeName}"); Assert.True(!enumerable.Any(r => r.Description.IsNullOrWhiteSpace()), $"description has nor been populated for type {typeName}"); } }
private IParser <IReadOnlyList <Modifier> > CreateParser() { var referenceService = new ReferenceService(_parsingData.ReferencedMatchers, _parsingData.StatMatchers); var regexGroupService = new RegexGroupService(_builderFactories.ValueBuilders); // The parsing pipeline using one IStatMatchers instance to parse a part of the stat. IParser <IIntermediateModifier> CreateInnerParser(IStatMatchers statMatchers) => new CachingParser <IIntermediateModifier>( new StatNormalizingParser <IIntermediateModifier>( new ResolvingParser( new MatcherDataParser( new StatMatcherRegexExpander(statMatchers, referenceService, regexGroupService)), referenceService, new IntermediateModifierResolver(new ModifierBuilder()), regexGroupService ) ) ); var innerParserCache = new Dictionary <IStatMatchers, IParser <IIntermediateModifier> >(); // The steps define the order in which the inner parsers, and by extent the IStatMatchers, are executed. IParser <IIntermediateModifier> StepToParser(TStep step) => innerParserCache.GetOrAdd(_parsingData.SelectStatMatcher(step), CreateInnerParser); // The full parsing pipeline. return (new ValidatingParser <IReadOnlyList <Modifier> >( new StatNormalizingParser <IReadOnlyList <Modifier> >( new ResultMappingParser <IReadOnlyList <IReadOnlyList <Modifier> >, IReadOnlyList <Modifier> >( new StatReplacingParser <IReadOnlyList <Modifier> >( new ResultMappingParser <IReadOnlyList <IIntermediateModifier>, IReadOnlyList <Modifier> >( new CompositeParser <IIntermediateModifier, TStep>(_parsingData.Stepper, StepToParser), AggregateAndBuild), _parsingData.StatReplacers ), ls => ls.Flatten().ToList() ) ) )); }
public void GetByCode_ShouldReturnExpectedEntity() { // Setup dependencies var occ1 = new RefOccupation { Code = "OCC1", Description = "Occupation 1" }; var occ2 = new RefOccupation { Code = "OCC2", Description = "Occupation 2" }; var referenceRepository = new MockReferenceRepository() .With(occ1) .With(occ2); // Call GetByCode var returnedEntity = new ReferenceService(referenceRepository).GetByCode <RefOccupation>("OCC1"); // Verify result Assert.AreEqual(occ1, returnedEntity); }
public void Get_ShouldReturnAllEntities() { // Setup Dependencies var occ1 = new RefOccupation { Code = "OCC1", Description = "Occupation 1" }; var occ2 = new RefOccupation { Code = "OCC2", Description = "Occupation 2" }; var referenceRepository = new MockReferenceRepository() .With(occ1) .With(occ2); // Call Get var returnedEntities = new ReferenceService(referenceRepository).Get <RefOccupation>(); // Verify result returnedEntities.ToList().AssertCollectionContainsItems(occ1, occ2); }
public void Can_Get_All_Types_From_Db() { var refService = new ReferenceService(ConnectionString); foreach (var rt in (ReferenceType[])Enum.GetValues(typeof(ReferenceType))) { var typeName = Enum.GetName(typeof(ReferenceType), rt); var referenceItems = refService.GetAll(rt); if (rt == ReferenceType.None) { referenceItems.Any().Should().BeFalse(); continue; } var enumerable = referenceItems as ReferenceItem[] ?? referenceItems.ToArray(); Assert.True(referenceItems != null && enumerable.Any(), $"No results returned for type {typeName}"); Assert.True(!enumerable.Any(r => r.Id <= 0 && r.Id != -99999), $"Primary key has not been populated for type {typeName}"); } }
public ReferenceServiceTest() { _referenceRepository = new Mock <IReferenceRepository>(); _systemRepository = new Mock <IItSystemRepository>(); _authorizationContext = new Mock <IAuthorizationContext>(); _transactionManager = new Mock <ITransactionManager>(); _dbTransaction = new Mock <IDatabaseTransaction>(); _systemUsageRepository = new Mock <IItSystemUsageRepository>(); _contractRepository = new Mock <IItContractRepository>(); _projectRepository = new Mock <IItProjectRepository>(); _sut = new ReferenceService( _referenceRepository.Object, _systemRepository.Object, _systemUsageRepository.Object, _contractRepository.Object, _projectRepository.Object, Mock.Of <IDataProcessingRegistrationRepository>(), _authorizationContext.Object, _transactionManager.Object, Mock.Of <IOperationClock>(x => x.Now == DateTime.Now), Mock.Of <IDomainEvents>() ); }
/// <summary> /// Saves a NEW resource. Only saves if resource with the MD5Sum has not previously been added. /// </summary> /// <param name="referenceRepository"></param> /// <param name="fileStream"></param> /// <param name="originalName"></param> /// <returns>DigitalResource with the length of the file. The Digital Resource may /// be newly created OR retrieved from the database if it already exists</returns> public ResourceModel.DigitalResource SaveOrGet(ReferenceRepository referenceRepository, ResourceModel.User owner, Stream fileStream, String originalName) { ResourceModel.DigitalResource resource = null; ResourceType imageRT = referenceRepository.AllResourceTypes().Where(x => x.Type == "Image").FirstOrDefault(); ResourceType otherRT = referenceRepository.AllResourceTypes().Where(x => x.Type == "Other").FirstOrDefault(); //User user = reference try { //calculate md5 of the file to upload string md5Sum = Md5Hash(fileStream); //bool exists = Exists(md5Sum); DigitalResource existingResource = Get(md5Sum); if (existingResource == null) { //create the resource object resource = new ResourceModel.DigitalResource { Md5 = md5Sum, OriginalFileName = originalName, Size = fileStream.Length, Uploaded = DateTime.Now, Owners = new List <ResourceModel.User>() }; resource.Owners.Add(owner); if (ReferenceService.IsValidImage(fileStream)) { resource.Type = imageRT; //resource.Type = "Image"; resource.Date = ReferenceService.GetDateTakenFromImage(fileStream); } else { resource.Type = otherRT; resource.Date = null; } //fileStream.Position = 0; //TransferUtilityUploadRequest tuu = new TransferUtilityUploadRequest //{ // InputStream = fileStream, // BucketName = "piccoli", // Key = "belvedere" //}; //tr.UploadAsync(tuu); //upload the file IAmazonS3 s3Client = new AmazonS3Client(); //ListBucketsResponse response = s3Client.ListBuckets(); using (TransferUtility tr = new TransferUtility(s3Client)) { tr.Upload(fileStream, "piccoli", md5Sum); //update the database SaveResource(resource); } } else { //another user also has a copy of this file if (existingResource.Owners.Where(x => x.UserName == owner.UserName).FirstOrDefault() == null) { existingResource.Owners.Add(owner); SaveResource(existingResource); } return(existingResource); } } catch (AmazonS3Exception ex) { throw ex; } return(resource); }
static void Main(string[] args) { try { Console.WriteLine(fileDirectory); string env = getEnvironment(args); logit("Environmemnt is set to " + env); string configFile = string.Format("qms_appsettings.{0}.json", env); logit(string.Format("Using {0} for configuration", configFile)); Config.Settings.Rebuild(configFile); logit("Building Context"); context = new QMSContext(); logit("Context Built"); logit("Retrieving Settings"); settingsList = retrieveSettings(env); logit("Settings defined"); setSettings(); sendQmsDataEmails(); logit("Instantiating Reference Service"); referenceService = new ReferenceService(context); logit("Instantiating Corrective Action Service"); correctiveActionService = new CorrectiveActionService(context); logit("Instantiating User Service"); userService = new UserService(context); logit("Instantiating Notification Service"); notificationService = new NotificationService(context); logit("Loading Active Users"); Users = userService.RetrieveActiveUsers(); logit("Should Event Based Emails be sent: " + shouldSendEventBasedEmails.ToString()); if (shouldSendEventBasedEmails) { logit("executeEventBasedEmails"); executeEventBasedEmails(); } logit("Check to see if time based emails have been sent for today"); EmailLog log = referenceService.RetrieveEmailLogByDate(logDate); if (log.EmailLogId == 0) //emails haven't been sent yet today { logit("Time based emails have not been sent for today"); sendReviewerNotifications(); sendSpecialistNotifications(); logit("saveNotifications"); saveNotifications(); log.SentDate = logDate; log.SentAmount = emailsSent; referenceService.SaveEmailLog(log); } else { logit("Time based emails have sent for today."); } logit("Write Log"); System.IO.File.WriteAllText(Config.Settings.LogDirectory + "EmailLog-" + env + ".txt", stringBuilder.ToString()); } catch (System.Exception x) { logit(x.ToString()); throw x; } }
private object OnCreateService(IServiceContainer container, Type serviceType) { object createdService = null; if (serviceType == typeof(ComponentSerializationService)) createdService = new XomlComponentSerializationService(LoaderHost); else if (serviceType == typeof(IReferenceService)) createdService = new ReferenceService(LoaderHost); else if (serviceType == typeof(IIdentifierCreationService)) createdService = new IdentifierCreationService(container, this); else if (serviceType == typeof(IWorkflowCompilerOptionsService)) createdService = new WorkflowCompilerOptionsService(); else if (serviceType == typeof(IDesignerVerbProviderService)) createdService = new DesignerVerbProviderService(); if (createdService != null) { if (this.createdServices == null) this.createdServices = new Hashtable(); object existingService = this.createdServices[serviceType]; this.createdServices[serviceType] = createdService; if (existingService != null) { OnDisposeService(serviceType, existingService); } } return createdService; }
public ReferencesController(ReferenceService referenceService) { _referenceService = referenceService; }
public ResultData DoStuff(EventData data) { ReferenceService refsvc; string res; switch ((CodesEnum)data.Code) { case CodesEnum.DEKBELCODE_ADDVOLUMETITLE: refsvc = new ReferenceService(); res = refsvc.EditVolumeTitle(data); Result = new ResultData { Code = 0, Message = $"New title set: {res}.", Cancel = string.IsNullOrWhiteSpace(res), }; break; case CodesEnum.DEKBELCODE_ADDBOOKTITLE: refsvc = new ReferenceService(); res = refsvc.AddReference <Book>(data); Result = new ResultData { Code = 0, Message = $"Added book: {res}.", Cancel = string.IsNullOrWhiteSpace(res), }; break; case CodesEnum.DEKBELCODE_ADDCHAPTER: refsvc = new ReferenceService(); res = refsvc.AddReference <Chapter>(data); Result = new ResultData { Code = 0, Message = $"Added chapter: {res}.", Cancel = string.IsNullOrWhiteSpace(res), }; break; case CodesEnum.DEKBELCODE_ADDSUBCHAPTER: refsvc = new ReferenceService(); res = refsvc.AddReference <SubChapter>(data); Result = new ResultData { Code = 0, Message = $"Added subchapter: {res}.", Cancel = string.IsNullOrWhiteSpace(res), }; break; case CodesEnum.DEKBELCODE_ADDPARAGRAPH: refsvc = new ReferenceService(); res = refsvc.AddReference <Paragraph>(data); Result = new ResultData { Code = 0, Message = $"Added paragraph: {res}.", Cancel = string.IsNullOrWhiteSpace(res), }; break; case CodesEnum.DEKBELCODE_ADDRAWCITATION: var mainService = new MainService(); var result = mainService.AddRawCitations(data); Result = new ResultData { Code = 0, Message = $"Added raw citation. Id = {result.Id}.", Cancel = false, }; break; case CodesEnum.DEKBELCODE_SHOWBEL: case CodesEnum.DEKBELCODE_ADDANDSHOWCITATION: BelGui belAdd = new BelGui(data); if (belAdd.IsDisposed) { Result = new ResultData { Cancel = true, Code = -1, Message = "Cancel" }; break; } belAdd.ShowDialog(); Result = belAdd.Result; break; case CodesEnum.DEKBELCODE_ADDCITATIONSILENT: var mainService2 = new MainService(); bool result2 = mainService2.AddCitationSilent(data); if (!result2) { Result = new ResultData { Cancel = true, Code = -1, Message = "Cancel" }; break; } break; case CodesEnum.DEKBELCODE_EDITCITATION: BelGui belEdit = new BelGui(data); if (belEdit.IsDisposed) { Result = new ResultData { Cancel = true, Code = -1, Message = "Cancel" }; break; } belEdit.ShowDialog(); Result = belEdit.Result; break; case CodesEnum.DEKBELCODE_STARTAUTOPAGINATION: refsvc = new ReferenceService(); var page = refsvc.AddPage(data); Result = new ResultData { Code = 0, Message = page == null ? "Page add canceled." : $"Added page reference. Id = {page.Id}.", Cancel = page == null, }; refsvc.Dispose(); break; default: break; } return(Result); }
private object OnCreateService(IServiceContainer container, Type serviceType) { object createdService = null; if (serviceType == typeof(IReferenceService)) createdService = new ReferenceService(LoaderHost); return createdService; }
public void GetReferencesReturnsEmptyEnumerableIfReferenceNameIsUnknown(string referenceName) { var sut = new ReferenceService(DefaultReferencedMatchersList, DefaultStatMatchersList); CollectionAssert.IsEmpty(sut.GetRegexes(referenceName)); }
/// <summary> /// Close all clients (connections) to web services. /// </summary> public static void CloseClients() { if (AnalysisService.IsNotNull()) { AnalysisService.CloseClients(); } if (GeoReferenceService.IsNotNull()) { GeoReferenceService.CloseClients(); } if (KulService.IsNotNull()) { KulService.CloseClients(); } if (MvmService.IsNotNull()) { MvmService.CloseClients(); } if (NorsService.IsNotNull()) { NorsService.CloseClients(); } if (NorwayTaxonService.IsNotNull()) { NorwayTaxonService.CloseClients(); } if (PESINameService.IsNotNull()) { PESINameService.CloseClients(); } if (PictureService.IsNotNull()) { PictureService.CloseClients(); } if (ReferenceService.IsNotNull()) { ReferenceService.CloseClients(); } if (SersService.IsNotNull()) { SersService.CloseClients(); } if (SpeciesObservationHarvestService.IsNotNull()) { SpeciesObservationHarvestService.CloseClients(); } if (SwedishSpeciesObservationService.IsNotNull()) { SwedishSpeciesObservationService.CloseClients(); } if (SwedishSpeciesObservationSOAPService.IsNotNull()) { SwedishSpeciesObservationSOAPService.CloseClients(); } if (TaxonAttributeService.IsNotNull()) { TaxonAttributeService.CloseClients(); } if (TaxonService.IsNotNull()) { TaxonService.CloseClients(); } if (DyntaxaInternalService.IsNotNull()) { DyntaxaInternalService.CloseClients(); } if (UserService.IsNotNull()) { UserService.CloseClients(); } if (WramService.IsNotNull()) { WramService.CloseClients(); } }
public SimpleRefVm(ReferenceService refSertvice) { _refSertvice = refSertvice; }
public ReferenceServiceTest(TestAppFixture testAppFixture) : base(testAppFixture) { _referenceService = GetService <ReferenceService>(); _referenceRepo = GetService <IGenericRepo <Reference> >(); _recordsRepo = GetService <IGenericRepo <KvantShared.Model.Record> >(); }
public bool TryGetMatcherDataReturnsCorrectResult(string referenceName, int matcherIndex) { var sut = new ReferenceService(DefaultReferencedMatchersList, DefaultStatMatchersList); return(sut.TryGetMatcherData(referenceName, matcherIndex, out var _)); }
private ExecutionResult Execute(string recipe, IAssetReference reference, IDictionary arguments) { if (recipe == null) { throw new ArgumentNullException("recipe"); } ThrowIfAlreadyExecutingRecipe(); Config.Recipe config = ThrowIfRecipeNotConfigured(recipe); ReferenceService referenceService = null; try { string appliesTo = GetReferenceAppliesToOrErrorMessage(reference); this.TraceInformation(Properties.Resources.Recipe_StartingExecution, recipe, reference != null ? String.Format(Properties.Resources.Recipe_ReferenceApplied, appliesTo) : ""); // This "parent" loader service is the one we created in OnSited that // wraps the one provided by the recipe manager itself, and adds resolution // relative to the package assembly location. ITypeResolutionService loader = GetService <ITypeResolutionService>(true); // Create the recipe from the configuration. currentRecipe = new Recipe(config); currentReference = reference; // Setup the alias resolution "gateway" loader service. // This resolves aliases defined for the recipe only. // This service will go away together with the recipe. currentRecipe.AddService(typeof(ITypeResolutionService), new AliasResolutionService( config.TypeAliasesByName, loader)); bool isPersisted; IPersistenceService persistenceService; arguments = LoadPersitedState(reference, arguments, out isPersisted, out persistenceService); // Construct the dictionary service. We don't pass the arguments at this // point as we want to go over the process of setting each in turn, so they are validated. DictionaryService dictionarysvc = new DictionaryService(null); AddService(typeof(IDictionaryService), dictionarysvc); // Expose the IComponentChangeService implementation too. AddService(typeof(IComponentChangeService), dictionarysvc); if (arguments != null && arguments.Count > 0) { bool shouldUpdateState = InitializeDictionaryService(arguments, dictionarysvc); // Persist changes if appropriate. if (isPersisted && shouldUpdateState) { persistenceService.SaveState(Configuration.Name, reference, arguments); } } // Construct the dictionary service, passing the persisted state (or null) as well // as the arguments configuration. // Site and execute the recipe. Add(currentRecipe); referenceService = new ReferenceService(); currentRecipe.AddService(typeof(IReferenceService), referenceService); bool allowsuspend = (reference != null && reference is IBoundAssetReference) || (arguments != null); EnsureInitializeMetadataForCurrentRecipe(); ExecutionResult result = currentRecipe.Execute(allowsuspend); this.TraceInformation(Properties.Resources.Recipe_ExecutionResult, result); if (result == ExecutionResult.Finish) { // If recipe is not recurrent and it's a bound reference, remove it. if (!currentRecipe.Configuration.Recurrent && reference is IBoundAssetReference) { IAssetReferenceService refsvc = GetService <IAssetReferenceService>(true); refsvc.Remove(reference); // Remove the persisted state. persistenceService.RemoveState(Configuration.Name, reference); } // Fire the AfterRecipeExecution event // note this will happen only when the recipe is finished (not suspend nor cancelled) if (AfterRecipeExecution != null) { this.AfterRecipeExecution(this, new RecipeEventArgs(config, isExecutingRecipeFromTemplate)); } } return(result); } finally { #region Cleanup if (referenceService != null) { currentRecipe.RemoveService(typeof(IReferenceService)); } // Remove recipe from container. Remove(currentRecipe); // Remove services we added. RemoveService(typeof(IDictionaryService)); RemoveService(typeof(IComponentChangeService)); // Dispose and clean current variables. if (currentRecipe != null) { currentRecipe.Dispose(); currentRecipe = null; } currentReference = null; #endregion Cleanup // Write a separator on the trace. this.TraceInformation(new string('-', 150)); } }
public IViewComponentResult Invoke() { ///////////////////////////////////////////////////////////////////////////////////////////// // The HttpContext.Items collection is used to store data while processing a single request. // The collection's contents are discarded after a request is processed. ///////////////////////////////////////////////////////////////////////////////////////////// string[] selectedErrorTypeIdStrings = (string[])HttpContext.Items[CorrectiveActionsConstants.SELECTED_ERROR_TYPES_KEY]; if (selectedErrorTypeIdStrings == null) { selectedErrorTypeIdStrings = new string[0]; } ////////////////////////////////////////////////////////////////////////////////////////////// // Convert the passed-in string array of ids to an integer array of ids ////////////////////////////////////////////////////////////////////////////////////////////// int[] selectedErrorTypeIds = Array.ConvertAll(selectedErrorTypeIdStrings, int.Parse); var selectedErrorTypeIdSet = new HashSet <int>(selectedErrorTypeIds); ////////////////////////////////////////////////////////////////////////////////////////////// // Retreive all error types ////////////////////////////////////////////////////////////////////////////////////////////// List <ErrorType> dbErrorTypes = new ReferenceService().RetrieveErrorTypes().ToList(); ////////////////////////////////////////////////////////////////////////////////////////////// // Create a View Model for each ErrorType amd place each in a View Model collection // If the IDs in both the ErrorType collection and array of IDs match, // assign the value of TRUE to the 'Selected' property. ////////////////////////////////////////////////////////////////////////////////////////////// int[] errorTypeSortingIndices = new int[dbErrorTypes.Count]; int count = 0; for (int column = 0; column < CorrectiveActionsConstants.NUMBER_OF_ERROR_TYPE_COLUMNS; column++) { for (int row = column; row < dbErrorTypes.Count; row += CorrectiveActionsConstants.NUMBER_OF_ERROR_TYPE_COLUMNS) { errorTypeSortingIndices[count++] = row; } } ErrorTypeViewModel[] vmErrorTypes = new ErrorTypeViewModel[dbErrorTypes.Count]; int index = 0; foreach (ErrorType dbErrorType in dbErrorTypes) { ErrorTypeViewModel vmErrorType = new ErrorTypeViewModel { Id = (int)dbErrorType.Id, Description = dbErrorType.Description, Selected = selectedErrorTypeIdSet.Contains((int)dbErrorType.Id) }; vmErrorTypes[errorTypeSortingIndices[index++]] = vmErrorType; } ViewBag.ErrorTypes = new List <ErrorTypeViewModel>(vmErrorTypes); ////////////////////////////////////////////////////////////////////////////////////////////// // Set SELECTED_ERROR_TYPES back to null ////////////////////////////////////////////////////////////////////////////////////////////// HttpContext.Items[CorrectiveActionsConstants.SELECTED_ERROR_TYPES_KEY] = null; return(View()); }