public void StartUploading( //intput BlockingCollection<Tuple<int, MemoryStream>> blobContents, RateLimiter rateLimiter, //output ConcurrentDictionary<int, string> blobIdsToFileKeys, BlockingCollection<long> uploadedBytes, //cancellation CancellationTokenSource cts, CancellationToken ct) { try { this.sqlConn.Open(); } catch (Exception) { cts.Cancel(); throw; } foreach (var blobContent in blobContents.GetConsumingEnumerable()) { ct.ThrowIfCancellationRequested(); var blobId = blobContent.Item1; var content = blobContent.Item2; try { using (var blobWriter = new BlobWriter(sqlConn)) { long length; using (var stream = blobWriter.OpenStream()) using (content) { length = content.Length; content.CopyTo(stream); } if (!blobIdsToFileKeys.TryAdd(blobId, blobWriter.GetBlobKey().ToString())) { throw new Exception("blobId already present in dictionary"); } rateLimiter.Decrement(length); uploadedBytes.Add(length); } } catch (Exception) { cts.Cancel(); throw; } } }
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 }); } } } }
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers) { ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition; if (contentDisposition == null) { // for form data, Content-Disposition header is a requirement throw new InvalidOperationException("Did not find required 'Content-Disposition' header field in MIME multipart body part."); } // if no filename parameter was found in the Content-Disposition header then return a memory stream. if (string.IsNullOrEmpty(contentDisposition.FileName)) { this.blobWriters.Add(null); return new MemoryStream(); } // if we have a file name then write contents to with the BlobWriter which will write it to the database else { var blobWriter = new BlobWriter(this.connection); this.blobWriters.Add(blobWriter); return blobWriter.OpenStream(); } }
private Guid WriteToBlob(byte[] content) { 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); return blobWriter.GetBlobKey(); } } }
public IHttpActionResult CreateDoc(PreDocDO preDoc) { using (var transaction = this.unitOfWork.BeginTransaction()) { 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"); DocFormatType electronicDocFormatType = this.unitOfWork.DbContext.Set<DocFormatType>().SingleOrDefault(e => e.Alias == "Electronic"); DocStatus draftStatus = this.unitOfWork.DbContext.Set<DocStatus>().SingleOrDefault(e => e.Alias == "Draft"); List<Doc> createdDocs = new List<Doc>(); for (int i = 0; i < preDoc.DocNumbers; i++) { Doc newDoc = this.docRepository.CreateDoc( preDoc.DocDirectionId, documentEntryType.DocEntryTypeId, draftStatus.DocStatusId, preDoc.DocSubject, preDoc.DocCasePartTypeId, null, null, preDoc.DocTypeId, preDoc.DocFormatTypeId, null, userContext); DocRelation parentDocRelation = null; if (preDoc.ParentDocId.HasValue) { parentDocRelation = this.unitOfWork.DbContext.Set<DocRelation>().FirstOrDefault(e => e.DocId == preDoc.ParentDocId.Value); } ElectronicServiceStage electronicServiceStage = null; if (parentDocRelation == null) { electronicServiceStage = this.unitOfWork.DbContext.Set<ElectronicServiceStage>() .SingleOrDefault(e => e.DocTypeId == newDoc.DocTypeId && e.IsFirstByDefault); } List<DocTypeUnitRole> docTypeUnitRoles = this.unitOfWork.DbContext.Set<DocTypeUnitRole>() .Where(e => e.DocDirectionId == newDoc.DocDirectionId && e.DocTypeId == newDoc.DocTypeId) .ToList(); DocUnitRole importedBy = this.unitOfWork.DbContext.Set<DocUnitRole>() .SingleOrDefault(e => e.Alias == "ImportedBy"); List<DocTypeClassification> docTypeClassifications = null; List<DocClassification> parentDocClassifications = null; if (parentDocRelation == null) { docTypeClassifications = this.unitOfWork.DbContext.Set<DocTypeClassification>() .Where(e => e.DocDirectionId == newDoc.DocDirectionId && e.DocTypeId == newDoc.DocTypeId && e.IsActive) .ToList(); } else { parentDocClassifications = this.unitOfWork.DbContext.Set<DocClassification>() .Where(e => e.DocId == parentDocRelation.DocId && e.IsActive && e.IsInherited) .ToList(); } newDoc.CreateDocProperties( parentDocRelation, preDoc.DocCasePartTypeId, docTypeClassifications, parentDocClassifications, electronicServiceStage, docTypeUnitRoles, importedBy, unitUser, preDoc.Correspondents, null, this.userContext); if (newDoc.IsCase) { this.docRepository.GenerateAccessCode(newDoc, this.userContext); } if (newDoc.DocFormatTypeId == electronicDocFormatType.DocFormatTypeId) { DocType docType = this.unitOfWork.DbContext.Set<DocType>().SingleOrDefault(e => e.DocTypeId == newDoc.DocTypeId); byte[] eDocFileContent = CreateRioObject(docType.ElectronicServiceFileTypeUri, parentDocRelation != null ? parentDocRelation.RootDocId : null, preDoc.ParentDocId); if (eDocFileContent != null) { Guid eDocFileBlobKey = Guid.Empty; using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString)) { connection.Open(); using (var blobWriter = new BlobWriter(connection)) using (var stream = blobWriter.OpenStream()) { stream.Write(eDocFileContent, 0, eDocFileContent.Length); eDocFileBlobKey = blobWriter.GetBlobKey(); } } DocFileKind publicDocFileKind = this.unitOfWork.DbContext.Set<DocFileKind>().SingleOrDefault(e => e.Alias == "PublicAttachedFile"); DocFileOriginType editableDocFileOriginType = this.unitOfWork.DbContext.Set<DocFileOriginType>().SingleOrDefault(e => e.Alias == "EditableFile"); DocFileType docFileType = this.unitOfWork.DbContext.Set<DocFileType>().SingleOrDefault(e => e.DocTypeUri == docType.ElectronicServiceFileTypeUri); newDoc.CreateDocFile( publicDocFileKind.DocFileKindId, docFileType.DocFileTypeId, editableDocFileOriginType.DocFileOriginTypeId, "Електронен документ", "E-Document.xml", String.Empty, eDocFileBlobKey, userContext); } } this.unitOfWork.Save(); this.docRepository.ExecSpSetDocTokens(docId: newDoc.DocId); this.docRepository.ExecSpSetDocUnitTokens(docId: newDoc.DocId); newDoc.SetReceiptOrder(this.docRepository.GetNextReceiptOrder(newDoc.DocId), this.userContext); if (preDoc.Register) { ClassificationPermission registerPermission = this.classificationRepository.GetByAlias("Register"); bool hasRegisterPermission = this.classificationRepository.HasPermission(unitUser.UnitId, newDoc.DocId, registerPermission.ClassificationPermissionId); if (!hasRegisterPermission) { return BadRequest("Not enough permissions!"); } this.docRepository.RegisterDoc(newDoc, unitUser, this.userContext); } this.unitOfWork.Save(); createdDocs.Add(newDoc); } transaction.Commit(); if (createdDocs.Count == 1 && !preDoc.Register) { return Ok(new { docId = createdDocs.FirstOrDefault().DocId }); } else { string ids = Helper.GetStringFromIdList(createdDocs.Select(e => e.DocId).ToList()); return Ok(new { ids = ids }); } } }
public IHttpActionResult CreateChildPubliclDoc(int id, NewPublicDocDO publicDoc) { using (var transaction = this.unitOfWork.BeginTransaction()) { UnitUser unitUser = this.unitOfWork.DbContext.Set<UnitUser>().FirstOrDefault(e => e.UserId == this.userContext.UserId); ClassificationPermission managementPermission = this.classificationRepository.GetByAlias("Management"); ClassificationPermission readPermission = this.classificationRepository.GetByAlias("Read"); ClassificationPermission registerPermission = this.classificationRepository.GetByAlias("Register"); bool hasManagementPermission = this.classificationRepository.HasPermission(unitUser.UnitId, id, managementPermission.ClassificationPermissionId) && this.classificationRepository.HasPermission(unitUser.UnitId, id, readPermission.ClassificationPermissionId); if (!hasManagementPermission) { return Unauthorized(); } DocEntryType documentEntryType = this.unitOfWork.DbContext.Set<DocEntryType>() .SingleOrDefault(e => e.Alias == "Document"); DocDirection outgoingDocDirection = this.unitOfWork.DbContext.Set<DocDirection>() .SingleOrDefault(e => e.Alias == "Outgoing"); DocFormatType electronicDocFormatType = this.unitOfWork.DbContext.Set<DocFormatType>() .SingleOrDefault(e => e.Alias == "Electronic"); DocStatus draftStatus = this.unitOfWork.DbContext.Set<DocStatus>() .SingleOrDefault(e => e.Alias == "Draft"); DocCasePartType publicDocCasePartType = this.unitOfWork.DbContext.Set<DocCasePartType>() .SingleOrDefault(e => e.Alias == "Public"); DocType docType = this.unitOfWork.DbContext.Set<DocType>() .SingleOrDefault(e => e.Alias.ToLower() == publicDoc.DocTypeAlias.ToLower()); Doc newDoc = this.docRepository.CreateDoc( outgoingDocDirection.DocDirectionId, documentEntryType.DocEntryTypeId, draftStatus.DocStatusId, docType.Name, publicDocCasePartType.DocCasePartTypeId, null, null, docType.DocTypeId, electronicDocFormatType.DocFormatTypeId, null, userContext); DocRelation parentDocRelation = this.unitOfWork.DbContext.Set<DocRelation>() .FirstOrDefault(e => e.DocId == id); List<DocTypeUnitRole> docTypeUnitRoles = this.unitOfWork.DbContext.Set<DocTypeUnitRole>() .Where(e => e.DocDirectionId == newDoc.DocDirectionId && e.DocTypeId == newDoc.DocTypeId) .ToList(); DocUnitRole importedBy = this.unitOfWork.DbContext.Set<DocUnitRole>() .SingleOrDefault(e => e.Alias == "ImportedBy"); List<DocClassification> parentDocClassifications = this.unitOfWork.DbContext.Set<DocClassification>() .Where(e => e.DocId == parentDocRelation.DocId && e.IsActive && e.IsInherited) .ToList(); newDoc.CreateDocProperties( parentDocRelation, publicDocCasePartType.DocCasePartTypeId, null, parentDocClassifications, null, docTypeUnitRoles, importedBy, unitUser, publicDoc.Correspondents, null, this.userContext); DocUnitRole from = this.unitOfWork.DbContext.Set<DocUnitRole>() .SingleOrDefault(e => e.Alias == "From"); newDoc.CreateDocUnit(unitUser.UnitId, from.DocUnitRoleId, this.userContext); DocUnitRole madeBy = this.unitOfWork.DbContext.Set<DocUnitRole>() .SingleOrDefault(e => e.Alias == "MadeBy"); newDoc.CreateDocUnit(unitUser.UnitId, madeBy.DocUnitRoleId, this.userContext); this.unitOfWork.Save(); byte[] eDocFileContent = CreateRioObject(docType.ElectronicServiceFileTypeUri, parentDocRelation.RootDocId, id, newDoc); if (eDocFileContent != null) { Guid eDocFileBlobKey = Guid.Empty; using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString)) { connection.Open(); using (var blobWriter = new BlobWriter(connection)) using (var stream = blobWriter.OpenStream()) { stream.Write(eDocFileContent, 0, eDocFileContent.Length); eDocFileBlobKey = blobWriter.GetBlobKey(); } } DocFileKind publicDocFileKind = this.unitOfWork.DbContext.Set<DocFileKind>().SingleOrDefault(e => e.Alias == "PublicAttachedFile"); DocFileOriginType editableDocFileOriginType = this.unitOfWork.DbContext.Set<DocFileOriginType>().SingleOrDefault(e => e.Alias == "EditableFile"); DocFileType docFileType = this.unitOfWork.DbContext.Set<DocFileType>().SingleOrDefault(e => e.DocTypeUri == docType.ElectronicServiceFileTypeUri); newDoc.CreateDocFile( publicDocFileKind.DocFileKindId, docFileType.DocFileTypeId, editableDocFileOriginType.DocFileOriginTypeId, "Електронен документ", "E-Document.xml", String.Empty, eDocFileBlobKey, userContext); } this.unitOfWork.Save(); this.docRepository.ExecSpSetDocTokens(docId: newDoc.DocId); this.docRepository.ExecSpSetDocUnitTokens(docId: newDoc.DocId); newDoc.SetReceiptOrder(this.docRepository.GetNextReceiptOrder(newDoc.DocId), this.userContext); bool hasRegisterPermission = this.classificationRepository.HasPermission(unitUser.UnitId, newDoc.DocId, registerPermission.ClassificationPermissionId); if (!hasRegisterPermission) { return Unauthorized(); } this.unitOfWork.Save(); transaction.Commit(); return Ok(new { docId = newDoc.DocId }); } }
public IHttpActionResult UpdateDoc(int id, DocDO doc) { using (var transaction = this.unitOfWork.BeginTransaction()) { 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.classificationRepository.HasPermission(unitUser.UnitId, id, editPermission.ClassificationPermissionId) && this.classificationRepository.HasPermission(unitUser.UnitId, id, readPermission.ClassificationPermissionId); if (!hasEditPermission) { return BadRequest("Not enough permissions!"); } DateTime currentDate = DateTime.Now; var oldDoc = this.docRepository.Find(id, e => e.DocCorrespondents, e => e.DocFiles.Select(df => df.DocFileOriginType), e => e.DocFiles.Select(df => df.DocFileType), e => e.DocUnits); if (oldDoc == null) { return NotFound(); } oldDoc.EnsureForProperVersion(doc.Version); oldDoc.DocSourceTypeId = doc.DocSourceTypeId; oldDoc.DocSubject = doc.DocSubject; oldDoc.DocBody = doc.DocBody; oldDoc.CorrRegNumber = doc.CorrRegNumber; oldDoc.CorrRegDate = doc.CorrRegDate; oldDoc.AssignmentTypeId = doc.AssignmentTypeId; oldDoc.AssignmentDate = doc.AssignmentDate; oldDoc.AssignmentDeadline = doc.AssignmentDeadline; oldDoc.ModifyDate = DateTime.Now; oldDoc.ModifyUserId = userContext.UserId; #region DocUnits List<DocUnitRole> docUnitRoles = this.unitOfWork.DbContext.Set<DocUnitRole>().ToList(); doc.DocUnitsFrom.ForEach(e => { e.ForeignKeyId = docUnitRoles.Single(p => p.Alias == "From").DocUnitRoleId; }); doc.DocUnitsTo.ForEach(e => { e.ForeignKeyId = docUnitRoles.Single(p => p.Alias == "To").DocUnitRoleId; }); doc.DocUnitsImportedBy.ForEach(e => { e.ForeignKeyId = docUnitRoles.Single(p => p.Alias == "ImportedBy").DocUnitRoleId; }); doc.DocUnitsMadeBy.ForEach(e => { e.ForeignKeyId = docUnitRoles.Single(p => p.Alias == "MadeBy").DocUnitRoleId; }); doc.DocUnitsCCopy.ForEach(e => { e.ForeignKeyId = docUnitRoles.Single(p => p.Alias == "CCopy").DocUnitRoleId; }); doc.DocUnitsInCharge.ForEach(e => { e.ForeignKeyId = docUnitRoles.Single(p => p.Alias == "InCharge").DocUnitRoleId; }); doc.DocUnitsControlling.ForEach(e => { e.ForeignKeyId = docUnitRoles.Single(p => p.Alias == "Controlling").DocUnitRoleId; }); doc.DocUnitsReaders.ForEach(e => { e.ForeignKeyId = docUnitRoles.Single(p => p.Alias == "Readers").DocUnitRoleId; }); doc.DocUnitsEditors.ForEach(e => { e.ForeignKeyId = docUnitRoles.Single(p => p.Alias == "Editors").DocUnitRoleId; }); doc.DocUnitsRegistrators.ForEach(e => { e.ForeignKeyId = docUnitRoles.Single(p => p.Alias == "Registrators").DocUnitRoleId; }); var allDocUnits = doc.DocUnitsTo.Union( doc.DocUnitsFrom.Union( doc.DocUnitsImportedBy.Union( doc.DocUnitsMadeBy.Union( doc.DocUnitsCCopy.Union( doc.DocUnitsInCharge.Union( doc.DocUnitsControlling.Union( doc.DocUnitsReaders.Union( doc.DocUnitsEditors.Union( doc.DocUnitsRegistrators))))))))); var listDocUnits = oldDoc.DocUnits.ToList(); for (var i = 0; i < listDocUnits.Count; i++) { var matching = allDocUnits .Where(e => e.NomValueId == listDocUnits[i].UnitId && e.ForeignKeyId == listDocUnits[i].DocUnitRoleId) .ToList(); if (matching.Any()) { matching.ForEach(e => { e.IsProcessed = true; }); } else { oldDoc.DeleteDocUnit(listDocUnits[i], this.userContext); } } foreach (var du in allDocUnits.Where(e => !e.IsProcessed)) { oldDoc.CreateDocUnit(du.NomValueId, du.ForeignKeyId, this.userContext); } #endregion #region DocCorrespondents var listDocCorrespondents = oldDoc.DocCorrespondents.ToList(); for (var i = 0; i < listDocCorrespondents.Count; i++) { var matching = doc.DocCorrespondents .Where(e => e.NomValueId == listDocCorrespondents[i].CorrespondentId) .ToList(); if (matching.Any()) { matching.ForEach(e => { e.IsProcessed = true; }); } else { oldDoc.DeleteDocCorrespondent(listDocCorrespondents[i], this.userContext); } } foreach (var du in doc.DocCorrespondents.Where(e => !e.IsProcessed)) { oldDoc.CreateDocCorrespondent(du.NomValueId, this.userContext); } #endregion #region DocFiles DocFile editable = oldDoc.DocFiles.FirstOrDefault(e => e.DocFileOriginTypeId.HasValue && e.DocFileOriginType.Alias == "EditableFile"); if (editable != null) { byte[] content = null; if (editable.DocFileType.DocTypeUri == "Checklist") { string contentStr = JsonConvert.SerializeObject(doc.JObject); content = System.Text.Encoding.UTF8.GetBytes(contentStr); } else //doc is rio object { content = RioObjectUtils.GetBytesFromJObject(editable.DocFileType.DocTypeUri, doc.JObject); } 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); editable.DocFileContentId = blobWriter.GetBlobKey(); } } } List<DocFileDO> allDocFiles = doc.DocFiles; List<DocFileType> docFileTypes = this.unitOfWork.DbContext.Set<DocFileType>().ToList(); foreach (var file in allDocFiles.Where(e => !e.IsNew && e.IsDeleted && e.DocFileId.HasValue)) { oldDoc.DeleteDocFile(file.DocFileId.Value, this.userContext); } foreach (var file in allDocFiles.Where(e => !e.IsNew && !e.IsDeleted && e.IsDirty && e.DocFileId.HasValue)) { var docFileType = docFileTypes.FirstOrDefault(e => e.Extention == Path.GetExtension(file.File.Name)); if (docFileType == null) { docFileType = docFileTypes.FirstOrDefault(e => e.Alias == "UnknownBinary"); } oldDoc.UpdateDocFile(file.DocFileId.Value, file.DocFileKindId, docFileType.DocFileTypeId, file.Name, file.File.Name, "", file.File.Key, userContext); } foreach (var file in allDocFiles.Where(e => e.IsNew && !e.IsDeleted)) { var docFileType = docFileTypes.FirstOrDefault(e => e.Extention == Path.GetExtension(file.File.Name)); if (docFileType == null) { docFileType = docFileTypes.FirstOrDefault(e => e.Alias == "UnknownBinary"); } oldDoc.CreateDocFile(file.DocFileKindId, docFileType.DocFileTypeId, file.Name, file.File.Name, String.Empty, file.File.Key, userContext); } #endregion this.unitOfWork.Save(); this.docRepository.ExecSpSetDocTokens(docId: oldDoc.DocId); this.docRepository.ExecSpSetDocUnitTokens(docId: oldDoc.DocId); transaction.Commit(); return Ok(); } }
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 }); }
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 }); } }
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 }); } }
public Guid SaveStreamToBlob(Stream stream, string connectionString) { Guid licenceEditionDocBlobKey; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (var blobWriter = new BlobWriter(connection)) using (var blobStream = blobWriter.OpenStream()) { stream.CopyTo(blobStream); licenceEditionDocBlobKey = blobWriter.GetBlobKey(); } } return licenceEditionDocBlobKey; }
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 }); } }