示例#1
0
        public void ChangeTemplateData(int templateId, WordTemplateDO template)
        {
            GvaWordTemplate templateData = this.unitOfWork.DbContext.Set<GvaWordTemplate>()
                .Where(t => t.GvaWordTemplateId == templateId)
                .Single();

            templateData.DataGeneratorCode = template.DataGenerator.Code;
            templateData.Description = template.Description;
            templateData.Name = template.Name;

            if (template.TemplateFile != null)
            {
                using (MemoryStream stream = new MemoryStream())
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                {
                    connection.Open();
                    using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", template.TemplateFile.Key))
                    {
                        blobStream.CopyTo(stream);
                        templateData.Template = stream.ToArray();
                    }
                }
            }

            this.unitOfWork.Save();
        }
示例#2
0
        public HttpResponseMessage Get(Guid fileKey, string mimeType = null, string fileName = null, string dispositionType = null)
        {
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new PushStreamContent(
                async (outputStream, httpContent, transportContext) =>
                {
                    using (outputStream)
                    {
                        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                        {
                            connection.Open();

                            var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", fileKey);
                            await blobStream.CopyToAsync(outputStream);
                        }
                    }
                });
            result.Content.Headers.ContentType =
                new MediaTypeHeaderValue(string.IsNullOrEmpty(mimeType) ? "application/octet-stream" : mimeType);
            result.Content.Headers.ContentDisposition =
                new ContentDispositionHeaderValue(string.IsNullOrEmpty(dispositionType) ? "inline" : dispositionType)
                {
                    FileName = fileName
                };

            return result;
        }
示例#3
0
        private async Task<HttpResponseMessage> SignDocumentAsync(SigningDocType signingDocType, Guid fileKey, string signatureXPath = null, IDictionary<string, string> signatureXPathNamespaces = null)
        {
            string serialNumber = System.Configuration.ConfigurationManager.AppSettings["Common.Api:CertificateSerialNumber"];
            string pinCode = System.Configuration.ConfigurationManager.AppSettings["Common.Api:CertificatePinCode"];

            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
            {
                await connection.OpenAsync();

                Stream signedStream = null;
                using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", fileKey))
                {
                    if (signingDocType == SigningDocType.Xml)
                    {
                        XmlSigner xmlSigner = new XmlSigner(serialNumber, pinCode);
                        signedStream = xmlSigner.Sign(blobStream, Encoding.UTF8, signatureXPath, signatureXPathNamespaces);
                    }
                    else if (signingDocType == SigningDocType.Office)
                    {
                        OfficeSigner xmlSigner = new OfficeSigner(serialNumber, pinCode);

                        try
                        {
                            signedStream = new MemoryStream();
                            blobStream.CopyTo(signedStream);
                            signedStream.Position = 0;

                            xmlSigner.SignInPlace(signedStream);
                        }
                        catch (Exception)
                        {
                            signedStream.Dispose();
                            throw;
                        }
                    }
                }

                using (signedStream)
                {
                    using (var blobWriter = new BlobWriter(connection))
                    using (var stream = await blobWriter.OpenStreamAsync())
                    {
                        signedStream.Position = 0;
                        signedStream.CopyTo(stream);

                        var blobKey = blobWriter.GetBlobKey();

                        return Request.CreateResponse(HttpStatusCode.OK, new { fileKey = blobKey });
                    }
                }
            }
        }
示例#4
0
        public void CreateNewTemplate(WordTemplateDO template)
        {
            GvaWordTemplate newTemplate = new GvaWordTemplate()
            {
                Name = template.Name,
                Description = template.Description,
                DataGeneratorCode = template.DataGenerator.Code
            };

            using (MemoryStream stream = new MemoryStream())
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
            {
                connection.Open();
                using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", template.TemplateFile.Key))
                {
                    blobStream.CopyTo(stream);
                    newTemplate.Template = stream.ToArray();
                }
            }

            this.unitOfWork.DbContext.Set<GvaWordTemplate>().Add(newTemplate);

            this.unitOfWork.Save();
        }
示例#5
0
        public IHttpActionResult CreateChildChecklist(int id, string identifier, string action)
        {
            using (var transaction = this.unitOfWork.BeginTransaction())
            {
                bool copy = false, correct = false;
                int docId;
                int checklistId = 0;

                AopApp app = this.unitOfWork.DbContext.Set<AopApp>().Find(id);

                if (identifier == "st")
                {
                    if (app.STDocId.HasValue)
                    {
                        docId = app.STDocId.Value;
                    }
                    else
                    {
                        throw new Exception("STDocId missing.");
                    }

                    if (action == "copy")
                    {
                        copy = true;

                        if (!app.STChecklistId.HasValue)
                        {
                            throw new Exception();
                        }

                        checklistId = app.STChecklistId.Value;
                    }
                    else if (action == "correct")
                    {
                        correct = true;

                        if (!app.STChecklistId.HasValue)
                        {
                            throw new Exception();
                        }

                        checklistId = app.STChecklistId.Value;
                    }
                }
                else if (identifier == "nd")
                {
                    if (app.NDDocId.HasValue)
                    {
                        docId = app.NDDocId.Value;
                    }
                    else
                    {
                        throw new Exception("NDDocId missing.");
                    }

                    if (action == "copy")
                    {
                        copy = true;

                        if (!app.NDChecklistId.HasValue && !app.STChecklistId.HasValue)
                        {
                            throw new Exception();
                        }

                        if (app.NDChecklistId.HasValue)
                        {
                            checklistId = app.NDChecklistId.Value;
                        }
                        else if (app.STChecklistId.HasValue)
                        {
                            checklistId = app.STChecklistId.Value;
                        }
                    }
                    else if (action == "correct")
                    {
                        correct = true;

                        if (!app.NDChecklistId.HasValue)
                        {
                            throw new Exception();
                        }

                        checklistId = app.NDChecklistId.Value;
                    }
                }
                else
                {
                    throw new Exception("Identifier missing.");
                }

                UnitUser unitUser = this.unitOfWork.DbContext.Set<UnitUser>().Include(e => e.Unit).FirstOrDefault(e => e.UserId == this.userContext.UserId);
                DocEntryType documentEntryType = this.unitOfWork.DbContext.Set<DocEntryType>().SingleOrDefault(e => e.Alias == "Document");

                if (correct)
                {
                    documentEntryType = this.unitOfWork.DbContext.Set<DocEntryType>().SingleOrDefault(e => e.Alias == "Resolution");
                }

                DocDirection internalDocDirection = this.unitOfWork.DbContext.Set<DocDirection>()
                    .SingleOrDefault(e => e.Alias.ToLower() == "Internal".ToLower());
                DocCasePartType internalDocCasePartType = this.unitOfWork.DbContext.Set<DocCasePartType>()
                    .SingleOrDefault(e => e.Alias.ToLower() == "Internal".ToLower());
                DocFormatType paperDocFormatType = this.unitOfWork.DbContext.Set<DocFormatType>()
                    .SingleOrDefault(e => e.Alias.ToLower() == "Paper".ToLower());
                DocStatus draftStatus = this.unitOfWork.DbContext.Set<DocStatus>().SingleOrDefault(e => e.Alias == "Draft");

                DocType docType = this.unitOfWork.DbContext.Set<DocType>()
                    .SingleOrDefault(e => e.Alias.ToLower() == "EditableDocumentFile".ToLower());
                string docSubject = "Чеклист";

                if (identifier == "st")
                {
                    docSubject = "Чеклист за първи етап";
                }
                else
                {
                    docSubject = "Чеклист за втори етап";
                }

                if (correct)
                {
                    docType = this.unitOfWork.DbContext.Set<DocType>().SingleOrDefault(e => e.Alias == "Resolution");
                    docSubject = "Поправка на " + docSubject.ToLower();
                }
                else if (copy)
                {
                    docSubject = "Копие на " + docSubject.ToLower();
                }

                Doc newDoc = this.docRepository.CreateDoc(
                    internalDocDirection.DocDirectionId,
                    documentEntryType.DocEntryTypeId,
                    draftStatus.DocStatusId,
                    docSubject,
                    internalDocCasePartType.DocCasePartTypeId,
                    null,
                    null,
                    docType.DocTypeId,
                    paperDocFormatType.DocFormatTypeId,
                    null,
                    userContext);

                DocRelation parentDocRelation = this.unitOfWork.DbContext.Set<DocRelation>().FirstOrDefault(e => e.DocId == docId);

                if (copy || correct)
                {
                    if (parentDocRelation.ParentDocId.HasValue)
                    {
                        parentDocRelation = this.unitOfWork.DbContext.Set<DocRelation>().FirstOrDefault(e => e.DocId == parentDocRelation.ParentDocId.Value);
                    }
                }

                ElectronicServiceStage electronicServiceStage = null;
                if (parentDocRelation == null)
                {
                    electronicServiceStage = this.unitOfWork.DbContext.Set<ElectronicServiceStage>()
                        .SingleOrDefault(e => e.DocTypeId == newDoc.DocTypeId && e.IsFirstByDefault);
                }

                List<DocUnitRole> docUnitRoles = this.unitOfWork.DbContext.Set<DocUnitRole>().ToList();

                List<DocTypeUnitRole> docTypeUnitRoles = new List<DocTypeUnitRole>();

                //from
                docTypeUnitRoles.Add(new DocTypeUnitRole
                {
                    DocTypeId = docType.DocTypeId,
                    DocDirectionId = internalDocDirection.DocDirectionId,
                    DocUnitRoleId = docUnitRoles.SingleOrDefault(e => e.Alias == "From").DocUnitRoleId,
                    UnitId = unitUser.UnitId,
                    IsActive = true
                });

                DocUnitRole importedBy = docUnitRoles.SingleOrDefault(e => e.Alias == "ImportedBy");

                if (correct)
                {
                    List<DocUnit> checklistImporters = this.unitOfWork.DbContext.Set<DocUnit>()
                        .Where(e => e.DocId == checklistId && e.DocUnitRoleId == importedBy.DocUnitRoleId)
                        .ToList();

                    foreach (var item in checklistImporters)
                    {
                        //InCharge
                        docTypeUnitRoles.Add(new DocTypeUnitRole
                        {
                            DocTypeId = docType.DocTypeId,
                            DocDirectionId = internalDocDirection.DocDirectionId,
                            DocUnitRoleId = docUnitRoles.SingleOrDefault(e => e.Alias == "InCharge").DocUnitRoleId,
                            UnitId = item.UnitId,
                            IsActive = true
                        });
                    }

                    AssignmentType noDeadline = this.unitOfWork.DbContext.Set<AssignmentType>()
                        .SingleOrDefault(e => e.Alias == "WithoutDeadline");

                    newDoc.AssignmentTypeId = noDeadline.AssignmentTypeId;
                    newDoc.AssignmentDate = DateTime.Now;
                }

                List<DocClassification> parentDocClassifications = this.unitOfWork.DbContext.Set<DocClassification>()
                        .Where(e => e.DocId == parentDocRelation.DocId &&
                            e.IsActive &&
                            e.IsInherited)
                        .ToList();

                newDoc.CreateDocProperties(
                    parentDocRelation,
                    null,
                    null,
                    parentDocClassifications,
                    electronicServiceStage, //? should there be a stage
                    docTypeUnitRoles,
                    importedBy,
                    unitUser,
                    null,
                    null,
                    this.userContext);

                Guid blobKey;

                string emptyChecklist = JsonConvert.SerializeObject(new
                {
                    version = "1",
                    author = unitUser.Unit.Name,
                    createDate = DateTime.Now
                }).ToString();

                string contentStr = string.Format("{{ versions: [{0}] }}", emptyChecklist);

                if (!copy && !correct)
                {
                    Doc doc = this.docRepository.Find(docId, e => e.DocFiles);

                    var fedFile = doc.DocFiles.FirstOrDefault(e => e.DocFileName.EndsWith(".fed"));

                    if (fedFile != null)
                    {
                        byte[] fedContent;

                        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                        {
                            connection.Open();

                            using (MemoryStream m1 = new MemoryStream())
                            using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", fedFile.DocFileContentId))
                            {
                                blobStream.CopyTo(m1);
                                fedContent = m1.ToArray();
                            }
                        }

                        List<NOMv5.nom> noms = FedHelper.GetFedDocumentNomenclatures();
                        List<NUTv5.item> nuts = FedHelper.GetFedDocumentNuts();

                        FEDv5.document fedDoc = XmlSerializerUtils.XmlDeserializeFromBytes<FEDv5.document>(fedContent);

                        FedExtractor.noms = noms;

                        string contractor = FedExtractor.GetContractor(fedDoc);
                        string contractorLotNum = FedExtractor.GetContractorBatch(fedDoc);

                        string procType = FedExtractor.GetProcedureTypeShort(fedDoc);
                        string obj = FedExtractor.GetObject(fedDoc);
                        string criteria = FedExtractor.GetOffersCriteriaOnly(fedDoc);
                        string subject = FedExtractor.GetSubject(fedDoc);
                        string val = FedExtractor.GetPredictedValue(fedDoc);

                        string fedValueChecklist = JsonConvert.SerializeObject(new
                        {
                            version = "1",
                            author = unitUser.Unit.Name,
                            createDate = DateTime.Now,
                            paragraph1 = new
                            {
                                employer = new
                                {
                                    table1 = new
                                    {
                                        row1 = contractor,
                                        row3 = contractorLotNum
                                    }
                                },
                                proc = new
                                {
                                    table1 = new
                                    {
                                        row1 = new
                                        {
                                            tick1 = procType == "Открита" ? true : false,
                                            tick2 = procType == "Ограничена" ? true : false,
                                            tick3 = procType == "Ускорена ограничена" ? true : false,
                                            tick4 = procType == "Договаряне" ? true : false,
                                            tick5 = procType == "Ускорена процедура на договаряне" || procType == "Ускорена на договаряне" ? true : false,
                                            tick6 = procType == "Състезателен диалог" ? true : false,
                                        },
                                        row2 = new
                                        {
                                            tick1 = obj == "Строителство" ? true : false,
                                            tick2 = obj == "Доставки" ? true : false,
                                            tick3 = obj == "Услуги" ? true : false
                                        },
                                        row4 = subject,
                                        row5 = val,
                                        row7 = new
                                        {
                                            tick1 = obj.ToLower() == "най-ниска цена" ? true : false,
                                            tick2 = obj == "икономически най-изгодна оферта с оглед на" || obj == "икономически най-изгодна оферта при" ? true : false
                                        }
                                    }
                                }
                            }
                        }).ToString();

                        contentStr = string.Format("{{ versions: [{0}] }}", fedValueChecklist);
                    }
                }

                if (copy || correct)
                {
                    DocFile editable = this.unitOfWork.DbContext.Set<DocFile>().FirstOrDefault(e => e.DocId == checklistId && e.DocFileOriginType.Alias == "EditableFile");

                    if (editable != null)
                    {
                        byte[] contentToBeCopied;

                        using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                        {
                            connection.Open();

                            using (MemoryStream m1 = new MemoryStream())
                            using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", editable.DocFileContentId))
                            {
                                blobStream.CopyTo(m1);
                                contentToBeCopied = m1.ToArray();
                            }
                        }

                        string contentToString = System.Text.Encoding.UTF8.GetString(contentToBeCopied);

                        JObject checklistObj = JsonConvert.DeserializeObject<JObject>(contentToString);
                        JArray checklistVersions = checklistObj["versions"] as JArray;
                        dynamic newChecklistVersion = checklistVersions.First().DeepClone();
                        newChecklistVersion.version = int.Parse(Convert.ToString(newChecklistVersion.version)) + 1;
                        newChecklistVersion.author = unitUser.Unit.Name;
                        newChecklistVersion.createDate = DateTime.Now;

                        checklistVersions.Insert(0, newChecklistVersion);

                        contentStr = JsonConvert.SerializeObject(checklistObj);
                    }
                }

                byte[] content = System.Text.Encoding.UTF8.GetBytes(contentStr);

                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                {
                    connection.Open();
                    using (var blobWriter = new BlobWriter(connection))
                    using (var stream = blobWriter.OpenStream())
                    {
                        stream.Write(content, 0, content.Length);
                        blobKey = blobWriter.GetBlobKey();
                    }
                }

                DocFileKind privateKind = this.unitOfWork.DbContext.Set<DocFileKind>()
                    .FirstOrDefault(e => e.Alias == "PrivateAttachedFile");
                DocFileType unknownType = this.unitOfWork.DbContext.Set<DocFileType>()
                    .FirstOrDefault(e => e.Alias == "Checklist");
                DocFileOriginType editableFile = this.unitOfWork.DbContext.Set<DocFileOriginType>()
                    .FirstOrDefault(e => e.Alias == "EditableFile");

                newDoc.CreateDocFile(
                    privateKind.DocFileKindId,
                    unknownType.DocFileTypeId,
                    editableFile.DocFileOriginTypeId,
                    "Checklist",
                    "Checklist",
                    "",
                    blobKey,
                    this.userContext);

                this.unitOfWork.Save();

                if (identifier == "st")
                {
                    app.STChecklistId = newDoc.DocId;
                }
                else if (identifier == "nd")
                {
                    app.NDChecklistId = newDoc.DocId;
                }

                this.docRepository.ExecSpSetDocTokens(docId: newDoc.DocId);
                this.docRepository.ExecSpSetDocUnitTokens(docId: newDoc.DocId);

                this.unitOfWork.Save();

                transaction.Commit();

                return Ok(new
                {
                    docId = newDoc.DocId
                });
            }
        }
示例#6
0
        private List<Rio.Data.Utils.RioObjectUtils.CompetenceContainerFile> GetCompetenceFilesByDocId(int? caseDocId)
        {
            List<Rio.Data.Utils.RioObjectUtils.CompetenceContainerFile> competenceFiles = new List<Rio.Data.Utils.RioObjectUtils.CompetenceContainerFile>();

            if (caseDocId.HasValue)
            {
                var publicCaseDocs = docRepository.FindPublicLeafsByDocId(caseDocId.Value);

                if (publicCaseDocs.Count > 0)
                {
                    using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                    using (var channelFactory = new ChannelFactory<IAbbcdn>("WSHttpBinding_IAbbcdn"))
                    using (var abbcdnStorage = new AbbcdnStorage(channelFactory))
                    {
                        connection.Open();

                        foreach (var doc in publicCaseDocs)
                        {
                            DocFile primaryDocFile =
                                this.unitOfWork.DbContext.Set<DocFile>()
                                .Include(d => d.DocFileType)
                                .Where(d => d.DocId == doc.DocId && d.DocFileKind.Alias == "PublicAttachedFile")
                                .OrderByDescending(d => d.IsPrimary)
                                .ThenBy(d => d.DocFileId)
                                .FirstOrDefault();

                            Rio.Data.Utils.RioObjectUtils.CompetenceContainerFile competenceContainerFile = new Rio.Data.Utils.RioObjectUtils.CompetenceContainerFile();
                            if (primaryDocFile == null)
                            {
                                competenceContainerFile.DocumentTypeName = doc.DocType.Name;
                                competenceContainerFile.DocumentRegIndex = doc.RegIndex;
                                competenceContainerFile.DocumentRegNumber = doc.RegNumber.ToString();
                                competenceContainerFile.DocumentRegDate = doc.RegDate;
                            }
                            else
                            {
                                byte[] fileContent = null;

                                using (MemoryStream mStream = new MemoryStream())
                                using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", primaryDocFile.DocFileContentId))
                                {
                                    blobStream.CopyTo(mStream);
                                    fileContent = mStream.ToArray();
                                }

                                var uploadFileInfo = abbcdnStorage.UploadFile(fileContent, primaryDocFile.DocFileName);

                                if (!String.IsNullOrWhiteSpace(primaryDocFile.DocFileType.DocTypeUri))
                                {
                                    competenceContainerFile.DocumentTypeName = RioDocumentMetadata.GetMetadataByDocumentTypeURI(primaryDocFile.DocFileType.DocTypeUri).DocumentTypeName;
                                }
                                else
                                {
                                    competenceContainerFile.DocumentTypeName = doc.DocType.Name;
                                }
                                competenceContainerFile.DocumentTypeUri = primaryDocFile.DocFileType.DocTypeUri;
                                competenceContainerFile.DocumentRegIndex = doc.RegIndex;
                                competenceContainerFile.DocumentRegNumber = doc.RegNumber.ToString();
                                competenceContainerFile.DocumentRegDate = doc.RegDate;
                                //competenceContainerFile.Abbcdnconfig = SerializeAbbcdn(uploadFileInfo, primaryDocFile.DocFileName, primaryDocFile.DocFileType.MimeType);
                                competenceContainerFile.Abbcdnconfig = new Abbcdnconfig()
                                {
                                    AttachedDocumentUniqueIdentifier = uploadFileInfo.FileKey.ToString(),
                                    AttachedDocumentHash = uploadFileInfo.ContentHash,
                                    AttachedDocumentSize = uploadFileInfo.ContentSize.ToString(),
                                    AttachedDocumentFileName = primaryDocFile.DocFileName,
                                    AttachedDocumentFileType = primaryDocFile.DocFileType.MimeType
                                };

                            }

                            competenceFiles.Add(competenceContainerFile);
                        }
                    }
                }
            }

            return competenceFiles;
        }
示例#7
0
        public IHttpActionResult SendCompetenceTransferDoc(int id, int electronicServiceProviderId)
        {
            var doc = this.docRepository.Find(id,
               e => e.DocFiles.Select(df => df.DocFileOriginType),
               e => e.DocFiles.Select(df => df.DocFileType));

            if (doc == null)
            {
                return BadRequest();
            }

            DocFile editable = doc.DocFiles.FirstOrDefault(e => e.DocFileOriginTypeId.HasValue && e.DocFileOriginType.Alias == "EditableFile");
            if (editable == null || editable.DocFileType.Alias != "ContainerTransferFileCompetence")
            {
                return BadRequest();
            }

            byte[] content;

            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
            {
                connection.Open();

                using (MemoryStream m1 = new MemoryStream())
                using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", editable.DocFileContentId))
                {
                    blobStream.CopyTo(m1);
                    content = m1.ToArray();
                }
            }

            string xmlContent = Utf8Utils.GetString(content);

            ElectronicServiceProvider electronicServiceProvider =
                this.unitOfWork.DbContext.Set<ElectronicServiceProvider>().FirstOrDefault(e => e.ElectronicServiceProviderId == electronicServiceProviderId);

            using (var channelFactory = new ChannelFactory<IApplicationCommunicator>("AppCommunicatorEndpoint", new EndpointAddress(electronicServiceProvider.EndPointAddress)))
            {
                DocumentRequest documentRequest = new DocumentRequest()
                {
                    DocumentData = xmlContent,
                    DocumentFileName = String.Format("CompetenceTransferDoc_{0}.xml", editable.DocFileContentId.ToString()),
                    DocumentGuid = editable.DocFileContentId
                };

                var service = channelFactory.CreateChannel();
                DocumentInfo documentInfo = service.ProcessStructuredDocument(documentRequest);
            }

            return Ok();
        }
示例#8
0
        public IHttpActionResult RegisterDoc(int id, string docVersion)
        {
            UnitUser unitUser = this.unitOfWork.DbContext.Set<UnitUser>().FirstOrDefault(e => e.UserId == this.userContext.UserId);

            ClassificationPermission registerPermission = this.classificationRepository.GetByAlias("Register");
            ClassificationPermission readPermission = this.classificationRepository.GetByAlias("Read");

            bool hasRegisterPermission =
                this.classificationRepository.HasPermission(unitUser.UnitId, id, registerPermission.ClassificationPermissionId) &&
                this.classificationRepository.HasPermission(unitUser.UnitId, id, readPermission.ClassificationPermissionId);

            if (!hasRegisterPermission)
            {
                return BadRequest("Not enough permissions!");
            }

            Doc doc = this.docRepository.Find(id,
                e => e.DocRelations);

            this.unitOfWork.DbContext.Set<DocFile>()
             .Include(e => e.DocFileOriginType)
             .Include(e => e.DocFileType)
             .Include(e => e.DocFileKind)
             .Where(e => e.DocId == id)
             .ToList();

            string result = this.docRepository.RegisterDoc(
                doc,
                unitUser,
                this.userContext,
                true,
                Helper.StringToVersion(docVersion));

            DocFile editable = doc.DocFiles.FirstOrDefault(e => e.DocFileOriginTypeId.HasValue && e.DocFileOriginType.Alias == "EditableFile");

            if (editable != null && editable.DocFileType.DocTypeUri != "Checklist")
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                {
                    connection.Open();

                    byte[] content;

                    using (MemoryStream m1 = new MemoryStream())
                    using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", editable.DocFileContentId))
                    {
                        blobStream.CopyTo(m1);
                        content = m1.ToArray();
                    }

                    content = AddRegistrationInfoToRioObject(content, editable.DocFileType.DocTypeUri, doc);

                    using (var blobWriter = new BlobWriter(connection))
                    using (var stream = blobWriter.OpenStream())
                    {
                        stream.Write(content, 0, content.Length);
                        editable.DocFileContentId = blobWriter.GetBlobKey();
                    }
                }
            }

            this.unitOfWork.Save();

            return Ok(new
            {
                result = result
            });
        }
示例#9
0
        public IHttpActionResult GetRioObjectEditableFile(int id)
        {
            var doc = this.docRepository.Find(id,
               e => e.DocFiles.Select(df => df.DocFileOriginType),
               e => e.DocFiles.Select(df => df.DocFileType));

            if (doc == null)
            {
                return NotFound();
            }

            DocFile editable = doc.DocFiles.FirstOrDefault(e => e.DocFileOriginTypeId.HasValue && e.DocFileOriginType.Alias == "EditableFile");

            byte[] content;

            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
            {
                connection.Open();

                using (MemoryStream m1 = new MemoryStream())
                using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", editable.DocFileContentId))
                {
                    blobStream.CopyTo(m1);
                    content = m1.ToArray();
                }
            }

            var jObject = RioObjectUtils.GetJObjectFromBytes(editable.DocFileType.DocTypeUri, content);

            return Ok(new
            {
                content = jObject
            });
        }
示例#10
0
        public IList<IntegrationDocRelationDO> GetCaseApplications(int docId)
        {
            var docRelations =
                this.docRepository
                .GetCaseRelationsByDocIdWithIncludes(docId, false, true)
                .Where(dr => dr.Doc.IsRegistered);

            List<IntegrationDocRelationDO> result = new List<IntegrationDocRelationDO>();

            foreach (var docRelation in docRelations)
            {
                if (!CaseTypeAliasByPortalAppCode.ContainsKey(docRelation.Doc.DocType.Alias))
                {
                    continue;
                }

                GvaCaseType caseType = this.caseTypeRepository.GetCaseType(CaseTypeAliasByPortalAppCode[docRelation.Doc.DocType.Alias]);
                IntegrationDocRelationDO intDocRelation = new IntegrationDocRelationDO(docRelation, caseType);
                result.Add(intDocRelation);

                var appDocFiles =
                    docRelation.Doc.DocFiles
                    .Where(df => df.DocFileOriginType != null && df.DocFileOriginType.Alias == "EApplication")
                    .ToList();

                if (appDocFiles.Count == 1)
                {
                    byte[] content;
                    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                    {
                        connection.Open();

                        using (MemoryStream m1 = new MemoryStream())
                        using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", appDocFiles[0].DocFileContentId))
                        {
                            blobStream.CopyTo(m1);
                            content = m1.ToArray();
                        }
                    }

                    string xmlContent = Utf8Utils.GetString(content);
                    object rioApplication = this.rioDocumentParser.XmlDeserializeApplication(xmlContent);

                    switch (docRelation.Doc.DocType.Alias)
                    {
                        case "R-4186":
                            {
                                var concreteApp = (R_4186.InitialCertificationCommercialPilotCapacityInstrumentFlightApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-4244":
                            {
                                var concreteApp = (R_4244.LicenseFlightCrewCabinCrewFlightEngineersNavigatorsFlightConvoyApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-4284":
                            {
                                var concreteApp = (R_4284.LicenseControllersAssistantFlightsATMCoordinatorsApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-4864":
                            {
                                var concreteApp = (R_4864.LicenseCabinCrewApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-5144":
                            {
                                var concreteApp = (R_5144.EstablishingAssessCompetenceApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-4296":
                            {
                                var concreteApp = (R_4296.RecognitionLicenseForeignNationals)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-5178":
                            {
                                var concreteApp = (R_5178.RegistrationRatingTypeClassAircraftIFRPilotLicensePilotPartFCLApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-5196":
                            {
                                var concreteApp = (R_5196.ConfirmationRecoveryRatingLicensePilotApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-5248":
                            {
                                var concreteApp = (R_5248.RegistrationAircraftTypePermissionFlightCrewApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-5250":
                            {
                                var concreteApp = (R_5250.ConfirmationRatingCrewApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-5242":
                            {
                                var concreteApp = (R_5242.RegistrationTrainingAircraftTypePermissionStewardHostessApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-5134":
                            {
                                var concreteApp = (R_5134.ChangeCompetentAuthorityLicensePilotAccordanceLicenseApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-5244":
                            {
                                var concreteApp = (R_5244.ConfirmationRecoveryTrainingAircraftTypePermissionStewardHostessApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-5246":
                            {
                                var concreteApp = (R_5246.ConfirmationConversionPursuantLicensePilotIssuedApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-4242":
                            {
                                var concreteApp = (R_4242.InitialIssueLicenseFlightDispatcherApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-5160":
                            {
                                var concreteApp = (R_5160.RegistrationRatingAuthorizationLicenseApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-5164":
                            {
                                var concreteApp = (R_5164.ConfirmationRecoveryRatingLicenseApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-5166":
                            {
                                var concreteApp = (R_5166.ReplacingLicenseFlightsCoordinatorsApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-4240":
                            {
                                var concreteApp = (R_4240.InitialAuthorizationMaintenanceAircraftAMLApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithFlightCrewDataToPersonData(concreteApp.FlightCrewPersonalData, caseType);
                                break;
                            }
                        case "R-4958":
                            {
                                var concreteApp = (R_4958.EngineeringTechnicalStaffPerformingMaintenanceFundsAirTrafficManagementApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithPersonAndForeignCitizenBasicDataToPersonData(
                                    concreteApp.CAAPersonalIdentificationNumber,
                                    concreteApp.ContactInformation.EmailAddress,
                                    concreteApp.PersonBasicData,
                                    concreteApp.ForeignCitizenBasicData,
                                    caseType);
                                break;
                            }
                        case "R-5218":
                            {
                                var concreteApp = (R_5218.ReplacementRemovalRestrictionsLicenseManagementApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithPersonAndForeignCitizenBasicDataToPersonData(
                                    concreteApp.CAAPersonalIdentificationNumber,
                                    concreteApp.ContactInformation.EmailAddress,
                                    concreteApp.PersonBasicData,
                                    concreteApp.ForeignCitizenBasicData,
                                    caseType);
                                break;
                            }
                        case "R-5170":
                            {
                                var concreteApp = (R_5170.ConfirmationRecoveryRatingLicenseEngineeringTechnicalStaffMaintenanceFundsManagementApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithPersonAndForeignCitizenBasicDataToPersonData(
                                    concreteApp.CAAPersonalIdentificationNumber,
                                    concreteApp.ContactInformation.EmailAddress,
                                    concreteApp.PersonBasicData,
                                    concreteApp.ForeignCitizenBasicData,
                                    caseType);
                                break;
                            }

                        case "R-5168":
                            {
                                var concreteApp = (R_5168.EntryRatingAuthorizationLicenseEngineeringTechnicalStaffEngagedMaintenanceFundsManagementApplication)rioApplication;
                                intDocRelation.PersonData = this.integrationRepository.ConvertAppWithPersonAndForeignCitizenBasicDataToPersonData(
                                    concreteApp.CAAPersonalIdentificationNumber,
                                    concreteApp.ContactInformation.EmailAddress,
                                    concreteApp.PersonBasicData,
                                    concreteApp.ForeignCitizenBasicData,
                                    caseType);
                                break;
                            }
                        case "R-4356":
                            {
                                var aircraftData = new AircraftDataDO();
                                var concreteApp = (R_4356.AircraftRegistrationCertificateApplication)rioApplication;
                                string producerName = concreteApp.AircraftManufactureData.ManufacturerContactData.ManufacturerName;
                                aircraftData.AircraftProducer = this.nomRepository.GetNomValues("aircraftProducers", producerName).FirstOrDefault();

                                intDocRelation.AircraftData = aircraftData;
                                break;
                            }
                        case "R-5132":
                            {
                                var organizationData = new OrganizationDataDO();
                                var concreteApp = (R_5132.ApprovalPartMSubpartGApplication)rioApplication;
                                organizationData.Name = concreteApp.EntityTradeName ?? concreteApp.EntityBasicData.Name;
                                string foreignName = null;
                                if (concreteApp.ForeignEntityBasicData != null)
                                {
                                    foreignName = concreteApp.ForeignEntityBasicData.ForeignEntityName;
                                }
                                organizationData.NameAlt = foreignName ?? organizationData.Name;
                                organizationData.Uin = concreteApp.EntityBasicData.Identifier;
                                organizationData.Valid = this.nomRepository.GetNomValue("boolean", "yes");

                                intDocRelation.OrganizationData = organizationData;
                                break;
                            }
                        // 4378
                        // 4396
                        // 4470
                        // 4490
                        // 4514
                        // 4544
                        // 4566
                        // 4578
                        // 4588
                        // 4590
                        // 4598
                        // 4606
                        // 4614
                        // 4686
                        // 4738
                        // 4764
                        // 4766
                        // 4810
                        // 4824
                        // 4834
                        // 4860
                        // 4862
                        // 4900
                        // 4926
                        // 5000
                        // 5090
                        // 5094
                        // 5096
                        // 5104
                        // 5116
                        default:
                            break;
                    }
                }
            }

            return result;
        }
示例#11
0
        public IHttpActionResult LoadChecklist(int id)
        {
            var doc = this.docRepository.Find(id,
               e => e.DocFiles.Select(df => df.DocFileOriginType));

            if (doc == null)
            {
                return NotFound();
            }

            DocFile editable = doc.DocFiles.FirstOrDefault(e => e.DocFileOriginTypeId.HasValue && e.DocFileOriginType.Alias == "EditableFile");

            byte[] content;

            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
            {
                connection.Open();

                using (MemoryStream m1 = new MemoryStream())
                using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", editable.DocFileContentId))
                {
                    blobStream.CopyTo(m1);
                    content = m1.ToArray();
                }
            }

            string contentToString = System.Text.Encoding.UTF8.GetString(content);

            AopApp aopApp = this.unitOfWork.DbContext.Set<AopApp>().FirstOrDefault(e => e.STChecklistId == id || e.NDChecklistId == id);
            int? aopApplicationId = aopApp != null ? aopApp.AopApplicationId : (int?)null;

            return Ok(new
            {
                aopApplicationId = aopApplicationId,
                content = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(contentToString)
            });
        }
示例#12
0
        public HttpResponseMessage DownloadChecklist(int id, string identifier)
        {
            int checklistId;

            AopApp app = this.unitOfWork.DbContext.Set<AopApp>().Find(id);

            if (identifier == "st")
            {
                checklistId = app.STChecklistId.Value;
            }
            else if (identifier == "nd")
            {
                checklistId = app.NDChecklistId.Value;
            }
            else
            {
                throw new Exception("Identifier missing.");
            }

            DocFile editable = this.unitOfWork.DbContext.Set<DocFile>().FirstOrDefault(e => e.DocId == checklistId && e.DocFileOriginType.Alias == "EditableFile");

            byte[] content;

            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
            {
                connection.Open();

                using (MemoryStream m1 = new MemoryStream())
                using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", editable.DocFileContentId))
                {
                    blobStream.CopyTo(m1);
                    content = m1.ToArray();
                }

                string contentToString = System.Text.Encoding.UTF8.GetString(content);
                JObject checklistObj = JsonConvert.DeserializeObject<JObject>(contentToString);
                JArray checklistVersions = checklistObj["versions"] as JArray;
                JObject latest = checklistVersions.First() as JObject;

                string templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"App\word_templates\checklist.docx");

                using (FileStream template = File.Open(templatePath, FileMode.Open, FileAccess.Read))
                {
                    var memoryStream = new MemoryStream();

                    template.CopyTo(memoryStream);

                    WordTemplateTransformer tt = new WordTemplateTransformer(memoryStream);
                    tt.Transform(latest);

                    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

                    memoryStream.Position = 0;
                    result.Content = new StreamContent(memoryStream);

                    result.Content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/octet-stream");

                    result.Content.Headers.ContentDisposition =
                        new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = "checklist_for_print.docx"
                        };

                    return result;
                }
            }
        }
示例#13
0
        public IHttpActionResult CreateChildReport(int id)
        {
            using (var transaction = this.unitOfWork.BeginTransaction())
            {
                int docId, checklistId;

                AopApp app = this.unitOfWork.DbContext.Set<AopApp>().Find(id);

                if (app.NDDocId.HasValue && app.NDChecklistId.HasValue)
                {
                    docId = app.NDDocId.Value;
                    checklistId = app.NDChecklistId.Value;
                }
                else
                {
                    throw new Exception("NDDocId OR NDChecklistId missing.");
                }

                UnitUser unitUser = this.unitOfWork.DbContext.Set<UnitUser>().FirstOrDefault(e => e.UserId == this.userContext.UserId);
                DocEntryType documentEntryType = this.unitOfWork.DbContext.Set<DocEntryType>().SingleOrDefault(e => e.Alias == "Document");

                DocDirection outgoingDocDirection = this.unitOfWork.DbContext.Set<DocDirection>()
                    .SingleOrDefault(e => e.Alias.ToLower() == "Outgoing".ToLower());
                DocCasePartType internalDocCasePartType = this.unitOfWork.DbContext.Set<DocCasePartType>()
                    .SingleOrDefault(e => e.Alias.ToLower() == "Internal".ToLower());
                DocFormatType paperDocFormatType = this.unitOfWork.DbContext.Set<DocFormatType>()
                    .SingleOrDefault(e => e.Alias.ToLower() == "Paper".ToLower());
                DocStatus draftStatus = this.unitOfWork.DbContext.Set<DocStatus>().SingleOrDefault(e => e.Alias == "Draft");

                DocType docType = this.unitOfWork.DbContext.Set<DocType>()
                    .SingleOrDefault(e => e.Alias.ToLower() == "Report".ToLower());
                string docSubject = "Генериран доклад";

                Doc newDoc = this.docRepository.CreateDoc(
                    outgoingDocDirection.DocDirectionId,
                    documentEntryType.DocEntryTypeId,
                    draftStatus.DocStatusId,
                    docSubject,
                    internalDocCasePartType.DocCasePartTypeId,
                    null,
                    null,
                    docType.DocTypeId,
                    paperDocFormatType.DocFormatTypeId,
                    null,
                    userContext);

                DocRelation parentDocRelation = this.unitOfWork.DbContext.Set<DocRelation>().FirstOrDefault(e => e.DocId == docId);

                ElectronicServiceStage electronicServiceStage = null;
                if (parentDocRelation == null)
                {
                    electronicServiceStage = this.unitOfWork.DbContext.Set<ElectronicServiceStage>()
                        .SingleOrDefault(e => e.DocTypeId == newDoc.DocTypeId && e.IsFirstByDefault);
                }

                List<DocUnitRole> docUnitRoles = this.unitOfWork.DbContext.Set<DocUnitRole>().ToList();

                List<DocTypeUnitRole> docTypeUnitRoles = new List<DocTypeUnitRole>();

                //from
                docTypeUnitRoles.Add(new DocTypeUnitRole
                {
                    DocTypeId = docType.DocTypeId,
                    DocDirectionId = outgoingDocDirection.DocDirectionId,
                    DocUnitRoleId = docUnitRoles.SingleOrDefault(e => e.Alias == "From").DocUnitRoleId,
                    UnitId = unitUser.UnitId,
                    IsActive = true
                });

                DocUnitRole importedBy = docUnitRoles.SingleOrDefault(e => e.Alias == "ImportedBy");

                List<DocClassification> parentDocClassifications = this.unitOfWork.DbContext.Set<DocClassification>()
                       .Where(e => e.DocId == parentDocRelation.DocId &&
                           e.IsActive &&
                           e.IsInherited)
                       .ToList();

                Doc caseDoc = this.docRepository.Find(this.docRepository.GetCaseId(docId),
                    e => e.DocCorrespondents);

                List<int> correspondentIds = caseDoc.DocCorrespondents.Select(e => e.CorrespondentId).ToList();

                newDoc.CreateDocProperties(
                    parentDocRelation,
                    null,
                    null,
                    parentDocClassifications,
                    electronicServiceStage,
                    docTypeUnitRoles,
                    importedBy,
                    unitUser,
                    correspondentIds,
                    null,
                    this.userContext);

                this.unitOfWork.Save();

                #region FileContent

                DocFile docFile = this.unitOfWork.DbContext.Set<DocFile>()
                    .FirstOrDefault(e => e.DocId == checklistId && e.DocFileOriginTypeId.HasValue && e.DocFileOriginType.Alias == "EditableFile");
                DocFileType docFileType = this.unitOfWork.DbContext.Set<DocFileType>().SingleOrDefault(e => e.Alias == "DOCX");
                DocFileKind docFileKind = this.unitOfWork.DbContext.Set<DocFileKind>().Single(e => e.Alias == "PublicAttachedFile");
                DocFileOriginType docFileOriginType = this.unitOfWork.DbContext.Set<DocFileOriginType>().Single(e => e.Alias == "AttachedFile");

                Guid blobKey;

                byte[] content;

                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                {
                    connection.Open();

                    using (MemoryStream m1 = new MemoryStream())
                    using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", docFile.DocFileContentId))
                    {
                        blobStream.CopyTo(m1);
                        content = m1.ToArray();
                    }

                    string contentToString = System.Text.Encoding.UTF8.GetString(content);
                    JObject checklistObj = JsonConvert.DeserializeObject<JObject>(contentToString);
                    JArray checklistVersions = checklistObj["versions"] as JArray;
                    JObject lastest = checklistVersions.First() as JObject;

                    DocUnit checklistMadeBy = this.unitOfWork.DbContext.Set<DocUnit>()
                        .Include(e => e.Unit.UnitRelations.Select(u => u.ParentUnit))
                        .Include(e => e.DocUnitRole)
                        .FirstOrDefault(e => e.DocId == checklistId && (e.DocUnitRole.Alias == "ImportedBy" || e.DocUnitRole.Alias == "MadeBy"));

                    DocWorkflow checklistDiscuss = this.unitOfWork.DbContext.Set<DocWorkflow>()
                        .Include(e => e.PrincipalUnit.UnitRelations.Select(u => u.ParentUnit))
                        .FirstOrDefault(e => e.DocId == checklistId && e.DocWorkflowAction.Alias == "Discuss");

                    JObject json = this.dataGenerator.GenerateReport(lastest,
                        date: DateTime.Now.ToString("dd.MM.yyyy"),
                        madeByName: checklistMadeBy != null ? checklistMadeBy.Unit.Name : string.Empty,
                        madeByPosition: checklistMadeBy != null ? checklistMadeBy.Unit.UnitRelations.First().ParentUnit.Name : string.Empty,
                        coordinatorName: checklistDiscuss != null ? checklistDiscuss.PrincipalUnit.Name : string.Empty,
                        coordinatorPosition: checklistDiscuss != null ? checklistDiscuss.PrincipalUnit.UnitRelations.First().ParentUnit.Name : string.Empty
                        );

                    string templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"App\word_templates\doklad_template.docx");

                    using (FileStream template = File.Open(templatePath, FileMode.Open, FileAccess.Read))
                    using (var memoryStream = new MemoryStream())
                    using (var blobWriter = new BlobWriter(connection))
                    using (var stream = blobWriter.OpenStream())
                    {
                        template.CopyTo(memoryStream);

                        WordTemplateTransformer tt = new WordTemplateTransformer(memoryStream);
                        tt.Transform(json);

                        memoryStream.Position = 0;
                        memoryStream.CopyTo(stream);

                        blobKey = blobWriter.GetBlobKey();
                    }
                }

                newDoc.CreateDocFile(
                    docFileKind.DocFileKindId,
                    docFileType.DocFileTypeId,
                    docFileOriginType.DocFileOriginTypeId,
                    "Report.docx",
                    "Report.docx",
                    "",
                    blobKey,
                    this.userContext);

                #endregion

                app.NDReportId = newDoc.DocId;

                this.docRepository.ExecSpSetDocTokens(docId: newDoc.DocId);
                this.docRepository.ExecSpSetDocUnitTokens(docId: newDoc.DocId);

                this.unitOfWork.Save();

                transaction.Commit();

                return Ok(new
                {
                    docId = newDoc.DocId
                });
            }
        }
示例#14
0
        public IHttpActionResult GetImage(string fileKey, string name)
        {
            GhostscriptVersionInfo lastInstalledVersion = GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL | GhostscriptLicense.AFPL, GhostscriptLicense.GPL);
            byte[] image;

            string[] extentions = { ".pdf", ".jpg", ".bmp", ".jpeg", ".png", ".tiff" };
            if (!extentions.Contains(Path.GetExtension(name)))
            {
                return Ok(new { err = "noPDForIMGFile" });
            }

            using (MemoryStream m1 = new MemoryStream())
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                {
                    connection.Open();

                    using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", fileKey))
                    {
                        blobStream.CopyTo(m1);
                    }
                }

                Bitmap bitmapImg;
                if (Path.GetExtension(name) == ".pdf")
                {
                    using (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer())
                    {
                        rasterizer.Open(m1, lastInstalledVersion, false);

                        //Copied, because rasterizer disposes itself
                        bitmapImg = new Bitmap(rasterizer.GetPage(300, 300, 1));
                    }
                }
                else
                {
                    bitmapImg = new Bitmap(m1);
                }

                using (bitmapImg)
                {
                    using (Bitmap bitmapImgResized = OMRReader.ResizeImage(bitmapImg, 580, 800))
                    {
                        using (MemoryStream m2 = new MemoryStream())
                        {
                            bitmapImgResized.Save(m2, ImageFormat.Jpeg);
                            image = m2.ToArray();
                        }
                    }
                }
            }

            return Ok(new { image = image });
        }
示例#15
0
        public IHttpActionResult ReadFedForSecondStage(int id)
        {
            UnitUser unitUser = this.unitOfWork.DbContext.Set<UnitUser>().FirstOrDefault(e => e.UserId == this.userContext.UserId);

            ClassificationPermission editPermission = this.classificationRepository.GetByAlias("Edit");
            ClassificationPermission readPermission = this.classificationRepository.GetByAlias("Read");

            bool hasEditPermission =
                this.appRepository.HasPermission(unitUser.UnitId, id, editPermission.ClassificationPermissionId) &&
                this.appRepository.HasPermission(unitUser.UnitId, id, readPermission.ClassificationPermissionId);

            if (!hasEditPermission)
            {
                return Unauthorized();
            }

            AopApp app = this.appRepository.Find(id);

            if (app.STDocId.HasValue)
            {
                Doc doc = this.docRepository.Find(app.STDocId.Value,
                    e => e.DocFiles);

                var fedFile = doc.DocFiles.FirstOrDefault(e => e.DocFileName.EndsWith(".fed"));

                if (fedFile != null)
                {
                    byte[] fedContent;

                    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                    {
                        connection.Open();

                        using (MemoryStream m1 = new MemoryStream())
                        using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", fedFile.DocFileContentId))
                        {
                            blobStream.CopyTo(m1);
                            fedContent = m1.ToArray();
                        }
                    }

                    List<NOMv5.nom> noms = FedHelper.GetFedDocumentNomenclatures();
                    List<NUTv5.item> nuts = FedHelper.GetFedDocumentNuts();

                    FEDv5.document fedDoc = XmlSerializerUtils.XmlDeserializeFromBytes<FEDv5.document>(fedContent);

                    FedExtractor.noms = noms;

                    //ND properties
                    string procType = FedExtractor.GetProcedureTypeShort(fedDoc);
                    string obj = FedExtractor.GetObject(fedDoc);
                    string criteria = FedExtractor.GetOffersCriteriaOnly(fedDoc);
                    string subject = FedExtractor.GetSubject(fedDoc);
                    string val = FedExtractor.GetPredictedValue(fedDoc);

                    var ndAopApplicationType = this.unitOfWork.DbContext.Set<NomValue>()
                        .FirstOrDefault(e => e.Nom.Alias == "AopApplicationType" && e.Name.ToLower().StartsWith(procType.ToLower()));
                    if (ndAopApplicationType != null)
                    {
                        app.NDAopApplicationTypeId = ndAopApplicationType.NomValueId;
                    }

                    var ndObject = this.unitOfWork.DbContext.Set<NomValue>()
                        .FirstOrDefault(e => e.Nom.Alias == "AopApplicationObject" && e.Name.ToLower().StartsWith(obj.ToLower()));
                    if (ndObject != null)
                    {
                        app.NDObjectId = ndObject.NomValueId;
                    }

                    var ndCriteria = this.unitOfWork.DbContext.Set<NomValue>()
                        .FirstOrDefault(e => e.Nom.Alias == "AopApplicationCriteria" && e.Name.ToLower().StartsWith(criteria.ToLower()));
                    if (ndCriteria != null)
                    {
                        app.NDCriteriaId = ndCriteria.NomValueId;
                    }

                    app.NDSubject = subject;
                    app.NDValue = val;

                    //възложител
                    string aopEmpUic = FedExtractor.GetEIK(fedDoc);

                    var aopEmp = this.unitOfWork.DbContext.Set<AopEmployer>()
                        .FirstOrDefault(e => e.Uic == aopEmpUic);

                    if (aopEmp != null && !app.AopEmployerId.HasValue)
                    {
                        app.AopEmployerId = aopEmp.AopEmployerId;
                    }
                    else
                    {
                        string aopEmpName = FedExtractor.GetContractor(fedDoc);
                        string aopEmpLotNum = FedExtractor.GetContractorBatch(fedDoc);

                        NomValue unknownAopEmpType = this.nomRepository.GetNomValue("AopApplicationObject", "Unknown");

                        AopEmployer emp = appRepository.CreateAopEmployer(aopEmpName, aopEmpLotNum, aopEmpUic, unknownAopEmpType.NomValueId);

                        this.unitOfWork.DbContext.Set<AopEmployer>().Add(emp);

                        this.unitOfWork.Save();

                        app.AopEmployerId = emp.AopEmployerId;
                    }

                    this.unitOfWork.Save();
                }
            }

            return Ok(new
            {
                err = "",
                aopApplicationId = app.AopApplicationId
            });
        }
示例#16
0
        public IHttpActionResult GetPreview(int gvaFileId)
        {
            GvaFile gvaFile = this.unitOfWork.DbContext.Set<GvaFile>().FirstOrDefault(e => e.GvaFileId == gvaFileId);
            byte[] file;

            using (MemoryStream m1 = new MemoryStream())
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                {
                    connection.Open();

                    using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", gvaFile.FileContentId))
                    {
                        blobStream.CopyTo(m1);
                    }
                }

                Bitmap bitmapImg = new Bitmap(m1);

                using (bitmapImg)
                using (Bitmap bitmapImgResized = OMRReader.ResizeImage(bitmapImg, 580, 800))
                {
                    using (MemoryStream m2 = new MemoryStream())
                    {
                        bitmapImgResized.Save(m2, System.Drawing.Imaging.ImageFormat.Jpeg);
                        file = m2.ToArray();
                    }
                }

                return Ok(new { file = file, gvaFile = new FileDataDO(gvaFile) });
            }
        }
示例#17
0
        public void Send(int pendingEmailId)
        {
            EmailStatus deliveredStatus = this.unitOfWork.DbContext.Set<EmailStatus>().Single(e => e.Alias == "Delivered");
            EmailStatus failedStatus = this.unitOfWork.DbContext.Set<EmailStatus>().Single(e => e.Alias == "Failed");

            try
            {
                Email email = this.unitOfWork.DbContext.Set<Email>()
                    .Include(e => e.EmailAddressees.Select(a => a.EmailAddresseeType))
                    .Include(e => e.EmailAttachments)
                    .Single(e => e.EmailId == pendingEmailId);

                if (!email.EmailAddressees.Any(e => e.EmailAddresseeType.Alias == "To" || e.EmailAddresseeType.Alias == "Cc"))
                {
                    //? different exception so it can be treated as a separate case
                    throw new Exception("Unspecified email recipient.");
                }

                MailMessage mailMessage = new MailMessage();
                mailMessage.Subject = email.Subject;
                mailMessage.Body = email.Body;
                mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                mailMessage.IsBodyHtml = true;

                var sender = email.EmailAddressees.FirstOrDefault(e => e.EmailAddresseeType.Alias == "From");

                if (sender != null)
                {
                    mailMessage.From = new MailAddress(sender.Address);
                }
                else
                {
                    mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["Docs.Api:DefaultEmailAccount"]);
                }

                foreach (var item in email.EmailAddressees.Where(e => e.EmailAddresseeType.Alias == "To"))
                {
                    mailMessage.To.Add(new MailAddress(item.Address));
                }

                foreach (var item in email.EmailAddressees.Where(e => e.EmailAddresseeType.Alias == "Cc"))
                {
                    mailMessage.CC.Add(new MailAddress(item.Address));
                }

                foreach (var item in email.EmailAddressees.Where(e => e.EmailAddresseeType.Alias == "Bcc"))
                {
                    mailMessage.Bcc.Add(new MailAddress(item.Address));
                }

                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                {
                    connection.Open();

                    foreach (var item in email.EmailAttachments)
                    {
                        // do not dispose the memory stream because the attachment needs it, it's safe to do so
                        MemoryStream m1 = new MemoryStream();
                        using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", item.ContentId))
                        {
                            blobStream.CopyTo(m1);

                            m1.Position = 0;

                            Attachment attachment = new Attachment(m1, item.Name);

                            mailMessage.Attachments.Add(attachment);
                        }
                    }
                }

                try
                {
                    this.SmtpClient.Send(mailMessage);
                    email.EmailStatusId = deliveredStatus.EmailStatusId;
                    email.SentDate = DateTime.Now;
                }
                catch (Exception ex)
                {
                    email.EmailStatusId = failedStatus.EmailStatusId;

                    StringBuilder errorText = new StringBuilder();
                    errorText.AppendLine(String.Format("Error while sending email message from server {0}", this.SmtpClient.Host.ToString()));
                    errorText.AppendLine(String.Format("Email: {0}", mailMessage.Subject));
                    errorText.AppendLine(String.Format("Email ID: {0}", email.EmailId));
                    errorText.AppendLine();

                    logger.Error("EmailSender Exception: " + errorText.ToString() + Helper.GetDetailedExceptionInfo(ex));
                }
            }
            catch (Exception ex)
            {
                logger.Error("EmailSender Exception: " + String.Format("Email ID={0} ", pendingEmailId) + Helper.GetDetailedExceptionInfo(ex));

                Email email = this.unitOfWork.DbContext.Set<Email>().Single(e => e.EmailId == pendingEmailId);
                email.EmailStatusId = failedStatus.EmailStatusId;
            }
            finally
            {
                this.unitOfWork.Save();
            }
        }
示例#18
0
        public IHttpActionResult GetAnswers(string fileKey, string name)
        {
            GhostscriptVersionInfo lastInstalledVersion = GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL | GhostscriptLicense.AFPL, GhostscriptLicense.GPL);
            Dictionary<string, List<List<bool>>> answers = new Dictionary<string, List<List<bool>>>();
            byte[] file;

            string[] extentions = { ".pdf", ".jpg", ".bmp", ".jpeg", ".png", ".tiff" };
            if (!extentions.Contains(Path.GetExtension(name)))
            {
                return Ok(new { err = "noPDForIMGFile" });
            }

            using (MemoryStream m1 = new MemoryStream())
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                {
                    connection.Open();

                    using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", fileKey))
                    {
                        blobStream.CopyTo(m1);
                    }
                }

                Bitmap bitmapImg;
                if (Path.GetExtension(name) == ".pdf")
                {
                    using (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer())
                    {
                        rasterizer.Open(m1, lastInstalledVersion, true);

                        //Copied, because rasterizer disposes itself
                        bitmapImg = new Bitmap(rasterizer.GetPage(300, 300, 1));
                    }
                }
                else
                {
                    bitmapImg = new Bitmap(m1);
                }

                OMRConfiguration conf = new OMRConfiguration();
                conf.AdjustmentBlock = new OMRAdjustmentBlock(1572, 3075, 425, 106);
                conf.WhiteBlock = new OMRAdjustmentBlock(1997, 3075, 106, 106);
                conf.DarkFactor = 0.90;
                conf.FillFactor = 1.60;
                conf.ImageWidth = 2182;
                conf.ImageHeight = 3210;
                conf.Blocks.Add(new OMRQuestionBlock("commonQuestions1", 387, 1059, 425, 530, 5));
                conf.Blocks.Add(new OMRQuestionBlock("commonQuestions2", 1312, 1059, 425, 530, 5));
                conf.Blocks.Add(new OMRQuestionBlock("specializedQuestions1", 387, 1798, 425, 1060, 10));
                conf.Blocks.Add(new OMRQuestionBlock("specializedQuestions2", 1312, 1798, 425, 1060, 10));

                using (var omr = new OMRReader(conf))
                using (bitmapImg)
                {
                    answers = omr.Read(bitmapImg);

                    using (Bitmap bitmapImgResized = OMRReader.ResizeImage(bitmapImg, 580, 800))
                    {
                        using (MemoryStream m2 = new MemoryStream())
                        {
                            bitmapImgResized.Save(m2, System.Drawing.Imaging.ImageFormat.Jpeg);
                            file = m2.ToArray();
                        }
                    }
                }
            }

            if (answers != null)
            {
                return Ok(new { answ = answers, file = file });
            }
            else
            {
                return Ok(new { err = "failedRecognition" });
            }
        }
示例#19
0
        public IHttpActionResult PostExtractPages(string fileKey, string name)
        {
            using (var transaction = this.unitOfWork.BeginTransaction())
            {
                GhostscriptVersionInfo lastInstalledVersion = GhostscriptVersionInfo.GetLastInstalledVersion(GhostscriptLicense.GPL | GhostscriptLicense.AFPL, GhostscriptLicense.GPL);
                List<GvaFile> gvaFiles = new List<GvaFile>();
                int pageCount;

                using (MemoryStream m1 = new MemoryStream())
                {
                    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                    {
                        connection.Open();

                        using (var blobStream = new BlobReadStream(connection, "dbo", "Blobs", "Content", "Key", fileKey))
                        {
                            blobStream.CopyTo(m1);
                        }
                    }

                    using (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer())
                    {
                        rasterizer.Open(m1, lastInstalledVersion, false);
                        pageCount = rasterizer.PageCount;

                        for (int i = 1; i <= pageCount; i++)
                        {
                            using (var ms = new MemoryStream())
                            {
                                GvaFile file = null;

                                Image img = rasterizer.GetPage(300, 300, i);
                                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString))
                                {
                                    connection.Open();
                                    using (var blobWriter = new BlobWriter(connection))
                                    using (var stream = blobWriter.OpenStream())
                                    {
                                        stream.Write(ms.ToArray(), 0, (int)ms.Length);

                                        file = new GvaFile()
                                        {
                                            Filename = Path.Combine(Path.GetFileNameWithoutExtension(name) + "-" + i.ToString() + ".jpg"),
                                            MimeType = "image/jpeg",
                                            FileContentId = blobWriter.GetBlobKey()
                                        };

                                        this.unitOfWork.DbContext.Set<GvaFile>().Add(file);
                                        gvaFiles.Add(file);
                                    }
                                }
                            }
                        }
                    }
                }

                this.unitOfWork.Save();
                transaction.Commit();

                List<int> gvaFileIds = gvaFiles.Select(e => e.GvaFileId).ToList();

                return Ok(new { pageCount = pageCount, gvaFileIds = gvaFileIds });
            }
        }