コード例 #1
0
        private async void DeleteDocumentCommandExecuted(DocumentsModel obj)
        {
            bool answer = await App.Current.MainPage.DisplayAlert("Eliminar", $"Desea eliminar el documento: {obj.Name}", "Si", "No");

            if (answer)
            {
                var response = await client.Delete <ListResponse>($"documents/deldocument?IdDocument={obj.IdDocument}");

                if (response != null)
                {
                    if (response.Result && response.Count > 0)
                    {
                        SnackSucces("Se elimino correctamente", "KYA", Helpers.TypeSnackBar.Top);
                        LoadDocument();
                    }
                    else
                    {
                        SnackError(response.Message, "Error", Helpers.TypeSnackBar.Top);
                    }
                }
                else
                {
                    SnackError("hubo un error intentelo mas tarde", "Error", Helpers.TypeSnackBar.Top);
                }
            }
        }
コード例 #2
0
        public ActionResult AddDocument(DocumentUploadModel document)
        {
            try
            {
                DocumentsModel addDocument = new DocumentsModel
                {
                    name = document.fileName
                };
                if (document.File.ContentLength > 0)
                {
                    string _FileName = Path.GetFileName(document.File.FileName);
                    string _path     = Path.Combine(Server.MapPath("~/Content/Documents"), _FileName);
                    document.File.SaveAs(_path);
                    addDocument.path = _path;
                }

                db.DocumentsModels.Add(addDocument);
                return(RedirectToAction("Index"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(View());
            }
        }
コード例 #3
0
ファイル: DocumentsController.cs プロジェクト: chipdlk/THD
        public IActionResult Index([FromQuery] SearchDocuments dto)
        {
            int            TotalItems     = 0;
            string         ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
            DocumentsModel data           = new DocumentsModel()
            {
                SearchData = dto
            };

            data.SearchData.Status = 0;
            data.ListItems         = DocumentsService.GetListPagination(data.SearchData, API.Models.Settings.SecretId + ControllerName);
            if (data.ListItems != null && data.ListItems.Count() > 0)
            {
                TotalItems = data.ListItems[0].TotalRows;
            }
            data.Pagination = new Areas.Admin.Models.Partial.PartialPagination()
            {
                CurrentPage = data.SearchData.CurrentPage, ItemsPerPage = data.SearchData.ItemsPerPage, TotalItems = TotalItems, QueryString = Request.QueryString.ToString()
            };
            data.ListDocumentsCategories = DocumentsCategoriesService.GetListSelectItems();
            data.ListDocumentsType       = DocumentsTypeService.GetListSelectItems();
            data.ListDocumentsField      = DocumentsFieldService.GetListSelectItems();
            data.ListDocumentsLevel      = DocumentsLevelService.GetListSelectItems();
            return(View(data));
        }
コード例 #4
0
        object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DocumentsModel myModel = (DocumentsModel)value;

            if (myModel.StatusType == EnumDocStatusType.Company)
            {
                return("公司");
            }
            else if (myModel.StatusType == EnumDocStatusType.Personal)
            {
                return("个人");
            }
            if (myModel.ShareRange == null)
            {
                return("仅自己");
            }
            if (myModel.ShareRange.departs == null)
            {
                myModel.ShareRange.departs = new List <DepartmentApiModel>();
            }
            if (myModel.ShareRange.users == null)
            {
                myModel.ShareRange.users = new List <ProfileApiModel>();
            }
            if (myModel.ShareRange.departs.Count + myModel.ShareRange.users.Count < 1)
            {
                return("仅自己");
            }
            string description = GetEnumDescription(myModel.StatusType);

            return(description);
        }
コード例 #5
0
        public Message <DocumentsModel> AddDocument(DocumentsModel documentsModel)
        {
            try
            {
                string documentPath = $@"C:\inetpub\wwwroot\HighSchool-API\media\{documentsModel.DocumentCategory.Description}\{documentsModel.DocumentDescription}.pdf";

                Helper.AddDocumentToDocumentSet(documentPath, documentsModel.FileBytes);

                Helper.SaveDocument(documentsModel, _repository, _mapper, _logger);

                return(new Message <DocumentsModel>()
                {
                    IsSuccess = true,
                    ReturnMessage = "OK",
                    StatusCode = 200,
                    Data = documentsModel
                });
            }
            catch (Exception ex)
            {
                _logger.LogError("Error", ex);

                return(new Message <DocumentsModel>()
                {
                    IsSuccess = false,
                    ReturnMessage = "Error",
                    StatusCode = 503,
                    Data = documentsModel
                });
            }
        }
コード例 #6
0
        public virtual async Task <DocumentsModel> PrepareDocuments(Customer customer)
        {
            var model = new DocumentsModel();

            model.CustomerId = customer.Id;
            var documentService     = _serviceProvider.GetRequiredService <IDocumentService>();
            var documentTypeService = _serviceProvider.GetRequiredService <IDocumentTypeService>();
            var documents           = await documentService.GetAll(customer.Id);

            foreach (var item in documents.Where(x => x.Published).OrderBy(x => x.DisplayOrder))
            {
                var doc = new Document();
                doc.Id             = item.Id;
                doc.Amount         = item.TotalAmount;
                doc.OutstandAmount = item.OutstandAmount;
                doc.Link           = item.Link;
                doc.Name           = item.Name;
                doc.Number         = item.Number;
                doc.Quantity       = item.Quantity;
                doc.Status         = item.DocumentStatus.GetLocalizedEnum(_localizationService, _workContext);
                doc.Description    = item.Description;
                doc.DocDate        = item.DocDate;
                doc.DueDate        = item.DueDate;
                doc.DocumentType   = (await documentTypeService.GetById(item.DocumentTypeId))?.Name;
                doc.DownloadId     = item.DownloadId;
                model.DocumentList.Add(doc);
            }
            return(model);
        }
コード例 #7
0
        public async Task <IActionResult> NextPage(string page)
        {
            DocumentsModel documentsInfo     = new DocumentsModel();
            string         Baseurl           = "https://localhost:44326/";
            var            documentsResponse = "";

            using (var client = new HttpClient())
            {
                //Passing service base url
                client.BaseAddress = new Uri(Baseurl);
                client.DefaultRequestHeaders.Clear();
                //Define request data format
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //Sending request to find web api REST service resource using HttpClient
                HttpResponseMessage Res = await client.GetAsync("https://www.federalregister.gov/api/v1/documents?format=json&order=newest&page=" + page + "&per_page=20");

                //Checking the response is successful or not which is sent using HttpClient
                if (Res.IsSuccessStatusCode)
                {
                    //Storing the response details recieved from web api
                    documentsResponse = Res.Content.ReadAsStringAsync().Result;
                    //Deserializing the response recieved from web api and storing into the Model
                    documentsInfo = JsonConvert.DeserializeObject <DocumentsModel>(documentsResponse);
                }
            }
            return(View(documentsInfo));
        }
コード例 #8
0
        public IActionResult SaveItem(string Id = null)
        {
            DocumentsModel data           = new DocumentsModel();
            string         ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
            int            IdDC           = Int32.Parse(MyModels.Decode(Id, API.Models.Settings.SecretId + ControllerName).ToString());

            data.SearchData = new SearchDocuments()
            {
                CurrentPage = 0, ItemsPerPage = 10, Keyword = ""
            };
            data.ListDocumentsCategories = DocumentsCategoriesService.GetListSelectItems();
            data.ListDocumentsType       = DocumentsTypeService.GetListSelectItems();
            data.ListDocumentsField      = DocumentsFieldService.GetListSelectItems();
            data.ListDocumentsLevel      = DocumentsLevelService.GetListSelectItems();
            Documents Item = new Documents()
            {
                IssuedDateShow    = DateTime.Now.ToString("dd/MM/yyyy"),
                EffectiveDateShow = DateTime.Now.ToString("dd/MM/yyyy")
            };

            if (IdDC > 0)
            {
                Item = DocumentsService.GetItem(IdDC, API.Models.Settings.SecretId + ControllerName);
            }

            data.Item = Item;

            return(View(data));
        }
コード例 #9
0
        public async Task OnPostSave()
        {
            this.ErrorMessage = "";

            bool isValid = this.ValidatePost();

            if (isValid)
            {
                //ensure we have session state before proceeding
                if (HttpContext.Session.Get <int>(SessionConstants.CurrentUserId) == 0)
                {
                    await base.SetSession();
                }

                await this.PopulateDataSources();

                this.CurrentDocumentId = HttpContext.Session.Get <int>(SessionConstants.CurrentDocumentId);

                string name        = Request.Form["document_details_name_createfolder"];
                string description = Request.Form["document_details_description_createfolder"];

                var user = HttpContext.Session.Get <UserModel>(SessionConstants.CurrentUser);

                var documentType     = this.DocumentTypes.Find(t => t.Text.Contains("Folder"));
                var documentCategory = this.DocumentCategories.Find(c => c.Text == "Folder");

                DocumentsModel folder = new DocumentsModel
                {
                    Name         = name,
                    ParentId     = this.CurrentDocumentId,
                    Category     = Convert.ToInt32(documentCategory.Value),
                    CompanyId    = user.CompanyId,
                    IsDocument   = false,
                    IsPrivate    = false,
                    Active       = true,
                    DocumentType = Convert.ToInt32(documentType.Value),
                    UploadedBy   = user.Id,
                    Description  = description
                };

                string email     = HttpContext.Session.Get <string>(SessionConstants.EmailClaim);
                string rootUrl   = HttpContext.Session.Get <string>(SessionConstants.WebServicesUrl);
                string encodedId = HttpContext.Session.Get <string>(SessionConstants.EncodedUserId);

                bool success = await new DocumentManagerPageModelService().UpdateDocument(email, rootUrl, encodedId, folder);

                if (!success)
                {
                    this.ErrorMessage = StringConstants.DocumentFolderCreateError;
                }
                else
                {
                    //force the document manager page to re-load the document manager treeview
                    HttpContext.Session.Set <ToolbarModel>(SessionConstants.DocumentManagerToolbar, null);
                    Response.Redirect("/DocumentManager/DocumentManager");
                }
            }
        }
コード例 #10
0
ファイル: ExecuteQueryCommand.cs プロジェクト: tal952/ravendb
        private Task GetFetchDocumentsMethod(DocumentsModel documentsModel)
        {
            var q = new IndexQuery
            {
                Start    = model.DocumentsResult.Value.Pager.Skip,
                PageSize = model.DocumentsResult.Value.Pager.PageSize,
                Query    = query,
            };

            if (model.SortBy != null && model.SortBy.Count > 0)
            {
                var sortedFields = new List <SortedField>();
                foreach (var sortByRef in model.SortBy)
                {
                    var sortBy = sortByRef.Value;
                    if (sortBy.EndsWith(QueryModel.SortByDescSuffix))
                    {
                        var field = sortBy.Remove(sortBy.Length - QueryModel.SortByDescSuffix.Length);
                        sortedFields.Add(new SortedField(field)
                        {
                            Descending = true
                        });
                    }
                    else
                    {
                        sortedFields.Add(new SortedField(sortBy));
                    }
                }
                q.SortedFields = sortedFields.ToArray();
            }

            if (model.IsSpatialQuerySupported)
            {
                q = new SpatialIndexQuery(q)
                {
                    Latitude  = model.Latitude.HasValue ? model.Latitude.Value : 0,
                    Longitude = model.Longitude.HasValue ? model.Longitude.Value : 0,
                    Radius    = model.Radius.HasValue ? model.Radius.Value : 0,
                };
            }

            return(DatabaseCommands.QueryAsync(model.IndexName, q, null)
                   .ContinueOnSuccessInTheUIThread(qr =>
            {
                var viewableDocuments = qr.Results.Select(obj => new ViewableDocument(obj.ToJsonDocument())).ToArray();
                documentsModel.Documents.Match(viewableDocuments);
                documentsModel.Pager.TotalResults.Value = qr.TotalResults;

                if (qr.TotalResults == 0)
                {
                    SuggestResults();
                }
            })
                   .Catch(ex => model.Error = ex.ExtractSingleInnerException().SimplifyError()));
        }
コード例 #11
0
 /// <summary>
 /// Update the document subscriber email and user names
 /// </summary>
 /// <param name="document"></param>
 /// <param name="users"></param>
 /// <returns></returns>
 public DocumentsModel UpdateDocumentSubscribers(DocumentsModel document, UserModels users)
 {
     if (document?.Subscribers == null || !document.Subscribers.Any() || users?.Users == null || !users.Users.Any())
     {
         return(document);
     }
     foreach (var t in document.Subscribers)
     {
         var user = users.Users.Find(u => u.Id == t.UserId);
         t.Username = user.UserName;
         t.Email    = user.Email;
     }
     return(document);
 }
コード例 #12
0
        public static void SaveDocument(DocumentsModel documentsModel, IRepository <Documents> repository, IMapper mapper, ILogger <Documents> logger)
        {
            try
            {
                var documentEntity = mapper.Map <Documents>(documentsModel);

                repository.Insert(documentEntity);
                repository.Save();
            }
            catch (Exception ex)
            {
                logger.LogError("Error", ex);
            }
        }
コード例 #13
0
        /// <summary>
        /// An add example for account documents
        /// </summary>
        public DocumentsModel AddAccountDocument(string orgCode, string type, string fileName, string documentData, string text, string accountCode)
        {
            //Note that sequence number isn't set for POST operations.  Ungerboeck will assign the sequence number automatically.
            var myDocument = new DocumentsModel
            {
                Organization    = orgCode,
                Type            = type,         //The file extension must be mapped to one of the recognized Ungerboeck document types.  Use USISDKConstants.DocumentTypeCodes to get the list of type codes.
                NewFileName     = fileName,
                NewDocumentData = documentData, //Files must be in the form of a byte array converted to a base 64 encoded string.  The APIUtil class contains conversion functions to help you: APIUtil.GetEncodedStringForDocuments(FileBytes)
                Description     = text,         //This will be the Ungerboeck description for the file
                Account         = accountCode,
            };

            return(APIUtil.AddDocument(USISDKClient, myDocument));
        }
コード例 #14
0
        public bool getStatus(DocumentsModel para)
        {
            if (para.StatusType == Api.Enum.EnumDocStatusType.Company)
            {
                if (para.Type == Api.Enum.EnumDocFileType.Folder)
                {
                    if (GlobalPara.CompanyDocEditRight)
                    {
                        return(true);
                    }
                    return(false);
                }
                else
                {
                    if (GlobalPara.CompanyFileEditRight)
                    {
                        return(true);
                    }
                    return(false);
                }
            }
            if (para.StatusType != Api.Enum.EnumDocStatusType.Share)
            {
                return(true);
            }
            if (para.CreatorId == GlobalPara.authToken.Profile.ProfileId)
            {
                return(true);
            }
            if (para.SynergyRange == null || para.SynergyRange.departs == null)
            {
                return(false);
            }
            bool hasSyncRight =
                (para.SynergyRange.departs.Select(p => p.DepartmentId).ToList().Intersect(GlobalPara.DepartId).Any() ||
                 para.SynergyRange.users.Select(p => p.ProfileId).ToList()
                 .Intersect(new List <string>()
            {
                GlobalPara.authToken.Profile.ProfileId
            }).Any());

            if (hasSyncRight)
            {
                return(true);
            }
            return(false);
        }
コード例 #15
0
        /// <summary>
        /// Returns a specified document by its model properties.
        /// The following model properties must be supplied:
        /// model.CompanyId
        /// model.UploadedBy
        /// model.Name
        /// </summary>
        /// <param name="email"></param>
        /// <param name="rooturl"></param>
        /// <param name="encodedId"></param>
        /// <param name="document"></param>
        /// <returns></returns>
        public async Task <DocumentsModel> GetDocumentByModel(string email, string rooturl, string encodedId, DocumentsModel document)
        {
            DocumentsModel result = null;

            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(rooturl) || string.IsNullOrEmpty(encodedId) ||
                document == null || document.CompanyId <= 0 || string.IsNullOrEmpty(document.Name) || document.UploadedBy <= 0)
            {
                return(null);
            }

            string payload = new SerializerServices().SerializeObject(document);
            string url     = $"{rooturl}api/documents?postdata={payload}";

            LoggingService service   = new LoggingService();
            var            stopwatch = new Stopwatch();

            try
            {
                string response = await new WebApiServices().GetData(url, encodedId);

                if (!string.IsNullOrEmpty(response))
                {
                    result = new SerializerServices()
                             .DeserializeObject <DocumentsModel>(response.NormalizeJsonString());
                }
            }
            catch (Exception ex)
            {
                service.TrackException(ex);
                throw;
            }
            finally
            {
                stopwatch.Stop();
                var properties = new Dictionary <string, string>
                {
                    { "UserEmail", email },
                    { "WebServicesEndpoint", rooturl },
                    { "EncodedId", encodedId },
                    { "DocumentName", document.Name }
                };
                service.TrackEvent(LoggingServiceConstants.GetDocumentById, stopwatch.Elapsed, properties);
            }
            return(result);
        }
コード例 #16
0
        /// <summary>
        /// Update a document
        /// </summary>
        /// <param name="email"></param>
        /// <param name="rooturl"></param>
        /// <param name="encodedId"></param>
        /// <param name="document"></param>
        /// <returns></returns>
        public async Task <bool> UpdateDocument(string email, string rooturl, string encodedId,
                                                DocumentsModel document)
        {
            bool result = false;

            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(rooturl) || string.IsNullOrEmpty(encodedId) ||
                document?.Name == null || document.CompanyId <= 0 || document.UploadedBy <= 0)
            {
                return(false);
            }

            string      payload = new SerializerServices().SerializeObject(document);
            string      url     = $"{rooturl}api/documents?action={DocumentActionTypeConstants.DocumentActionUpsert}";
            HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

            LoggingService service   = new LoggingService();
            var            stopwatch = new Stopwatch();

            try
            {
                var response = await new WebApiServices().PostData(url, content, encodedId);
                result = response.IsSuccessStatusCode;
            }
            catch (Exception ex)
            {
                service.TrackException(ex);
                throw;
            }
            finally
            {
                stopwatch.Stop();
                var properties = new Dictionary <string, string>
                {
                    { "UserEmail", email },
                    { "WebServicesEndpoint", rooturl },
                    { "EncodedId", encodedId },
                    { "DocumentId", document.Id.ToString() }
                };
                service.TrackEvent(LoggingServiceConstants.UpdateDocument, stopwatch.Elapsed, properties);
            }
            return(result);
        }
コード例 #17
0
        public ActionResult Create(Guid id, IEnumerable <HttpPostedFileBase> upload)
        {
            string savePath = Settings.UserFiles + Domain + "/sitemap/doc/" + id + "/";

            foreach (HttpPostedFileBase doc in upload)
            {
                if (doc != null && doc.ContentLength > 0)
                {
                    int    idx        = doc.FileName.LastIndexOf('.');
                    string Title      = doc.FileName.Substring(0, idx);
                    string TransTitle = Transliteration.Translit(Title);
                    string FileName   = TransTitle + Path.GetExtension(doc.FileName);

                    if (System.IO.File.Exists(Server.MapPath(Path.Combine(savePath, FileName))))
                    {
                        FileName = TransTitle + "(1)" + Path.GetExtension(doc.FileName);
                        Title    = Title + "(1)";
                    }
                    string FullName = savePath + FileName;
                    if (!Directory.Exists(Server.MapPath(savePath)))
                    {
                        Directory.CreateDirectory(Server.MapPath(savePath));
                    }
                    //сохраняем оригинал
                    doc.SaveAs(Server.MapPath(Path.Combine(savePath, FileName)));


                    DocumentsModel docModel = new DocumentsModel()
                    {
                        FilePath = FullName,
                        Title    = Title,
                        idPage   = id
                    };

                    _cmsRepository.insDocuments(docModel);
                }
            }

            model.List = _cmsRepository.getDocuments(id);
            return(View(model));
        }
コード例 #18
0
        public ActionResult SaveItem(Documents model)
        {
            string         ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
            int            IdDC           = Int32.Parse(MyModels.Decode(model.Ids, API.Models.Settings.SecretId + ControllerName).ToString());
            DocumentsModel data           = new DocumentsModel()
            {
                Item = model
            };

            data.ListDocumentsCategories = DocumentsCategoriesService.GetListSelectItems();
            data.ListDocumentsType       = DocumentsTypeService.GetListSelectItems();
            data.ListDocumentsField      = DocumentsFieldService.GetListSelectItems();
            data.ListDocumentsLevel      = DocumentsLevelService.GetListSelectItems();
            if (ModelState.IsValid)
            {
                if (model.Id == IdDC)
                {
                    model.CreatedBy  = int.Parse(HttpContext.Request.Headers["Id"]);
                    model.ModifiedBy = int.Parse(HttpContext.Request.Headers["Id"]);
                    try
                    {
                        DocumentsService.SaveItem(model);
                        if (model.Id > 0)
                        {
                            TempData["MessageSuccess"] = "Cập nhật thành công";
                        }
                        else
                        {
                            TempData["MessageSuccess"] = "Thêm mới thành công";
                        }
                        return(RedirectToAction("Index"));
                    }
                    catch
                    {
                        TempData["MessageError"] = "Lỗi khi lưu dữ liệu";
                    }
                }
            }
            return(View(data));
        }
コード例 #19
0
        /// <summary>
        /// Returns a decorated instance of a <see cref="DocumentsModel"/> object for display
        /// </summary>
        /// <param name="response"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ExpandoObject GetDocumentForDisplay(DocumentsModel response, int userId)
        {
            //use an ExpandoObject to decorate the return object with dynamic properties
            dynamic document = new ExpandoObject();

            document.Description = response.Description;
            if (response.LastViewed == DateTime.MinValue)
            {
                document.LastView = StringConstants.LastViewedNever;
            }
            else
            {
                document.LastView = response.LastViewed;
            }
            document.DocumentFolder              = response.IsDocument ? "Document" : "Folder";
            document.Created                     = response.Created;
            document.LastViewed                  = response.LastViewed;
            document.UploadedByUsername          = response.UploadedByUsername;
            document.DocumentTypeDescription     = response.DocumentTypeDescription;
            document.DocumentCategoryDescription = response.DocumentCategoryDescription;
            document.OwnerSubscriber             = userId == response.UploadedBy ? StringConstants.DocumentOwner : StringConstants.DocumentSubscriber;
            if (response.IsDocument)
            {
                document.OwnerSubscriber = userId == response.UploadedBy ? StringConstants.DocumentOwner : StringConstants.DocumentSubscriber;
            }
            else
            {
                document.OwnerSubscriber = userId == response.UploadedBy ? StringConstants.FolderOwner : StringConstants.FolderSubscriber;
            }
            if (response.Subscribers != null && response.Subscribers.Any())
            {
                document.Subscribers = new List <string>();
                foreach (var subscriber in response.Subscribers)
                {
                    document.Subscribers.Add(subscriber.Username);
                }
            }
            return(document);
        }
コード例 #20
0
        public override bool insDocuments(DocumentsModel insert)
        {
            int MaxPermit = 0;

            using (var db = new CMSdb(_context))
            {
                var queryMaxSort = db.content_documentss
                                   .Where(w => w.id_page == insert.idPage)
                                   .Select(s => s.n_sort);

                int maxSort = queryMaxSort.Any() ? queryMaxSort.Max() + 1 : 1;

                MaxPermit = MaxPermit + 1;
                var data = db.content_documentss
                           .Value(v => v.c_title, insert.Title)
                           .Value(v => v.c_file_path, insert.FilePath)
                           .Value(v => v.id_page, insert.idPage)
                           .Value(v => v.n_sort, maxSort)
                           .Insert();
                return(true);
            }
        }
コード例 #21
0
        public async Task <ApiResponse <DocumentsModel> > GetDocumentsAsync(
            string accessToken,
            string refCorrelationId,
            CancellationToken cancellationToken)
        {
            HttpResponseMessage response = await SendApiRequestAsync(
                accessToken,
                $"/document?refCorrelationId={refCorrelationId}",
                HttpMethod.Get,
                cancellationToken : cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                return(new ApiResponse <DocumentsModel>(response.StatusCode));
            }

            string json = await response.Content.ReadAsStringAsync();

            DocumentsModel model = JsonConvert.DeserializeObject <DocumentsModel>(json);

            return(new ApiResponse <DocumentsModel>(model));
        }
コード例 #22
0
        public static bool hasSyncRight(DocumentsModel value)
        {
            if (value.CreatorId == Global.authToken.Profile.ProfileId)
            {
                return(true);
            }
            if (value.SynergyRange.departs == null)
            {
                return(false);
            }
            bool hasSyncRight =
                (value.SynergyRange.departs.Select(p => p.DepartmentId).ToList().Intersect(Global.DepartId).Any() ||
                 value.SynergyRange.users.Select(p => p.ProfileId).ToList()
                 .Intersect(new List <string>()
            {
                Global.authToken.Profile.ProfileId
            }).Any());

            {
                return(true);
            }
            return(false);
        }
コード例 #23
0
        /// <summary>
        /// Send the notifications to the document subscribers
        /// </summary>
        /// <param name="document"></param>
        /// <param name="rooturl"></param>
        /// <returns></returns>
        public async Task <bool> NotifySubscribers(DocumentsModel document, string rooturl)
        {
            if (document?.Subscribers == null || !document.Subscribers.Any() || string.IsNullOrEmpty(document.Name) || string.IsNullOrEmpty(document.UploadedByUsername))
            {
                return(false);
            }
            bool result = true;

            foreach (var subscriber in document.Subscribers)
            {
                var notification =
                    new DocumentSubscriberNotificationModel
                {
                    UserName       = subscriber.Username,
                    DocumentName   = document.Name,
                    UploaderName   = document.UploadedByUsername,
                    EmailRecipient = new List <string>()
                };
                notification.EmailRecipient.Add(subscriber.Email);
                var response = await new SendEmailService().SendDocumentNotification(notification, rooturl);
                result = result && response;
            }
            return(result);
        }
コード例 #24
0
        private Task GetFetchDocumentsMethod(DocumentsModel documentsModel)
        {
            var q = new IndexQuery
            {
                Start    = model.DocumentsResult.Value.Pager.Skip,
                PageSize = model.DocumentsResult.Value.Pager.PageSize,
                Query    = query,
            };

            if (model.SortBy != null && model.SortBy.Count > 0)
            {
                var sortedFields = new List <SortedField>();
                foreach (var sortByRef in model.SortBy)
                {
                    var sortBy = sortByRef.Value;
                    if (sortBy.EndsWith(QueryModel.SortByDescSuffix))
                    {
                        var field = sortBy.Remove(sortBy.Length - QueryModel.SortByDescSuffix.Length);
                        sortedFields.Add(new SortedField(field)
                        {
                            Descending = true
                        });
                    }
                    else
                    {
                        sortedFields.Add(new SortedField(sortBy));
                    }
                }
                q.SortedFields = sortedFields.ToArray();
            }

            if (model.IsSpatialQuerySupported)
            {
                q = new SpatialIndexQuery(q)
                {
                    Latitude  = model.Latitude.HasValue ? model.Latitude.Value : 0,
                    Longitude = model.Longitude.HasValue ? model.Longitude.Value : 0,
                    Radius    = model.Radius.HasValue ? model.Radius.Value : 0,
                };
            }

            var queryStartTime = DateTime.Now.Ticks;
            var queryEndtime   = DateTime.MinValue.Ticks;

            return(DatabaseCommands.QueryAsync(model.IndexName, q, null)
                   .ContinueWith(task =>
            {
                queryEndtime = DateTime.Now.Ticks;
                return task;
            })
                   .Unwrap()
                   .ContinueOnSuccessInTheUIThread(qr =>
            {
                model.QueryTime = new TimeSpan(queryEndtime - queryStartTime);
                model.Results = new RavenQueryStatistics
                {
                    IndexEtag = qr.IndexEtag,
                    IndexName = qr.IndexName,
                    IndexTimestamp = qr.IndexTimestamp,
                    IsStale = qr.IsStale,
                    SkippedResults = qr.SkippedResults,
                    Timestamp = DateTime.Now,
                    TotalResults = qr.TotalResults
                };
                var viewableDocuments = qr.Results.Select(obj => new ViewableDocument(obj.ToJsonDocument())).ToArray();

                var documetsIds = new List <string>();
                ProjectionData.Projections.Clear();
                foreach (var viewableDocument in viewableDocuments)
                {
                    var id = string.IsNullOrEmpty(viewableDocument.Id) == false ? viewableDocument.Id : Guid.NewGuid().ToString();

                    if (string.IsNullOrEmpty(viewableDocument.Id))
                    {
                        ProjectionData.Projections.Add(id, viewableDocument);
                    }

                    documetsIds.Add(id);

                    viewableDocument.NeighborsIds = documetsIds;
                }

                documentsModel.Documents.Match(viewableDocuments);
                documentsModel.Pager.TotalResults.Value = qr.TotalResults;

                if (qr.TotalResults == 0)
                {
                    SuggestResults();
                }
            })
                   .CatchIgnore <WebException>(ex => model.Error = ex.SimplifyError()));
        }
コード例 #25
0
        public async Task <Message <DocumentsModel> > GenerateDocuments(DocumentsModel documentsModel)
        {
            try
            {
                var studentCertificateData = await _documentsRepository.GetStudentCertificateData(Convert.ToInt32(documentsModel.UserId));

                var model = new StudentCertificationDrop();

                model.CreationDate = DateTime.Now;
                model.NoAmze       = studentCertificateData[0].NrAmze;
                model.SchoolName   = studentCertificateData[0].SchoolName;
                model.StudentName  = studentCertificateData[0].FullName;
                model.StudentYear  = studentCertificateData[0].ClassYear;

                var globalSettings = new GlobalSettings
                {
                    ColorMode   = ColorMode.Color,
                    Orientation = Orientation.Portrait,
                    PaperSize   = PaperKind.A4,
                    Margins     = new MarginSettings {
                        Top = 10
                    },
                    DocumentTitle = "Vertetim Studenti",
                    //Out = $@"C:\inetpub\wwwroot\HighSchool-API\media\vertetim\VertetimUser{model.StudentName}.pdf"
                };

                var objectSettings = new ObjectSettings
                {
                    PagesCount     = true,
                    HtmlContent    = TemplateGenerator.GetStudentCertificationHtml("vertetim", model),
                    FooterSettings = { FontName = "Arial", FontSize = 9, Right = "Faqe [page] nga [toPage]", Line = true }
                };


                var pdf = new HtmlToPdfDocument()
                {
                    GlobalSettings = globalSettings,
                    Objects        = { objectSettings }
                };

                var output = _converter.Convert(pdf);

                string documentPath = $@"C:\inetpub\wwwroot\HighSchool-API\media\vertetim\VertetimUser{model.StudentName}.pdf";

                Helper.AddDocumentToDocumentSet(documentPath, output);

                documentsModel.FileBytes = output;

                Helper.SaveDocument(documentsModel, _repository, _mapper, _logger);

                return(new Message <DocumentsModel>()
                {
                    IsSuccess = true,
                    ReturnMessage = "OK",
                    StatusCode = 200,
                    Data = documentsModel
                });
                //return File(output, "application/pdf");
            }
            catch (Exception ex)
            {
                _logger.LogError("Error on generating", ex);
                return(new Message <DocumentsModel>()
                {
                    IsSuccess = false,
                    ReturnMessage = "Error",
                    StatusCode = 500,
                    Data = null
                });
            }
        }
コード例 #26
0
 private async void SelectedDocumentCommandExecuted(DocumentsModel obj)
 {
     await NavigationPushModalAsync(new Views.Administrator.DocumentsPage(obj));
 }
コード例 #27
0
        public async Task <Message <DocumentsModel> > GenerateDocuments(DocumentsModel model, string token)
        {
            var requestUrl = CreateRequestUri(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Documents/GenerateStudentCertificate"));

            return(await PostAsync <DocumentsModel>(requestUrl, model, token));
        }
コード例 #28
0
 public ExportDocumentDetailsCommand(DocumentsModel model)
 {
     this.model = model;
 }
コード例 #29
0
ファイル: DocStore.cs プロジェクト: countersoft/App-DocStore
        public override WidgetResult Show(IssueDto args)
        {
            _projectManager = new ProjectManager(Cache, UserContext, GeminiContext);

            _projectDocumentManager = new ProjectDocumentManager(Cache, UserContext, GeminiContext);

            IssuesGridFilter tmp = new IssuesGridFilter();

            HttpSessionManager HttpSessionManager = new HttpSessionManager();

            var projects = new List <int>();

            int selectedFolderKey = 0;

            // Safety check required because of http://gemini.countersoft.com/project/DEV/21/item/5088
            try
            {
                if (CurrentCard.IsNew)
                {
                    tmp = new IssuesGridFilter(HttpSessionManager.GetFilter(CurrentCard.Id, CurrentCard.Filter));

                    if (tmp == null)
                    {
                        tmp = CurrentCard.Options[AppGuid].FromJson <IssuesGridFilter>();
                    }

                    projects = tmp.GetProjects();
                }
                else
                {
                    var cardOptions = CurrentCard.Options[AppGuid].FromJson <DocumentAppNavCard>();

                    projects.Add(cardOptions.projectId);

                    selectedFolderKey = cardOptions.folderKey;
                }
            }
            catch (Exception ex)
            {
                tmp = new IssuesGridFilter(HttpSessionManager.GetFilter(CurrentCard.Id, IssuesFilter.CreateProjectFilter(UserContext.User.Entity.Id, UserContext.Project.Entity.Id)));

                projects = tmp.GetProjects();
            }

            var activeProjects = _projectManager.GetActive();

            var viewableProjects = new List <ProjectDto>();

            int?currentProjectId = projects.Count > 0 ? projects.First() : 0;

            if (activeProjects == null || activeProjects.Count == 0)
            {
                activeProjects = new List <ProjectDto>();
            }
            else
            {
                viewableProjects = ProjectManager.GetAppViewableProjects(this);
            }

            if (!viewableProjects.Any(s => s.Entity.Id == currentProjectId.Value))
            {
                currentProjectId = viewableProjects.Count > 0 ? viewableProjects.First().Entity.Id : 0;
            }


            var model = new DocumentsModel
            {
                Projects      = viewableProjects,
                FolderList    = _projectDocumentManager.GetFolders(currentProjectId),
                MaxFileUpload = GeminiApp.Config.MaxFileUploadSizeBytes
            };

            model.ProjectList = new SelectList(model.Projects, "Entity.Id", "Entity.Name", currentProjectId);

            model.Projects = viewableProjects;

            model.SelectedFolder = selectedFolderKey;

            model.HeaderText.Add(new HeaderTextItem(ResourceKeys.Documents));

            if (!model.FolderList.Any() && currentProjectId > 0)
            {
                var entity = new ProjectDocument
                {
                    Name      = ResourceKeys.Documents,
                    IsFolder  = true,
                    ProjectId = currentProjectId
                };

                model.FolderList.Add(_projectDocumentManager.Create(entity));
            }

            if (ProjectManager.GetAppEditableProjects(this).Count > 0)
            {
                ViewBag.EditPermission = true;
            }
            else
            {
                ViewBag.EditPermission = false;
            }

            WidgetResult result = new WidgetResult();

            result.Markup = new WidgetMarkup("views\\Documents.cshtml", model);

            result.Success = true;

            return(result);
        }
コード例 #30
0
        public async Task <Message <DocumentsModel> > AddDocument(DocumentsModel model, string token)
        {
            var requestUrl = CreateRequestUri(string.Format(System.Globalization.CultureInfo.InvariantCulture, "User/SaveUser"));

            return(await PostAsync <DocumentsModel>(requestUrl, model, token));
        }