public string GetFileStreamUrl(File file)
        {
            if (file == null)
            {
                return(string.Empty);
            }

            var fileId = ThirdPartySelector.GetFileId(file.ID.ToString());

            Global.Logger.Debug("BoxApp: get file stream url " + fileId);

            var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(ThirdPartyAppHandler.HandlerPath));

            if (uriBuilder.Uri.IsLoopback)
            {
                uriBuilder.Host = Dns.GetHostName();
            }
            var query = uriBuilder.Query;

            query += FilesLinkUtility.Action + "=stream&";
            query += FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(fileId) + "&";
            query += CommonLinkUtility.ParamName_UserUserID + "=" + HttpUtility.UrlEncode(SecurityContext.CurrentAccount.ID.ToString()) + "&";
            query += FilesLinkUtility.AuthKey + "=" + EmailValidationKeyProvider.GetEmailKey(fileId + SecurityContext.CurrentAccount.ID) + "&";
            query += ThirdPartySelector.AppAttr + "=" + AppAttr;

            return(uriBuilder.Uri + "?" + query);
        }
Beispiel #2
0
        private static void SaveReportFile(ReportTaskState state)
        {
            int  tenantId;
            Guid userId;

            ParseCacheKey(state.Id, out tenantId, out userId);

            CoreContext.TenantManager.SetCurrentTenant(tenantId);
            SecurityContext.AuthenticateMe(userId);

            var daoFactory = Global.DaoFactory;
            var url        = state.Response.GetFileUrl(TmpFileName);
            var data       = new WebClient().DownloadData(url);

            using (var stream = new MemoryStream(data))
            {
                var document = new ASC.Files.Core.File
                {
                    Title         = state.FileName,
                    FolderID      = daoFactory.GetFileDao().GetRoot(),
                    ContentLength = stream.Length
                };

                var file = daoFactory.GetFileDao().SaveFile(document, stream);

                daoFactory.GetReportDao().SaveFile((int)file.ID, (int)state.ReportType);

                state.Percentage  = 100;
                state.IsCompleted = true;
                state.Status      = ReportTaskStatus.Done;
                state.FileId      = (int)file.ID;

                SetCacheValue(state);
            }
        }
        private static File SaveFile(Invoice data, string url, DaoFactory daoFactory)
        {
            File file = null;

            var request = (HttpWebRequest)WebRequest.Create(url);

            using (var response = request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    if (stream != null)
                    {
                        var document = new File
                        {
                            Title         = string.Format("{0}{1}", data.Number, FormatPdf),
                            FolderID      = daoFactory.FileDao.GetRoot(),
                            ContentLength = response.ContentLength
                        };

                        if (data.GetInvoiceFile(daoFactory) != null)
                        {
                            document.ID = data.FileID;
                        }

                        file = daoFactory.FileDao.SaveFile(document, stream);
                    }
                }
            }

            return(file);
        }
        public File GetFile(string fileId, out bool editable)
        {
            Global.Logger.Debug("BoxApp: get file " + fileId);
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token = Token.GetToken(AppAttr);

            var boxFile = GetBoxFile(fileId, token);

            editable = true;

            if (boxFile == null)
            {
                return(null);
            }

            var jsonFile = JObject.Parse(boxFile);

            var file = new File
            {
                ID            = ThirdPartySelector.BuildAppFileId(AppAttr, jsonFile.Value <string>("id")),
                Title         = Global.ReplaceInvalidCharsAndTruncate(jsonFile.Value <string>("name")),
                CreateOn      = TenantUtil.DateTimeFromUtc(jsonFile.Value <DateTime>("created_at")),
                ModifiedOn    = TenantUtil.DateTimeFromUtc(jsonFile.Value <DateTime>("modified_at")),
                ContentLength = Convert.ToInt64(jsonFile.Value <string>("size")),
                ProviderKey   = "Box"
            };

            var modifiedBy = jsonFile.Value <JObject>("modified_by");

            if (modifiedBy != null)
            {
                file.ModifiedByString = modifiedBy.Value <string>("name");
            }

            var createdBy = jsonFile.Value <JObject>("created_by");

            if (createdBy != null)
            {
                file.CreateByString = createdBy.Value <string>("name");
            }


            var locked = jsonFile.Value <JObject>("lock");

            if (locked != null)
            {
                var lockedBy = locked.Value <JObject>("created_by");
                if (lockedBy != null)
                {
                    var lockedUserId = lockedBy.Value <string>("id");
                    Global.Logger.Debug("BoxApp: locked by " + lockedUserId);

                    editable = CurrentUser(lockedUserId);
                }
            }

            return(file);
        }
Beispiel #5
0
        public static void CreateAndSaveFile(int invoiceId)
        {
            var log = log4net.LogManager.GetLogger("ASC.CRM");

            log.DebugFormat("PdfCreator. CreateAndSaveFile. Invoice ID = {0}", invoiceId);
            try
            {
                var invoice = Global.DaoFactory.GetInvoiceDao().GetByID(invoiceId);
                if (invoice == null)
                {
                    throw new Exception(CRMErrorsResource.InvoiceNotFound + ". Invoice ID = " + invoiceId);
                }

                log.DebugFormat("PdfCreator. CreateAndSaveFile. Invoice ID = {0}. Convertation", invoiceId);

                string urlToFile;
                using (var docxStream = GetStreamDocx(invoice))
                {
                    urlToFile = GetUrlToFile(docxStream);
                }

                log.DebugFormat("PdfCreator. CreateAndSaveFile. Invoice ID = {0}. UrlToFile = {1}", invoiceId, urlToFile);

                var file = new File
                {
                    Title    = string.Format("{0}{1}", invoice.Number, FormatPdf),
                    FolderID = Global.DaoFactory.GetFileDao().GetRoot()
                };

                var request = WebRequest.Create(urlToFile);
                using (var response = request.GetResponse())
                    using (var stream = response.GetResponseStream())
                    {
                        file.ContentLength = response.ContentLength;

                        log.DebugFormat("PdfCreator. CreateAndSaveFile. Invoice ID = {0}. SaveFile", invoiceId);
                        file = Global.DaoFactory.GetFileDao().SaveFile(file, stream);
                    }

                if (file == null)
                {
                    throw new Exception(CRMErrorsResource.FileCreateError);
                }

                invoice.FileID = Int32.Parse(file.ID.ToString());

                log.DebugFormat("PdfCreator. CreateAndSaveFile. Invoice ID = {0}. UpdateInvoiceFileID. FileID = {1}", invoiceId, file.ID);
                Global.DaoFactory.GetInvoiceDao().UpdateInvoiceFileID(invoice.ID, invoice.FileID);

                log.DebugFormat("PdfCreator. CreateAndSaveFile. Invoice ID = {0}. AttachFiles. FileID = {1}", invoiceId, file.ID);
                Global.DaoFactory.GetRelationshipEventDao().AttachFiles(invoice.ContactID, invoice.EntityType, invoice.EntityID, new[] { invoice.FileID });
            }
            catch (Exception e)
            {
                log.Error(e);
            }
        }
        public static FilesWrapper GetFilesWrapper(File d, List <object> parentFolders)
        {
            var wrapper = (FilesWrapper)d;

            wrapper.Folders = parentFolders.Select(r => new FilesFoldersWrapper()
            {
                FolderId = r.ToString()
            }).ToList();
            return(wrapper);
        }
Beispiel #7
0
        private static void SaveReportFile(ReportState state, string url)
        {
            using (var scope = DIHelper.Resolve())
            {
                var daoFactory = scope.Resolve <DaoFactory>();
                var data       = new WebClient().DownloadData(url);

                using (var stream = new MemoryStream(data))
                {
                    var document = new ASC.Files.Core.File
                    {
                        Title         = state.FileName,
                        FolderID      = daoFactory.FileDao.GetRoot(),
                        ContentLength = stream.Length
                    };

                    var file = daoFactory.FileDao.SaveFile(document, stream);

                    daoFactory.ReportDao.SaveFile((int)file.ID, state.ReportType);
                    state.FileId = (int)file.ID;
                }
            }
        }
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded;
            var isExtenral   = false;

            File           file;
            var            fileUri = string.Empty;
            IThirdPartyApp app     = null;

            try
            {
                if (string.IsNullOrEmpty(RequestFileUrl))
                {
                    _fileNew = (Request["new"] ?? "") == "true";

                    app = ThirdPartySelector.GetAppByFileId(RequestFileId);
                    if (app == null)
                    {
                        var ver = string.IsNullOrEmpty(Request[FilesLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[FilesLinkUtility.Version]);

                        file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, _fileNew, editPossible, !RequestView, out _docParams);

                        _fileNew = _fileNew && file.Version == 1 && file.ConvertedType != null && file.CreateOn == file.ModifiedOn;
                    }
                    else
                    {
                        isExtenral = true;

                        bool editable;
                        _thirdPartyApp = true;
                        file           = app.GetFile(RequestFileId, out editable);
                        file           = DocumentServiceHelper.GetParams(file, true, true, true, editable, editable, editable, out _docParams);

                        _docParams.FileUri   = app.GetFileStreamUrl(file);
                        _docParams.FolderUrl = string.Empty;
                    }
                }
                else
                {
                    isExtenral = true;

                    fileUri = RequestFileUrl;
                    var fileTitle = Request[FilesLinkUtility.FileTitle];
                    if (string.IsNullOrEmpty(fileTitle))
                    {
                        fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";
                    }

                    if (CoreContext.Configuration.Standalone)
                    {
                        try
                        {
                            var webRequest = WebRequest.Create(RequestFileUrl);
                            using (var response = webRequest.GetResponse())
                                using (var responseStream = new ResponseStream(response))
                                {
                                    var externalFileKey = DocumentServiceConnector.GenerateRevisionId(RequestFileUrl);
                                    fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), externalFileKey);
                                }
                        }
                        catch (Exception error)
                        {
                            Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error);
                        }
                    }

                    file = new File
                    {
                        ID    = RequestFileUrl,
                        Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                    };

                    file = DocumentServiceHelper.GetParams(file, true, true, true, false, false, false, out _docParams);
                    _docParams.CanEdit = editPossible && !CoreContext.Configuration.Standalone;
                    _editByUrl         = true;

                    _docParams.FileUri = fileUri;
                }
            }
            catch (Exception ex)
            {
                _errorMessage = ex.Message;
                return;
            }

            if (_docParams.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception e)
                {
                    _docParams    = null;
                    _errorMessage = e.Message;
                    return;
                }

                var comment = "#message/" + HttpUtility.UrlEncode(FilesCommonResource.CopyForEdit);

                Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = file.Title;

            _newScheme = FileUtility.ExtsNewService.Contains(FileUtility.GetFileExtension(file.Title)) &&
                         (string.IsNullOrEmpty(RequestShareLinkKey)
                                 ? OnlineEditorsSettings.NewScheme
                                 : OnlineEditorsSettings.NewSchemeFor(file.CreateBy)) &&
                         app == null;
            if (_newScheme)
            {
                DocServiceApiUrl = FilesLinkUtility.DocServiceApiUrlNew;
            }

            if (string.IsNullOrEmpty(_docParams.FolderUrl))
            {
                _docParams.FolderUrl = Request[FilesLinkUtility.FolderUrl] ?? "";
            }
            if (MobileDetector.IsRequestMatchesMobile(true))
            {
                _docParams.FolderUrl = string.Empty;
            }

            if (RequestEmbedded)
            {
                _docParams.Type = DocumentServiceParams.EditorType.Embedded;

                var shareLinkParam = "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
                _docParams.ViewerUrl   = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=view" + shareLinkParam);
                _docParams.DownloadUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath + "?" + FilesLinkUtility.Action + "=download" + shareLinkParam);
                _docParams.EmbeddedUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=embedded" + shareLinkParam);
            }
            else
            {
                _docParams.Type = IsMobile ? DocumentServiceParams.EditorType.Mobile : DocumentServiceParams.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file))
                {
                    _docParams.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(Share.Location + "?" + FilesLinkUtility.FileId + "=" + file.ID);
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                FileMarker.RemoveMarkAsNew(file);
            }

            if (_docParams.ModeWrite)
            {
                _tabId        = FileTracker.Add(file.ID, _fileNew);
                _fixedVersion = FileTracker.FixedVersion(file.ID);
            }
            else
            {
                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                            : FileConverter.MustConvert(_docParams.File) || _newScheme
                                                  ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID))
                                                  : string.Empty;
            }
        }
Beispiel #9
0
        private void SaveFiles(IBaseCamp basecampManeger, IEnumerable <IAttachment> attachments, int projectID)
        {
            var step = 100.0 / attachments.Count();

            StatusState.StatusLogInfo(string.Format(ImportResource.ImportFileStarted, attachments.Count()));

            //select last version
            foreach (var attachment in attachments)
            {
                StatusState.StatusFileProgress(step);

                try
                {
                    var httpWReq = basecampManeger.Service.GetRequest(attachment.DownloadUrl);
                    using (var httpWResp = (HttpWebResponse)httpWReq.GetResponse())
                    {
                        if (attachment.ByteSize > SetupInfo.MaxUploadSize)
                        {
                            StatusState.StatusLogError(string.Format(ImportResource.FailedSaveFileMaxSizeExided, attachment.Name), new Exception());
                            continue;
                        }

                        var file = new ASC.Files.Core.File
                        {
                            FolderID      = _engineFactory.FileEngine.GetRoot(FindProject(projectID)),
                            Title         = attachment.Name,
                            ContentLength = attachment.ByteSize,
                            CreateBy      = FindUser(attachment.AuthorID),
                            CreateOn      = attachment.CreatedOn.ToUniversalTime(),
                            Comment       = ImportResource.CommentImport,
                        };
                        if (file.Title.LastIndexOf('\\') != -1)
                        {
                            file.Title = file.Title.Substring(file.Title.LastIndexOf('\\') + 1);
                        }

                        file = _engineFactory.FileEngine.SaveFile(file, httpWResp.GetResponseStream());

                        if ("Message".Equals(attachment.OwnerType, StringComparison.OrdinalIgnoreCase))
                        {
                            try
                            {
                                var messageId = FindMessage(attachment.OwnerID);
                                _engineFactory.MessageEngine.AttachFile(new Message {
                                    ID = messageId
                                }, file.ID, false);                                                                    //It's not critical
                            }
                            catch (Exception e)
                            {
                                LogError(string.Format("not critical. attaching file '{0}' to message  failed", attachment.Name), e);
                            }
                        }

                        if ("Todo".Equals(attachment.OwnerType, StringComparison.OrdinalIgnoreCase))
                        {
                            try
                            {
                                var taskId = FindTask(attachment.OwnerID);
                                _engineFactory.TaskEngine.AttachFile(new Task {
                                    ID = taskId
                                }, file.ID, false);                                                           //It's not critical
                            }
                            catch (Exception e)
                            {
                                LogError(string.Format("not critical. attaching file '{0}' to message  failed", attachment.Name), e);
                            }
                        }

                        _newFilesID.Add(new FileIDWrapper
                        {
                            InBasecamp = attachment.ID,
                            InProjects = file.ID
                        });
                    }
                }
                catch (Exception e)
                {
                    try
                    {
                        StatusState.StatusLogError(string.Format(ImportResource.FailedToSaveFile, attachment.Name), e);
                        LogError(string.Format("file '{0}' failed", attachment.Name), e);
                        _newFilesID.RemoveAll(x => x.InBasecamp == attachment.ID);
                    }
                    catch (Exception ex)
                    {
                        LogError(string.Format("file remove after error failed"), ex);
                    }
                }
            }
        }
        private void SaveFiles(BaseCamp basecampManeger, IEnumerable<IAttachment> attachments)
        {
            var step = 100.0 / attachments.Count();

            Status.LogInfo(string.Format(SettingsResource.ImportFileStarted, attachments.Count()));

            //select last version
            foreach (var attachment in attachments.GroupBy(a => a.Collection).Select(g => g.OrderByDescending(a => a.Vers).FirstOrDefault()))
            {
                Status.FileProgress += step;
                try
                {
                    HttpWebRequest HttpWReq = basecampManeger.Service.GetRequest(attachment.DownloadUrl);
                    using (HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse())
                    {
                        if (attachment.ByteSize > SetupInfo.MaxUploadSize) break;

                        var file = new ASC.Files.Core.File();
                        file.FolderID = attachment.CategoryID != -1 ? FindFileCategory(attachment.CategoryID) : FileEngine2.GetRoot(FindProject(attachment.ProjectID));
                        file.Title = attachment.Name;
                        file.ContentLength = attachment.ByteSize;
                        file.ContentType = MimeMapping.GetMimeMapping(attachment.Name);
                        file.CreateBy = FindUser(attachment.AuthorID);
                        file.CreateOn = attachment.CreatedOn.ToUniversalTime();
                        if (file.Title.LastIndexOf('\\') != -1) file.Title = file.Title.Substring(file.Title.LastIndexOf('\\') + 1);

                        file = FileEngine2.SaveFile(file, HttpWResp.GetResponseStream());

                        if ("Post".Equals(attachment.OwnerType,StringComparison.OrdinalIgnoreCase) )
                        {
                            try
                            {
                                var messageId = FindMessage(attachment.OwnerID);
                                FileEngine2.AttachFileToMessage(messageId, file.ID);//It's not critical 
                            }
                            catch (Exception e)
                            {
                                LogError(string.Format("not critical. attaching file '{0}' to message  failed", attachment.Name), e);
                            }
                        }

                        NewFilesID.Add(new FileIDWrapper
                        {
                            inBasecamp = attachment.ID,
                            inProjects = file.ID,
                            version = attachment.Vers,
                            collection = attachment.Collection
                        });
                    }
                }
                catch (Exception e)
                {
                    try
                    {
                        Status.LogError(string.Format(SettingsResource.FailedToSaveFile, attachment.Name), e);
                        LogError(string.Format("file '{0}' failed", attachment.Name), e);
                        NewFilesID.RemoveAll(x => x.inBasecamp == attachment.ID && x.version == attachment.Vers);
                    }
                    catch (Exception ex)
                    {
                        LogError(string.Format("file remove after error failed"), ex);
                    }
                }
            }
        }
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(RequestFileUrl))
                {
                    var app = ThirdPartySelector.GetAppByFileId(RequestFileId);
                    if (app == null)
                    {
                        var ver = string.IsNullOrEmpty(Request[FilesLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[FilesLinkUtility.Version]);
                        file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, editPossible, !RequestView, true, out _configuration);
                    }
                    else
                    {
                        isExtenral = true;

                        bool editable;
                        _thirdPartyApp = true;
                        file           = app.GetFile(RequestFileId, out editable);
                        file           = DocumentServiceHelper.GetParams(file, true, editPossible ? FileShare.ReadWrite : FileShare.Read, false, editable, editable, editable, true, out _configuration);

                        _configuration.Document.Url = app.GetFileStreamUrl(file);
                        _configuration.EditorConfig.Customization.GobackUrl = string.Empty;
                    }
                }
                else
                {
                    isExtenral = true;

                    fileUri = RequestFileUrl;
                    var fileTitle = Request[FilesLinkUtility.FileTitle];
                    if (string.IsNullOrEmpty(fileTitle))
                    {
                        fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";
                    }

                    if (CoreContext.Configuration.Standalone)
                    {
                        try
                        {
                            var webRequest = (HttpWebRequest)WebRequest.Create(RequestFileUrl);

                            // hack. http://ubuntuforums.org/showthread.php?t=1841740
                            if (WorkContext.IsMono)
                            {
                                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                            }

                            using (var response = webRequest.GetResponse())
                                using (var responseStream = new ResponseStream(response))
                                {
                                    var externalFileKey = DocumentServiceConnector.GenerateRevisionId(RequestFileUrl);
                                    fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), externalFileKey);
                                }
                        }
                        catch (Exception error)
                        {
                            Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error);
                        }
                    }

                    file = new File
                    {
                        ID    = RequestFileUrl,
                        Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                    };

                    file = DocumentServiceHelper.GetParams(file, true, FileShare.Read, false, false, false, false, false, out _configuration);
                    _configuration.Document.Permissions.Edit          = editPossible && !CoreContext.Configuration.Standalone;
                    _configuration.Document.Permissions.Rename        = false;
                    _configuration.Document.Permissions.Review        = false;
                    _configuration.Document.Permissions.ChangeHistory = false;
                    _editByUrl = true;

                    _configuration.Document.Url = fileUri;
                }
                ErrorMessage = _configuration.ErrorMessage;
            }
            catch (Exception ex)
            {
                Global.Logger.Warn("DocEditor", ex);
                ErrorMessage = ex.Message;
                return;
            }

            if (_configuration.EditorConfig.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception ex)
                {
                    _configuration = null;
                    Global.Logger.Error("DocEditor", ex);
                    ErrorMessage = ex.Message;
                    return;
                }

                var comment = "#message/" + HttpUtility.UrlEncode(FilesCommonResource.CopyForEdit);

                Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = file.Title;

            if (_configuration.EditorConfig.Customization.Goback == null || string.IsNullOrEmpty(_configuration.EditorConfig.Customization.Goback.Url))
            {
                _configuration.EditorConfig.Customization.GobackUrl = Request[FilesLinkUtility.FolderUrl] ?? "";
            }

            _configuration.EditorConfig.Customization.IsRetina = TenantLogoManager.IsRetina(Request);

            if (RequestEmbedded)
            {
                _configuration.Type = Services.DocumentService.Configuration.EditorType.Embedded;

                _configuration.EditorConfig.Embedded.ShareLinkParam = string.IsNullOrEmpty(RequestShareLinkKey) ? string.Empty : "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
            }
            else
            {
                _configuration.Type = IsMobile ? Services.DocumentService.Configuration.EditorType.Mobile : Services.DocumentService.Configuration.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file))
                {
                    _configuration.EditorConfig.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(Share.Location + "?" + FilesLinkUtility.FileId + "=" + file.ID);
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                FileMarker.RemoveMarkAsNew(file);
            }

            if (_configuration.EditorConfig.ModeWrite)
            {
                _tabId = FileTracker.Add(file.ID);
                if (SecurityContext.IsAuthenticated)
                {
                    _configuration.EditorConfig.FileChoiceUrl  = CommonLinkUtility.GetFullAbsolutePath(FileChoice.Location) + "?" + FileChoice.ParamFilterExt + "=xlsx&" + FileChoice.MailMergeParam + "=true";
                    _configuration.EditorConfig.MergeFolderUrl = CommonLinkUtility.GetFullAbsolutePath(MailMerge.GetUrl);
                }
            }
            else
            {
                _linkToEdit = _editByUrl
                                  ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                  : CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID));

                if (FileConverter.MustConvert(_configuration.Document.Info.File))
                {
                    _editByUrl = true;
                }
            }
        }
Beispiel #12
0
        public string GetFileStreamUrl(File file)
        {
            if (file == null) return string.Empty;

            var fileId = ThirdPartySelector.GetFileId(file.ID.ToString());

            Global.Logger.Debug("BoxApp: get file stream url " + fileId);

            var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(ThirdPartyAppHandler.HandlerPath));
            if (uriBuilder.Uri.IsLoopback)
            {
                uriBuilder.Host = Dns.GetHostName();
            }
            var query = uriBuilder.Query;
            query += FilesLinkUtility.Action + "=stream&";
            query += FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(fileId) + "&";
            query += CommonLinkUtility.ParamName_UserUserID + "=" + HttpUtility.UrlEncode(SecurityContext.CurrentAccount.ID.ToString()) + "&";
            query += FilesLinkUtility.AuthKey + "=" + EmailValidationKeyProvider.GetEmailKey(fileId + SecurityContext.CurrentAccount.ID) + "&";
            query += ThirdPartySelector.AppAttr + "=" + AppAttr;

            return uriBuilder.Uri + "?" + query;
        }
Beispiel #13
0
        public File GetFile(string fileId, out bool editable)
        {
            Global.Logger.Debug("BoxApp: get file " + fileId);
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token = Token.GetToken(AppAttr);

            var boxFile = GetBoxFile(fileId, token);
            editable = true;

            if (boxFile == null) return null;

            var jsonFile = JObject.Parse(boxFile);

            var file = new File
                {
                    ID = ThirdPartySelector.BuildAppFileId(AppAttr, jsonFile.Value<string>("id")),
                    Title = Global.ReplaceInvalidCharsAndTruncate(jsonFile.Value<string>("name")),
                    CreateOn = TenantUtil.DateTimeFromUtc(jsonFile.Value<DateTime>("created_at")),
                    ModifiedOn = TenantUtil.DateTimeFromUtc(jsonFile.Value<DateTime>("modified_at")),
                    ContentLength = Convert.ToInt64(jsonFile.Value<string>("size")),
                    ProviderKey = "Box"
                };

            var modifiedBy = jsonFile.Value<JObject>("modified_by");
            if (modifiedBy != null)
            {
                file.ModifiedByString = modifiedBy.Value<string>("name");
            }

            var createdBy = jsonFile.Value<JObject>("created_by");
            if (createdBy != null)
            {
                file.CreateByString = createdBy.Value<string>("name");
            }


            var locked = jsonFile.Value<JObject>("lock");
            if (locked != null)
            {
                var lockedBy = locked.Value<JObject>("created_by");
                if (lockedBy != null)
                {
                    var lockedUserId = lockedBy.Value<string>("id");
                    Global.Logger.Debug("BoxApp: locked by " + lockedUserId);

                    editable = CurrentUser(lockedUserId);
                }
            }

            return file;
        }
        public static void CreateAndSaveFile(int invoiceId)
        {
            var log = log4net.LogManager.GetLogger("ASC.CRM");
            try
            {
                var invoice = Global.DaoFactory.GetInvoiceDao().GetByID(invoiceId);
                if (invoice == null)
                {
                    throw new Exception("Invoice not found " + invoiceId);
                }

                var exist = invoice.GetInvoiceFile() != null;

                string urlToFile;
                using (var docxStream = GetStreamDocx(invoice))
                {
                    urlToFile = GetUrlToFile(docxStream);
                }

                if (string.IsNullOrEmpty(urlToFile))
                {
                    throw new Exception("Empty url to pdf file " + invoiceId);
                }

                var file = new ASC.Files.Core.File
                    {
                        Title = string.Format("{0}{1}", invoice.Number, FormatPdf),
                        FolderID = Global.DaoFactory.GetFileDao().GetRoot(),
                    };

                if (exist)
                {
                    file.ID = invoice.FileID;
                }

                var request = WebRequest.Create(urlToFile);
                using (var response = request.GetResponse())
                using (var stream = response.GetResponseStream())
                {
                    file.ContentLength = response.ContentLength;
                    file = Global.DaoFactory.GetFileDao().SaveFile(file, stream);
                }

                if (file != null)
                {
                    invoice.FileID = Int32.Parse(file.ID.ToString());
                    Global.DaoFactory.GetInvoiceDao().UpdateInvoiceFileID(invoice.ID, invoice.FileID);
                    if (!exist)
                    {
                        Global.DaoFactory.GetRelationshipEventDao().AttachFiles(invoice.ContactID, invoice.EntityType, invoice.EntityID, new[] { invoice.FileID });
                    }
                }
                else
                {
                    throw new Exception("file is null");
                }
            }
            catch (Exception e)
            {
                log.Error(e.Message);
            }
        }
        private void SaveFiles(IBaseCamp basecampManeger, IEnumerable<IAttachment> attachments, int projectID)
        {
            var step = 100.0 / attachments.Count();

            Status.LogInfo(string.Format(ImportResource.ImportFileStarted, attachments.Count()));

            //select last version
            foreach (var attachment in attachments)
            {
                Status.FileProgress += step;
                try
                {
                    var httpWReq = basecampManeger.Service.GetRequest(attachment.DownloadUrl);
                    using (var httpWResp = (HttpWebResponse)httpWReq.GetResponse())
                    {
                        if (attachment.ByteSize > SetupInfo.MaxUploadSize)
                        {
                            Status.LogError(string.Format(ImportResource.FailedSaveFileMaxSizeExided, attachment.Name), new Exception());
                            continue;
                        }

                        var file = new ASC.Files.Core.File
                            {
                                FolderID = FileEngine2.GetRoot(FindProject(projectID)),
                                Title = attachment.Name,
                                ContentLength = attachment.ByteSize,
                                CreateBy = FindUser(attachment.AuthorID),
                                CreateOn = attachment.CreatedOn.ToUniversalTime()
                            };
                        if (file.Title.LastIndexOf('\\') != -1) file.Title = file.Title.Substring(file.Title.LastIndexOf('\\') + 1);

                        file = FileEngine2.SaveFile(file, httpWResp.GetResponseStream());

                        if ("Message".Equals(attachment.OwnerType, StringComparison.OrdinalIgnoreCase))
                        {
                            try
                            {
                                var messageId = FindMessage(attachment.OwnerID);
                                FileEngine2.AttachFileToMessage(new Message {ID = messageId}, file.ID); //It's not critical 
                            }
                            catch(Exception e)
                            {
                                LogError(string.Format("not critical. attaching file '{0}' to message  failed", attachment.Name), e);
                            }
                        }

                        if ("Todo".Equals(attachment.OwnerType, StringComparison.OrdinalIgnoreCase))
                        {
                            try
                            {
                                var taskId = FindTask(attachment.OwnerID);
                                FileEngine2.AttachFileToTask(new Task {ID = taskId}, file.ID); //It's not critical 
                            }
                            catch(Exception e)
                            {
                                LogError(string.Format("not critical. attaching file '{0}' to message  failed", attachment.Name), e);
                            }
                        }

                        _newFilesID.Add(new FileIDWrapper
                            {
                                InBasecamp = attachment.ID,
                                InProjects = file.ID
                            });
                    }
                }
                catch(Exception e)
                {
                    try
                    {
                        Status.LogError(string.Format(ImportResource.FailedToSaveFile, attachment.Name), e);
                        LogError(string.Format("file '{0}' failed", attachment.Name), e);
                        _newFilesID.RemoveAll(x => x.InBasecamp == attachment.ID);
                    }
                    catch(Exception ex)
                    {
                        LogError(string.Format("file remove after error failed"), ex);
                    }
                }
            }
        }
        private void SaveFiles(BaseCamp basecampManeger, IEnumerable <IAttachment> attachments)
        {
            var step = 100.0 / attachments.Count();

            Status.LogInfo(string.Format(SettingsResource.ImportFileStarted, attachments.Count()));

            //select last version
            foreach (var attachment in attachments.GroupBy(a => a.Collection).Select(g => g.OrderByDescending(a => a.Vers).FirstOrDefault()))
            {
                Status.FileProgress += step;
                try
                {
                    HttpWebRequest HttpWReq = basecampManeger.Service.GetRequest(attachment.DownloadUrl);
                    using (HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse())
                    {
                        if (attachment.ByteSize > SetupInfo.MaxUploadSize)
                        {
                            break;
                        }

                        var file = new ASC.Files.Core.File();
                        file.FolderID      = attachment.CategoryID != -1 ? FindFileCategory(attachment.CategoryID) : FileEngine2.GetRoot(FindProject(attachment.ProjectID));
                        file.Title         = attachment.Name;
                        file.ContentLength = attachment.ByteSize;
                        file.ContentType   = MimeMapping.GetMimeMapping(attachment.Name);
                        file.CreateBy      = FindUser(attachment.AuthorID);
                        file.CreateOn      = attachment.CreatedOn.ToUniversalTime();
                        if (file.Title.LastIndexOf('\\') != -1)
                        {
                            file.Title = file.Title.Substring(file.Title.LastIndexOf('\\') + 1);
                        }

                        file = FileEngine2.SaveFile(file, HttpWResp.GetResponseStream());

                        if ("Post".Equals(attachment.OwnerType, StringComparison.OrdinalIgnoreCase))
                        {
                            try
                            {
                                var messageId = FindMessage(attachment.OwnerID);
                                FileEngine2.AttachFileToMessage(messageId, file.ID);//It's not critical
                            }
                            catch (Exception e)
                            {
                                LogError(string.Format("not critical. attaching file '{0}' to message  failed", attachment.Name), e);
                            }
                        }

                        NewFilesID.Add(new FileIDWrapper
                        {
                            inBasecamp = attachment.ID,
                            inProjects = file.ID,
                            version    = attachment.Vers,
                            collection = attachment.Collection
                        });
                    }
                }
                catch (Exception e)
                {
                    try
                    {
                        Status.LogError(string.Format(SettingsResource.FailedToSaveFile, attachment.Name), e);
                        LogError(string.Format("file '{0}' failed", attachment.Name), e);
                        NewFilesID.RemoveAll(x => x.inBasecamp == attachment.ID && x.version == attachment.Vers);
                    }
                    catch (Exception ex)
                    {
                        LogError(string.Format("file remove after error failed"), ex);
                    }
                }
            }
        }
Beispiel #17
0
        private static ASC.Files.Core.File SaveFile(Invoice data, string url)
        {
            ASC.Files.Core.File file = null;

            var request = (HttpWebRequest)WebRequest.Create(url);

            using (var response = request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    if (stream != null)
                    {
                        var document = new ASC.Files.Core.File
                        {
                            Title = string.Format("{0}{1}", data.Number, FormatPdf),
                            FolderID = Global.DaoFactory.GetFileDao().GetRoot(),
                            ContentLength = response.ContentLength
                        };

                        if (data.GetInvoiceFile() != null)
                        {
                            document.ID = data.FileID;
                        }

                        file = Global.DaoFactory.GetFileDao().SaveFile(document, stream);
                    }
                }
            }

            return file;
        }
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded && !IsMobile;
            var isExtenral = false;

            File file;
            var fileUri = string.Empty;
            if (!ItsTry)
            {
                try
                {
                    if (string.IsNullOrEmpty(RequestFileUrl))
                    {
                        _fileNew = !string.IsNullOrEmpty(Request[UrlConstant.New]) && Request[UrlConstant.New] == "true";

                        var ver = string.IsNullOrEmpty(Request[CommonLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[CommonLinkUtility.Version]);

                        file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, _fileNew, editPossible, !RequestView, out _docParams);

                        _fileNew = file.Version == 1 && file.ConvertedType != null && _fileNew && file.CreateOn == file.ModifiedOn;
                    }
                    else
                    {
                        isExtenral = true;

                        fileUri = RequestFileUrl;
                        var fileTitle = Request[CommonLinkUtility.FileTitle];
                        if (string.IsNullOrEmpty(fileTitle))
                            fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";

                        if (CoreContext.Configuration.Standalone)
                        {
                            try
                            {
                                var webRequest = WebRequest.Create(RequestFileUrl);
                                using (var response = webRequest.GetResponse())
                                using (var responseStream = new ResponseStream(response))
                                {
                                    fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), "new");
                                }
                            }
                            catch (Exception error)
                            {
                                Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error);
                            }
                        }

                        file = new File
                            {
                                ID = fileUri.GetHashCode(),
                                Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                            };

                        file = DocumentServiceHelper.GetParams(file, true, true, true, false, false, false, out _docParams);
                        _docParams.CanEdit = editPossible && !CoreContext.Configuration.Standalone;
                        _editByUrl = true;

                        _docParams.FileUri = fileUri;
                    }
                }
                catch (Exception ex)
                {
                    _errorMessage = ex.Message;
                    return;
                }
            }
            else
            {
                FileType tryType;
                try
                {
                    tryType = (FileType)Enum.Parse(typeof(FileType), Request[CommonLinkUtility.TryParam]);
                }
                catch
                {
                    tryType = FileType.Document;
                }

                var fileTitle = "Demo";
                fileTitle += FileUtility.InternalExtension[tryType];

                var relativeUri = string.Format(CommonLinkUtility.FileHandlerPath + UrlConstant.ParamsDemo, tryType);
                fileUri = new Uri(Request.Url, relativeUri).ToString();

                file = new File
                    {
                        ID = Guid.NewGuid(),
                        Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                    };

                file = DocumentServiceHelper.GetParams(file, true, true, true, editPossible, editPossible, true, out _docParams);

                _docParams.FileUri = fileUri;
                _editByUrl = true;
            }

            if (_docParams.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception e)
                {
                    _docParams = null;
                    _errorMessage = e.Message;
                    return;
                }

                var comment = "#message/" + HttpUtility.UrlEncode(FilesCommonResource.CopyForEdit);

                Response.Redirect(CommonLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = HeaderStringHelper.GetPageTitle(file.Title);

            if (string.IsNullOrEmpty(_docParams.FolderUrl))
            {
                _docParams.FolderUrl = Request[CommonLinkUtility.FolderUrl] ?? "";
            }
            if (MobileDetector.IsRequestMatchesMobile(Context.Request.UserAgent, true))
            {
                _docParams.FolderUrl = string.Empty;
            }

            if (RequestEmbedded)
            {
                _docParams.Type = DocumentServiceParams.EditorType.Embedded;

                var shareLinkParam = "&" + CommonLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
                _docParams.ViewerUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FilesBaseAbsolutePath + CommonLinkUtility.EditorPage + "?" + CommonLinkUtility.Action + "=view" + shareLinkParam);
                _docParams.DownloadUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FileHandlerPath + "?" + CommonLinkUtility.Action + "=download" + shareLinkParam);
                _docParams.EmbeddedUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FilesBaseAbsolutePath + CommonLinkUtility.EditorPage + "?" + CommonLinkUtility.Action + "=embedded" + shareLinkParam);
            }
            else
            {
                _docParams.Type = IsMobile ? DocumentServiceParams.EditorType.Mobile : DocumentServiceParams.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file))
                {
                    _docParams.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FilesBaseAbsolutePath + "share.aspx" + "?" + CommonLinkUtility.FileId + "=" + file.ID + "&" + CommonLinkUtility.FileTitle + "=" + HttpUtility.UrlEncode(file.Title));
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                if (!ItsTry)
                    FileMarker.RemoveMarkAsNew(file);
            }

            if (_docParams.ModeWrite)
            {
                _tabId = FileLocker.Add(file.ID, _fileNew);
                _lockVersion = FileLocker.LockVersion(file.ID);

                if (ItsTry)
                {
                    AppendAuthControl();
                }
            }
            else
            {
                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(string.Format(CommonLinkUtility.FileWebEditorExternalUrlString, HttpUtility.UrlEncode(fileUri), file.Title))
                                            : FileConverter.MustConvert(_docParams.File)
                                                  ? CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetFileWebEditorUrl(file.ID))
                                                  : string.Empty;
            }

            if (CoreContext.Configuration.YourDocsDemo && IsMobile)
            {
                _docParams.CanEdit = false;
            }
        }
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(RequestFileUrl))
                {
                    _fileNew = (Request["new"] ?? "") == "true";

                    var app = ThirdPartySelector.GetAppByFileId(RequestFileId);
                    if (app == null)
                    {
                        var ver = string.IsNullOrEmpty(Request[FilesLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[FilesLinkUtility.Version]);

                        file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, _fileNew, editPossible, !RequestView, out _docParams);

                        _fileNew = _fileNew && file.Version == 1 && file.CreateOn == file.ModifiedOn;
                    }
                    else
                    {
                        isExtenral = true;

                        bool editable;
                        _thirdPartyApp = true;
                        file           = app.GetFile(RequestFileId, out editable);
                        file           = DocumentServiceHelper.GetParams(file, true, true, true, editable, editable, editable, editable, out _docParams);

                        _docParams.FileUri   = app.GetFileStreamUrl(file);
                        _docParams.FolderUrl = string.Empty;
                    }
                }
                else
                {
                    isExtenral = true;

                    fileUri = RequestFileUrl;
                    var fileTitle = Request[FilesLinkUtility.FileTitle];
                    if (string.IsNullOrEmpty(fileTitle))
                    {
                        fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";
                    }

                    if (CoreContext.Configuration.Standalone)
                    {
                        try
                        {
                            var webRequest = (HttpWebRequest)WebRequest.Create(RequestFileUrl);

                            // hack. http://ubuntuforums.org/showthread.php?t=1841740
                            if (WorkContext.IsMono)
                            {
                                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                            }

                            using (var response = webRequest.GetResponse())
                                using (var responseStream = new ResponseStream(response))
                                {
                                    var externalFileKey = DocumentServiceConnector.GenerateRevisionId(RequestFileUrl);
                                    fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), externalFileKey);
                                }
                        }
                        catch (Exception error)
                        {
                            Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error);
                        }
                    }

                    file = new File
                    {
                        ID    = RequestFileUrl,
                        Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                    };

                    file = DocumentServiceHelper.GetParams(file, true, true, true, false, false, false, false, out _docParams);
                    _docParams.CanEdit   = editPossible && !CoreContext.Configuration.Standalone;
                    _docParams.CanReview = _docParams.CanEdit;
                    _editByUrl           = true;

                    _docParams.FileUri = fileUri;
                }
            }
            catch (Exception ex)
            {
                Global.Logger.Error("DocEditor", ex);
                _errorMessage = ex.Message;
                return;
            }

            if (_docParams.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception ex)
                {
                    _docParams = null;
                    Global.Logger.Error("DocEditor", ex);
                    _errorMessage = ex.Message;
                    return;
                }

                var comment = "#message/" + HttpUtility.UrlEncode(FilesCommonResource.CopyForEdit);

                Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = file.Title;

            if (string.IsNullOrEmpty(_docParams.FolderUrl))
            {
                _docParams.FolderUrl = Request[FilesLinkUtility.FolderUrl] ?? "";
            }
            if (MobileDetector.IsRequestMatchesMobile(true))
            {
                _docParams.FolderUrl = string.Empty;
            }

            if (RequestEmbedded)
            {
                _docParams.Type = DocumentServiceParams.EditorType.Embedded;

                var shareLinkParam = "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
                _docParams.ViewerUrl   = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=view" + shareLinkParam);
                _docParams.DownloadUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath + "?" + FilesLinkUtility.Action + "=download" + shareLinkParam);
                _docParams.EmbeddedUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=embedded" + shareLinkParam);
            }
            else
            {
                _docParams.Type = IsMobile ? DocumentServiceParams.EditorType.Mobile : DocumentServiceParams.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file))
                {
                    _docParams.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(Share.Location + "?" + FilesLinkUtility.FileId + "=" + file.ID);
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                FileMarker.RemoveMarkAsNew(file);
            }

            if (_docParams.ModeWrite)
            {
                _tabId        = FileTracker.Add(file.ID, _fileNew);
                _fixedVersion = FileTracker.FixedVersion(file.ID);
                if (SecurityContext.IsAuthenticated)
                {
                    _docParams.FileChoiceUrl  = CommonLinkUtility.GetFullAbsolutePath(FileChoice.Location) + "?" + FileChoice.ParamFilterExt + "=xlsx&" + FileChoice.MailMergeParam + "=true";
                    _docParams.MergeFolderUrl = CommonLinkUtility.GetFullAbsolutePath(MailMerge.GetUrl);
                }
            }
            else
            {
                if (!RequestView && FileTracker.IsEditingAlone(file.ID))
                {
                    var editingBy = FileTracker.GetEditingBy(file.ID).FirstOrDefault();
                    _errorMessage = string.Format(FilesCommonResource.ErrorMassage_EditingMobile, Global.GetUserName(editingBy));
                }

                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                            : CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID));

                if (FileConverter.MustConvert(_docParams.File))
                {
                    _editByUrl = true;
                }
            }
        }
Beispiel #20
0
        public static void CreateAndSaveFile(int invoiceId)
        {
            var log = log4net.LogManager.GetLogger("ASC.CRM");

            try
            {
                var invoice = Global.DaoFactory.GetInvoiceDao().GetByID(invoiceId);
                if (invoice == null)
                {
                    throw new Exception("Invoice not found " + invoiceId);
                }

                var exist = invoice.GetInvoiceFile() != null;

                string urlToFile;
                using (var docxStream = GetStreamDocx(invoice))
                {
                    urlToFile = GetUrlToFile(docxStream);
                }

                if (string.IsNullOrEmpty(urlToFile))
                {
                    throw new Exception("Empty url to pdf file " + invoiceId);
                }

                var file = new ASC.Files.Core.File
                {
                    Title    = string.Format("{0}{1}", invoice.Number, FormatPdf),
                    FolderID = Global.DaoFactory.GetFileDao().GetRoot(),
                };

                if (exist)
                {
                    file.ID = invoice.FileID;
                }

                var request = WebRequest.Create(urlToFile);
                using (var response = request.GetResponse())
                    using (var stream = response.GetResponseStream())
                    {
                        file.ContentLength = response.ContentLength;
                        file = Global.DaoFactory.GetFileDao().SaveFile(file, stream);
                    }

                if (file != null)
                {
                    invoice.FileID = Int32.Parse(file.ID.ToString());
                    Global.DaoFactory.GetInvoiceDao().UpdateInvoiceFileID(invoice.ID, invoice.FileID);
                    if (!exist)
                    {
                        Global.DaoFactory.GetRelationshipEventDao().AttachFiles(invoice.ContactID, invoice.EntityType, invoice.EntityID, new[] { invoice.FileID });
                    }
                }
                else
                {
                    throw new Exception("file is null");
                }
            }
            catch (Exception e)
            {
                log.Error(e.Message);
            }
        }
Beispiel #21
0
        public static void CreateAndSaveFile(int invoiceId)
        {
            var log = log4net.LogManager.GetLogger("ASC.CRM");
            log.DebugFormat("PdfCreator. CreateAndSaveFile. Invoice ID = {0}", invoiceId);
            try
            {
                var invoice = Global.DaoFactory.GetInvoiceDao().GetByID(invoiceId);
                if (invoice == null)
                {
                    throw new Exception(CRMErrorsResource.InvoiceNotFound + ". Invoice ID = " + invoiceId);
                }

                log.DebugFormat("PdfCreator. CreateAndSaveFile. Invoice ID = {0}. Convertation", invoiceId);

                string urlToFile;
                using (var docxStream = GetStreamDocx(invoice))
                {
                    urlToFile = GetUrlToFile(docxStream);
                }

                log.DebugFormat("PdfCreator. CreateAndSaveFile. Invoice ID = {0}. UrlToFile = {1}", invoiceId, urlToFile);

                var file = new ASC.Files.Core.File
                    {
                        Title = string.Format("{0}{1}", invoice.Number, FormatPdf),
                        FolderID = Global.DaoFactory.GetFileDao().GetRoot()
                    };

                var request = WebRequest.Create(urlToFile);
                using (var response = request.GetResponse())
                using (var stream = response.GetResponseStream())
                {
                    file.ContentLength = response.ContentLength;

                    log.DebugFormat("PdfCreator. CreateAndSaveFile. Invoice ID = {0}. SaveFile", invoiceId);
                    file = Global.DaoFactory.GetFileDao().SaveFile(file, stream);
                }

                if (file == null)
                {
                    throw new Exception(CRMErrorsResource.FileCreateError);
                }

                invoice.FileID = Int32.Parse(file.ID.ToString());

                log.DebugFormat("PdfCreator. CreateAndSaveFile. Invoice ID = {0}. UpdateInvoiceFileID. FileID = {1}", invoiceId, file.ID);
                Global.DaoFactory.GetInvoiceDao().UpdateInvoiceFileID(invoice.ID, invoice.FileID);

                log.DebugFormat("PdfCreator. CreateAndSaveFile. Invoice ID = {0}. AttachFiles. FileID = {1}", invoiceId, file.ID);
                Global.DaoFactory.GetRelationshipEventDao().AttachFiles(invoice.ContactID, invoice.EntityType, invoice.EntityID, new[] {invoice.FileID});
            }
            catch (Exception e)
            {
                log.Error(e);
            }
        }
Beispiel #22
0
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded && !IsMobile;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            if (!ItsTry)
            {
                try
                {
                    if (string.IsNullOrEmpty(RequestFileUrl))
                    {
                        _fileNew = !string.IsNullOrEmpty(Request[UrlConstant.New]) && Request[UrlConstant.New] == "true";

                        var ver = string.IsNullOrEmpty(Request[CommonLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[CommonLinkUtility.Version]);

                        file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, _fileNew, editPossible, !RequestView, out _docParams);

                        _fileNew = file.Version == 1 && file.ConvertedType != null && _fileNew && file.CreateOn == file.ModifiedOn;
                    }
                    else
                    {
                        isExtenral = true;

                        fileUri = RequestFileUrl;
                        var fileTitle = Request[CommonLinkUtility.FileTitle];
                        if (string.IsNullOrEmpty(fileTitle))
                        {
                            fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";
                        }

                        if (CoreContext.Configuration.Standalone)
                        {
                            try
                            {
                                var webRequest = WebRequest.Create(RequestFileUrl);
                                using (var response = webRequest.GetResponse())
                                    using (var responseStream = new ResponseStream(response))
                                    {
                                        fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), "new");
                                    }
                            }
                            catch (Exception error)
                            {
                                Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error);
                            }
                        }

                        file = new File
                        {
                            ID    = fileUri.GetHashCode(),
                            Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                        };

                        file = DocumentServiceHelper.GetParams(file, true, true, true, false, false, false, out _docParams);
                        _docParams.CanEdit = editPossible && !CoreContext.Configuration.Standalone;
                        _editByUrl         = true;

                        _docParams.FileUri = fileUri;
                    }
                }
                catch (Exception ex)
                {
                    _errorMessage = ex.Message;
                    return;
                }
            }
            else
            {
                FileType tryType;
                try
                {
                    tryType = (FileType)Enum.Parse(typeof(FileType), Request[CommonLinkUtility.TryParam]);
                }
                catch
                {
                    tryType = FileType.Document;
                }

                var fileTitle = "Demo";
                fileTitle += FileUtility.InternalExtension[tryType];

                var relativeUri = string.Format(CommonLinkUtility.FileHandlerPath + UrlConstant.ParamsDemo, tryType);
                fileUri = new Uri(Request.Url, relativeUri).ToString();

                file = new File
                {
                    ID    = Guid.NewGuid(),
                    Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                };

                file = DocumentServiceHelper.GetParams(file, true, true, true, editPossible, editPossible, true, out _docParams);

                _docParams.FileUri = fileUri;
                _editByUrl         = true;
            }

            if (_docParams.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception e)
                {
                    _docParams    = null;
                    _errorMessage = e.Message;
                    return;
                }

                var comment = "#message/" + HttpUtility.UrlEncode(FilesCommonResource.CopyForEdit);

                Response.Redirect(CommonLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = HeaderStringHelper.GetPageTitle(file.Title);

            if (string.IsNullOrEmpty(_docParams.FolderUrl))
            {
                _docParams.FolderUrl = Request[CommonLinkUtility.FolderUrl] ?? "";
            }
            if (MobileDetector.IsRequestMatchesMobile(Context.Request.UserAgent, true))
            {
                _docParams.FolderUrl = string.Empty;
            }

            if (RequestEmbedded)
            {
                _docParams.Type = DocumentServiceParams.EditorType.Embedded;

                var shareLinkParam = "&" + CommonLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
                _docParams.ViewerUrl   = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FilesBaseAbsolutePath + CommonLinkUtility.EditorPage + "?" + CommonLinkUtility.Action + "=view" + shareLinkParam);
                _docParams.DownloadUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FileHandlerPath + "?" + CommonLinkUtility.Action + "=download" + shareLinkParam);
                _docParams.EmbeddedUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FilesBaseAbsolutePath + CommonLinkUtility.EditorPage + "?" + CommonLinkUtility.Action + "=embedded" + shareLinkParam);
            }
            else
            {
                _docParams.Type = IsMobile ? DocumentServiceParams.EditorType.Mobile : DocumentServiceParams.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file))
                {
                    _docParams.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FilesBaseAbsolutePath + "share.aspx" + "?" + CommonLinkUtility.FileId + "=" + file.ID + "&" + CommonLinkUtility.FileTitle + "=" + HttpUtility.UrlEncode(file.Title));
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                if (!ItsTry)
                {
                    FileMarker.RemoveMarkAsNew(file);
                }
            }

            if (_docParams.ModeWrite)
            {
                _tabId       = FileLocker.Add(file.ID, _fileNew);
                _lockVersion = FileLocker.LockVersion(file.ID);

                if (ItsTry)
                {
                    AppendAuthControl();
                }
            }
            else
            {
                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(string.Format(CommonLinkUtility.FileWebEditorExternalUrlString, HttpUtility.UrlEncode(fileUri), file.Title))
                                            : FileConverter.MustConvert(_docParams.File)
                                                  ? CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetFileWebEditorUrl(file.ID))
                                                  : string.Empty;
            }

            if (CoreContext.Configuration.YourDocsDemo && IsMobile)
            {
                _docParams.CanEdit = false;
            }
        }