Source

main / Source / WebClient / Web.BizLogic / Services / DocumentService.cs

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using DataUp.Web.DataLayer;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DataUp.Web.Common;
using System.Collections;

namespace DataUp.Web.BizLogic
{
    /// <summary>
    /// Class that provides functionality for uploaded documents.
    /// </summary>
    public class DocumentService : IDocumentService
    {
        private IDocumentStoreRepository documentStoreRepository;
        private IBlobDataRepository blobDataRepository;
        private IUploadService uploadService;

        public DocumentService(IUploadService uploadService, IDocumentStoreRepository documentStoreRepository, IBlobDataRepository blobDataRepository)
        {
            this.uploadService = uploadService;
            this.documentStoreRepository = documentStoreRepository;
            this.blobDataRepository = blobDataRepository;
        }

        /// <summary>
        /// Gets the documents.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <returns>Collection of Documents</returns>
        public Collection<DocumentDetail> GetDocuments(int userId)
        {
            var documents = this.documentStoreRepository.GetItems(userId);

            Collection<DocumentDetail> documentDetailList = new Collection<DocumentDetail>();

            if (documents != null && documents.Count() > 0)
            {
                foreach (var item in documents)
                {
                    DocumentDetail documentDetail = new DocumentDetail();
                    documentDetail.SetValuesFrom(item);

                    documentDetailList.Add(documentDetail);
                }
            }

            return documentDetailList;
        }

        public DocumentDetail GetDocument(int documentId, int userId)
        {
            var documents = this.documentStoreRepository.GetItem(userId, documentId);

            DocumentDetail documentDetail = null;

            if (documents != null)
            {
                documentDetail = new DocumentDetail();
                documentDetail.SetValuesFrom(documents);
            }

            return documentDetail;
        }

        public OperationStatus DeleteDocument(int documentId, int userId)
        {
            var documents = this.documentStoreRepository.GetItem(userId, documentId);

            OperationStatus status = null;
            if (documents != null)
            {
                try
                {
                    this.documentStoreRepository.Delete(documents);
                    this.documentStoreRepository.SaveChanges();

                    status = OperationStatus.CreateSuccessStatus();
                }
                catch (Exception ex)
                {
                    status = OperationStatus.CreateFailureStatus(ex);
                }
            }
            else
            {
                status = OperationStatus.CreateFailureStatus("Item not found");
            }

            return status;
        }

        /// <summary>
        /// Downloads the document.
        /// </summary>
        /// <param name="documentId">The document id.</param>
        /// <param name="userId">The user id.</param>
        /// <returns></returns>
        public DataDetail DownloadDocument(int documentId, int userId)
        {
            var documentStore = this.documentStoreRepository.GetItem(userId, documentId);

            DataDetail dataDetail = null;

            if (documentStore != null)
            {
                DocumentDetail documentDetail = new DocumentDetail();
                documentDetail.SetValuesFrom(documentStore);

                dataDetail = documentDetail.Data;
                dataDetail.DataStream = GetFileStream(documentStore);
                if (dataDetail.Extension == ".csv")
                {
                    dataDetail.DataStream = GetCSVFileStream(dataDetail, documentStore);
                    dataDetail.MimeType = "multipart/x-zip";
                    dataDetail.FileName = dataDetail.FileName + ".zip";
                    return dataDetail;
                }

                // Update/Create Metadata sheet based on the metadata values.
                if (!string.IsNullOrWhiteSpace(documentStore.Metadata) && dataDetail.DataStream != null)
                {
                    var metadataList = documentStore.Metadata.DeserializeXML<MetadataDetailList>();
                    var citaionNode = metadataList.Metadata.Where(item => item.Name == Constants.CitationContent).FirstOrDefault();
                    if (citaionNode != null)
                    {
                        citaionNode.Value = documentStore.Citation;
                    }
                    else
                    {
                        metadataList.Metadata.Add(new MetadataDetail() { Name = Constants.CitationContent, Value = documentStore.Citation });
                    }

                    var identifierNode = metadataList.Metadata.Where(item => item.Name == Constants.IdentifierKeyName).FirstOrDefault();
                    if (identifierNode != null)
                    {
                        identifierNode.Value = documentStore.Identifier;
                    }
                    else
                    {
                        metadataList.Metadata.Add(new MetadataDetail() { Name = Constants.IdentifierKeyName, Value = documentStore.Identifier });
                    }

                    using (SpreadsheetDocument excelDocument = SpreadsheetDocument.Open(dataDetail.DataStream, true))
                    {
                        var metadataSheet = excelDocument.GetSheet(Constants.MetadataSheetName);

                        if (metadataSheet == null && CheckMandatoryMetadataFields(metadataList))
                        {
                            metadataSheet = excelDocument.InsertMetadataWorksheet((metadataList.ParamterMetadata.Count > 0));
                        }

                        if (metadataSheet != null)
                        {
                            for (int i = 0; i < metadataList.Metadata.Count; i++)
                            {
                                excelDocument.SetCellValue(metadataSheet, string.Format("A{0}", i + 2), metadataList.Metadata[i].Name);
                                excelDocument.SetCellValue(metadataSheet, string.Format("B{0}", i + 2), metadataList.Metadata[i].Value);
                            }

                            int cellCount = 2;
                            foreach(var val in metadataList.ParamterMetadata)
                            {
                                val.AttributeList.ForEach(q =>
                                {
                                    excelDocument.SetCellValue(metadataSheet, string.Format("D{0}", cellCount), val.EntityName);
                                    excelDocument.SetCellValue(metadataSheet, string.Format("E{0}", cellCount), val.EntityDescription);
                                    excelDocument.SetCellValue(metadataSheet, string.Format("F{0}", cellCount), q.Name);
                                    excelDocument.SetCellValue(metadataSheet, string.Format("G{0}", cellCount), q.Description);
                                    excelDocument.SetCellValue(metadataSheet, string.Format("H{0}", cellCount), q.Type);
                                    excelDocument.SetCellValue(metadataSheet, string.Format("I{0}", cellCount), q.Units);

                                    cellCount++;
                                });
                            }

                            WorksheetPart wsPart = excelDocument.WorkbookPart.GetPartById(metadataSheet.Id) as WorksheetPart;
                            if (wsPart != null)
                            {
                                TableDefinitionPart metadataTable = null;
                                TableDefinitionPart parameterTable = null;

                                // get the tables in Excel
                                var tableParts = wsPart.GetPartsOfType<TableDefinitionPart>();
                                if (tableParts != null)
                                {
                                    foreach (var item in tableParts)
                                    {
                                        if (item.Table.Name == Constants.MetadataRangeName)
                                        {
                                            metadataTable = item;
                                            metadataTable.Table.Reference = "A1:B" + (metadataList.Metadata.Count + 1);
                                            metadataTable.Table.Save();  
                                        }
                                        if (item.Table.Name == Constants.ParaMetadataRangeName && metadataList.ParamterMetadata.Count > 0)
                                        {
                                            parameterTable = item;
                                            parameterTable.Table.Reference = "D1:I" + ((metadataList.ParamterMetadata.Count == 0) ? 2 : cellCount);
                                            parameterTable.Table.Save();
                                        }
                                    }
                                }
                            }
                            excelDocument.WorkbookPart.Workbook.Save();
                        }
                    }
                }
            }
            return dataDetail;
        }

        /// <summary>
        /// Downloads the document for post.
        /// </summary>
        /// <param name="documentId">The document id.</param>
        /// <param name="userId">The user id.</param>
        /// <returns>The document details</returns>
        public DataDetail DownloadDocumentForPost(int documentId, int userId)
        {
            var documentStore = this.documentStoreRepository.GetItem(userId, documentId);

            DataDetail dataDetail = null;

            if (documentStore != null)
            {
                DocumentDetail documentDetail = new DocumentDetail();
                documentDetail.SetValuesFrom(documentStore);

                dataDetail = documentDetail.Data;
                dataDetail.DataStream = GetFileStream(documentStore);

                // Update/Create Metadata sheet based on the metadata values.
                if (!string.IsNullOrWhiteSpace(documentStore.Metadata) && dataDetail.DataStream != null)
                {
                    var metadataList = documentStore.Metadata.DeserializeXML<MetadataDetailList>();
                    var citaionNode = metadataList.Metadata.Where(item => item.Name == Constants.CitationContent).FirstOrDefault();
                    if (citaionNode != null)
                    {
                        citaionNode.Value = documentStore.Citation;
                    }
                    else
                    {
                        metadataList.Metadata.Add(new MetadataDetail() { Name = Constants.CitationContent, Value = documentStore.Citation });
                    }

                    var identifierNode = metadataList.Metadata.Where(item => item.Name == Constants.IdentifierKeyName).FirstOrDefault();
                    if (identifierNode != null)
                    {
                        identifierNode.Value = documentStore.Identifier;
                    }
                    else
                    {
                        metadataList.Metadata.Add(new MetadataDetail() { Name = Constants.IdentifierKeyName, Value = documentStore.Identifier });
                    }

                    using (SpreadsheetDocument excelDocument = SpreadsheetDocument.Open(dataDetail.DataStream, true))
                    {
                        var metadataSheet = excelDocument.GetSheet(Constants.MetadataSheetName);
                        if (metadataSheet == null)
                        {
                            metadataSheet = excelDocument.InsertMetadataWorksheet((metadataList.ParamterMetadata.Count > 0));
                        }

                        if (metadataSheet != null)
                        {
                            for (int i = 0; i < metadataList.Metadata.Count; i++)
                            {
                                excelDocument.SetCellValue(metadataSheet, string.Format("A{0}", i + 2), metadataList.Metadata[i].Name);
                                excelDocument.SetCellValue(metadataSheet, string.Format("B{0}", i + 2), metadataList.Metadata[i].Value);
                            }

                            int cellCount = 2;
                            foreach (var val in metadataList.ParamterMetadata)
                            {
                                val.AttributeList.ForEach(q =>
                                {
                                    excelDocument.SetCellValue(metadataSheet, string.Format("D{0}", cellCount), val.EntityName);
                                    excelDocument.SetCellValue(metadataSheet, string.Format("E{0}", cellCount), val.EntityDescription);
                                    excelDocument.SetCellValue(metadataSheet, string.Format("F{0}", cellCount), q.Name);
                                    excelDocument.SetCellValue(metadataSheet, string.Format("G{0}", cellCount), q.Description);
                                    excelDocument.SetCellValue(metadataSheet, string.Format("H{0}", cellCount), q.Type);
                                    excelDocument.SetCellValue(metadataSheet, string.Format("I{0}", cellCount), q.Units);

                                    cellCount++;
                                });
                            }

                            WorksheetPart wsPart = excelDocument.WorkbookPart.GetPartById(metadataSheet.Id) as WorksheetPart;
                            if (wsPart != null)
                            {
                                TableDefinitionPart metadataTable = null;
                                TableDefinitionPart parameterTable = null;

                                // get the tables in Excel
                                var tableParts = wsPart.GetPartsOfType<TableDefinitionPart>();
                                if (tableParts != null)
                                {
                                    foreach (var item in tableParts)
                                    {
                                        if (item.Table.Name == Constants.MetadataRangeName)
                                        {
                                            metadataTable = item;
                                            metadataTable.Table.Reference = "A1:B" + (metadataList.Metadata.Count + 1);
                                            metadataTable.Table.Save();
                                        }
                                        if (item.Table.Name == Constants.ParaMetadataRangeName && metadataList.ParamterMetadata.Count > 0)
                                        {
                                            parameterTable = item;
                                            parameterTable.Table.Reference = "D1:G" + ((metadataList.ParamterMetadata.Count == 0) ? 2 : (metadataList.ParamterMetadata.Count + 1));
                                            parameterTable.Table.Save();
                                        }
                                    }
                                }
                            }
                            excelDocument.WorkbookPart.Workbook.Save();
                        }
                    }
                }
            }
            return dataDetail;
        }

        /// <summary>
        /// Gets the file stream from the Document Store
        /// </summary>
        /// <param name="documentStore">The document store.</param>
        /// <returns>File as IO Stream</returns>
        private Stream GetFileStream(DocumentStore documentStore)
        {
            Stream dataStream = null;
            if (!string.IsNullOrWhiteSpace(documentStore.FileId))
            {
                var blobDetails = this.blobDataRepository.GetBlobContent(documentStore.FileId);
                dataStream = blobDetails.Data;
            }
            else
            {
                // TODO : Get the Stream of data from the 
                // documents.FileData
            }

            return dataStream;
        }

        /// <summary>
        /// Creates a CSV File Stream from uploaded Excel file stream.
        /// </summary>
        /// <param name="dataDetail">The data detail.</param>
        /// <param name="documentStore">The document store.</param>
        /// <returns>File as Zipped IO Stream</returns>
        private Stream GetCSVFileStream(DataDetail dataDetail, DocumentStore documentStore)
        {
            StreamWriter file = null;
            MetadataDetailList metadataList = documentStore.Metadata.DeserializeXML<MetadataDetailList>();
            string fileName = string.Format("{0}\\{1}\\", Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));

            DirectoryInfo dir = Directory.CreateDirectory(fileName);
            try
            {
                CreateCSVFromExcel(dataDetail, dir);
                StringBuilder sbMetaData = new StringBuilder();
                if (CheckMandatoryMetadataFields(metadataList))
                {
                    if (metadataList.Metadata != null)
                    {
                        sbMetaData.Append("Name,Value");
                        sbMetaData.Append(Environment.NewLine);
                        metadataList.Metadata.ToList().ForEach(q =>
                        {
                            sbMetaData.Append(q.Name + "," + q.Value);
                            sbMetaData.Append(Environment.NewLine);
                        });
                    }

                    if (metadataList.ParamterMetadata != null && metadataList.ParamterMetadata.Count > 0)
                    {
                        sbMetaData.Append(Environment.NewLine);
                        sbMetaData.Append("EntityName,EntityDescription,Name,Description,Type,Units");
                        sbMetaData.Append(Environment.NewLine);
                        metadataList.ParamterMetadata.ToList().ForEach(q =>
                        {
                            q.AttributeList.ForEach(m =>
                            {
                                sbMetaData.Append(q.EntityName + "," + q.EntityDescription + "," + m.Name + "," + m.Description + "," + m.Type + "," + m.Units);
                                sbMetaData.Append(Environment.NewLine);
                            });
                        });
                    }

                    string filename = string.Format("{0}{1}-{2}.csv", dir.FullName, "File", "metadata");
                    if (sbMetaData.Length > 0)
                    {
                        file = new StreamWriter(filename);
                        file.WriteLine(sbMetaData.ToString());
                        sbMetaData = null;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to create TEMP file or set its attributes: " + ex.Message);
            }
            finally
            {
                if (file != null)
                {
                    file.Dispose();
                }
            }
            
            return ZipFileHelper.ZipFiles(dir.FullName);
        }

        /// <summary>
        /// Creates the CSV from excel.
        /// </summary>
        /// <param name="dataDetail">The data detail.</param>
        /// <param name="dir">The dir.</param>
        private void CreateCSVFromExcel(DataDetail dataDetail, DirectoryInfo dir)
        {
            Stream filestream = new MemoryStream();
            dataDetail.DataStream.CopyToStream(filestream);
            StringBuilder sbValue = new StringBuilder();
            string sheetName = Path.GetFileNameWithoutExtension(dataDetail.FileName);
            using (SpreadsheetDocument excelDocument = SpreadsheetDocument.Open(filestream, true))
            {
                Sheet sheet = excelDocument.GetSheet(sheetName);
                WorksheetPart worksheetPart = (WorksheetPart)excelDocument.WorkbookPart.GetPartById(sheet.Id);

                SheetData sheetdata = worksheetPart.Worksheet.Elements<SheetData>().FirstOrDefault();
                foreach (var row in sheetdata.Descendants<Row>())
                {
                    if (row != null)
                    {
                        foreach (Cell cell in row.Descendants<Cell>())
                        {
                            if (cell.CellValue != null)
                            {
                                sbValue.AppendFormat("{0},", CsvHelper.Unescape(cell.CellValue.Text));
                            }
                        }
                        sbValue.Append(Environment.NewLine);
                    }
                }
                if (sbValue.Length > 0)
                {
                    string filename = string.Format("{0}{1}-{2}.csv", dir.FullName, "File", sheetName);
                    StreamWriter file = null;
                    try
                    {
                        file = new StreamWriter(filename);
                        file.WriteLine(sbValue.ToString());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Unable to create TEMP file or set its attributes: " + ex.Message);
                    }
                    finally
                    {
                        if (file != null)
                        {
                            file.Dispose();
                        }
                    }
                }
            }
            if (filestream != null)
            {
                filestream.Dispose();
            }
            sbValue = null;
        }

        public void UpdateMetadata(int documentId, int userId)
        {
            var document = this.documentStoreRepository.GetItem(item => item.UserId == userId && item.Id == documentId);

            if (document != null)
            {
                var fileStream = GetFileStream(document);
                if (fileStream != null)
                {
                    using (SpreadsheetDocument excelDocument = SpreadsheetDocument.Open(fileStream, true))
                    {
                        MetadataDetailList metadataList = excelDocument.GetMetadataDetails();
                        document.UpdateMetadata(metadataList);

                        var citaionNode = metadataList.Metadata.Where(item => item.Name == Constants.CitationContent).FirstOrDefault();
                        if (citaionNode != null)
                        {
                            document.Citation = citaionNode.Value;
                        }

                        var identifierNode = metadataList.Metadata.Where(item => item.Name == Constants.IdentifierKeyName).FirstOrDefault();
                        if (identifierNode != null)
                        {
                            document.Identifier = identifierNode.Value;
                        }

                        this.documentStoreRepository.SaveChanges();
                    }
                }
            }
        }

        public MetadataDetailList GetMetadata(int documentId, int userId)
        {
            //var document = this.documentStoreRepository.GetItem(item => item.UserId == userId && item.Id == documentId);
            var document = this.documentStoreRepository.GetItem(userId, documentId);

            MetadataDetailList metadataList = null;

            if (document != null)
            {
                if (string.IsNullOrWhiteSpace(document.Metadata))
                {
                    var fileStream = GetFileStream(document);
                    if (fileStream != null)
                    {
                        using (SpreadsheetDocument excelDocument = SpreadsheetDocument.Open(fileStream, true))
                        {
                            metadataList = excelDocument.GetMetadataDetails();
                        }
                    }
                    else
                    {
                        metadataList = new MetadataDetailList()
                        {
                            Metadata = MetadataHelper.GetDefaultMetadataList()
                        };
                    }
                }
                else
                {
                    var dbMetadata = document.Metadata.DeserializeXML<MetadataDetailList>();

                    MetadataDetailList updatedMetadataList = new MetadataDetailList()
                    {
                        Metadata = MetadataHelper.GetDefaultMetadataList()
                    };

                    updatedMetadataList.UpdateFrom(dbMetadata);

                    metadataList = updatedMetadataList;
                }
            }

            return metadataList;
        }

        public OperationStatus SaveDocument(DocumentDetail documentDetail)
        {
            return SaveDocument(documentDetail, null);
        }

        public OperationStatus SaveDocument(DocumentDetail documentDetail, MetadataDetailList metadataList)
        {
            OperationStatus status = null;

            try
            {
                var documents = this.documentStoreRepository.GetItem(documentDetail.CreatedById, documentDetail.Id);

                if (documents != null)
                {
                    documents.SetValuesFrom(documentDetail);

                    if (metadataList != null)
                    {
                        documents.UpdateMetadata(metadataList);

                    }

                    if (documentDetail.Data != null && documentDetail.Data.DataStream != null)
                    {
                        UploadDetails uploadDetails = new UploadDetails();
                        uploadDetails.Data = documentDetail.Data;

                        this.uploadService.UploadFile(uploadDetails, documents);
                    }

                    this.documentStoreRepository.SaveChanges();

                    status = OperationStatus.CreateSuccessStatus();
                }
                else
                {
                    status = OperationStatus.CreateFailureStatus("Item Not found");
                }
            }
            catch (Exception ex)
            {
                status = OperationStatus.CreateFailureStatus(ex.Message, ex);
            }

            return status;
        }

        private bool CheckMandatoryMetadataFields(MetadataDetailList metadataList)
        {
            return ( (metadataList.Metadata.FirstOrDefault(q => q.Name == Constants.FirstName).Value != null) && 
                        (metadataList.Metadata.FirstOrDefault(q => q.Name == Constants.LastName).Value != null) &&
                            (metadataList.Metadata.FirstOrDefault(q => q.Name == Constants.Email).Value != null) &&
                                (metadataList.Metadata.FirstOrDefault(q => q.Name == Constants.Abstract).Value != null) &&
                                    (metadataList.Metadata.FirstOrDefault(q => q.Name == Constants.KeyWords).Value != null)
                );
        }

   }
}