public ActionResult CheckArchivePreservationConfiguration(Guid id) { return(ActionResultHelper.TryCatchWithLogger(() => { CheckPreservationArchiveConfigurationViewModel model = new CheckPreservationArchiveConfigurationViewModel() { IdArchive = id }; DocumentArchive archive = ArchiveService.GetArchive(id); ICollection <DocumentAttribute> archiveAttributes = AttributeService.GetAttributesFromArchive(id); model.ArchiveName = archive.Name; model.ArchiveAttributes = archiveAttributes.Where(x => !x.KeyOrder.HasValue || x.KeyOrder == 0) .OrderBy(o => o.DisplayName) .ToDictionary(k => k.IdAttribute.ToString(), v => v.DisplayName); //model.DateAttributes.Add(Guid.Empty.ToString(), "--Crea attributo (Date)"); archiveAttributes.Where(x => x.AttributeType.Equals("System.DateTime", StringComparison.InvariantCultureIgnoreCase)) .OrderBy(o => o.DisplayName).ToList().ForEach(f => model.DateAttributes.Add(f.IdAttribute.ToString(), f.DisplayName)); model.PathPreservation = archive.PathPreservation; model.MainDateAttribute = archiveAttributes.Where(x => x.IsMainDate == true).Select(s => s.IdAttribute.ToString()).SingleOrDefault(); model.PrimaryKeyAttributes = archiveAttributes.Where(x => x.KeyOrder > 0).OrderBy(o => o.KeyOrder) .ToDictionary(k => k.IdAttribute.ToString(), v => v.DisplayName); ValidateArchiveForPreservationInteractor interactor = new ValidateArchiveForPreservationInteractor(_loggerService); ValidateArchiveForPreservationResponseModel response = interactor.Process(new ValidateArchiveForPreservationRequestModel() { IdArchive = id }); model.HasPreservations = response.HasPreservations; model.ValidationErrors = response.ValidationErrors; model.IsValidated = response.IsValidated; return PartialView("_CheckArchivePreservationConfiguration", model); }, _loggerService)); }
private BindingList <Document> getDocumentsByAttributeValue(DocumentArchive archive, DocumentAttributeValue attributeValue, bool?stringContains, int?skip, int?take) { try { logger.InfoFormat("getDocumentsByAttributeValue archive.IdArchive:{0} archive.Name:{1} attributeValue.Attribute.Name:{2} attributeValue.Value:{3}", archive.IdArchive, archive.Name, attributeValue.Attribute.Name, attributeValue.Value); BindingList <DocumentAttribute> attributes = AttributeService.GetAttributesFromArchive(archive.IdArchive); // Recupero la lista di documenti. BindingList <Document> documents = DocumentService.GetDocumentsByAttributeValue(archive, attributeValue, stringContains, skip, take); if (documents == null || documents.Count == 0) { throw new DocumentNotFound_Exception("Nessun documento trovato con attributo \"{0}\" e valore \"{1}\".", attributeValue.Attribute.Name, attributeValue.Value); } logger.InfoFormat("getDocumentsByAttributeValue documenti trovati: {0}.", documents.Count); return(documents); } catch (Exception ex) { logger.Error(ex); throw; } }
public EmptyResponseModel Process(ModifyArchivePreservationAttributesRequestModel request) { _logger.Info($"Process -> Edit preservation attributes for archive {request.IdArchive}"); DocumentArchive archive = ArchiveService.GetArchive(request.IdArchive); if (archive == null) { _logger.Error($"Archive with id {request.IdArchive} not found"); throw new Exception($"Archive with id {request.IdArchive} not found"); } ICollection <DocumentAttribute> attributes = AttributeService.GetAttributesFromArchive(request.IdArchive); if (attributes == null || attributes.Count == 0) { _logger.Error($"There aren't attributes for archive with id {request.IdArchive}"); throw new Exception($"There aren't attributes for archive with id {request.IdArchive}"); } foreach (DocumentAttribute attribute in attributes) { attribute.ConservationPosition = null; if (request.OrderedPreservationAttributes.ContainsKey(attribute.IdAttribute)) { attribute.ConservationPosition = request.OrderedPreservationAttributes[attribute.IdAttribute]; } _logger.Debug($"Update attribute {attribute.IdAttribute}: ConservationPosition = {attribute.ConservationPosition}"); AttributeService.UpdateAttribute(attribute); } return(new EmptyResponseModel()); }
protected override long SaveDocument(string LocalFilePath, BiblosDS.Library.Common.Objects.DocumentStorage Storage, BiblosDS.Library.Common.Objects.DocumentStorageArea StorageArea, BiblosDS.Library.Common.Objects.Document Document, System.ComponentModel.BindingList <BiblosDS.Library.Common.Objects.DocumentAttributeValue> attributeValue) { if (string.IsNullOrEmpty(Document.Storage.AuthenticationKey)) { Document.Storage = StorageService.GetStorage(Document.Storage.IdStorage); } StorageAccountInfo account = StorageAccountInfo.GetAccountInfoFromConfiguration( string.Empty, Storage.MainPath, Document.Storage.AuthenticationKey, true); BlobStorage blobStorage = BlobStorage.Create(account); blobStorage.RetryPolicy = RetryPolicies.RetryN(2, TimeSpan.FromMilliseconds(100)); //Check if exist storage area //If exist put the storage in the configured path if (!string.IsNullOrEmpty(StorageArea.Path)) { container = blobStorage.GetBlobContainer(Storage.Name.ToLower() + StorageArea.Path.ToLower()); } else { container = blobStorage.GetBlobContainer(Storage.Name.ToLower()); } //Create the container if it does not exist. if (!container.DoesContainerExist()) { BindingList <DocumentAttribute> attribute = AttributeService.GetAttributesFromArchive(Document.Archive.IdArchive); NameValueCollection containerMetadata = new NameValueCollection(); foreach (DocumentAttribute item in attribute) { containerMetadata.Add(item.Name, item.Name); } container.CreateContainer(containerMetadata, ContainerAccessControl.Private); } //ContainerAccessControl acl = container.GetContainerAccessControl(); // BlobProperties blobProperty = new BlobProperties(GetFileName(Document)); NameValueCollection metadata = new NameValueCollection(); foreach (DocumentAttributeValue item in Document.AttributeValues) { metadata.Add(item.Attribute.Name, item.Value.ToString()); } blobProperty.Metadata = metadata; container.CreateBlob( blobProperty, new BlobContents(Document.Content.Blob), true ); return(Document.Content.Blob.Length); }
protected override BindingList <DocumentAttributeValue> LoadAttributes(Document Document) { BindingList <DocumentAttributeValue> attributeValues = new BindingList <DocumentAttributeValue>(); ClientContext context = new ClientContext(Document.Storage.MainPath); context.Credentials = new NetworkCredential(Document.Storage.AuthenticationKey, Document.Storage.AuthenticationPassword); Web web = context.Web; List docs = web.Lists.GetByTitle(Document.Storage.Name); context.ExecuteQuery(); Folder foolder = docs.RootFolder; if (!string.IsNullOrEmpty(Document.StorageArea.Path)) { if ((foolder = docs.RootFolder.Folders.Where(x => x.Name == Document.StorageArea.Path).FirstOrDefault()) == null) { throw new BiblosDS.Library.Common.Exceptions.StorageAreaConfiguration_Exception("StorageArea not found:" + Document.StorageArea.Path); } } context.ExecuteQuery(); string fileName = GetIdDocuemnt(Document) + System.IO.Path.GetExtension(Document.Name); IEnumerable <File> resultFiles = context.LoadQuery(foolder.Files.Where(x => x.Name == fileName).Include(x => x.ListItemAllFields)); context.ExecuteQuery(); File file = resultFiles.FirstOrDefault(); if (file == null) { throw new BiblosDS.Library.Common.Exceptions.FileNotFound_Exception(); } //if (Document.StorageVersion.HasValue && file.Versions.Count > 0) // file = file.Versions.Where(x => x.VersionLabel == Document.StorageVersion.Value.ToString()).First(); BindingList <DocumentAttribute> attributes = AttributeService.GetAttributesFromArchive(Document.Archive.IdArchive); ListItem listItem = file.ListItemAllFields; foreach (var item in listItem.FieldValues.Keys) { try { DocumentAttribute attribute = attributes.Where(x => x.Name == item).Single(); if (attribute != null) { DocumentAttributeValue attr = new DocumentAttributeValue(); attr.Attribute = attribute; attr.Value = listItem.FieldValues[item]; attributeValues.Add(attr); } } catch (Exception) { } } return(attributeValues); }
protected override BindingList <DocumentAttributeValue> LoadAttributes(Document Document) { BindingList <DocumentAttributeValue> attributeValues = new BindingList <DocumentAttributeValue>(); try { SPSite site = null; SPWeb web = null; SPDocumentLibrary doclib = null; SPFile file = null; using (site = new SPSite(Document.Storage.MainPath)) { using (web = site.OpenWeb()) { //SPFolder Folder = web.GetFolder(Document.Storage.Name); doclib = web.Lists[Document.Storage.Name] as SPDocumentLibrary; if (!string.IsNullOrEmpty(Document.StorageArea.Path)) { file = doclib.RootFolder.SubFolders[Document.StorageArea.Path].Files[GetIdDocuemnt(Document) + Path.GetExtension(Document.Name)]; } else { file = doclib.RootFolder.Files[GetIdDocuemnt(Document) + Path.GetExtension(Document.Name)]; } BindingList <DocumentAttribute> attributes = AttributeService.GetAttributesFromArchive(Document.Archive.IdArchive); foreach (var item in file.Properties.Keys) { try { DocumentAttribute attribute = attributes.Where(x => x.Name == item.ToString()).Single(); if (attribute != null) { DocumentAttributeValue attr = new DocumentAttributeValue(); attr.Attribute = attribute; attr.Value = file.Properties[item].ToString(); attributeValues.Add(attr); } } catch (Exception) { } } } } } catch (Exception ex) { //Write the log throw new FileNotFound_Exception("File non trovato" + Environment.NewLine + ex.ToString()); } return(attributeValues); }
private DocumentAttribute getAttributeByArchiveAndName(DocumentArchive archive, string attributeName) { // Recupero l'attributo a partire dal suo nome. BindingList <DocumentAttribute> attributes = AttributeService.GetAttributesFromArchive(archive.IdArchive); foreach (DocumentAttribute item in attributes) { if (item.Name.Equals(attributeName, StringComparison.InvariantCultureIgnoreCase)) { return(item); } } throw new AttributeNotFoundException("Attributo \"{0}\" non configurato per l'archivio \"{1}\".", attributeName, archive.Name); }
public ActionResult FindDocuments([DataSourceRequest] DataSourceRequest request, Guid?idArchive, DateTime?fromDate, DateTime?toDate, string dynamicFilters) { return(ActionResultHelper.TryCatchWithLogger(() => { DataSourceResult result = new DataSourceResult(); if (!idArchive.HasValue) { result.Total = 0; result.Data = new List <DistributionPackagesGridViewModel>(); return Json(result, JsonRequestBehavior.AllowGet); } IDictionary <string, string> filters = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(dynamicFilters)) { filters = JsonConvert.DeserializeObject <IDictionary <string, string> >(dynamicFilters); } SearchDocumentsRequestModel requestModel = new SearchDocumentsRequestModel() { IdArchive = idArchive.Value, FromDate = fromDate, ToDate = toDate, DynamicFilters = filters, Skip = (request.Page - 1) * request.PageSize, Top = request.PageSize }; SearchDocumentsResponseModel responseModel = _searchDocumentsInteractor.Process(requestModel); ICollection <DocumentAttribute> attributes = AttributeService.GetAttributesFromArchive(idArchive.Value).OrderBy(x => x.Name).ToList(); result.Total = responseModel.Counter; result.Data = responseModel.Documents.Select(s => new DistributionPackagesGridViewModel() { IdDocument = s.IdDocument, DocumentCreated = s.DateCreated, DocumentName = s.Name, IdPreservation = s.IdPreservation, IsConservated = s.IdPreservation.HasValue, Metadata = attributes.Select(ss => new DistributionPackagesGridMetadataViewModel() { MetadataName = ss.Name, MetadataValue = FormatAttributeValue(s.AttributeValues.FirstOrDefault(x => x.Attribute.IdAttribute == ss.IdAttribute)) }).ToArray() }); return Json(result, JsonRequestBehavior.AllowGet); }, _loggerService)); }
protected override BindingList <DocumentAttributeValue> LoadAttributes(Document Document) { BindingList <DocumentAttributeValue> attributeValues = new BindingList <DocumentAttributeValue>(); try { BasicHttpBinding binding = new BasicHttpBinding(); binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None; BiblosSvcClient client = new BiblosSvcClient(binding, new EndpointAddress(Document.Storage.MainPath)); client.ClientCredentials.Windows.ClientCredential = new NetworkCredential(Document.Storage.AuthenticationKey, Document.Storage.AuthenticationPassword); client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation; string fileName = GetIdDocuemnt(Document) + Path.GetExtension(Document.Name); var attributesSP = client.GetFileAttributes(Document.Storage.Name, Document.StorageArea.Path, Document.DocumentParent.IdDocument.ToString(), fileName, Document.StorageVersion.HasValue ? (int)Document.StorageVersion.Value : 0); BindingList <DocumentAttribute> attributes = AttributeService.GetAttributesFromArchive(Document.Archive.IdArchive); foreach (var item in attributes) { try { if (attributesSP.ContainsKey(item.Name)) { DocumentAttributeValue attr = new DocumentAttributeValue(); attr.Attribute = item; attr.Value = attributesSP[item.Name]; attributeValues.Add(attr); } } catch (Exception) { } } } catch (Exception ex) { //Write the log Logging.WriteLogEvent(BiblosDS.Library.Common.Enums.LoggingSource.BiblosDS_Sharepoint, "LoadAttributes", ex.ToString(), BiblosDS.Library.Common.Enums.LoggingOperationType.BiblosDS_General, BiblosDS.Library.Common.Enums.LoggingLevel.BiblosDS_Errors); throw; } return(attributeValues); }
public ValidateArchiveForPreservationResponseModel Process(ValidateArchiveForPreservationRequestModel request) { DocumentArchive archive = ArchiveService.GetArchive(request.IdArchive); if (archive == null) { _logger.Error($"Archive with id {request.IdArchive} not found"); throw new Exception($"Archive with id {request.IdArchive} not found"); } ValidateArchiveForPreservationResponseModel response = new ValidateArchiveForPreservationResponseModel() { IdArchive = request.IdArchive }; if (_preservationService.ExistPreservationsByArchive(archive)) { response.HasPreservations = true; response.ValidationErrors.Add("Non è possibile configurare un archivio con delle conservazioni già eseguite"); } response.HasPathPreservation = true; if (string.IsNullOrEmpty(archive.PathPreservation)) { response.HasPathPreservation = false; response.ValidationErrors.Add("Non è stato definito il percorso di conservazione"); } ICollection <DocumentAttribute> archiveAttributes = AttributeService.GetAttributesFromArchive(archive.IdArchive); response.HasDateMainAttribute = true; if (!archiveAttributes.Any(x => x.IsMainDate == true)) { response.HasDateMainAttribute = false; response.ValidationErrors.Add("Non è stato definito un attributo di tipo MainDate"); } response.HasPrimaryKeyAttribute = true; if (!archiveAttributes.Any(x => x.KeyOrder.HasValue && x.KeyOrder.Value > 0)) { response.HasPrimaryKeyAttribute = false; response.ValidationErrors.Add("Non è stato definito un attributo di tipo Primary Key"); } return(response); }
public ActionResult DynamicFormFields(Guid id) { return(ActionResultHelper.TryCatchWithLogger(() => { ICollection <DocumentAttribute> archiveAttributes = AttributeService.GetAttributesFromArchive(id); DynamicFormFieldsViewModel viewModel = new DynamicFormFieldsViewModel() { DynamicControlViewModels = archiveAttributes.OrderBy(x => x.Name).Select(s => new DynamicControlViewModel() { Caption = string.IsNullOrEmpty(s.Description) ? s.Name : s.Description, ControlName = s.Name, ControlType = s.AttributeType }).ToList() }; return PartialView("_DynamicFormFields", viewModel); }, _loggerService)); }
public ActionResult DistributionPackagesGrid(Guid id) { return(ActionResultHelper.TryCatchWithLogger(() => { DistributionPackagesSearchGridViewModel viewModel = new DistributionPackagesSearchGridViewModel() { IdArchive = id, ArchiveAttributes = AttributeService.GetAttributesFromArchive(id).OrderBy(x => x.Name).Select(s => new AttributeModel() { Name = s.Name, Description = string.IsNullOrEmpty(s.Description) ? s.Name : s.Description }).ToList() }; return PartialView("_DistributionPackagesGrid", viewModel); }, _loggerService)); }
public ActionResult ArchivePreservationConfigurationSummary(Guid id, bool isCompleteWithErrors) { return(ActionResultHelper.TryCatchWithLogger(() => { DocumentArchive archive = ArchiveService.GetArchive(id); ICollection <DocumentAttribute> attributes = AttributeService.GetAttributesFromArchive(id); ArchiveWizardStepBaseViewModel model = new ArchiveWizardStepBaseViewModel() { IdArchive = id, ArchiveName = archive.Name, PathPreservation = archive.PathPreservation, MainDateAttribute = attributes.SingleOrDefault(s => s.IsMainDate == true).DisplayName, SelectedPreservationAttributes = attributes.Where(x => x.ConservationPosition > 0).OrderBy(o => o.ConservationPosition).Select(s => s.DisplayName).ToList(), SelectedPrimaryKeyAttributes = attributes.Where(x => x.KeyOrder > 0).OrderBy(o => o.KeyOrder).Select(s => s.DisplayName).ToList(), IsCompleted = true, IsCompleteWithErrors = isCompleteWithErrors }; return PartialView("_ArchivePreservationConfigurationSummary", model); }, _loggerService)); }
public ActionResult ArchivePreservationAttributesConfiguration(Guid id) { return(ActionResultHelper.TryCatchWithLogger(() => { DocumentArchive archive = ArchiveService.GetArchive(id); ICollection <DocumentAttribute> archiveAttributes = AttributeService.GetAttributesFromArchive(id); ArchivePreservationAttributesConfigurationViewModel model = new ArchivePreservationAttributesConfigurationViewModel() { IdArchive = id, ArchiveName = archive.Name, ArchiveAttributes = archiveAttributes.Where(x => !x.ConservationPosition.HasValue || x.ConservationPosition == 0) .OrderBy(o => o.DisplayName) .ToDictionary(k => k.IdAttribute.ToString(), v => v.DisplayName), PreservationAttributes = archiveAttributes.Where(x => x.ConservationPosition > 0).OrderBy(o => o.ConservationPosition) .ToDictionary(k => k.IdAttribute.ToString(), v => v.DisplayName) }; return PartialView("_ArchivePreservationAttributesConfiguration", model); }, _loggerService)); }
private BindingList <Document> getDocumentsByAttributeValue(string archiveName, string attributeName, string attributeValue, bool?stringContains, int?skip, int?take) { try { // Recupero l'archivio. DocumentArchive archive = ArchiveService.GetArchiveByName(archiveName); // Recupero l'attributo a partire dal suo nome. BindingList <DocumentAttribute> attributes = AttributeService.GetAttributesFromArchive(archive.IdArchive); DocumentAttribute attribute = getAttributeByArchiveAndName(archive, attributeName); DocumentAttributeValue value = new DocumentAttributeValue { Attribute = attribute, Value = attributeValue }; return(getDocumentsByAttributeValue(archive, value, stringContains, skip, take)); } catch (Exception ex) { logger.Error(ex); throw; } }
public override async Task Execute(CommandModel commandModel) { try { if (!(commandModel is CommandConfigureArchiveForPreservation)) { _logger.Error($"Command is not of type {nameof(CommandConfigureArchiveForPreservation)}"); return; } CommandConfigureArchiveForPreservation @command = commandModel as CommandConfigureArchiveForPreservation; await SendNotification(command.ReferenceId, $"Inizio attività di configurazione per l'archivio con id {command.IdArchive}", NotifyLevel.Info); DocumentArchive currentArchive = ArchiveService.GetArchive(command.IdArchive); if (currentArchive == null) { _logger.Error($"Archive with Id {command.IdArchive} not found"); throw new Exception($"Non è stato trovato un archivio con ID {command.IdArchive}"); } Company currentCompany = ArchiveService.GetCompany(command.IdCompany); if (currentCompany == null) { _logger.Error($"Company with Id {command.IdCompany} not found"); throw new Exception($"Non è stata trovata una azienda con ID {command.IdCompany}"); } BindingList <DocumentAttribute> archiveAttributes = AttributeService.GetAttributesFromArchive(command.IdArchive); if (archiveAttributes == null || archiveAttributes.Count == 0) { _logger.Error($"There aren't attributes for archive with Id {command.IdArchive}"); throw new Exception($"Non sono stati trovati attributi per l'archivio con ID {command.IdArchive}"); } if (string.IsNullOrEmpty(currentArchive.PathPreservation)) { _logger.Error($"PathPreservation is null for archive with Id {command.IdArchive}"); throw new Exception($"Non è stato definito il percorso di conservazione per l'archivio con ID {command.IdArchive}"); } DocumentAttribute mainDateAttribute = archiveAttributes.SingleOrDefault(x => x.IsMainDate == true); if (mainDateAttribute == null) { _logger.Error($"MainDate attribute is not defined for archive with Id {command.IdArchive}"); throw new Exception($"Non è stato definito l'attributo di tipo MainDate per l'archivio con ID {command.IdArchive}"); } ICollection <DocumentAttribute> preservationAttributes = archiveAttributes.Where(x => x.ConservationPosition > 0).ToList(); if (preservationAttributes.Count == 0) { _logger.Error($"There aren't conservation attributes for archive with Id {command.IdArchive}"); throw new Exception($"Non sono stati definiti gli attributi di conservazione per l'archivio con ID {command.IdArchive}"); } if (_preservationService.ExistPreservationsByArchive(currentArchive)) { _logger.Error($"The archive {command.IdArchive} already has some conservation done"); throw new Exception($"L'archivio {command.IdArchive} presenta già delle conservazioni eseguite"); } _logger.Info($"Enable archive {currentArchive.Name} to conservation"); await SendNotification(commandModel.ReferenceId, $"Abilitazione archivio {currentArchive.Name}({currentArchive.IdArchive}) alla conservazione", NotifyLevel.Info); currentArchive.IsLegal = true; ArchiveService.UpdateArchive(currentArchive, false); ICollection <Document> documents = DocumentService.GetDocumentsFromArchive(currentArchive); _logger.Debug($"Found {documents.Count} documents to process"); await SendNotification(commandModel.ReferenceId, $"Trovati {documents.Count} documenti da processare. L'attività può richiedere diversi minuti...", NotifyLevel.Info); BindingList <DocumentAttributeValue> documentAttributeValues; DateTime?mainDate; string primaryKey; decimal percentage, pulsePercentageLimit = 20; int progress = 1, totalItems = documents.Count, totalErrorDocuments = 0; ICollection <NotificationDetailModel> errorDetails = new List <NotificationDetailModel>(); foreach (Document document in documents) { try { _logger.Debug($"Process document {document.IdDocument}({progress} di {totalItems})"); documentAttributeValues = AttributeService.GetFullDocumentAttributeValues(document.IdDocument); mainDate = document.DateCreated; primaryKey = AttributeService.ParseAttributeValues(documentAttributeValues, archiveAttributes, out mainDate); DocumentService.UpdatePrimaryKeyAndDateMainDocument(document, mainDate, primaryKey); } catch (Exception ex) { _logger.Error($"Error on update document {document.IdDocument}", ex); errorDetails.Add(new NotificationDetailModel() { Id = document.IdDocument, ActivityName = $"Modifica primary key e maindate del documento {document.IdDocument}", Detail = $"{ex.Message}\r\n{ex.StackTrace}" }); totalErrorDocuments++; } percentage = ((decimal)progress / totalItems) * 100.0m; if (Math.Ceiling(percentage) > pulsePercentageLimit) { await SendNotification(commandModel.ReferenceId, $"Migrazione documenti ({pulsePercentageLimit}%, {totalErrorDocuments} in errore)", (totalErrorDocuments > 0 ? NotifyLevel.Warning : NotifyLevel.Info), errorDetails); pulsePercentageLimit += 20; } progress++; } await SendNotification(commandModel.ReferenceId, $"Migrazione documenti (100%, {totalErrorDocuments} in errore)", (totalErrorDocuments > 0 ? NotifyLevel.Warning : NotifyLevel.Info)); _logger.Info("Build Index and AwardBatch style files"); await SendNotification(commandModel.ReferenceId, "Creazione fogli di stile per visualizzazione file di Indice e Lotti", NotifyLevel.Info); string indexXsl = _preservationService.BuildPreservationIndexXSL(currentArchive); string awardBatchXsl = _preservationService.GetAwardBatchXSL(); ArchiveCompany archiveCompany = _preservationService.GetArchiveCompanies(currentArchive.IdArchive).SingleOrDefault(); if (archiveCompany == null) { archiveCompany = new ArchiveCompany() { IdArchive = currentArchive.IdArchive, IdCompany = currentCompany.IdCompany, WorkingDir = $@"{currentArchive.PathPreservation}\{currentArchive.Name}\Comunicazioni", XmlFileTemplatePath = $@"{currentArchive.PathPreservation}\{currentArchive.Name}\Comunicazioni\Template.xml" }; archiveCompany = ArchiveService.AddArchiveCompany(archiveCompany); } archiveCompany.AwardBatchXSLTFile = awardBatchXsl; archiveCompany.TemplateXSLTFile = indexXsl; ArchiveService.UpdateArchiveCompany(archiveCompany); StringBuilder resultBuilder = new StringBuilder(); resultBuilder.Append($"Archivio {currentArchive.Name} configurato correttamente per la conservazione"); if (totalErrorDocuments > 0) { resultBuilder.Append(". Alcuni documenti non sono stati migrati e potrebbero dare errore in fase di conservazione"); } await SendNotification(commandModel.ReferenceId, resultBuilder.ToString(), NotifyLevel.Info, true); } catch (Exception ex) { _logger.Error("Error on configure archive for preservation", ex); await SendNotification(commandModel.ReferenceId, $"Errore nella configurazione dell'archivio per la conservazione", NotifyLevel.Error, new List <NotificationDetailModel>() { new NotificationDetailModel() { Id = Guid.NewGuid(), ActivityName = $"Errore configurazione archivo", Detail = $"{ex.Message}\r\n{ex.StackTrace}" } }, true); } }
public override async Task Execute(CommandModel commandModel) { try { if (!(commandModel is CommandInsertPreservationPDV)) { _logger.Error($"Command is not of type {nameof(CommandInsertPreservationPDV)}"); return; } CommandInsertPreservationPDV @command = commandModel as CommandInsertPreservationPDV; await SendNotification(command.ReferenceId, $"Inizio salvataggio PDV per il lotto di versamento con id {command.IdAwardBatch}", NotifyLevel.Info); DocumentArchive pdvArchive = ArchiveService.GetArchiveByName(command.PDVArchive); if (pdvArchive == null) { _logger.Error($"Archive with name {command.PDVArchive} not found"); throw new Exception($"Non è stato trovato un archivio con nome {command.PDVArchive}"); } ICollection <DocumentAttribute> attributes = AttributeService.GetAttributesFromArchive(pdvArchive.IdArchive); AwardBatch awardBatch = _preservationService.GetAwardBatch(command.IdAwardBatch); if (awardBatch == null) { _logger.Error($"Award batch with id {command.IdAwardBatch} not found"); throw new Exception($"Non è stato trovato un lotto di versamento con id {command.IdAwardBatch}"); } Document document = new Document { Content = new DocumentContent() { Blob = Convert.FromBase64String(command.Content) }, Name = string.Concat(UtilityService.GetSafeFileName(awardBatch.Name), ".xml"), Archive = pdvArchive, AttributeValues = new BindingList <DocumentAttributeValue>() }; document.AttributeValues.Add(new DocumentAttributeValue() { Value = document.Name, Attribute = attributes.Single(f => f.Name.Equals("Filename", StringComparison.InvariantCultureIgnoreCase)) }); document.AttributeValues.Add(new DocumentAttributeValue() { Value = awardBatch.Name, Attribute = attributes.Single(f => f.Name.Equals("Signature", StringComparison.InvariantCultureIgnoreCase)) }); using (var clientChannel = WCFUtility.GetClientConfigChannel <IDocuments>(ServerService.WCF_Document_HostName)) { document = (clientChannel as IDocuments).AddDocumentToChain(document, null, DocumentContentFormat.Binary); } awardBatch.IdPDVDocument = document.IdDocument; _preservationService.UpdateAwardBatch(awardBatch); _logger.Info($"Saved PDV with id {awardBatch.IdPDVDocument} for awardbatch {awardBatch.IdAwardBatch}"); await SendNotification(command.ReferenceId, $"PDV salvato con id {awardBatch.IdPDVDocument} per il lotto di versamento con id {awardBatch.IdAwardBatch}", NotifyLevel.Info); } catch (Exception ex) { _logger.Error("Error on insert PDV", ex); await SendNotification(commandModel.ReferenceId, $"Errore nella fase di inserimento PDV", NotifyLevel.Error); } }
public EmptyResponseModel Process(ModifyArchivePreservationConfigurationRequestModel request) { _logger.Info($"Process -> Edit preservation configuration for archive {request.IdArchive}"); DocumentArchive archive = ArchiveService.GetArchive(request.IdArchive); if (archive == null) { _logger.Error($"Archive with id {request.IdArchive} not found"); throw new Exception($"Archive with id {request.IdArchive} not found"); } ICollection <DocumentAttribute> attributes = AttributeService.GetAttributesFromArchive(request.IdArchive); if (attributes == null || attributes.Count == 0) { _logger.Error($"There aren't attributes for archive with id {request.IdArchive}"); throw new Exception($"There aren't attributes for archive with id {request.IdArchive}"); } if (archive.PathPreservation != request.PathPreservation) { _logger.Debug($"Update archive preservation path from '{archive.PathPreservation}' to '{request.PathPreservation}'"); archive.PathPreservation = request.PathPreservation; ArchiveService.UpdateArchive(archive, false); } foreach (DocumentAttribute attribute in attributes) { attribute.IsMainDate = ((attribute.IdAttribute == request.MainDateAttribute) || (request.MainDateAttribute == Guid.Empty && attribute.Name == DEFAULT_MAIN_DATE_ATTRIBUTE_NAME && attribute.AttributeType == DATE_TIME_ATTRIBUTE_TYPE)); attribute.KeyOrder = null; if (request.OrderedPrimaryKeyAttributes.ContainsKey(attribute.IdAttribute)) { attribute.KeyOrder = request.OrderedPrimaryKeyAttributes[attribute.IdAttribute]; if (string.IsNullOrEmpty(attribute.KeyFormat) && attribute.KeyOrder < request.OrderedPrimaryKeyAttributes.Max(x => x.Value)) { attribute.KeyFormat = "{0}|"; } } _logger.Debug($"Update attribute {attribute.IdAttribute}: IsMainDate = {attribute.IsMainDate}; KeyOrder = {attribute.KeyOrder}"); AttributeService.UpdateAttribute(attribute); } if (request.MainDateAttribute == Guid.Empty && !attributes.Any(x => x.Name == DEFAULT_MAIN_DATE_ATTRIBUTE_NAME && x.AttributeType == DATE_TIME_ATTRIBUTE_TYPE)) { DocumentAttribute dateMainAttribute = new DocumentAttribute { Name = "Date", AttributeType = "System.DateTime", IsMainDate = true, IsRequired = true, Archive = archive, ConservationPosition = Convert.ToInt16(request.OrderedPrimaryKeyAttributes.Max(x => x.Value) + 1), Mode = new DocumentAttributeMode(0), AttributeGroup = AttributeService.GetAttributeGroup(archive.IdArchive).SingleOrDefault(s => s.GroupType == AttributeGroupType.Undefined) }; _logger.Debug($"Create new MainDate attribute 'Date' for archive {archive.IdArchive}"); AttributeService.AddAttribute(dateMainAttribute); } return(new EmptyResponseModel()); }
public BindingList <DocumentAttribute> GetAttributesFromArchive(Guid IdArchive) { return(AttributeService.GetAttributesFromArchive(IdArchive)); }