示例#1
0
        private Dictionary <string, DocumentAttribute> ParseGlobalAttributes(XmlNode globalAttributeListNode)
        {
            XmlNodeList globalAttributeNodes = globalAttributeListNode.SelectNodes("attribute");
            var         globalAttributes     = new Dictionary <string, DocumentAttribute>(StringComparer.InvariantCultureIgnoreCase);

            //string _value = "";
            foreach (XmlNode node in globalAttributeNodes)
            {
                if (node.NodeType == XmlNodeType.Element)
                {
                    string name = node.Attributes[0].Value;

                    DocumentAttribute toAdd = GetCommonAttribute(name);
                    if (toAdd != null)
                    {
                        globalAttributes.Add(name, toAdd);
                    }
                    else
                    {
                        throw new PolicyException("Global attribute '" + name + "' was not defined in <common-attributes>");
                    }

                    //if (!globalAttributes.ContainsKey(_name))
                    //    globalAttributes.Add(_name, new AntiSamyPattern(_name, _value));
                }
            }
            return(globalAttributes);
        }
示例#2
0
        public void AddAttribute(DocumentAttribute Attribute)
        {
            using (Model.BiblosDS2010Entities db = new Model.BiblosDS2010Entities(BiblosDSConnectionString))
            {
                Model.Attributes entityAttribute = Attribute.TryToConvertTo <Model.Attributes>(false);

                if (Attribute.Mode != null)
                {
                    entityAttribute.IdMode = Attribute.Mode.IdMode;
                }

                if (Attribute.Archive != null)
                {
                    entityAttribute.IdArchive = Attribute.Archive.IdArchive;
                }

                if (Attribute.AttributeGroup != null)
                {
                    entityAttribute.IdAttributeGroup = Attribute.AttributeGroup.IdAttributeGroup;
                }

                db.AddToAttributes(entityAttribute);
                db.SaveChanges();
            }
        }
示例#3
0
        public void UpdateAttribute(DocumentAttribute Attribute)
        {
            using (Model.BiblosDS2010Entities db = new Model.BiblosDS2010Entities(BiblosDSConnectionString))
            {
                Model.Attributes entityAttribute = Attribute.TryToConvertTo <Model.Attributes>(false);

                if (entityAttribute.EntityKey == null)
                {
                    entityAttribute.EntityKey = db.CreateEntityKey(entityAttribute.GetType().Name, entityAttribute);
                }

                var attachedEntity = db.GetObjectByKey(entityAttribute.EntityKey) as Model.Attributes;

                if (Attribute.Mode != null)
                {
                    entityAttribute.IdMode = Attribute.Mode.IdMode;
                }

                if (Attribute.Archive != null)
                {
                    entityAttribute.IdArchive = Attribute.Archive.IdArchive;
                }

                if (Attribute.AttributeGroup != null)
                {
                    entityAttribute.IdAttributeGroup = Attribute.AttributeGroup.IdAttributeGroup;
                }

                db.ApplyCurrentValues(entityAttribute.EntityKey.EntitySetName, entityAttribute);
                db.SaveChanges();
            }
        }
示例#4
0
 private static DocumentAttributeValue Convert(this MetadatoItem metadato, DocumentAttribute biblosDSMetadato)
 {
     return(new DocumentAttributeValue
     {
         IdAttribute = biblosDSMetadato.IdAttribute,
         Attribute = biblosDSMetadato,
         Value = metadato.Value
     });
 }
        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);
        }
示例#6
0
 /// <summary>
 /// Salva le modifiche a un DocumentAttribute
 /// </summary>
 /// <param name="DocumentAttribute">DocumentAttribute modificato</param>
 public static void UpdateAttribute(DocumentAttribute DocumentAttribute)
 {
     if (DocumentAttribute.IdAttribute == Guid.Empty ||
         string.IsNullOrEmpty(DocumentAttribute.Name) ||
         string.IsNullOrEmpty(DocumentAttribute.AttributeType) ||
         DocumentAttribute.Archive == null ||
         DocumentAttribute.Mode == null)
     {
         throw new Exception("Requisiti non sufficienti per l'operazione");
     }
     DbAdminProvider.UpdateAttribute(DocumentAttribute);
 }
示例#7
0
        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);
        }
示例#8
0
        public ActionResult Detail(DocumentFieldViewModel model)
        {
            List <HttpPostedFileBase> listFile = new List <HttpPostedFileBase>();

            if (Session["file"] != null)
            {
                listFile = (List <HttpPostedFileBase>)Session["file"];
            }

            if (listFile.Count <= 0)
            {
                TempData[Globals.FailedMessageKey] = App_GlobalResources.Error.InsertUnsucess;
                return(View(model));
            }
            else
            {
                int dem = DocumentAttributeRepository.GetAllDocumentAttribute().Where(x => x.DocumentFieldId == model.Id).OrderByDescending(x => x.OrderNo).FirstOrDefault().OrderNo.Value;
                foreach (var item in listFile)
                {
                    dem = dem + 1;
                    var type              = item.FileName.Split('.').Last();
                    var FileName          = model.Name.Replace(" ", "_");
                    var name              = Erp.BackOffice.Helpers.Common.ChuyenThanhKhongDau(FileName).ToLower();
                    var DocumentAttribute = new DocumentAttribute();
                    DocumentAttribute.IsDeleted       = false;
                    DocumentAttribute.CreatedUserId   = WebSecurity.CurrentUserId;
                    DocumentAttribute.ModifiedUserId  = WebSecurity.CurrentUserId;
                    DocumentAttribute.AssignedUserId  = WebSecurity.CurrentUserId;
                    DocumentAttribute.CreatedDate     = DateTime.Now;
                    DocumentAttribute.ModifiedDate    = DateTime.Now;
                    DocumentAttribute.OrderNo         = dem;
                    DocumentAttribute.File            = name + "(" + model.Id + "_" + DocumentAttribute.OrderNo + ")" + "." + type;
                    DocumentAttribute.Size            = item.ContentLength.ToString();
                    DocumentAttribute.TypeFile        = type;
                    DocumentAttribute.DocumentFieldId = model.Id;
                    DocumentAttributeRepository.InsertDocumentAttribute(DocumentAttribute);
                    var  documentfield = DocumentFieldRepository.GetDocumentFieldById(model.Id);
                    var  path          = System.Web.HttpContext.Current.Server.MapPath("~" + Helpers.Common.GetSetting(documentfield.Category));
                    bool isExists      = System.IO.Directory.Exists(path);
                    if (!isExists)
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    item.SaveAs(path + DocumentAttribute.File);
                }
                TempData[Globals.SuccessMessageKey] = App_GlobalResources.Wording.InsertSuccess;
                return(RedirectToAction("Detail", new { Id = model.Id }));
            }
        }
示例#9
0
    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;
        }
    }
示例#10
0
 public void AddAttribute(DocumentAttribute DocumentAttribute)
 {
     AttributeService.AddAttribute(DocumentAttribute);
 }
示例#11
0
        private Dictionary <string, DocumentAttribute> ParseCommonAttributes(XmlNode commonAttributeListNode)
        {
            XmlNodeList commonAttributeNodes = commonAttributeListNode.SelectNodes("attribute");
            var         commonAttributes     = new Dictionary <string, DocumentAttribute>(StringComparer.InvariantCultureIgnoreCase);

            foreach (XmlNode node in commonAttributeNodes)
            {
                if (node.NodeType == XmlNodeType.Element)
                {
                    var         allowedRegExp  = new List <string>();
                    XmlNodeList regExpListNode = node.SelectNodes("regexp-list");
                    if (regExpListNode != null && regExpListNode.Count > 0)
                    {
                        XmlNodeList regExpList = regExpListNode[0].SelectNodes("regexp");
                        foreach (XmlNode regExpNode in regExpList)
                        {
                            string regExpName = regExpNode.Attributes["name"]?.Value;
                            string value      = regExpNode.Attributes["value"]?.Value;

                            //TODO: java version uses "Pattern" class to hold regular expressions.  I'm storing them as strings below
                            //find out if I need an equiv to pattern
                            if (!string.IsNullOrEmpty(regExpName))
                            {
                                allowedRegExp.Add(GetRegularExpression(regExpName));
                            }
                            else
                            {
                                allowedRegExp.Add(RegexpBegin + value + RegexpEnd);
                            }
                        }
                    }

                    var     allowedValues   = new List <string>();
                    XmlNode literalListNode = node.SelectNodes("literal-list")[0];
                    if (literalListNode != null)
                    {
                        XmlNodeList literalNodes = literalListNode.SelectNodes("literal");
                        foreach (XmlNode literalNode in literalNodes)
                        {
                            string value = literalNode.Attributes["value"]?.Value;
                            if (!string.IsNullOrEmpty(value))
                            {
                                allowedValues.Add(value);
                            }
                            else if (literalNode.Value != null)
                            {
                                allowedValues.Add(literalNode.Value);
                            }
                        }
                    }

                    string onInvalid = node.Attributes["onInvalid"]?.Value;
                    string name      = node.Attributes["name"]?.Value;
                    var    attribute = new DocumentAttribute(name,
                                                             allowedRegExp,
                                                             allowedValues,
                                                             !string.IsNullOrEmpty(onInvalid) ? onInvalid : DefaultOninvalid,
                                                             node.Attributes["description"]?.Value);

                    commonAttributes.Add(name, attribute);
                }
            }
            return(commonAttributes);
        }
        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);
            }
        }
示例#13
0
 public void UpdateAttribute(DocumentAttribute DocumentAttribute)
 {
     AttributeService.UpdateAttribute(DocumentAttribute);
 }
示例#14
0
        void createTaskEDX()
        {
            //connect to the QDS
            ServiceInfo[] MyQDS = Client.GetServices(ServiceTypes.QlikViewDistributionService);

            //get a list of source docs
            DocumentNode[] SourceDocs;
            SourceDocs = Client.GetSourceDocuments(MyQDS[0].ID);

            //Create the new task object
            DocumentTask myTask = new DocumentTask();

            //find the ID for the doc we created above
            for (int i = 0; i < SourceDocs.Length; i++)
            {
                if (SourceDocs[i].Name == targetDoc + ".qvw")
                {
                    myTask.Document = SourceDocs[i];
                }
            }

            //set some basic settings
            myTask.QDSID = MyQDS[0].ID;
            myTask.Scope = DocumentTaskScope.All;
            myTask.Reload = new DocumentTask.TaskReload();
            myTask.Reload.Mode = TaskReloadMode.Full;

            //apply some category data to the task
            myTask.DocumentInfo = new DocumentTask.TaskDocumentInfo();
            myTask.DocumentInfo.Category = "OnDemand Reload task";
            DocumentAttribute[] attribs = new DocumentAttribute[1];
            attribs[0] = new DocumentAttribute();
            attribs[0].Name = "OnDemandApp";
            attribs[0].Value = "OnDemandApp";
            myTask.DocumentInfo.Attributes = attribs;

            //add a task name and enable it
            myTask.General = new DocumentTask.TaskGeneral();
            myTask.General.TaskName = "OnDemand Reload Task for - " + targetDoc;
            myTask.General.Enabled = true;

            //create the tasks EDX trigger
            ExternalEventTrigger eet = new ExternalEventTrigger();
            eet.Type = TaskTriggerType.ExternalEventTrigger;
            eet.ID = Guid.NewGuid();
            eet.Password = "";
            eet.Enabled = true;

            List<Trigger> TrigList = new List<Trigger>();
            TrigList.Add(new Trigger());
            TrigList[0] = eet;

            myTask.Triggering = new DocumentTask.TaskTriggering();
            myTask.Triggering.Triggers = TrigList.ToArray();
            myTask.Triggering.ExecutionAttempts = 1;
            myTask.Triggering.ExecutionTimeout = 1000;
            myTask.Triggering.TaskDependencies = new TaskInfo[0];

            //Set up distribution
            TaskDistributionDestination taskDestination = new TaskDistributionDestination();
            taskDestination.Type = TaskDistributionDestinationType.QlikViewServer;
            taskDestination.QlikViewServer = new TaskDistributionDestination.TaskDistributionDestinationQlikViewServer();
            taskDestination.QlikViewServer.ID = Client.GetServices(ServiceTypes.QlikViewServer)[0].ID;
            taskDestination.QlikViewServer.Name = Client.GetServices(ServiceTypes.QlikViewServer)[0].Name;
            taskDestination.QlikViewServer.Mount = "";

            DirectoryServiceObject[] recipients = new DirectoryServiceObject[1];
            recipients[0] = new DirectoryServiceObject();
            recipients[0].Type = DirectoryServiceObjectType.Authenticated;
            TaskDistributionEntry[] taskDistributionEntry = new TaskDistributionEntry[1];
            taskDistributionEntry[0] = new TaskDistributionEntry();
            taskDistributionEntry[0].Destination = taskDestination;
            taskDistributionEntry[0].Recipients = recipients;

            myTask.Distribute = new DocumentTask.TaskDistribute();
            myTask.Distribute.Static = new DocumentTask.TaskDistribute.TaskDistributeStatic();
            myTask.Distribute.Static.DistributionEntries = taskDistributionEntry;
            myTask.Distribute.Output = new DocumentTask.TaskDistribute.TaskDistributeOutput();
            myTask.Distribute.Output.Type = TaskDistributionOutputType.QlikViewDocument;

            myTask.Distribute.Dynamic = new DocumentTask.TaskDistribute.TaskDistributeDynamic();
            myTask.Distribute.Dynamic.IdentityType = UserIdentityValueType.SAMAccountName;
            myTask.Distribute.Dynamic.Destinations = new TaskDistributionDestination[0];

            myTask.Distribute.Notification = new DocumentTask.TaskDistribute.TaskDistributeNotification();
            myTask.Distribute.Notification.SendNotificationEmail = false;

            //Set output name
            myTask.Reduce = new DocumentTask.TaskReduce();
            myTask.Reduce.DocumentNameTemplate = targetDoc;
            myTask.Reduce.Static = new DocumentTask.TaskReduce.TaskReduceStatic();
            myTask.Reduce.Static.Reductions = new TaskReduction[0];

            myTask.Reduce.Dynamic = new DocumentTask.TaskReduce.TaskReduceDynamic();

            // Fill out server tab defaults
            myTask.Server = new DocumentTask.TaskServer();
            myTask.Server.Access = new DocumentTask.TaskServer.TaskServerAccess();
            myTask.Server.Access.Download = DocumentDownloadAccess.None;
            myTask.Server.Access.DownloadUsers = new string[0];
            myTask.Server.Access.Export = DocumentDownloadAccess.All;
            myTask.Server.Access.ExportUsers = new string[0];
            myTask.Server.Access.Methods = DocumentAccessMethods.All;
            myTask.Server.Access.MaxConcurrentSessions = 1000;
            myTask.Server.Access.DocumentTimeout = 0;
            myTask.Server.Access.SessionTimeout = 0;
            myTask.Server.Access.ZeroFootprintClientURL = "";
            myTask.Server.DocumentLoading = new DocumentTask.TaskServer.TaskServerDocumentLoading();
            myTask.Server.DocumentLoading.ServerSettings = new DocumentTask.TaskServer.TaskServerDocumentLoading.TaskServerDocumentLoadServerSetting[0];
            myTask.Server.Collaboration = new DocumentTask.TaskServer.TaskServerCollaboration();
            myTask.Server.Collaboration.CreatorUserNames = new string[1];
            myTask.Server.Collaboration.CreationMode = DocumentCollaborationCreationMode.All;

            //Finished the object so save it to the server
            Client.SaveDocumentTask(myTask);

            //Wait 5 seconds for it to catch up, then get the object back for use later on
            System.Threading.Thread.Sleep(5000);
            TaskInfo[] alltasksfordoc = Client.GetTasksForDocument(myTask.Document.ID);
            targetTask = Client.GetDocumentTask(alltasksfordoc[alltasksfordoc.Count() - 1].ID, DocumentTaskScope.All);
        }
示例#15
0
        public static void SaveUpload(string NameField, string IsSearch, int CategoryId, string Category, string FailedMessageKey = null, string fileName = null)
        {
            //insert và upload documentField, documentAttribute.
            List <HttpPostedFileBase> listFile = new List <HttpPostedFileBase>();

            if (System.Web.HttpContext.Current.Session["file"] != null)
            {
                listFile = (List <HttpPostedFileBase>)System.Web.HttpContext.Current.Session["file"];
            }

            DocumentFieldRepository DocumentFieldRepository = new DocumentFieldRepository(new Domain.Staff.ErpStaffDbContext());

            DocumentAttributeRepository DocumentAttributeRepository = new DocumentAttributeRepository(new Domain.Staff.ErpStaffDbContext());

            if (listFile.Count > 0)
            {
                var DocumentField = new DocumentField();

                DocumentField.IsDeleted      = false;
                DocumentField.CreatedUserId  = WebSecurity.CurrentUserId;
                DocumentField.ModifiedUserId = WebSecurity.CurrentUserId;
                DocumentField.AssignedUserId = WebSecurity.CurrentUserId;
                DocumentField.CreatedDate    = DateTime.Now;
                DocumentField.ModifiedDate   = DateTime.Now;
                DocumentField.Name           = NameField;
                //  DocumentField.DocumentTypeId = DocumentTypeId;
                DocumentField.IsSearch   = IsSearch;
                DocumentField.Category   = Category;
                DocumentField.CategoryId = CategoryId;
                DocumentFieldRepository.InsertDocumentField(DocumentField);
                var prefix = Erp.BackOffice.Helpers.Common.GetSetting("prefixOrderNo_DocumentField");
                DocumentField.Code = Erp.BackOffice.Helpers.Common.GetCode(prefix, DocumentField.Id);
                DocumentFieldRepository.UpdateDocumentField(DocumentField);
                int dem = 0;
                foreach (var item in listFile)
                {
                    dem = dem + 1;
                    var type              = item.FileName.Split('.').Last();
                    var FileName          = DocumentField.Name.Replace(" ", "_");
                    var name              = Erp.BackOffice.Helpers.Common.ChuyenThanhKhongDau(FileName).ToLower();
                    var DocumentAttribute = new DocumentAttribute();
                    DocumentAttribute.IsDeleted      = false;
                    DocumentAttribute.CreatedUserId  = WebSecurity.CurrentUserId;
                    DocumentAttribute.ModifiedUserId = WebSecurity.CurrentUserId;
                    DocumentAttribute.AssignedUserId = WebSecurity.CurrentUserId;
                    DocumentAttribute.CreatedDate    = DateTime.Now;
                    DocumentAttribute.ModifiedDate   = DateTime.Now;
                    DocumentAttribute.OrderNo        = dem;
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        DocumentAttribute.File = fileName + "(" + DocumentField.Id + "_" + DocumentAttribute.OrderNo + ")" + "." + type;
                    }
                    else
                    {
                        DocumentAttribute.File = name + "(" + DocumentField.Id + "_" + DocumentAttribute.OrderNo + ")" + "." + type;
                    }
                    DocumentAttribute.Size            = item.ContentLength.ToString();
                    DocumentAttribute.TypeFile        = type;
                    DocumentAttribute.DocumentFieldId = DocumentField.Id;
                    DocumentAttributeRepository.InsertDocumentAttribute(DocumentAttribute);
                    var  path     = System.Web.HttpContext.Current.Server.MapPath("~" + Helpers.Common.GetSetting(Category));
                    bool isExists = System.IO.Directory.Exists(path);
                    if (!isExists)
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    item.SaveAs(path + DocumentAttribute.File);
                }
            }
            else
            {
                FailedMessageKey = "Vui lòng chụp ảnh!";
            }
        }
示例#16
0
        public static Guid CloneArchive(string templateName, string archiveName)
        {
            DocumentArchive            archiveToClone = null, existingArchive;
            List <DocumentAttribute>   attributesAdded   = new List <DocumentAttribute>();
            List <DocumentStorageArea> storageAreasAdded = new List <DocumentStorageArea>();
            List <DocumentStorage>     storagesAdded     = new List <DocumentStorage>();

            try
            {
                if (string.IsNullOrWhiteSpace(archiveName))
                {
                    throw new BiblosDS.Library.Common.Exceptions.Archive_Exception(string.Format("Destination archive name is null or empty for source archive {0}.", templateName));
                }

                archiveToClone = ArchiveService.GetArchiveByName(templateName);
                if (archiveToClone == null)
                {
                    throw new BiblosDS.Library.Common.Exceptions.Archive_Exception(string.Format("Archive with name {0} not found.", templateName));
                }
                //Il nome può essere lungo al massimo 63 caratteri.
                if (archiveName.Length > 63)
                {
                    archiveName = archiveName.Remove(63);
                }
                //Controlla se per caso l'archivio che si desidera clonare è già presente in banca dati.
                existingArchive = ArchiveService.GetArchiveByName(archiveName);

                if (existingArchive != null)
                {
                    return(existingArchive.IdArchive);
                }

                Guid idArchiveToClone = archiveToClone.IdArchive;
                archiveToClone.IdArchive = Guid.NewGuid();
                archiveToClone.Name      = Regex.Replace(archiveName, @"[^a-zA-Z0-9]", "-");
                if (!string.IsNullOrEmpty(archiveToClone.PathTransito) && archiveToClone.PathTransito.LastIndexOf('\\') > 0)
                {
                    archiveToClone.PathTransito = Path.Combine(archiveToClone.PathTransito.Substring(0, archiveToClone.PathTransito.LastIndexOf('\\')), archiveToClone.Name);
                }

                if (!string.IsNullOrEmpty(archiveToClone.PathPreservation) && archiveToClone.PathPreservation.LastIndexOf('\\') > 0)
                {
                    archiveToClone.PathPreservation = Path.Combine(archiveToClone.PathPreservation.Substring(0, archiveToClone.PathPreservation.LastIndexOf('\\')), archiveToClone.Name);
                }

                DbAdminProvider.AddArchive(archiveToClone);
                //Clone attributes
                var attributes = AttributeService.GetAttributesFromArchive(idArchiveToClone);
                foreach (var attributeItem in attributes)
                {
                    var attribute = new DocumentAttribute {
                        IdAttribute = Guid.NewGuid(), Archive = archiveToClone, AttributeType = attributeItem.AttributeType, ConservationPosition = attributeItem.ConservationPosition, DefaultValue = attributeItem.DefaultValue, Description = attributeItem.Description, Disabled = attributeItem.Disabled, Format = attributeItem.Format, IsAutoInc = attributeItem.IsAutoInc, IsChainAttribute = attributeItem.IsChainAttribute, IsEnumerator = attributeItem.IsEnumerator, IsMainDate = attributeItem.IsMainDate, IsRequired = attributeItem.IsRequired, IsRequiredForPreservation = attributeItem.IsRequiredForPreservation, IsSectional = attributeItem.IsSectional, IsUnique = attributeItem.IsUnique, IsVisible = attributeItem.IsVisible, IsVisibleForUser = attributeItem.IsVisibleForUser, KeyFilter = attributeItem.KeyFilter, KeyFormat = attributeItem.KeyFormat, KeyOrder = attributeItem.KeyOrder, MaxLenght = attributeItem.MaxLenght, Mode = attributeItem.Mode, Name = attributeItem.Name, Validation = attributeItem.Validation
                    };
                    DbAdminProvider.AddAttribute(attribute);
                    attributesAdded.Add(attribute);
                }
                //Retrive storage
                var storage = DbProvider.GetStoragesActiveFromArchive(idArchiveToClone);
                foreach (var storageItem in storage)
                {
                    var storageArea = DbProvider.GetStorageAreaActiveFromStorage(storageItem.IdStorage);
                    if (storageArea.Any(x => x.Archive != null && x.Archive.IdArchive == idArchiveToClone))
                    {
                        storageArea = new BindingList <DocumentStorageArea>(storageArea.Where(x => x.Archive != null && x.Archive.IdArchive == idArchiveToClone).ToList());
                    }

                    foreach (var storageAreaItem in storageArea)
                    {
                        var newStorageArea = new DocumentStorageArea {
                            IdStorageArea = Guid.NewGuid(), Archive = archiveToClone, Storage = storageItem, Enable = true, MaxFileNumber = storageAreaItem.MaxFileNumber, MaxSize = storageAreaItem.MaxSize, Name = archiveToClone.Name, Path = archiveToClone.Name, Priority = storageAreaItem.Priority, Status = storageAreaItem.Status
                        };
                        DbAdminProvider.AddStorageArea(newStorageArea);
                        storageAreasAdded.Add(newStorageArea);
                    }
                    DbAdminProvider.AddArchiveStorage(new DocumentArchiveStorage {
                        Storage = storageItem, Archive = archiveToClone, Active = true
                    });
                    storagesAdded.Add(storageItem);
                }
                return(archiveToClone.IdArchive);
            }
            catch (Exception)
            {
                try
                {
                    if (archiveToClone != null)
                    {
                        foreach (var item in storagesAdded)
                        {
                            DbAdminProvider.DeleteArchiveStorage(new DocumentArchiveStorage {
                                Archive = archiveToClone, Storage = item
                            });;
                        }
                        foreach (var item in storageAreasAdded)
                        {
                            DbAdminProvider.DeleteStorageArea(item.IdStorageArea);
                        }
                        foreach (var item in attributesAdded)
                        {
                            DbAdminProvider.DeleteAttribute(item.IdAttribute, false);
                        }
                        DbAdminProvider.DeleteArchive(archiveToClone);
                    }
                }
                catch (Exception ex)
                {
                    logger.Warn(ex);
                    throw;
                }
                throw;
            }
        }
 public void Init()
 {
     instance = new DocumentAttribute();
 }
示例#18
0
        private Dictionary <string, DocumentTag> ParseTagRules(XmlNode tagAttributeListNode)
        {
            var         tags    = new Dictionary <string, DocumentTag>(StringComparer.InvariantCultureIgnoreCase);
            XmlNodeList tagList = tagAttributeListNode.SelectNodes("tag");

            foreach (XmlNode tagNode in tagList)
            {
                if (tagNode.NodeType == XmlNodeType.Element)
                {
                    string name   = tagNode.Attributes["name"]?.Value;
                    string action = tagNode.Attributes["action"]?.Value;

                    var tag = new DocumentTag(name, action);

                    XmlNodeList attributeList = tagNode.SelectNodes("attribute");
                    foreach (XmlNode attributeNode in attributeList)
                    {
                        if (IsCommonAttributeRule(attributeNode))
                        {
                            DocumentAttribute commonAttribute = GetCommonAttribute(attributeNode.Attributes["name"].Value);

                            if (commonAttribute != null)
                            {
                                string onInvalid   = attributeNode.Attributes["onInvalid"]?.Value;
                                string description = attributeNode.Attributes["description"]?.Value;
                                if (!string.IsNullOrEmpty(onInvalid))
                                {
                                    commonAttribute.OnInvalid = onInvalid;
                                }
                                if (!string.IsNullOrEmpty(description))
                                {
                                    commonAttribute.Description = description;
                                }

                                tag.AddAllowedAttribute((DocumentAttribute)commonAttribute.Clone());
                            }
                        }
                        else
                        {
                            var     allowedRegExps = new List <string>();
                            XmlNode regExpListNode = attributeNode.SelectNodes("regexp-list")[0];
                            if (regExpListNode != null)
                            {
                                XmlNodeList regExpList = regExpListNode.SelectNodes("regexp");
                                foreach (XmlNode regExpNode in regExpList)
                                {
                                    string regExpName = regExpNode.Attributes["name"]?.Value;
                                    string value      = regExpNode.Attributes["value"]?.Value;
                                    if (!string.IsNullOrEmpty(regExpName))
                                    {
                                        //AntiSamyPattern pattern = getRegularExpression(regExpName);
                                        string pattern = GetRegularExpression(regExpName);
                                        if (pattern != null)
                                        {
                                            allowedRegExps.Add(pattern);
                                        }

                                        //attribute.addAllowedRegExp(pattern.Pattern);
                                        else
                                        {
                                            throw new PolicyException("Regular expression '" + regExpName + "' was referenced as a common regexp in definition of '" + tag.Name + "', but does not exist in <common-regexp>");
                                        }
                                    }
                                    else if (!string.IsNullOrEmpty(value))
                                    {
                                        allowedRegExps.Add(RegexpBegin + value + RegexpEnd);
                                    }
                                }
                            }

                            var     allowedValues   = new List <string>();
                            XmlNode literalListNode = attributeNode.SelectNodes("literal-list")[0];
                            if (literalListNode != null)
                            {
                                XmlNodeList literalNodes = literalListNode.SelectNodes("literal");
                                foreach (XmlNode literalNode in literalNodes)
                                {
                                    string value = literalNode.Attributes["value"]?.Value;
                                    if (!string.IsNullOrEmpty(value))
                                    {
                                        allowedValues.Add(value);
                                    }
                                    else if (literalNode.Value != null)
                                    {
                                        allowedValues.Add(literalNode.Value);
                                    }
                                }
                            }

                            /* Custom attribute for this tag */
                            var attribute = new DocumentAttribute(attributeNode.Attributes["name"].Value,
                                                                  allowedRegExps,
                                                                  allowedValues,
                                                                  attributeNode.Attributes["onInvalid"]?.Value,
                                                                  attributeNode.Attributes["description"]?.Value);
                            tag.AddAllowedAttribute(attribute);
                        }
                    }

                    tags.Add(name, tag);
                }
            }
            return(tags);
        }
示例#19
0
        public void CreateLabourContract(vwLabourContract model)
        {
            // var branch = branchRepository.GetvwBranchById(model.StaffbranchId.Value);
            // var staff = staffRepository.GetStaffsById(model.StaffId.Value);
            // string filePath = Server.MapPath("~/Data/LabourContract.html");

            // string strOutput = System.IO.File.ReadAllText(filePath, Encoding.UTF8);
            //// thông tin bên A
            // strOutput = strOutput.Replace("#ApprovedUserName#", model.ApprovedUserName);
            // strOutput = strOutput.Replace("#ApprovedUserPositionName#", model.ApprovedUserPositionName);
            // strOutput = strOutput.Replace("#ApprovedBranchName#", model.ApprovedBranchName);
            // strOutput = strOutput.Replace("#ApprovedPhoneBranch#", branch.Phone);
            // strOutput = strOutput.Replace("#ApprovedBranchAddress#", branch.Address+" - "+branch.WardName+" - "+branch.DistrictName+" - " +branch.ProvinceName);
            // strOutput = strOutput.Replace("#StaffName#", model.StaffName);
            // strOutput = strOutput.Replace("#StaffBirthday#", model.StaffBirthday.Value.ToString("dd/MM/yyyy"));
            // strOutput = strOutput.Replace("#Job#", staff.Technique);
            // strOutput = strOutput.Replace("#StaffAddress#", model.StaffAddress);
            // strOutput = strOutput.Replace("#StaffWard#", model.StaffWard);
            // strOutput = strOutput.Replace("#StaffDistrict#", model.StaffDistrict);
            // strOutput = strOutput.Replace("#StaffProvince#", model.StaffProvince);
            // //thông tin bên B
            // strOutput = strOutput.Replace("#StaffIdCardNumber#", model.StaffIdCardNumber);
            // strOutput = strOutput.Replace("#StaffIdCardDate#", model.StaffIdCardDate.Value.ToString("dd/MM/yyyy"));
            // strOutput = strOutput.Replace("#StaffCardIssuedName#", model.StaffCardIssuedName);
            // strOutput = strOutput.Replace("#ContractTypeName#", model.ContractTypeName);
            // strOutput = strOutput.Replace("#EffectiveDate#", model.EffectiveDate.Value.ToString("dd/MM/yyyy"));
            // strOutput = strOutput.Replace("#ExpiryDate#", model.ExpiryDate.Value.ToString("dd/MM/yyyy"));
            // strOutput = strOutput.Replace("#FormWork#", model.FormWork);
            // strOutput = strOutput.Replace("#WageAgreement#", Erp.BackOffice.Helpers.Common.PhanCachHangNgan(model.WageAgreement));
            // strOutput = strOutput.Replace("#StaffPositionName#", model.StaffPositionName);
            // strOutput = strOutput.Replace("#Content#", model.Content);
            // strOutput = strOutput.Replace("#Code#", model.Code);
            // strOutput = strOutput.Replace("#SignedDay.Date#", model.SignedDay.Value.ToString("dd"));
            // strOutput = strOutput.Replace("#SignedDay.Month#", model.SignedDay.Value.ToString("MM"));
            // strOutput = strOutput.Replace("#SignedDay.Year#", model.SignedDay.Value.ToString("yyyy"));
            // strOutput = strOutput.Replace("#Name#", model.Name);
            //strOutput = strOutput.Replace("#Place#", contract.Place);
            //strOutput = strOutput.Replace("#Day#", contract.CreatedDate.Value.Day.ToString());
            //strOutput = strOutput.Replace("#Month#", contract.CreatedDate.Value.Month.ToString());
            //strOutput = strOutput.Replace("#Year#", contract.CreatedDate.Value.Year.ToString());

            //lưu thông tin dữ liệu vào database
            //lưu document field

            var DocumentField = new DocumentField();

            DocumentField.IsDeleted      = false;
            DocumentField.CreatedUserId  = WebSecurity.CurrentUserId;
            DocumentField.ModifiedUserId = WebSecurity.CurrentUserId;
            DocumentField.AssignedUserId = WebSecurity.CurrentUserId;
            DocumentField.CreatedDate    = DateTime.Now;
            DocumentField.ModifiedDate   = DateTime.Now;
            DocumentField.Name           = model.Code;
            DocumentField.DocumentTypeId = 9;
            // DocumentField.IsSearch = "";
            DocumentField.Category   = "LabourContract";
            DocumentField.CategoryId = model.Id;
            DocumentFieldRepository.InsertDocumentField(DocumentField);
            var prefix = Erp.BackOffice.Helpers.Common.GetSetting("prefixOrderNo_DocumentField");

            DocumentField.Code = Erp.BackOffice.Helpers.Common.GetCode(prefix, DocumentField.Id);
            DocumentFieldRepository.UpdateDocumentField(DocumentField);
            // lưu dữ liệu thành file word
            var    originalDirectory = new DirectoryInfo(string.Format("{0}Files\\somefiles", System.Web.HttpContext.Current.Server.MapPath(@"\")));
            string pathString        = System.IO.Path.Combine(originalDirectory.ToString(), "DocumentAttribute");
            bool   isExists          = System.IO.Directory.Exists(pathString);

            if (!isExists)
            {
                System.IO.Directory.CreateDirectory(pathString);
            }
            var name = model.Code + "(" + DocumentField.Id + ")" + ".doc";
            var path = string.Format("{0}\\{1}", pathString, name);

            System.IO.File.WriteAllText(path, model.Content);
            //lưu documentAttribute
            var DocumentAttribute = new DocumentAttribute();

            DocumentAttribute.IsDeleted      = false;
            DocumentAttribute.CreatedUserId  = WebSecurity.CurrentUserId;
            DocumentAttribute.ModifiedUserId = WebSecurity.CurrentUserId;
            DocumentAttribute.AssignedUserId = WebSecurity.CurrentUserId;
            DocumentAttribute.CreatedDate    = DateTime.Now;
            DocumentAttribute.ModifiedDate   = DateTime.Now;
            DocumentAttribute.OrderNo        = 1;
            DocumentAttribute.File           = name;
            byte[] str = System.IO.File.ReadAllBytes(path);
            DocumentAttribute.Size            = str.Length.ToString();
            DocumentAttribute.TypeFile        = "doc";
            DocumentAttribute.DocumentFieldId = DocumentField.Id;
            DocumentAttributeRepository.InsertDocumentAttribute(DocumentAttribute);
        }
示例#20
0
 private void BuildExtensionMap(Hashtable mapNameToExtension, DocumentAttribute [] aDocumentAttributes)
 {
     foreach (DocumentAttribute attribute in aDocumentAttributes)
     {
         if (mapNameToExtension.Contains(attribute.Name))
         {
             StringBuilder extensionBuilder = mapNameToExtension[attribute.Name] as StringBuilder;
             extensionBuilder.Append("|");
             extensionBuilder.Append(attribute.Extension);
         }
         else
         {
             StringBuilder extensionBuilder = new StringBuilder();
             extensionBuilder.Append(attribute.Extension);
             mapNameToExtension.Add(attribute.Name, extensionBuilder);
         }
     }
 }
示例#21
0
        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());
        }
示例#22
0
        private void LoadOpenFilterString(StringBuilder stringBuilder, DocumentAttribute [] aDocumentAttributes)
        {
            Hashtable mapNameToExtension = new Hashtable();

            BuildExtensionMap(mapNameToExtension, aDocumentAttributes);

            foreach (string sName in mapNameToExtension.Keys)
            {
                StringBuilder extensions = mapNameToExtension[sName] as StringBuilder;
                string sExtensions = extensions.ToString();

                stringBuilder.Append(sName);
                stringBuilder.Append(" (");
                stringBuilder.Append(sExtensions.Replace("|", ", "));
                stringBuilder.Append(")|");

                string [] asExtensions = sExtensions.Split(new char[] { '|' });

                for (int nExtension = 0 ; nExtension < asExtensions.Length; nExtension++)
                {
                    if (nExtension > 0)
                    {
                        stringBuilder.Append(';');
                    }

                    stringBuilder.Append('*');
                    stringBuilder.Append(asExtensions[nExtension]);
                }

                stringBuilder.Append("|");
            }
        }
示例#23
0
 private void LoadCreateFilterString(StringBuilder stringBuilder, DocumentAttribute [] aDocumentAttributes)
 {
     foreach (DocumentAttribute attribute in aDocumentAttributes)
     {
         stringBuilder.Append(attribute.Name);
         stringBuilder.Append(" (*");
         stringBuilder.Append(attribute.Extension);
         stringBuilder.Append(")|*");
         stringBuilder.Append(attribute.Extension);
         stringBuilder.Append("|");
     }
 }
示例#24
0
 private void LoadAttributes(System.Type type, DocumentAttribute [] aDocumentAttributes)
 {
     foreach (DocumentAttribute attribute in aDocumentAttributes)
     {
         m_mapExtensionToType.Add(attribute.Extension, type);
     }
 }