示例#1
0
        public static byte[] add_custom_cover(Guid applicationId, Guid currentUserId, byte[] pdfContent, Guid coverId, Guid ownerNodeId)
        {
            DocFileInfo pdfCover = null;

            pdfCover = DocumentsController.get_file(applicationId, coverId);
            if (pdfCover == null || string.IsNullOrEmpty(pdfCover.Extension) || pdfCover.Extension.ToLower() != "pdf")
            {
                pdfCover = null;
            }

            byte[] coverContent = pdfContent == null ? null : pdfCover.toByteArray(applicationId);

            if (coverContent == null || coverContent.Length == 0)
            {
                return(pdfContent);
            }

            Dictionary <string, string> dic = CNAPI.get_replacement_dictionary(applicationId, currentUserId, ownerNodeId, true);

            List <FormElement> tempElems = dic.Keys.ToList().Select(key => new FormElement()
            {
                Name      = key,
                Type      = FormElementTypes.Text,
                TextValue = dic[key]
            }).ToList();

            byte[] cover = PDFTemplates.fill_template(coverContent, tempElems);

            return(PDFUtil.merge_documents(new List <object>()
            {
                cover, pdfContent
            }));
        }
示例#2
0
        protected void btnPostFile_Click(object sender, EventArgs e)
        {
            int          files        = 0;
            UploadStatus uploadstatus = HttpUploadModule.GetUploadStatus();
            bool         flag         = uploadstatus.Reason == UploadTerminationReason.NotTerminated;

            if (flag)
            {
                foreach (UploadedFile file in uploadstatus.GetUploadedFiles())
                {
                    string clientFileName = file.ClientName;
                    bool   flag2          = file.ContentLength.Equals(0L);
                    if (flag2)
                    {
                        base.PromptDialog(string.Format("[{0}]文件大小为0字节,系统不支持文件大小为0字节的文件上传,请重新选择文件上传。", clientFileName));
                        return;
                    }
                    bool flag3 = !this.filelist.MaxFileSize.Equals(0.0) && file.ContentLength > this.filelist.MaxFileSize;
                    if (flag3)
                    {
                        base.PromptDialog(string.Format("[{0}]文件大小已超出规定的 {1}上限,上传失败。", clientFileName, this.filelist.MaxFileSize.FormatFileSize()));
                        return;
                    }
                    DocFileInfo fileInfo = FileService.AddFile(file.ServerPath, clientFileName, file.ContentLength, this.hidFileGroup.Value.ToDouble());
                    this.hidFileGroup.Value   = fileInfo.FileGroupId.ToString();
                    this.filelist.FileGroupId = fileInfo.FileGroupId;
                    this.UpdateBusinessFileGroup();
                    files = this.UpdateBusinessFiles();
                }
            }
            this.UpdateTempletFileFieldRI(files);
            base.CurMaster_OnQuery(null, null);
        }
示例#3
0
        public ActionResult GenerateByUploadedExcel(DateTime paymentDate, string asOfDate)
        {
            return(ActionUtils.Json(() =>
            {
                var path = DemoJianYuanUtils.GetExcelReportPath();
                CommUtils.Assert(System.IO.File.Exists(path), "请先上传服务商报告文件(path={0})", path);

                Resource resource = null;
                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    var ms = new MemoryStream();
                    var docFileInfo = new DocFileInfo {
                        DisplayName = "信托受托机构报告.docx"
                    };

                    var utils = new DemoJianYuanUtils();
                    utils.Generate(ms, fs, "服务商报告.xls", paymentDate, asOfDate);

                    ms.Seek(0, SeekOrigin.Begin);
                    var result = Tuple.Create(ms, docFileInfo);

                    //生成报告
                    var userName = string.IsNullOrWhiteSpace(CurrentUserName) ? "anonymous" : CurrentUserName;
                    resource = ResourcePool.RegisterMemoryStream(userName, result.Item2.DisplayName, result.Item1);
                }

                return ActionUtils.Success(resource.Guid.ToString());
            }));
        }
示例#4
0
        protected void convert2image(DocFileInfo file, string password, DocFileInfo destFile, bool?repair, ref string responseText)
        {
            bool?status = PDFUtil.pdf2image_isprocessing(file.FileID.Value);

            if ((!status.HasValue || !status.Value) && repair.HasValue && repair.Value)
            {
                PublicMethods.set_timeout(() => {
                    PDFUtil.pdf2image(paramsContainer.Tenant.Id, file, password, destFile, ImageFormat.Png, true);
                }, 0);

                responseText = "{\"Status\":\"" + "Processing" + "\"}";

                //PDFUtil.pdf2image(paramsContainer.Tenant.Id, file.FileID.Value, fileAddress, destFolder, ImageFormat.Png, true);
                //responseText = "{\"Status\":\"" + "Ready" + "\"}";
            }
            else if (status.HasValue)
            {
                responseText = "{\"Status\":\"" + (status.Value ? "Processing" : "Ready") + "\"}";
            }
            else
            {
                PublicMethods.set_timeout(() => {
                    PDFUtil.pdf2image(paramsContainer.Tenant.Id, file, password, destFile, ImageFormat.Png, false);
                }, 0);

                responseText = "{\"Status\":\"" + "Processing" + "\"}";

                //PDFUtil.pdf2image(paramsContainer.Tenant.Id, file.FileID.Value, fileAddress, destFolder, ImageFormat.Png, false);
                //responseText = "{\"Status\":\"" + "Ready" + "\"}";
            }
        }
        private static void _parse_file_owner_nodes(ref IDataReader reader, ref List <DocFileInfo> lstFiles)
        {
            while (reader.Read())
            {
                try
                {
                    DocFileInfo file = new DocFileInfo();

                    if (!string.IsNullOrEmpty(reader["FileID"].ToString()))
                    {
                        file.FileID = (Guid)reader["FileID"];
                    }
                    if (!string.IsNullOrEmpty(reader["NodeID"].ToString()))
                    {
                        file.OwnerNodeID = (Guid)reader["NodeID"];
                    }
                    if (!string.IsNullOrEmpty(reader["Name"].ToString()))
                    {
                        file.OwnerNodeName = (string)reader["Name"];
                    }
                    if (!string.IsNullOrEmpty(reader["NodeType"].ToString()))
                    {
                        file.OwnerNodeType = (string)reader["NodeType"];
                    }

                    lstFiles.Add(file);
                }
                catch { }
            }

            if (!reader.IsClosed)
            {
                reader.Close();
            }
        }
示例#6
0
        public static bool import_form(Guid applicationId, Guid?instanceId, DocFileInfo uploadedFile,
                                       string map, Guid currentUserId, ref List <FormElement> savedElements, ref string nodeName,
                                       ref DocFileInfo logo, ref string errorMessage)
        {
            if (uploadedFile != null)
            {
                uploadedFile.FolderName = FolderNames.TemporaryFiles;
            }

            List <FormElement> nodeElements = new List <FormElement>();

            nodeElements.Add(new FormElement()
            {
                ElementID = Guid.NewGuid(), Name = "node_name", Type = FormElementTypes.Text
            });
            nodeElements.Add(new FormElement()
            {
                ElementID = Guid.NewGuid(), Name = "node_logo", Type = FormElementTypes.Text
            });

            if (!FGImport.import_form(applicationId, instanceId, uploadedFile,
                                      PublicMethods.fromJSON(map), currentUserId, ref savedElements, nodeElements, ref errorMessage))
            {
                return(false);
            }

            nodeName = nodeElements.Where(u => u.Name == "node_name").Select(x => x.TextValue).FirstOrDefault();
            string nodeLogo = nodeElements.Where(u => u.Name == "node_logo").Select(x => x.TextValue).FirstOrDefault();

            logo = DocumentUtilities.decode_base64_file_content(applicationId, null, nodeLogo, FileOwnerTypes.None);

            return(true);
        }
示例#7
0
        protected void get_page(int?pageNumber, DocFileInfo destFile)
        {
            if (!pageNumber.HasValue)
            {
                pageNumber = 1;
            }

            try
            {
                ImageFormat imageFormat = ImageFormat.Png;

                destFile.FileName  = pageNumber.ToString();
                destFile.Extension = imageFormat.ToString().ToLower();

                byte[] fileBytes = !destFile.exists(paramsContainer.ApplicationID) ?
                                   File.ReadAllBytes(PublicMethods.map_path(PublicConsts.NoPDFPage)) :
                                   destFile.toByteArray(paramsContainer.ApplicationID);

                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.AddHeader("Content-Disposition",
                                                       string.Format("attachment;filename=\"{0}\"",
                                                                     pageNumber.ToString() + "." + imageFormat.ToString().ToLower()));
                HttpContext.Current.Response.AddHeader("Content-Length", fileBytes.Length.ToString());
                HttpContext.Current.Response.BinaryWrite(fileBytes);
                HttpContext.Current.Response.End();
            }
            catch { }
        }
示例#8
0
文件: DocManager.cs 项目: qdjx/C5
        public string FileSimpleCreate(long FileID)
        {
            DocFileInfo docFileInfo     = GetDocFile(FileID);
            string      FileRealityName = docFileInfo.RealityPath + docFileInfo.FolderName + docFileInfo.FileName;
            string      FilePreviewName = ConfigurationManager.AppSettings["MediaPath"] + docFileInfo.VirtualPath + docFileInfo.FolderName;

            Utils.CreateDirectory(FilePreviewName);
            FilePreviewName += docFileInfo.FileName + ".jpg";

            //创建预览
            double SimpleWidthMax  = 198;
            double SimpleHeightMax = 198;
            double SimpleWidth;
            double SimpleHeight;

            if (".FLV.HEVC.MP4.AVI.MPEG.RMVB.WMV".Contains(docFileInfo.FileExtName.ToUpper()))
            {
                string ffmpeg     = HttpContext.Current.Server.MapPath("/Bin/ffmpeg.exe");
                string FlvImgSize = SimpleWidthMax + "*" + SimpleHeightMax;
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg)
                {
                    WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                    Arguments   = " -i " + FileRealityName + "  -y -f image2 -t 0.1 -vf scale=" + SimpleWidthMax + ":" + SimpleWidthMax + "/a " + FilePreviewName
                };
                System.Diagnostics.Process.Start(startInfo);
            }
            else if (".BMP.GIF.JPG.JPEG.EXIF.PNG.TIFF".Contains(docFileInfo.FileExtName.ToUpper()))
            {
                Image SourceImage = Image.FromFile(FileRealityName, true);
                if (SourceImage.Width > SourceImage.Height)
                {
                    SimpleWidth  = SimpleWidthMax;
                    SimpleHeight = SourceImage.Height * (SimpleWidth / SourceImage.Width);
                }
                else
                {
                    SimpleHeight = SimpleHeightMax;
                    SimpleWidth  = SourceImage.Width * (SimpleHeight / SourceImage.Height);
                }
                if (SimpleWidth < 50 || SimpleHeight < 50)
                {
                    SimpleWidth  += 50;
                    SimpleHeight += 50;
                }
                using (Image SimpleImage = new Bitmap((int)SimpleWidth, (int)SimpleHeight))
                    using (Graphics SimpleGraphics = Graphics.FromImage(SimpleImage))
                    {
                        SimpleGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                        SimpleGraphics.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        SimpleGraphics.DrawImage(SourceImage
                                                 , new Rectangle(0, 0, SimpleImage.Width, SimpleImage.Height)
                                                 , new Rectangle(0, 0, SourceImage.Width, SourceImage.Height)
                                                 , GraphicsUnit.Pixel);
                        SimpleImage.Save(FilePreviewName, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                SourceImage.Dispose();
            }
            return("文件[" + FileID + "]创建预览回调完成。");
        }
示例#9
0
        public static bool add_file(Guid applicationId, Guid ownerId,
                                    FileOwnerTypes ownerType, DocFileInfo attachment, Guid currentUserId)
        {
            List <DocFileInfo> atts = new List <DocFileInfo>();

            atts.Add(attachment);
            return(add_files(applicationId, ownerId, ownerType, ref atts, currentUserId));
        }
示例#10
0
        public static int get_pages_count(Guid applicationId, DocFileInfo pdf, string password, ref bool invalidPassword)
        {
            try
            {
                PdfReader reader = PDFUtil.open_pdf_file(applicationId, pdf, password, ref invalidPassword);

                return(reader == null ? 0 : reader.NumberOfPages);
            }
            catch { return(0); }
        }
示例#11
0
文件: DocManager.cs 项目: qdjx/C5
        public DocFileInfo GetDocFile(long FileID, string ReadAction = null, List <string> FilterExtNames = null, string OrderByLastAccessTime = null)
        {
            using (var EF = new EF())
            {
                var docFiles = (from docFile in EF.DocFile
                                join docFolder in EF.DocFolder on docFile.DocFolderID equals docFolder.ID into t1
                                from docFolder in t1.DefaultIfEmpty()
                                join docPath in EF.DocPath on docFile.DocPathID equals docPath.ID into t2
                                from docPath in t2.DefaultIfEmpty()
                                join fileExtName in EF.FileExtName on docFile.ExtNameID equals fileExtName.ID into t3
                                from fileExtName in t3.DefaultIfEmpty()
                                select new DocFileInfo
                {
                    FileID = docFile.ID,
                    RealityPath = docPath.RealityPath,
                    VirtualPath = docPath.VirtualPath,
                    FolderName = docFolder.Name,
                    FileName = docFile.Name,
                    FileExtName = fileExtName.Name,
                    LastAccessTime = docFile.LastAccessTime
                });

                //当前项
                if (!new string[] { "Previous", "Next" }.Contains(ReadAction))
                {
                    return(docFiles.Where(i => i.FileID == FileID).FirstOrDefault());
                }
                //筛选
                if (FilterExtNames != null && FilterExtNames.Count > 0)
                {
                    docFiles = docFiles.Where(i => FilterExtNames.Contains(i.FileExtName));
                }
                //排序
                if (OrderByLastAccessTime == "asc")
                {
                    docFiles = docFiles.OrderBy(i => i.FileID).OrderBy(i => i.LastAccessTime);
                }
                else if (OrderByLastAccessTime == "desc")
                {
                    docFiles = docFiles.OrderBy(i => i.FileID).OrderByDescending(i => i.LastAccessTime);
                }
                //前后项
                var         list    = docFiles.ToList();
                DocFileInfo current = list.Where(i => i.FileID == FileID).FirstOrDefault();
                if (ReadAction == "Next")
                {
                    return(list.Where(i => i.OrderByID > current.OrderByID).FirstOrDefault());
                }
                else
                {
                    return(list.Where(i => i.OrderByID < current.OrderByID).OrderByDescending(i => i.OrderByID).FirstOrDefault());
                }
            }
        }
示例#12
0
        protected void get_pages_count(DocFileInfo file, string password, DocFileInfo destFile, ref string responseText)
        {
            bool invalidPassword = false;

            int count          = PDFUtil.get_pages_count(paramsContainer.Tenant.Id, file, password, ref invalidPassword);
            int convertedCount = count == 0 ? 0 : PDFUtil.get_converted_pages_count(paramsContainer.Tenant.Id, destFile);

            responseText = "{\"Count\":" + count.ToString() +
                           ",\"ConvertedCount\":" + convertedCount.ToString() +
                           (!invalidPassword ? string.Empty : ",\"InvalidPassword\":" + invalidPassword.ToString().ToLower()) +
                           "}";
        }
示例#13
0
        private Tuple <MemoryStream, DocFileInfo> UploadDemoJianYuanReport(HttpPostedFileBase file, DateTime paymentDate, string asOfDate)
        {
            var ms          = new MemoryStream();
            var docFileInfo = new DocFileInfo {
                DisplayName = "信托受托机构报告.docx"
            };

            var utils = new DemoJianYuanUtils();

            utils.Generate(ms, file.InputStream, file.FileName, paymentDate, asOfDate);

            ms.Seek(0, SeekOrigin.Begin);
            return(Tuple.Create(ms, docFileInfo));
        }
        public Tuple <MemoryStream, DocFileInfo> UploadDemoJianYuanReport(HttpPostedFileBase file, string shortCode)
        {
            var ms          = new MemoryStream();
            var docFileInfo = new DocFileInfo {
                DisplayName = "信托受托机构报告.docx"
            };

            var docFactiory = new DocumentFactory(m_userName);

            docFactiory.Generate(DocPatternType.DemoJianYuanReport, ms,
                                 shortCode, file.InputStream, file.FileName);

            ms.Seek(0, SeekOrigin.Begin);
            return(Tuple.Create(ms, docFileInfo));
        }
示例#15
0
        public static string extract_file_content(Guid applicationId, DocFileInfo file)
        {
            ISolrOperations <SolrDoc> solr = get_solr_operator();

            using (Stream content = new MemoryStream(file.toByteArray(applicationId)))
            {
                ExtractResponse response = solr.Extract(new ExtractParameters(content,
                                                                              PublicMethods.get_random_number().ToString(), PublicMethods.random_string(10))
                {
                    ExtractOnly   = true,
                    ExtractFormat = ExtractFormat.Text
                });

                return(response.Content);
            }
        }
示例#16
0
        private static void _parse_files(Guid applicationId, ref IDataReader reader, ref List <DocFileInfo> lstFiles)
        {
            while (reader.Read())
            {
                try
                {
                    DocFileInfo file = new DocFileInfo();

                    if (!string.IsNullOrEmpty(reader["OwnerID"].ToString()))
                    {
                        file.OwnerID = (Guid)reader["OwnerID"];
                    }
                    if (!string.IsNullOrEmpty(reader["FileID"].ToString()))
                    {
                        file.FileID = (Guid)reader["FileID"];
                    }
                    if (!string.IsNullOrEmpty(reader["FileName"].ToString()))
                    {
                        file.FileName = (string)reader["FileName"];
                    }
                    if (!string.IsNullOrEmpty(reader["Extension"].ToString()))
                    {
                        file.Extension = (string)reader["Extension"];
                    }
                    if (!string.IsNullOrEmpty(reader["Size"].ToString()))
                    {
                        file.Size = (long)reader["Size"];
                    }

                    FileOwnerTypes fot = FileOwnerTypes.None;
                    if (Enum.TryParse <FileOwnerTypes>(reader["OwnerType"].ToString(), out fot))
                    {
                        file.OwnerType = fot;
                    }

                    lstFiles.Add(file);
                }
                catch { }
            }

            if (!reader.IsClosed)
            {
                reader.Close();
            }
        }
        /// 3. Taiin e yek file az DB ke mantnash estekhraj nashode ast.
        /// 4. Estekhraj e matn e file.
        /// 5. Zakhire ye matn e estekhraj shode dar DB (movaffagh ya Na movaffagh)
        public static void ExtractOneDocument(Guid applicationId, ref bool notExist)
        {
            //Taiin e yek file az DB ke mantnash estekhraj nashode ast.
            DocFileInfo file = DocumentsController.get_not_extracted_files(applicationId,
                                                                           "pdf,doc,docx,xlsx,ppt,pptx,txt,xml,htm,html", ',', 1).FirstOrDefault();

            if (file == null || !file.FileID.HasValue)
            {
                notExist = true;
                return;
            }

            // vojoode file dar folder ha
            file.refresh_folder_name();

            bool find = file.exists(applicationId);

            //estekhraje mant e file ba farakhani method e "ExtractFileContent"
            string content        = string.Empty;
            bool   NotExtractable = false;
            double duration       = 0;

            string errorText = string.Empty;

            if (find)
            {
                DateTime dtBegin = DateTime.Now;
                content  = FileContentExtractor.ExtractFileContent(applicationId, file, ref errorText);
                duration = DateTime.Now.Subtract(dtBegin).TotalMilliseconds;
            }

            if (!find)
            {
                find = false;
            }
            else if (string.IsNullOrEmpty(content))
            {
                NotExtractable = true;
            }

            // Zakhire ye matn e estekhraj shode dar DB dar halate movaffagh boodan.
            DocumentsController.save_file_content(applicationId,
                                                  file.FileID.Value, content, NotExtractable, !find, duration, errorText);
        }
示例#18
0
        protected bool remove_file(DocFileInfo file, ref string responseText)
        {
            try
            {
                if (file != null && file.FolderName.HasValue && file.FolderName.Value == FolderNames.TemporaryFiles)
                {
                    file.delete(paramsContainer.Tenant.Id);
                }
            }
            catch { }

            bool result = file != null && file.FileID.HasValue &&
                          DocumentsController.remove_file(paramsContainer.Tenant.Id, file.FileID.Value);

            responseText = result ? "{\"Succeed\":\"" + Messages.OperationCompletedSuccessfully + "\"}" :
                           "{\"ErrorText\":\"" + Messages.OperationFailed + "\"}";

            return(result);
        }
示例#19
0
        private static FSDirectory HardDir(Guid applicationId)
        {
            if (_HardDirs == null)
            {
                _HardDirs = new SortedList <Guid, FSDirectory>();
            }

            if (!_HardDirs.ContainsKey(applicationId))
            {
                string path = DocFileInfo.index_folder_address(applicationId);
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }

                FSDirectory dir = FSDirectory.Open(new DirectoryInfo(path));
                _HardDirs.Add(applicationId, dir);
            }

            return(_HardDirs[applicationId]);
        }
示例#20
0
        private static Dictionary <string, string> get_theme_content(Guid?applicationId, string name)
        {
            if (!string.IsNullOrEmpty(name))
            {
                name = name.Trim().ToLower();
            }

            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }
            else if (ThemeContent.ContainsKey(name))
            {
                return(ThemeContent[name]);
            }

            string thm = new DocFileInfo()
            {
                FileName   = name,
                Extension  = "css",
                FolderName = FolderNames.Themes
            }.get_text_content(applicationId);

            if (string.IsNullOrEmpty(thm))
            {
                return(null);
            }

            Dictionary <string, string> vars = extract_variables(thm);

            if (!PublicMethods.is_dev())
            {
                ThemeContent[name] = vars;
            }

            return(vars);
        }
示例#21
0
        private void activate_node_type_icon(Guid applicationId, string id)
        {
            Guid?templateNodeTypeId = IDs.get_id_from_template(id);

            if (!templateNodeTypeId.HasValue)
            {
                return;
            }

            DocFileInfo pic = new DocFileInfo()
            {
                FileID     = templateNodeTypeId,
                Extension  = "jpg",
                FileName   = templateNodeTypeId.ToString(),
                FolderName = FolderNames.Icons
            };

            byte[] fileContent = pic.toByteArray(RaaiVanSettings.ReferenceTenantID);

            if (fileContent.Length == 0)
            {
                return;
            }

            Guid?newFileId = IDs.new_id(id);

            DocFileInfo newPic = new DocFileInfo()
            {
                FileID     = newFileId,
                Extension  = "jpg",
                FileName   = newFileId.ToString(),
                FolderName = FolderNames.Icons
            };

            newPic.store(applicationId, fileContent);
        }
示例#22
0
        public override IList <IElement> End(IWorkerContext ctx, Tag tag, IList <IElement> currentContent)
        {
            IDictionary <string, string> attributes = tag.Attributes;
            string src;

            if (!attributes.TryGetValue(itsXmlHtml.HTML.Attribute.SRC, out src))
            {
                return(new List <IElement>(1));
            }

            if (string.IsNullOrEmpty(src))
            {
                return(new List <IElement>(1));
            }

            //convert url to base64 image
            if (!src.StartsWith("data:image/", StringComparison.InvariantCultureIgnoreCase))
            {
                int index = src.ToLower().IndexOf("fileid=");

                if (index >= 0)
                {
                    string newSrc = src.Substring(index + "fileid=".Length);
                    if (newSrc.IndexOf("&") > 0)
                    {
                        newSrc = newSrc.Substring(0, newSrc.IndexOf("&"));
                    }

                    Guid?       fileId = PublicMethods.parse_guid(newSrc);
                    DocFileInfo fi     = DocumentsController.get_file(ApplicationID, fileId.Value);
                    if (fi != null)
                    {
                        fi.refresh_folder_name();
                    }

                    if (!fi.exists(ApplicationID))
                    {
                        try
                        {
                            System.Drawing.Image img = null;

                            using (MemoryStream stream = new MemoryStream(fi.toByteArray(ApplicationID)))
                                img = System.Drawing.Bitmap.FromStream(stream);

                            string strWidth = tag == null || tag.CSS == null || !tag.CSS.ContainsKey("width") ?
                                              string.Empty : tag.CSS["width"];
                            string strHeight = tag == null || tag.CSS == null || !tag.CSS.ContainsKey("height") ?
                                               string.Empty : tag.CSS["height"];

                            if (!string.IsNullOrEmpty(strWidth))
                            {
                                strWidth = strWidth.ToLower().Replace("px", "");
                            }
                            if (!string.IsNullOrEmpty(strHeight))
                            {
                                strHeight = strHeight.ToLower().Replace("px", "");
                            }

                            int width = 0, height = 0, maxWidth = 650, maxHeight = 900;

                            if (string.IsNullOrEmpty(strWidth) ||
                                !int.TryParse(strWidth, out width) || width < 0)
                            {
                                width = img.Width;
                            }
                            if (string.IsNullOrEmpty(strHeight) ||
                                !int.TryParse(strHeight, out height) || height < 0)
                            {
                                height = img.Height;
                            }

                            double coeff = Math.Min(width <= maxWidth ? 1 : (double)maxWidth / (double)width,
                                                    height <= maxHeight ? 1 : (double)maxHeight / (double)height);

                            width  = (int)Math.Floor(coeff * (double)width);
                            height = (int)Math.Floor(coeff * (double)height);

                            if (width != img.Width || height != img.Height)
                            {
                                string msg = string.Empty;
                                if (RVGraphics.make_thumbnail(img, width, height, 0, 0, ref img, ref msg))
                                {
                                    tag.CSS["width"]  = (width = img.Width).ToString() + "px";
                                    tag.CSS["height"] = (height = img.Height).ToString() + "px";
                                }
                            }

                            newSrc = PublicMethods.image_to_base64(img, System.Drawing.Imaging.ImageFormat.Png);

                            if (!string.IsNullOrEmpty(newSrc))
                            {
                                src = "data:image/png;base64," + newSrc;
                            }
                        }
                        catch { }
                    }
                }
            }
            //end of convert url to base64 image

            if (src.StartsWith("data:image/", StringComparison.InvariantCultureIgnoreCase))
            {
                // data:[<MIME-type>][;charset=<encoding>][;base64],<data>
                var base64Data = src.Substring(src.IndexOf(",") + 1);
                var imagedata  = Convert.FromBase64String(base64Data);
                var image      = iTextSharp.text.Image.GetInstance(imagedata);

                image.ScaleToFitLineWhenOverflow = true;
                image.ScaleToFitHeight           = false;
                var      list = new List <IElement>();
                var      htmlPipelineContext = GetHtmlPipelineContext(ctx);
                IElement imgElement          = GetCssAppliers().Apply(new Chunk((iTextSharp.text.Image)GetCssAppliers()
                                                                                .Apply(image, tag, htmlPipelineContext), 0, 0, true), tag, htmlPipelineContext);

                list.Add(imgElement);
                return(list);
            }
            else
            {
                return(base.End(ctx, tag, currentContent));
            }
        }
示例#23
0
        private static FormElement _extract_xml_node_data(Guid applicationId,
                                                          XmlNode parentNode, XmlNodeList nodeList, XmlNamespaceManager nsmgr, FormElement formElement,
                                                          Dictionary <string, object> map, Dictionary <string, object> parentMap)
        {
            if (formElement == null || !formElement.ElementID.HasValue ||
                nodeList == null || nodeList.Count == 0)
            {
                return(null);
            }

            FormElement retElement = new FormElement()
            {
                ElementID      = formElement.ElementID,
                RefElementID   = formElement.RefElementID,
                FormInstanceID = formElement.FormInstanceID,
                Type           = formElement.Type,
                SequenceNumber = formElement.SequenceNumber,
                Name           = formElement.Name
            };

            if (!retElement.RefElementID.HasValue || retElement.RefElementID == retElement.ElementID)
            {
                retElement.RefElementID = retElement.ElementID;
                retElement.ElementID    = Guid.NewGuid();
            }

            switch (formElement.Type)
            {
            case FormElementTypes.Text:
            case FormElementTypes.Select:
            case FormElementTypes.Node:
            case FormElementTypes.User:
            {
                string strValue = nodeList.Item(0).InnerText.Trim();
                int    intValue = 0;

                List <string> options = null;

                if (formElement.Type == FormElementTypes.Select &&
                    int.TryParse(strValue, out intValue) && intValue > 0)
                {
                    //if strValue is an integer, probably it is the index of selected option
                    Dictionary <string, object> dic = PublicMethods.fromJSON(formElement.Info);
                    if (dic.ContainsKey("Options") && dic["Options"].GetType() == typeof(ArrayList))
                    {
                        ArrayList arr = (ArrayList)dic["Options"];
                        options = new List <string>();
                        foreach (object obj in arr)
                        {
                            options.Add(Base64.decode((string)obj));
                        }

                        if (options.Count >= intValue && !options.Any(u => u == strValue))
                        {
                            strValue = options[intValue - 1];
                        }
                    }
                }

                if (!string.IsNullOrEmpty(strValue))
                {
                    retElement.TextValue = strValue;
                    return(retElement);
                }
                else
                {
                    return(null);
                }
            }

            case FormElementTypes.Checkbox:
            case FormElementTypes.MultiLevel:
            {
                List <string> strItems = new List <string>();
                foreach (XmlNode nd in nodeList)
                {
                    strItems.Add(nd.InnerText.Trim());
                }
                string strValue = string.Join(" ~ ", strItems.Where(u => !string.IsNullOrEmpty(u)));
                if (!string.IsNullOrEmpty(strValue))
                {
                    retElement.TextValue = strValue;
                    return(retElement);
                }
                else
                {
                    return(null);
                }
            }

            case FormElementTypes.Binary:
            {
                Dictionary <string, object> dic = PublicMethods.fromJSON(formElement.Info);

                string yes = dic.ContainsKey("Yes") ? Base64.decode((string)dic["Yes"]) : string.Empty;
                string no  = dic.ContainsKey("No") ? Base64.decode((string)dic["No"]) : string.Empty;

                string txt      = nodeList.Item(0).InnerText.Trim().ToLower();
                bool?  bitValue = null;
                if (!string.IsNullOrEmpty(txt) && "truefalse".IndexOf(txt) >= 0)
                {
                    bitValue = txt == "true";
                }
                if (bitValue.HasValue)
                {
                    retElement.BitValue  = bitValue;
                    retElement.TextValue = bitValue.Value ? (string.IsNullOrEmpty(yes) ? null : yes) :
                                           (string.IsNullOrEmpty(no) ? null : no);
                    return(retElement);
                }
                else
                {
                    return(null);
                }
            }

            case FormElementTypes.Numeric:
            {
                double dblValue = 0;
                if (double.TryParse(nodeList.Item(0).InnerText, out dblValue))
                {
                    retElement.FloatValue = dblValue;
                    return(retElement);
                }
                else
                {
                    return(null);
                }
            }

            case FormElementTypes.Date:
            {
                string calendarType = map != null && map.ContainsKey("calendar_type") ?
                                      map["calendar_type"].ToString() : string.Empty;
                DateTime?dateValue = null;

                if (string.IsNullOrEmpty(calendarType) || calendarType.ToLower() == "jalali")
                {
                    string[] parts = nodeList.Item(0).InnerText.Trim().Split('/');
                    int      first = 0, second = 0, third = 0;
                    if (parts.Length == 3 && int.TryParse(parts[0], out first) &&
                        int.TryParse(parts[1], out second) && int.TryParse(parts[2], out third))
                    {
                        dateValue = PublicMethods.persian_to_gregorian_date(first, second, third, null, null, null);
                    }
                }

                if (!dateValue.HasValue && parentMap != null)
                {
                    int year = 0;
                    if (int.TryParse(nodeList.Item(0).InnerText, out year) && year > 0)
                    {
                        dateValue = extract_date_from_parts(year, retElement.Name, parentNode, nsmgr, parentMap);
                    }
                }

                if (dateValue.HasValue)
                {
                    retElement.DateValue = dateValue;
                    retElement.TextValue = PublicMethods.get_local_date(dateValue);
                    return(retElement);
                }
                else
                {
                    string strValue = nodeList.Item(0).InnerText.Trim();
                    if (!string.IsNullOrEmpty(strValue))
                    {
                        retElement.TextValue = strValue;
                        return(retElement);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }

            case FormElementTypes.File:
            {
                string      strContent = nodeList.Item(0).InnerText.Trim();
                DocFileInfo doc        = DocumentUtilities.decode_base64_file_content(applicationId,
                                                                                      retElement.ElementID, strContent, FileOwnerTypes.FormElement);
                if (doc != null && !string.IsNullOrEmpty(doc.FileName) && doc.Size.HasValue && doc.Size > 0)
                {
                    retElement.AttachedFiles.Add(doc);
                }
                return(retElement.AttachedFiles.Count > 0 ? retElement : null);
            }

            case FormElementTypes.Form:
            {
                Dictionary <string, object> dic = PublicMethods.fromJSON(formElement.Info);

                Guid formId = Guid.Empty;
                if (!dic.ContainsKey("FormID") || map == null || !map.ContainsKey("sub") ||
                    map["sub"].GetType() != typeof(Dictionary <string, object>) ||
                    !Guid.TryParse(dic["FormID"].ToString(), out formId))
                {
                    return(null);
                }

                List <FormElement> elements = FGController.get_form_elements(applicationId, formId);

                if (elements == null || elements.Count == 0)
                {
                    return(null);
                }

                Dictionary <string, object> subMap = (Dictionary <string, object>)map["sub"];

                foreach (XmlNode node in nodeList)
                {
                    Guid formInstanceId = Guid.NewGuid();

                    List <FormElement> subElements = new List <FormElement>();

                    foreach (string name in subMap.Keys)
                    {
                        List <FormElement> newElements = _parse_imported_form(applicationId, node,
                                                                              get_child_nodes(node, name, nsmgr), nsmgr, subMap[name], elements, subMap);

                        if (newElements != null && newElements.Count > 0)
                        {
                            subElements.AddRange(newElements);
                        }
                    }

                    if (subElements.Count == 0)
                    {
                        continue;
                    }

                    //add [national_id], [first_name], [last_name] & [full_name] elements that are empty
                    List <string> strAll = new List <string>();
                    strAll.AddRange(StrNationalID);
                    strAll.AddRange(StrFirstName);
                    strAll.AddRange(StrLastName);
                    strAll.AddRange(StrFullName);

                    foreach (FormElement e in elements.Where(u => u.Type == FormElementTypes.Text &&
                                                             field_name_match(u.Name, strAll) && !subElements.Any(x => x.RefElementID == u.ElementID)))
                    {
                        subElements.Add(new FormElement()
                            {
                                ElementID      = Guid.NewGuid(),
                                RefElementID   = e.ElementID,
                                FormInstanceID = formInstanceId,
                                Type           = e.Type,
                                SequenceNumber = e.SequenceNumber,
                                Name           = e.Name
                            });
                    }
                    //end of add [national_id], [first_name], [last_name] & [full_name] elements that are empty

                    retElement.TableContent.Add(new FormType()
                        {
                            FormID     = formId,
                            InstanceID = formInstanceId,
                            OwnerID    = retElement.ElementID,
                            Elements   = subElements
                        });
                }

                return(retElement.TableContent.Count > 0 ? retElement : null);
            }

            default:
                return(null);
            }
        }
示例#24
0
    static void GetInfoFromFile(FileSystemInfo file, string docFolder)
    {
        if (!Directory.Exists(DOC_PATH + docFolder))
        {
            Directory.CreateDirectory(DOC_PATH + docFolder);
        }
        Debug.Log("Gen file =>" + file.Name);
        //get all comments
        List <string> data = GetCommentData(file.FullName);
        DocFileInfo   dfi  = new DocFileInfo();

        dfi.fileContent = data;
        dfi.docFolder   = docFolder;
        //get class info
        bool start = false;
        int  functionsBeginLines = 0;

        for (int i = 0; i < data.Count; i++)
        {
            string s = data [i];
            if (!start && s.Contains("public class "))
            {
                dfi.mainClassName = s.Replace("public class", "").Trim();
                if (dfi.mainClassName.Contains(":"))
                {
                    dfi.mainClassName = dfi.mainClassName.Split(':') [0].Trim();
                }
                functionsBeginLines = i + 1;
                break;
            }
            if (s.Contains("</summary>"))
            {
                start = false;
            }
            if (start)
            {
                string tmpStr = dfi.mainClassDescription + s.Replace("///", "").Trim() + "\n";
                dfi.mainClassDescription         = HandleSpecialMark(tmpStr, "../");
                dfi.mainClassDescriptionForIndex = HandleSpecialMark(tmpStr, "");
            }
            if (s.Contains("<summary>") && dfi.mainClassDescription.Equals(""))
            {
                start = true;
            }
        }
        //get functions info (only public functions)
        start = false;
        string commentString = "";

        for (int i = functionsBeginLines; i < data.Count; i++)
        {
            string s = data [i];
            if (s.Trim().StartsWith("public "))
            {
                start = false;
                if (s.Contains("{"))
                {
                    dfi.variables.Add(GenVariable(commentString, s));
                }
                else if (s.Contains(" class "))
                {
                    //inner class
                }
                else if (s.Contains("enum"))
                {
                    //do nothing
                }
                else
                {
                    int index = i + 1;
                    while (!s.Contains(")"))
                    {
                        s = s + data [index];
                        index++;
                    }
                    Function f = GenFunction(commentString, s);
                    // returnType is empty means ctor
                    if (!f.returnType.Trim().Equals(""))
                    {
                        dfi.functions.Add(f);
                    }
                }
                commentString = "";
            }
            if (s.Contains("<summary>"))
            {
                commentString = "";
                start         = true;
            }
            if (start)
            {
                commentString += s.Replace("///", "").Trim() + "\n";
            }
        }

        allDocs.Add(dfi);
    }
示例#25
0
        public void ProcessRequest(HttpContext context)
        {
            //Privacy Check: OK
            paramsContainer = new ParamsContainer(context, nullTenantResponse: false);

            Guid fileId = string.IsNullOrEmpty(context.Request.Params["FileID"]) ?
                          Guid.Empty : Guid.Parse(context.Request.Params["FileID"]);

            if (fileId == Guid.Empty && !Guid.TryParse(context.Request.Params["ATTFID"], out fileId))
            {
                fileId = Guid.Empty;
            }

            string category = PublicMethods.parse_string(context.Request.Params["Category"], false);

            bool   isTemporary = category.ToLower() == FolderNames.TemporaryFiles.ToString().ToLower();
            bool?  addFooter   = PublicMethods.parse_bool(context.Request.Params["Meta"]);
            Guid?  coverId     = PublicMethods.parse_guid(context.Request.Params["CoverID"]);
            string pdfPassword = PublicMethods.parse_string(context.Request.Params["PS"]);

            List <FolderNames> freeFolders = new[] {
                FolderNames.ProfileImages,
                FolderNames.HighQualityProfileImage,
                FolderNames.CoverPhoto,
                FolderNames.HighQualityCoverPhoto,
                FolderNames.Icons,
                FolderNames.HighQualityIcon,
                FolderNames.ApplicationIcons,
                FolderNames.HighQualityApplicationIcon,
                FolderNames.Pictures
            }.ToList();

            bool isFreeFolder = !string.IsNullOrEmpty(category) && freeFolders.Any(f => f.ToString().ToLower() == category.ToLower());

            if (isFreeFolder)
            {
                FolderNames fn = freeFolders.Where(u => u.ToString().ToLower() == category.ToLower()).FirstOrDefault();

                DocFileInfo pic =
                    new DocFileInfo()
                {
                    FileID = fileId, Extension = "jpg", FileName = fileId.ToString(), FolderName = fn
                };

                send_file(pic, false);
            }

            if (!paramsContainer.ApplicationID.HasValue)
            {
                paramsContainer.return_response(PublicConsts.NullTenantResponse);
                return;
            }

            if (isTemporary)
            {
                string ext = PublicMethods.parse_string(context.Request.Params["Extension"]);

                DocFileInfo temp = new DocFileInfo()
                {
                    FileID     = fileId,
                    Extension  = ext,
                    FileName   = fileId.ToString(),
                    FolderName = FolderNames.TemporaryFiles
                };

                send_file(temp, false);
            }
            else
            {
                DocFileInfo AttachFile = DocumentsController.get_file(paramsContainer.Tenant.Id, fileId);

                if (AttachFile == null)
                {
                    paramsContainer.return_response("{\"ErrorText\":\"" + Messages.AccessDenied + "\"}");
                    return;
                }

                PrivacyObjectType pot = AttachFile.OwnerType == FileOwnerTypes.Node ?
                                        PrivacyObjectType.Node : PrivacyObjectType.None;

                DocFileInfo ownerNode = !AttachFile.FileID.HasValue ? null :
                                        DocumentsController.get_file_owner_node(paramsContainer.Tenant.Id, AttachFile.FileID.Value);
                if (ownerNode != null)
                {
                    AttachFile.OwnerNodeID   = ownerNode.OwnerNodeID;
                    AttachFile.OwnerNodeName = ownerNode.OwnerNodeName;
                    AttachFile.OwnerNodeType = ownerNode.OwnerNodeType;
                }

                bool accessDenied =
                    !PrivacyController.check_access(paramsContainer.Tenant.Id,
                                                    paramsContainer.CurrentUserID, AttachFile.OwnerID.Value, pot, PermissionType.View) &&
                    !(
                        paramsContainer.CurrentUserID.HasValue &&
                        new CNAPI()
                {
                    paramsContainer = this.paramsContainer
                }
                        ._is_admin(paramsContainer.Tenant.Id, AttachFile.OwnerID.Value,
                                   paramsContainer.CurrentUserID.Value, CNAPI.AdminLevel.Creator, false)
                        );

                if (accessDenied)
                {
                    //Save Log
                    try
                    {
                        LogController.save_log(paramsContainer.Tenant.Id, new Log()
                        {
                            UserID           = paramsContainer.CurrentUserID,
                            HostAddress      = PublicMethods.get_client_ip(HttpContext.Current),
                            HostName         = PublicMethods.get_client_host_name(HttpContext.Current),
                            Action           = Modules.Log.Action.Download_AccessDenied,
                            SubjectID        = fileId,
                            Info             = "{\"Error\":\"" + Base64.encode(Messages.AccessDenied.ToString()) + "\"}",
                            ModuleIdentifier = ModuleIdentifier.DCT
                        });
                    }
                    catch { }
                    //end of Save Log

                    paramsContainer.return_response("{\"ErrorText\":\"" + Messages.AccessDenied + "\"}");

                    return;
                }

                AttachFile.refresh_folder_name();

                string ext = AttachFile == null || string.IsNullOrEmpty(AttachFile.Extension) ? string.Empty :
                             AttachFile.Extension.ToLower();
                bool isImage = ext == "jpg" || ext == "jpeg" || ext == "png" || ext == "gif" || ext == "bmp";

                if (string.IsNullOrEmpty(AttachFile.Extension) || AttachFile.Extension.ToLower() != "pdf")
                {
                    coverId = null;
                }

                bool   dl          = !isImage || PublicMethods.parse_bool(context.Request.Params["dl"], defaultValue: true) == true;
                string contentType = !dl && isImage?PublicMethods.get_mime_type_by_extension(ext) : null;

                send_file(AttachFile, !isImage, addPDFCover: true,
                          addPDFFooter: addFooter.HasValue && addFooter.Value,
                          coverId: coverId,
                          pdfPassword: pdfPassword,
                          contentType: contentType,
                          isAttachment: dl);
            }
        }
示例#26
0
        public void ProcessRequest(HttpContext context)
        {
            //Privacy Check: OK
            paramsContainer = new ParamsContainer(context, nullTenantResponse: true);
            if (!paramsContainer.ApplicationID.HasValue)
            {
                return;
            }

            string responseText = string.Empty;

            string command = PublicMethods.parse_string(context.Request.Params["Command"], false);

            if (string.IsNullOrEmpty(command))
            {
                return;
            }

            Guid currentUserId = paramsContainer.CurrentUserID.HasValue ? paramsContainer.CurrentUserID.Value : Guid.Empty;

            Guid        fileId = string.IsNullOrEmpty(context.Request.Params["FileID"]) ? Guid.Empty : Guid.Parse(context.Request.Params["FileID"]);
            DocFileInfo file   = DocumentsController.get_file(paramsContainer.Tenant.Id, fileId);

            if (file == null)
            {
                paramsContainer.return_response(PublicConsts.BadRequestResponse);
                return;
            }

            bool isTemporary =
                PublicMethods.parse_string(HttpContext.Current.Request.Params["Category"], false).ToLower() == "temporary";

            bool hasAccess = isTemporary || PublicMethods.is_system_admin(paramsContainer.Tenant.Id, currentUserId);

            PrivacyObjectType pot = file.OwnerType == FileOwnerTypes.Node ? PrivacyObjectType.Node : PrivacyObjectType.None;

            hasAccess = hasAccess || PrivacyController.check_access(paramsContainer.Tenant.Id,
                                                                    paramsContainer.CurrentUserID, file.OwnerID.Value, pot, PermissionType.View);

            if (!hasAccess && currentUserId != Guid.Empty &&
                CNController.is_node(paramsContainer.Tenant.Id, file.OwnerID.Value))
            {
                bool isCreator = false, isContributor = false, isExpert = false, isMember = false, isAdminMember = false,
                     isServiceAdmin = false, isAreaAdmin = false, perCreatorLevel = false;

                CNController.get_user2node_status(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID.Value,
                                                  file.OwnerID.Value, ref isCreator, ref isContributor, ref isExpert, ref isMember, ref isAdminMember,
                                                  ref isServiceAdmin, ref isAreaAdmin, ref perCreatorLevel);

                hasAccess = isServiceAdmin || isAreaAdmin || isCreator || isContributor || isExpert || isMember;
            }

            if (!hasAccess)
            {
                paramsContainer.return_response("{\"ErrorText\":\"" + Messages.AccessDenied.ToString() + "\"}");
            }

            if (isTemporary)
            {
                file.FolderName = FolderNames.TemporaryFiles;
            }
            else
            {
                file.refresh_folder_name();
            }

            if (!file.exists(paramsContainer.Tenant.Id))
            {
                _return_response(ref responseText);
            }

            DocFileInfo destFile = new DocFileInfo()
            {
                FileID = file.FileID, FolderName = FolderNames.PDFImages
            };

            switch (command)
            {
            case "Convert2Image":
                convert2image(file,
                              PublicMethods.parse_string(context.Request.Params["PS"]),
                              destFile,
                              PublicMethods.parse_bool(context.Request.Params["Repair"]), ref responseText);
                _return_response(ref responseText);
                return;

            case "GetPagesCount":
                get_pages_count(file,
                                PublicMethods.parse_string(context.Request.Params["PS"]),
                                destFile, ref responseText);
                _return_response(ref responseText);
                return;

            case "GetPage":
                get_page(PublicMethods.parse_int(context.Request.Params["Page"], 1), destFile);
                return;
            }

            paramsContainer.return_response(PublicConsts.BadRequestResponse);
        }
示例#27
0
 public SearchDoc()
 {
     FileInfo = new DocFileInfo();
 }
示例#28
0
        public static bool import_form(Guid applicationId, Guid?instanceId, DocFileInfo uploadedFile,
                                       Dictionary <string, object> map, Guid currentUserId, ref List <FormElement> savedElements,
                                       List <FormElement> nodeElements, ref string errorMessage)
        {
            if (!instanceId.HasValue || uploadedFile == null || !uploadedFile.FileID.HasValue)
            {
                return(false);
            }

            if (!uploadedFile.exists(applicationId))
            {
                return(false);
            }

            if (map.ContainsKey("sub"))
            {
                map = (Dictionary <string, object>)map["sub"];
            }

            FormType formInstance = FGController.get_form_instance(applicationId, instanceId.Value);

            if (formInstance == null || !formInstance.InstanceID.HasValue || !formInstance.FormID.HasValue)
            {
                return(false);
            }

            List <FormElement> formElements = FGController.get_form_instance_elements(applicationId,
                                                                                      instanceId.Value).OrderBy(u => u.SequenceNumber).ToList();

            if (formElements == null || formElements.Count == 0)
            {
                return(false);
            }

            XmlDocument doc = new XmlDocument();

            try
            {
                using (MemoryStream stream = new MemoryStream(uploadedFile.toByteArray(applicationId)))
                    doc.Load(stream);
            }
            catch (Exception ex)
            {
                LogController.save_error_log(applicationId, currentUserId,
                                             "FG_ImportForm_LoadFile", ex, ModuleIdentifier.FG);
                errorMessage = Messages.OperationFailed.ToString();
                return(false);
            }

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

            if (!string.IsNullOrEmpty(doc.DocumentElement.GetNamespaceOfPrefix("")))
            {
                nsmgr.AddNamespace(DEFAULTPREFIX, doc.DocumentElement.GetNamespaceOfPrefix(""));
                nsmgr.AddNamespace("", doc.DocumentElement.GetNamespaceOfPrefix(""));
            }
            foreach (XmlAttribute attr in doc.SelectSingleNode("/*").Attributes)
            {
                if (attr.Prefix == "xmlns")
                {
                    nsmgr.AddNamespace(attr.LocalName, attr.Value);
                }
            }

            List <FormElement> theElements = new List <FormElement>();

            //add node elements
            if (nodeElements == null)
            {
                nodeElements = new List <FormElement>();
            }

            foreach (FormElement e in nodeElements)
            {
                e.Type = FormElementTypes.Text;
                formElements.Add(e);
            }
            //end of add node elements

            foreach (string name in map.Keys)
            {
                List <FormElement> newElems = _parse_imported_form(applicationId, doc.DocumentElement,
                                                                   get_child_nodes(doc.DocumentElement, name, nsmgr), nsmgr, map[name], formElements, map);
                if (newElems != null && newElems.Count > 0)
                {
                    theElements.AddRange(newElems);
                }
            }

            //remove node elements
            foreach (FormElement e in nodeElements)
            {
                FormElement elem = theElements.Where(
                    u => (u.ElementID == e.ElementID || u.RefElementID == e.ElementID) && u.Name == e.Name).FirstOrDefault();

                if (elem != null)
                {
                    e.TextValue = elem.TextValue;
                    theElements.Remove(elem);
                }
            }
            //end of remove node elements

            List <FormType>    newFormInstances = new List <FormType>();
            List <FormElement> newElements      = new List <FormElement>();
            List <DocFileInfo> newFiles         = new List <DocFileInfo>();

            get_save_items(formInstance, theElements, ref newFormInstances, ref newElements, ref newFiles);

            //set_national_ids(ref newElements);
            set_identity_values(ref newElements);

            //remove empty text elements
            newElements = newElements
                          .Where(u => u.Type != FormElementTypes.Text || !string.IsNullOrEmpty(u.TextValue)).ToList();
            //end of remove empty text elements

            if (newFiles != null)
            {
                newFiles.ForEach(f => f.move(applicationId, FolderNames.TemporaryFiles, FolderNames.Attachments));
            }

            bool result = newFormInstances == null || newFormInstances.Count == 0 ||
                          FGController.create_form_instances(applicationId, newFormInstances, currentUserId);

            result = result && FGController.save_form_instance_elements(applicationId,
                                                                        ref newElements, new List <Guid>(), currentUserId, ref errorMessage);

            if (!result && newFiles != null)
            {
                newFiles.ForEach(f => f.move(applicationId, FolderNames.Attachments, FolderNames.TemporaryFiles));
            }

            if (result)
            {
                savedElements = theElements;
            }

            return(result);
        }
        protected void handle_imported_file(DocFileInfo file, ref string responseText)
        {
            //Privacy Check: OK
            if (!paramsContainer.GBEdit)
            {
                return;
            }

            if (!AuthorizationManager.has_right(AccessRoleName.DataImport, paramsContainer.CurrentUserID))
            {
                responseText = "{\"ErrorText\":\"" + Messages.AccessDenied + "\"}";
                return;
            }

            if (!file.exists(paramsContainer.Tenant.Id))
            {
                responseText = "{\"ErrorText\":\"" + Messages.OperationFailed + "\"}";
                return;
            }

            XmlDocument xmlDoc = new XmlDocument();

            try
            {
                using (MemoryStream stream = new MemoryStream(file.toByteArray(paramsContainer.Tenant.Id)))
                    xmlDoc.Load(stream);
            }
            catch (Exception ex)
            {
                responseText = "{\"ErrorText\":\"" + Messages.OperationFailed + "\"}";
                return;
            }

            string docName = xmlDoc.DocumentElement.Name.ToLower();

            bool result = false;

            switch (docName)
            {
            case "nodes":
                result = update_nodes(ref xmlDoc);
                break;

            case "nodeids":
                result = update_node_ids(ref xmlDoc);
                break;

            case "removenodes":
                result = remove_nodes(ref xmlDoc);
                break;

            case "users":
                result = update_users(ref xmlDoc);
                break;

            case "members":
                result = update_members(ref xmlDoc);
                break;

            case "experts":
                result = update_experts(ref xmlDoc);
                break;

            case "relations":
                result = update_relations(ref xmlDoc);
                break;

            case "authors":
                result = update_authors(ref xmlDoc);
                break;

            case "userconfidentialities":
                result = update_user_confidentialities(ref xmlDoc);
                break;

            case "permissions":
                result = update_permissions(ref xmlDoc);
                break;
            }

            responseText = result ? "{\"Succeed\":\"" + Messages.OperationCompletedSuccessfully + "\"}" :
                           "{\"ErrorText\":\"" + Messages.OperationFailed + "\"}";
        }
示例#30
0
        protected void send_file(DocFileInfo file, bool logNeeded, bool addPDFCover = false, bool addPDFFooter = false,
                                 Guid?coverId = null, string pdfPassword = null, string contentType = null, bool isAttachment = true)
        {
            byte[] fileContent = file.toByteArray(paramsContainer.ApplicationID);

            if (fileContent.Length == 0)
            {
                send_empty_response();
                return;
            }

            //Save Log
            if (logNeeded && paramsContainer.CurrentUserID.HasValue)
            {
                LogController.save_log(paramsContainer.Tenant.Id, new Log()
                {
                    UserID           = paramsContainer.CurrentUserID,
                    Date             = DateTime.Now,
                    HostAddress      = PublicMethods.get_client_ip(HttpContext.Current),
                    HostName         = PublicMethods.get_client_host_name(HttpContext.Current),
                    Action           = Modules.Log.Action.Download,
                    SubjectID        = file.FileID,
                    Info             = file.toJson(paramsContainer.Tenant.Id),
                    ModuleIdentifier = ModuleIdentifier.DCT
                });
            }
            //end of Save Log

            if (file.Extension.ToLower() == "pdf")
            {
                addPDFCover = addPDFCover && file.OwnerNodeID.HasValue && coverId.HasValue &&
                              paramsContainer.ApplicationID.HasValue && paramsContainer.CurrentUserID.HasValue;

                if (addPDFFooter || addPDFCover)
                {
                    bool invalidPassword = false;

                    fileContent = PDFUtil.get_pdf_content(paramsContainer.Tenant.Id, fileContent, pdfPassword, ref invalidPassword);

                    if (invalidPassword)
                    {
                        string responseText = "{\"InvalidPassword\":" + true.ToString().ToLower() + "}";
                        paramsContainer.return_response(ref responseText);
                        return;
                    }
                }

                if (addPDFFooter)
                {
                    User currentUser = !paramsContainer.CurrentUserID.HasValue ? null :
                                       UsersController.get_user(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID.Value);

                    if (currentUser == null)
                    {
                        currentUser = new User()
                        {
                            UserID    = Guid.NewGuid(),
                            UserName  = "******",
                            FirstName = "[anonymous]",
                            LastName  = "[anonymous]"
                        };
                    }

                    DownloadedFileMeta meta = new DownloadedFileMeta(PublicMethods.get_client_ip(HttpContext.Current),
                                                                     currentUser.UserName, currentUser.FirstName, currentUser.LastName, null);

                    fileContent = PDFTemplates.append_footer(fileContent, meta.toString());
                }

                if (addPDFCover)
                {
                    fileContent = Wiki2PDF.add_custom_cover(paramsContainer.Tenant.Id,
                                                            paramsContainer.CurrentUserID.Value, fileContent, coverId.Value, file.OwnerNodeID.Value);
                }

                if (!string.IsNullOrEmpty(pdfPassword))
                {
                    fileContent = PDFUtil.set_password(fileContent, pdfPassword);
                }
            }

            string retFileName = file.FileName + (string.IsNullOrEmpty(file.Extension) ? string.Empty : "." + file.Extension);

            paramsContainer.file_response(fileContent, retFileName, contentType: contentType, isAttachment: isAttachment);
        }