Source

main-vinayFork / Source / WebClient / Web.Client / Controllers / DocumentController.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
using System.Web.Mvc;
using DataUp.Web.Client.ViewModel;
using DataUp.Web.Client.Infrastructure;
using System.Web;
using System.IO;
using DataUp.Web.BizLogic;
using System;
using System.Linq;
using DataUp.Web.DataLayer;
using System.Collections.Generic;
using DataUp.Web.Client.Model;
using DataUp.Web.Service.Model;
using System.Web.Script.Serialization;
using System.Collections.ObjectModel;
using BizLogicModel = DataUp.Web.BizLogic.Model;

namespace DataUp.Web.Client.Controllers
{
    /// <summary>
    /// Controller that handles all the Document functionality.
    /// </summary>
    [RegisteredUser]
    public class DocumentController : Controller
    {
        private IUploadService uploadService;
        private IDocumentService documentService;
        private IExcelService excelService;
        private IRepositoryService repositoryService;

        public DocumentController(IUploadService uploadService, IDocumentService documentService, IExcelService excelService, IRepositoryService repositoryService)
        {
            this.uploadService = uploadService;
            this.documentService = documentService;
            this.excelService = excelService;
            this.repositoryService = repositoryService;
        }

        public ActionResult Index()
        {
            var documentViewModel = GetDocuments();

            return View(documentViewModel);
        }

        /// <summary>
        /// Fetches the metadata.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns>Metadata in Json format</returns>
        public JsonResult FetchMetadata(int id)
        {
            try
            {
                var metadataList = this.documentService.GetMetadata(id, Helper.GetLoggedInUserID());
                return Json(new { data = metadataList.Metadata, Status = true, Message = "" });
            }
            catch (Exception exception)
            {
                return Json(new { data = "", Status = false, Message = exception.Message });
            }

        }

        /// <summary>
        /// Retrieve Document details for the specified id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <param name="isPostAsXSL">if set to <c>true</c> [is post as XSL].</param>
        /// <returns>The Document as a View</returns>
        public ActionResult Detail(int id, bool isPostAsXSL)
        {
            var documentDetailViewModel = GetDocument(id, isPostAsXSL);

            return View(documentDetailViewModel);
        }

        /// <summary>
        /// Removes the selected Error Type from Document.
        /// </summary>
        /// <param name="documentId">The document id.</param>
        /// <param name="ids">The ids.</param>
        /// <param name="sheetName">Name of the sheet.</param>
        /// <returns>The updated View</returns>
        public void RemoveSelected(int documentId, string ids, string sheetName)
        {
            if (this.excelService != null)
            {
                string[] erroraddress = ids.Split('-');

                foreach (string address in erroraddress)
                {
                    if (!String.IsNullOrEmpty(address.Trim()))
                    {
                        string[] values = address.Split('+');
                        var indexOf = values[1].IndexOf(",");
                        if (indexOf > 0)
                        {
                            values[1].Remove(indexOf, 1);
                        }
                        ErrorDetails error = new ErrorDetails()
                        {
                            ErrorAddress = values[0],
                            SheetName = sheetName,
                            Error = (ErrorType)Enum.Parse(typeof(ErrorType), values[1])
                        };

                        this.excelService.RemoveSelected(documentId, Helper.GetLoggedInUserID(), error);
                    }
                }
            }
        }

        /// <summary>
        /// Removes all the Compatibility Errors from the Document.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public ActionResult RemoveAll(int id)
        {
            if (this.excelService != null)
            {
                this.excelService.RemoveAll(id, Helper.GetLoggedInUserID());
            }
            return null;
        }

        /// <summary>
        /// Downloads Document with the specified id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns>The Response Stream</returns>
        public ActionResult Download(int id)
        {
            var datadetails = this.documentService.DownloadDocument(id, Helper.GetLoggedInUserID());

            if (datadetails != null)
            {
                return GetFileStream(datadetails);
            }

            return null;
        }

        /// <summary>
        /// Retrieves a List of Documents
        /// </summary>
        /// <returns>View</returns>
        [HttpPost]
        public ActionResult List()
        {
            var documentViewModel = GetDocuments();

            return View("DocumentList", documentViewModel);
        }

        /// <summary>
        /// Saves the Document detail.
        /// </summary>
        /// <param name="documentDetail">The document detail.</param>
        /// <returns>Success/Failure of the operation as JSON</returns>
        [HttpPost]
        //[ValidateAntiForgeryToken(Salt="SaveDocumentDetail")]
        public JsonResult SaveDetail(DocumentDetailViewModel documentDetail)
        {
            try
            {
                if (null != documentDetail.ParameterMetadataList)
                {
                    documentDetail.ParameterMetadataList = documentDetail.ParameterMetadataList.Where(m => !string.IsNullOrWhiteSpace(m.Name)).ToList();
                }
                var status = this.Save(documentDetail);

                if (status.Succeeded)
                {
                    //Done to re map Parameter Metadata after correctly updating the EntityName and Descriptions.
                    var document = GetDocument(documentDetail.DocumentId, documentDetail.IsPostAsXSL);
                    ModelState.Clear();
                    // TODO: Don't set message here
                    return Json(new { Type = "Save", Status = true, Message = "Saved Successfully.", PartialViewHtml = RenderPartialViewToString("_ParameterMetadata", document) });
                }
                else
                {
                    return Json(new { Type = "Save", Status = false, Message = status.ErrorMessage });
                }
            }
            catch (Exception exception)
            {
                return Json(new { Type = "Save", Status = false, Message = exception.Message });           }
        }

        /// <summary>
        /// Posts the specified document detail.
        /// </summary>
        /// <param name="documentDetail">The document detail.</param>
        /// <param name="name">The name.</param>
        /// <returns>Success/Failure as JSON</returns>
        [HttpPost]
        //[ValidateAntiForgeryToken(Salt = "SaveDocumentDetail")]
        [ValidateInput(false)]
        public JsonResult Post(DocumentDetailViewModel documentDetail, string name)
        {
            try
            {
                // Get Identifier if identifier is not present.
                if (string.IsNullOrWhiteSpace(documentDetail.Citation.Identifier))
                {
                    DateTime date = new DateTime();
                    DateTime.TryParse(documentDetail.MetadataList.Where(m => m.Label.ToLowerInvariant().Contains("today's date")).FirstOrDefault().Value, out date);

                    string identifier = this.repositoryService.GetIdentifier(new IdentifierDetail()
                    {
                        Authorization = Convert.ToBase64String(System.Text.UTF8Encoding.UTF8.GetBytes(documentDetail.PostUserName + ":" + documentDetail.PostPassword)),
                        RepositoryName = name,
                        What = documentDetail.Citation.Title,
                        When = date,
                        Who = documentDetail.Citation.Publisher
                    });
                    if (identifier.Contains("|"))
                    {
                        if (identifier.Split('|')[0].Equals("false"))
                        {
                            return Json(new { Type = "Post", Status = false, Message = identifier.Split('|')[1] });
                        }
                        else
                        {
                            documentDetail.Citation.Identifier = identifier.Split('|')[1];
                        }
                    }
                    else
                    {
                        documentDetail.Citation.Identifier = identifier;
                    }
                }
                if (documentDetail.ParameterMetadataList != null)
                {
                    documentDetail.ParameterMetadataList = documentDetail.ParameterMetadataList.Where(m => !string.IsNullOrWhiteSpace(m.Name)).ToList();
                }
                var status = this.Save(documentDetail);

                if (status.Succeeded)
                {
                    PostFileDetail postfileDetail = new PostFileDetail();

                    postfileDetail.SetValuesFrom(documentDetail);

                    // TODO: Need to change it back to get it in document detail.
                    postfileDetail.RepositoryName = name;
                    postfileDetail.Authorization = Convert.ToBase64String(System.Text.UTF8Encoding.UTF8.GetBytes(documentDetail.PostUserName + ":" + documentDetail.PostPassword));

                    postfileDetail.UserId = Helper.GetLoggedInUserID();

                    var metadataList = documentDetail.GetMetadataList();
                    var datadetails = this.documentService.DownloadDocumentForPost(postfileDetail.Id, Helper.GetLoggedInUserID());
                    if (datadetails != null && datadetails.DataStream != null)
                    {
                        var response = this.repositoryService.PublishFile(postfileDetail, metadataList, datadetails);
                        if (response.Contains("false|"))
                        {
                            return Json(new { Type = "Post", Status = false, Message = response.Split('|')[1] });
                        }


                        if (postfileDetail.IsCompressed && Path.GetExtension(postfileDetail.FileName) != ".csv")
                        {
                            this.excelService.RemoveAll(documentDetail.DocumentId, Helper.GetLoggedInUserID());
                        }

                        //Update Session Information:
                        BizLogicModel.User user = (BizLogicModel.User)Session["User"];
                        var list = new List<BizLogicModel.Repository>();

                        foreach (var val in user.RepositoryList)
                        {
                            if (val.Name == name)
                            {
                                val.AcceptUserAgreement = true;
                                val.UserName = documentDetail.PostUserName;
                            }
                            list.Add(val);
                        }
                        user.RepositoryList = list;
                        Session["User"] = user;

                        // TODO: Set the message here
                        return Json(new { Type = "Post", Status = true, Message = response });
                    }

                    else
                    {
                        return Json(new { Type = "Post", Status = false, Message = "Not able to update metadata." });
                    }
                }               
                else
                {
                    return Json(new { Type = "Post", Status = false, Message = status.ErrorMessage });
                }
            }
            catch (Exception exception)
            {
                return Json(new { Type = "Post", Status = false, Message = exception.Message });
            }
        }

        [HttpPost]
        // [ValidateAntiForgeryToken(Salt = "DocumentDelete")]
        public ActionResult Delete(int documentId)
        {
            var status = this.documentService.DeleteDocument(documentId, Helper.GetLoggedInUserID());

            if (status.Succeeded)
            {
                var documentViewModel = GetDocuments();

                return View("DocumentList", documentViewModel);
            }
            else
            {
                return RedirectToAction("General", "Error", new { errorMessage = status.ErrorMessage });
            }
        }

        [HttpPost]
        public void UploadDropedFile()
        {
            if (!string.IsNullOrEmpty(Request.Headers["X-File-Name"]))
            {
                UploadFile(Request.InputStream, Request.Headers["X-File-Name"], Common.Constants.DefaultMimeType);
            }
        }

        /// <summary>
        /// Adds the posted file.
        /// </summary>
        /// <param name="addContent">Content of the uploaded File</param>
        [HttpPost]
        public void AddPostedFile(HttpPostedFileBase addContent)
        {
            if (!string.IsNullOrEmpty(addContent.FileName))
            {
                UploadFile(addContent.InputStream, addContent.FileName, addContent.ContentType);
            }
        }

        /// <summary>
        /// Checks the duplicate.
        /// </summary>
        /// <param name="fileNames">The file names.</param>
        /// <returns>File Names as JSON</returns>
        [HttpPost]
        public JsonResult CheckDuplicate(string fileNames)
        {
            if (!string.IsNullOrWhiteSpace(fileNames))
            {
                string[] files = fileNames.Split(",".ToCharArray());
                IDictionary<int, string> existingList = this.uploadService.CheckIfExists(files, Helper.GetLoggedInUserID());
                if (existingList != null)
                {
                    return Json(new { DuplicateFileNames = string.Join(",", existingList.Select(f => f.Value)) });
                }
            }

            return Json(new { DuplicateFileNames = string.Empty });
        }

        private OperationStatus Save(DocumentDetailViewModel details)
        {
            DocumentDetail documentDetail = new DocumentDetail();

            documentDetail.SetValuesFrom(details);

            documentDetail.CreatedById = Helper.GetLoggedInUserID();

            var metadataList = details.GetMetadataList();

            return new OperationStatus
            {
                Succeeded = this.documentService.SaveDocument(documentDetail, metadataList).Succeeded,
                CustomReturnValues = metadataList.ParamterMetadata
            };
        }

        /// <summary>
        /// Gets the User agreement for the Repository
        /// </summary>
        /// <param name="repositoryName">Name of the repository.</param>
        /// <returns>User Agreement as String</returns>
        [HttpPost]
        public string GetAgreement(string repositoryName)
        {
            return this.repositoryService.GetUserAgreement(repositoryName);
        }

        private DocumentViewModel GetDocuments()
        {
            var documents = documentService.GetDocuments(Helper.GetLoggedInUserID());

            var documentViewModel = new DocumentViewModel();
            if (documents != null && documents.Count > 0)
            {
                foreach (var item in documents)
                {
                    Model.Document document = new Model.Document();
                    document.SetValuesFrom(item);

                    documentViewModel.DocumentList.Add(document);
                }
            }
            return documentViewModel;
        }

        private OperationStatus UploadFile(Stream inputStream, string filename, string mimetype)
        {
            DataDetail fileDetail = new DataDetail();
            fileDetail.DataStream = inputStream;
            fileDetail.FileName = Path.GetFileName(filename);
            fileDetail.Size = inputStream.Length;
            fileDetail.MimeType = mimetype;
            UploadDetails uploadDetails = new UploadDetails()
            {
                CreatedById = Helper.GetLoggedInUserID(),
                CreatedDateTime = DateTime.UtcNow,
                Data = fileDetail,
                FileName = Path.GetFileName(filename),
                Status = Common.DocumentStatus.Uploaded
            };

            OperationStatus status = this.uploadService.PublishFile(uploadDetails);
            fileDetail = null;
            return status;
        }

        private FileStreamResult GetFileStream(DataDetail blobDetails)
        {
            // Update the response header.
            Response.AddHeader("Content-Encoding", blobDetails.MimeType);
            Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", blobDetails.FileName));
            // Set the position to Begin.
            blobDetails.DataStream.Seek(0, SeekOrigin.Begin);

            return new FileStreamResult(blobDetails.DataStream, blobDetails.MimeType);
        }

        private DocumentDetailViewModel GetDocument(int id, bool isPostAsXSL)
        {
            var documentDetailViewModel = new DocumentDetailViewModel();

            var documentDetails = this.documentService.GetDocument(id, Helper.GetLoggedInUserID());

            if (documentDetails != null)
            {
                // Whether is POst As CSV 
                documentDetailViewModel.IsPostAsXSL = isPostAsXSL;

                documentDetailViewModel.SetValuesFrom(documentDetails);

                // Get Errors.
                IEnumerable<ErrorDetails> errors = (Path.GetExtension(documentDetails.FileName) != ".csv") ? this.excelService.Validate(id, Helper.GetLoggedInUserID())
                                                        : this.excelService.ValidateCsv(id, Helper.GetLoggedInUserID());

                documentDetailViewModel.UpdateErrors(errors);

                if (errors.Count() == 0)
                {
                    documentDetailViewModel.NoError = true;
                }

                // Get Metadata.
                var metadataList = this.documentService.GetMetadata(id, Helper.GetLoggedInUserID());
                if (metadataList != null && metadataList.Metadata != null && metadataList.Metadata.Count > 0)
                {
                    documentDetailViewModel.UpdateMetadata(metadataList.Metadata);
                    documentDetailViewModel.UpdateParameterMetadata(metadataList.ParamterMetadata);
                    // Update Citation
                    documentDetailViewModel.UpdateCitation(documentDetails, metadataList.Metadata);
                }
                else
                {
                    // Update Citation
                    documentDetailViewModel.UpdateCitation(documentDetails, new List<MetadataDetail>());
                }

                // Update Repositories.
                IEnumerable<RepositoryDetail> repositories = this.repositoryService.RetrieveRespositories();
                if (repositories != null)
                {
                    List<DocumentRepository> documentRepositories = new List<DocumentRepository>();

                    foreach (var item in repositories)
                    {
                        documentRepositories.Add(new DocumentRepository() { Id = item.RepositoryId.ToString(), Name = item.RepositoryName });
                    }

                    documentDetailViewModel.AvailableRepositories = new SelectList(documentRepositories, "Id", "Name");


                    var values = from val in repositories
                                 select new { Id = val.RepositoryId, Required = val.IsPasswordRequired, RepoType = val.Type };
                    documentDetailViewModel.RepositoryTypesJson = new JavaScriptSerializer().Serialize(Json(values).Data);

                    BizLogicModel.User user = (BizLogicModel.User)Session["User"];
                    if (user.RepositoryList == null)
                    {
                        user.RepositoryList = (from val in documentRepositories
                                               select new BizLogicModel.Repository { Name = val.Name, UserName = "", AcceptUserAgreement = false });
                        Session["User"] = user;
                    }

                    var agreements = from val in user.RepositoryList
                                     select new { Name = val.Name, UserName = val.UserName, Agree = val.AcceptUserAgreement };
                    documentDetailViewModel.UserAgreementJson = new JavaScriptSerializer().Serialize(Json(agreements).Data);
                    
                }
            }
            return documentDetailViewModel;
        }


        protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }

    }
}