コード例 #1
0
        public List <UsageSpaceStatItemWrapper> GetSpaceUsageStatistics(Guid id)
        {
            SecurityContext.DemandPermissions(Tenant, SecutiryConstants.EditPortalSettings);

            var webtem = WebItemManager.Instance.GetItems(Tenant, WebZoneType.All, ItemAvailableState.All)
                         .FirstOrDefault(item =>
                                         item != null &&
                                         item.ID == id &&
                                         item.Context != null &&
                                         item.Context.SpaceUsageStatManager != null);

            if (webtem == null)
            {
                return(new List <UsageSpaceStatItemWrapper>());
            }

            return(webtem.Context.SpaceUsageStatManager.GetStatData()
                   .ConvertAll(it => new UsageSpaceStatItemWrapper
            {
                Name = it.Name.HtmlEncode(),
                Icon = it.ImgUrl,
                Disabled = it.Disabled,
                Size = FileSizeComment.FilesSizeToString(it.SpaceUsage),
                Url = it.Url
            }));
        }
コード例 #2
0
        private Tuple <string, string> GetPersonalTariffNotify()
        {
            var maxTotalSize = CoreContext.Configuration.PersonalMaxSpace;

            var webItem           = WebItemManager.Instance[WebItemManager.DocumentsProductID];
            var spaceUsageManager = webItem.Context.SpaceUsageStatManager as IUserSpaceUsage;

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

            var usedSize = spaceUsageManager.GetUserSpaceUsage(SecurityContext.CurrentAccount.ID);

            long notifySize;

            long.TryParse(ConfigurationManager.AppSettings["web.tariff-notify.storage"] ?? "104857600", out notifySize); //100 MB

            if (notifySize > 0 && maxTotalSize - usedSize < notifySize)
            {
                var head = string.Format(Resource.PersonalTariffExceedLimit, FileSizeComment.FilesSizeToString(maxTotalSize));
                var text = String.Format(Resource.PersonalTariffExceedLimitInfoText, "<a target=\"_blank\" href=\"https://support.onlyoffice.com\">", "</a>", "</br>");
                return(new Tuple <string, string>(head, text));
            }

            return(null);
        }
コード例 #3
0
        private void _itemsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var product = e.Item.DataItem as Product;
            var webItem = WebItemManager.Instance[product.Id];

            var data  = new List <object>();
            var items = webItem.Context.SpaceUsageStatManager.GetStatData();

            foreach (var it in items)
            {
                data.Add(new { Name = it.Name, Icon = it.ImgUrl, Size = FileSizeComment.FilesSizeToString(it.SpaceUsage), Url = it.Url });
            }

            if (items.Count == 0)
            {
                e.Item.FindControl("_emptyUsageSpace").Visible = true;
                e.Item.FindControl("_showMorePanel").Visible   = false;
            }
            else
            {
                var repeater = (Repeater)e.Item.FindControl("_usageSpaceRepeater");
                repeater.DataSource = data;
                repeater.DataBind();


                e.Item.FindControl("_showMorePanel").Visible   = (items.Count > 10);
                e.Item.FindControl("_emptyUsageSpace").Visible = false;
            }
        }
コード例 #4
0
 private void DemandSize()
 {
     if (BackupHelper.ExceedsMaxAvailableSize(TenantManager.GetCurrentTenant().TenantId))
     {
         throw new InvalidOperationException(string.Format(UserControlsCommonResource.BackupSpaceExceed,
                                                           FileSizeComment.FilesSizeToString(BackupHelper.AvailableZipSize),
                                                           "",
                                                           ""));
     }
 }
コード例 #5
0
ファイル: TenantExtra.cs プロジェクト: sainabob/teamlab.v7.5
        public static string GetTariffNotify()
        {
            var tariff = GetCurrentTariff();

            if (tariff.State == TariffState.Trial)
            {
                var count = tariff.DueDate.Subtract(DateTime.Today.Date).Days;
                if (count <= 0)
                {
                    return(Resource.TrialPeriodExpired);
                }

                string end;
                var    num = count % 100;

                if (num >= 11 && num <= 19)
                {
                    end = Resource.DaysTwo;
                }
                else
                {
                    var i = count % 10;
                    switch (i)
                    {
                    case (1):
                        end = Resource.Day;
                        break;

                    case (2):
                    case (3):
                    case (4):
                        end = Resource.DaysOne;
                        break;

                    default:
                        end = Resource.DaysTwo;
                        break;
                    }
                }
                return(string.Format(Resource.TrialPeriod, count, end));
            }

            if (tariff.State == TariffState.Paid)
            {
                var  quota = GetTenantQuota();
                long notifySize;
                long.TryParse(ConfigurationManager.AppSettings["web.tariff-notify.storage"] ?? "314572800", out notifySize); //300 MB
                if (notifySize > 0 && quota.MaxTotalSize - TenantStatisticsProvider.GetUsedSize() < notifySize)
                {
                    return(string.Format(Resource.TariffExceedLimit, FileSizeComment.FilesSizeToString(quota.MaxTotalSize)));
                }
            }

            return(string.Empty);
        }
コード例 #6
0
 public string GetSpaceUsage()
 {
     try
     {
         var spaceUsage = TalkSpaceUsageStatManager.GetSpaceUsage();
         return(spaceUsage > 0 ? FileSizeComment.FilesSizeToString(spaceUsage) : String.Empty);
     }
     catch (Exception ex)
     {
         LogManager.GetLogger("ASC.Talk").Error(ex);
         return(String.Empty);
     }
 }
コード例 #7
0
        public override SearchResultItem[] Search(string text)
        {
            using (var folderDao = Global.DaoFactory.GetFolderDao())
            {
                var result = SearchFiles(text)
                             .Select(r =>
                {
                    var folders = EntryManager.GetBreadCrumbs(r.FolderID, folderDao);
                    return(new SearchResultItem
                    {
                        Name = r.Title ?? string.Empty,
                        Description = string.Empty,
                        URL = FilesLinkUtility.GetFileWebPreviewUrl(r.Title, r.ID),
                        Date = r.ModifiedOn,
                        Additional = new Dictionary <string, object>
                        {
                            { "Author", r.CreateByString.HtmlEncode() },
                            { "Path", FolderPathBuilder(folders) },
                            { "FullPath", FolderFullPathBuilder(folders) },
                            { "FolderUrl", PathProvider.GetFolderUrl(r.FolderID) },
                            { "Size", FileSizeComment.FilesSizeToString(r.ContentLength) }
                        }
                    });
                });

                var resultFolder = SearchFolders(text)
                                   .Select(f =>
                {
                    var folders = EntryManager.GetBreadCrumbs(f.ID, folderDao);
                    return(new SearchResultItem
                    {
                        Name = f.Title ?? string.Empty,
                        Description = String.Empty,
                        URL = PathProvider.GetFolderUrl(f),
                        Date = f.ModifiedOn,
                        Additional = new Dictionary <string, object>
                        {
                            { "Author", f.CreateByString.HtmlEncode() },
                            { "Path", FolderPathBuilder(folders) },
                            { "FullPath", FolderFullPathBuilder(folders) },
                            { "IsFolder", true }
                        }
                    });
                });

                return(result.Concat(resultFolder).ToArray());
            }
        }
コード例 #8
0
 public void SendMsgRemoveUserDataCompleted(Guid recipientId, Guid fromUserId, string fromUserName, long docsSpace, long crmSpace, long mailSpace, long talkSpace)
 {
     client.SendNoticeToAsync(
         CoreContext.Configuration.CustomMode ? Actions.RemoveUserDataCompletedCustomMode : Actions.RemoveUserDataCompleted,
         null,
         new[] { StudioNotifyHelper.ToRecipient(recipientId) },
         new[] { EMailSenderName },
         null,
         new TagValue(Tags.UserName, DisplayUserSettings.GetFullUserName(recipientId)),
         new TagValue(Tags.FromUserName, fromUserName.HtmlEncode()),
         new TagValue(Tags.FromUserLink, GetUserProfileLink(fromUserId)),
         new TagValue("DocsSpace", FileSizeComment.FilesSizeToString(docsSpace)),
         new TagValue("CrmSpace", FileSizeComment.FilesSizeToString(crmSpace)),
         new TagValue("MailSpace", FileSizeComment.FilesSizeToString(mailSpace)),
         new TagValue("TalkSpace", FileSizeComment.FilesSizeToString(talkSpace)));
 }
コード例 #9
0
ファイル: SearchHandler.cs プロジェクト: ONLYOFFICE/AppServer
        public SearchResultItem[] Search(string text)
        {
            var folderDao = DaoFactory.GetFolderDao <int>();
            var files     = SearchFiles(text);
            List <SearchResultItem> list = new List <SearchResultItem>();

            foreach (var file in files)
            {
                var searchResultItem = new SearchResultItem
                {
                    Name        = file.Title ?? string.Empty,
                    Description = string.Empty,
                    URL         = FilesLinkUtility.GetFileWebPreviewUrl(FileUtility, file.Title, file.ID),
                    Date        = file.ModifiedOn,
                    Additional  = new Dictionary <string, object>
                    {
                        { "Author", file.CreateByString.HtmlEncode() },
                        { "Path", FolderPathBuilder <int>(EntryManager.GetBreadCrumbs(file.FolderID, folderDao)) },
                        { "Size", FileSizeComment.FilesSizeToString(file.ContentLength) }
                    }
                };
                list.Add(searchResultItem);
            }

            var folders = SearchFolders(text);

            foreach (var folder in folders)
            {
                var searchResultItem = new SearchResultItem
                {
                    Name        = folder.Title ?? string.Empty,
                    Description = string.Empty,
                    URL         = PathProvider.GetFolderUrl(folder),
                    Date        = folder.ModifiedOn,
                    Additional  = new Dictionary <string, object>
                    {
                        { "Author", folder.CreateByString.HtmlEncode() },
                        { "Path", FolderPathBuilder <int>(EntryManager.GetBreadCrumbs(folder.ID, folderDao)) },
                        { "IsFolder", true }
                    }
                };
                list.Add(searchResultItem);
            }

            return(list.ToArray());
        }
コード例 #10
0
ファイル: Search.aspx.cs プロジェクト: Wifisoft/teamlab.v6.5
        private void ContentSearch()
        {
            var security = Global.GetFilesSecurity();

            using (var folderDao = Global.DaoFactory.GetFolderDao())
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    var files = fileDao.Search(SearchText, FolderType.USER | FolderType.COMMON)
                                .Where(security.CanRead)
                                .Select(r => new SearchItem
                    {
                        ID             = r.ID,
                        FileTitle      = r.Title ?? string.Empty,
                        Owner          = CoreContext.UserManager.GetUsers(r.CreateBy).DisplayUserName() ?? string.Empty,
                        Uploaded       = r.ModifiedOn.ToString(DateTimeExtension.ShortDatePattern),
                        Size           = FileSizeComment.FilesSizeToString(r.ContentLength),
                        FolderPathPart = FolderPathBuilder(folderDao.GetParentFolders(r.FolderID)),
                        ItemUrl        = FileUtility.ExtsWebPreviewed.Contains(FileUtility.GetFileExtension(r.Title), StringComparer.CurrentCultureIgnoreCase) ? CommonLinkUtility.GetFileWebViewerUrl(r.ID) : r.ViewUrl,
                        IsFolder       = false
                    });

                    var folders = folderDao.Search(SearchText, FolderType.USER | FolderType.COMMON)
                                  .Where(security.CanRead)
                                  .Select(f => new SearchItem
                    {
                        ID             = f.ID,
                        FileTitle      = f.Title ?? string.Empty,
                        Body           = string.Empty,
                        Owner          = CoreContext.UserManager.GetUsers(f.CreateBy).DisplayUserName() ?? string.Empty,
                        Uploaded       = f.ModifiedOn.ToString(DateTimeExtension.ShortDatePattern),
                        FolderPathPart = FolderPathBuilder(folderDao.GetParentFolders(f.ID)),
                        ItemUrl        = PathProvider.GetFolderUrl(f),
                        IsFolder       = true
                    });

                    NumberOfFileFound   = files.Count();
                    NumberOfFolderFound = folders.Count();

                    var result = folders.Concat(files).ToList();
                    if (result.Count != 0)
                    {
                        ContentSearchRepeater.DataSource = result;
                        ContentSearchRepeater.DataBind();
                    }
                }
        }
コード例 #11
0
        public override SearchResultItem[] Search(string text)
        {
            var security = Global.GetFilesSecurity();

            using (var folderDao = Global.DaoFactory.GetFolderDao())
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    var files = fileDao.Search(text, FolderType.USER | FolderType.COMMON)
                                .Where(security.CanRead)
                                .Select(r => new SearchResultItem
                    {
                        Name        = r.Title ?? string.Empty,
                        Description = string.Empty,
                        URL         = FileUtility.ExtsWebPreviewed.Contains(FileUtility.GetFileExtension(r.Title), StringComparer.CurrentCultureIgnoreCase)
                                                   ? CommonLinkUtility.GetFileWebViewerUrl(r.ID)
                                                   : r.ViewUrl,
                        Date       = r.ModifiedOn,
                        Additional = new Dictionary <string, object>
                        {
                            { "Author", r.CreateByString.HtmlEncode() },
                            { "Container", folderDao.GetParentFolders(r.FolderID) },
                            { "IsFolder", false },
                            { "Size", FileSizeComment.FilesSizeToString(r.ContentLength) }
                        }
                    });

                    var folders = folderDao.Search(text, FolderType.USER | FolderType.COMMON)
                                  .Where(security.CanRead)
                                  .Select(f => new SearchResultItem
                    {
                        Name        = f.Title ?? string.Empty,
                        Description = String.Empty,
                        URL         = PathProvider.GetFolderUrl(f),
                        Date        = f.ModifiedOn,
                        Additional  = new Dictionary <string, object>
                        {
                            { "Author", f.CreateByString.HtmlEncode() },
                            { "Container", folderDao.GetParentFolders(f.ID) },
                            { "IsFolder", true }
                        }
                    });

                    return(folders.Concat(files).ToArray());
                }
        }
コード例 #12
0
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            try
            {
                if (context.Request.Files.Count == 0)
                {
                    throw new Exception("there is no file");
                }

                var file = context.Request.Files[0];

                if (file.ContentLength > SetupInfo.MaxImageUploadSize)
                {
                    throw FileSizeComment.FileImageSizeException;
                }

                var UserId   = context.Request["ownjid"];
                var FileName = file.FileName.Replace("~", "-");
                var FileURL  = String.Empty;
                var FileSize = file.InputStream.Length;
                //if (String.IsNullOrEmpty(UserId))
                //{
                //    throw new Exception("there is no userId");
                //}
                var FilePath = StorageFactory.GetStorage(TenantProvider.CurrentTenantID.ToString(), "talk").Save(Path.Combine(MD5Hash(UserId), FileName), file.InputStream);
                FileURL  = FilePath.ToString();
                FileName = FileURL.Substring(FileURL.LastIndexOf("/") + 1);
                return(new FileUploadResult
                {
                    FileName = FileName,
                    Data = FileSizeComment.FilesSizeToString(FileSize),
                    FileURL = CommonLinkUtility.GetFullAbsolutePath(FileURL),
                    Success = true
                });
            }
            catch (Exception ex)
            {
                return(new FileUploadResult()
                {
                    Success = false,
                    Message = ex.Message
                });
            }
        }
コード例 #13
0
        public override SearchResultItem[] Search(string text)
        {
            var security = Global.GetFilesSecurity();

            using (var folderDao = Global.DaoFactory.GetFolderDao())
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    var files = fileDao.Search(text, FolderType.USER | FolderType.COMMON)
                                .Where(security.CanRead)
                                .Select(r => new SearchResultItem
                    {
                        Name        = r.Title ?? string.Empty,
                        Description = string.Empty,
                        URL         = CommonLinkUtility.GetFileWebPreviewUrl(r.Title, r.ID),
                        Date        = r.ModifiedOn,
                        Additional  = new Dictionary <string, object>
                        {
                            { "Author", r.CreateByString.HtmlEncode() },
                            { "Path", FolderPathBuilder(EntryManager.GetBreadCrumbs(r.FolderID, folderDao)) },
                            { "Size", FileSizeComment.FilesSizeToString(r.ContentLength) }
                        }
                    });

                    var folders = folderDao.Search(text, FolderType.USER | FolderType.COMMON)
                                  .Where(security.CanRead)
                                  .Select(f => new SearchResultItem
                    {
                        Name        = f.Title ?? string.Empty,
                        Description = String.Empty,
                        URL         = PathProvider.GetFolderUrl(f),
                        Date        = f.ModifiedOn,
                        Additional  = new Dictionary <string, object>
                        {
                            { "Author", f.CreateByString.HtmlEncode() },
                            { "Path", FolderPathBuilder(EntryManager.GetBreadCrumbs(f.ID, folderDao)) },
                            { "IsFolder", true }
                        }
                    });

                    return(folders.Concat(files).ToArray());
                }
        }
コード例 #14
0
        private Tuple <string, string> GetPersonalTariffNotify()
        {
            var maxTotalSize = CoreContext.Configuration.PersonalMaxSpace;

            var webItem           = WebItemManager.Instance[WebItemManager.DocumentsProductID];
            var spaceUsageManager = webItem.Context.SpaceUsageStatManager as IUserSpaceUsage;

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

            var usedSize = spaceUsageManager.GetUserSpaceUsage(SecurityContext.CurrentAccount.ID);

            long notifySize;

            long.TryParse(ConfigurationManagerExtension.AppSettings["web.tariff-notify.storage"] ?? "104857600", out notifySize); //100 MB

            if (notifySize > 0 && maxTotalSize - usedSize < notifySize)
            {
                var head = string.Format(Resource.PersonalTariffExceedLimit, FileSizeComment.FilesSizeToString(maxTotalSize));

                string text;

                if (CoreContext.Configuration.CustomMode)
                {
                    text = string.Format(Resource.PersonalTariffExceedLimitInfoText, string.Empty, string.Empty, "</br>");
                }
                else
                {
                    var settings    = MailWhiteLabelSettings.Instance;
                    var supportLink = string.Format("<a target=\"_blank\" href=\"{0}\">", settings.SupportUrl);
                    text = string.Format(Resource.PersonalTariffExceedLimitInfoText, supportLink, "</a>", "</br>");
                }

                return(new Tuple <string, string>(head, text));
            }

            return(null);
        }
コード例 #15
0
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            try
            {
                if (context.Request.Files.Count == 0)
                {
                    throw new Exception("there is no file");
                }

                var file = context.Request.Files[0];

                if (file.ContentLength > SetupInfo.MaxImageUploadSize)
                {
                    throw FileSizeComment.FileImageSizeException;
                }

                var fileName = file.FileName.Replace("~", "-");
                var storage  = StorageFactory.GetStorage(TenantProvider.CurrentTenantID.ToString(CultureInfo.InvariantCulture), "talk");
                var md5Hash  = TalkSpaceUsageStatManager.GetUserMd5Hash(SecurityContext.CurrentAccount.ID);
                var fileUrl  = storage.Save(Path.Combine(md5Hash, GenerateRandomString(), fileName), file.InputStream).ToString();
                fileName = Path.GetFileName(fileUrl);

                return(new FileUploadResult
                {
                    FileName = fileName,
                    Data = FileSizeComment.FilesSizeToString(file.InputStream.Length),
                    FileURL = CommonLinkUtility.GetFullAbsolutePath(fileUrl),
                    Success = true
                });
            }
            catch (Exception ex)
            {
                return(new FileUploadResult
                {
                    Success = false,
                    Message = ex.Message
                });
            }
        }
コード例 #16
0
        private static string CreateConvertedFile(string driveFile, Token token)
        {
            var jsonFile = JObject.Parse(driveFile);
            var fileName = GetCorrectTitle(jsonFile);

            fileName = FileUtility.ReplaceFileExtension(fileName, FileUtility.GetInternalExtension(fileName));

            var folderId = (string)jsonFile.SelectToken("parents[0]");

            Global.Logger.Info("GoogleDriveApp: create copy - " + fileName);

            var ext    = GetCorrectExt(jsonFile);
            var fileId = jsonFile.Value <string>("id");

            if (GoogleLoginProvider.GoogleDriveExt.Contains(ext))
            {
                var fileType         = FileUtility.GetFileTypeByExtention(ext);
                var internalExt      = FileUtility.InternalExtension[fileType];
                var requiredMimeType = MimeMapping.GetMimeMapping(internalExt);

                var downloadUrl = GoogleLoginProvider.GoogleUrlFile
                                  + string.Format("{0}/export?mimeType={1}",
                                                  fileId,
                                                  HttpUtility.UrlEncode(requiredMimeType));

                var request = (HttpWebRequest)WebRequest.Create(downloadUrl);
                request.Method = "GET";
                request.Headers.Add("Authorization", "Bearer " + token);

                Global.Logger.Debug("GoogleDriveApp: download exportLink - " + downloadUrl);
                try
                {
                    using (var response = request.GetResponse())
                        using (var fileStream = new ResponseStream(response))
                        {
                            driveFile = CreateFile(fileStream, fileName, folderId, token);
                        }
                }
                catch (WebException e)
                {
                    Global.Logger.Error("GoogleDriveApp: Error download exportLink", e);
                    request.Abort();
                }
            }
            else
            {
                var downloadUrl = GoogleLoginProvider.GoogleUrlFile + fileId + "?alt=media";

                var convertedUrl = ConvertFile(downloadUrl, ext, token);

                if (string.IsNullOrEmpty(convertedUrl))
                {
                    Global.Logger.ErrorFormat("GoogleDriveApp: Error convertUrl. size {0}", FileSizeComment.FilesSizeToString(jsonFile.Value <int>("size")));
                    throw new Exception(FilesCommonResource.ErrorMassage_DocServiceException + " (convert)");
                }

                driveFile = CreateFile(convertedUrl, fileName, folderId, token);
            }

            jsonFile = JObject.Parse(driveFile);
            return(jsonFile.Value <string>("id"));
        }
コード例 #17
0
        private static Tuple <string, string> GetTariffNotify()
        {
            var tariff = TenantExtra.GetCurrentTariff();

            var count = tariff.DueDate.Date.Subtract(DateTime.Today).Days;

            if (tariff.State == TariffState.Trial)
            {
                if (count <= 5)
                {
                    var text = String.Format(CoreContext.Configuration.Standalone ? Resource.TariffLinkStandalone : Resource.TrialPeriodInfoText,
                                             "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>");

                    if (count <= 0)
                    {
                        return(new Tuple <string, string>(Resource.TrialPeriodExpired, text));
                    }

                    var end = GetNumeralResourceByCount(count, Resource.Day, Resource.DaysOne, Resource.DaysTwo);
                    return(new Tuple <string, string>(string.Format(Resource.TrialPeriod, count, end), text));
                }

                if (CoreContext.Configuration.Standalone)
                {
                    return(new Tuple <string, string>(Resource.TrialPeriodInfoTextLicense, string.Empty));
                }
            }

            if (tariff.State == TariffState.Paid)
            {
                if (CoreContext.Configuration.Standalone && count < 10)
                {
                    var text = String.Format(Resource.TariffLinkStandalone,
                                             "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>");
                    if (count <= 0)
                    {
                        return(new Tuple <string, string>(Resource.PaidPeriodExpiredStandalone, text));
                    }

                    var end = GetNumeralResourceByCount(count, Resource.Day, Resource.DaysOne, Resource.DaysTwo);
                    return(new Tuple <string, string>(string.Format(Resource.PaidPeriodStandalone, count, end), text));
                }

                var  quota = TenantExtra.GetTenantQuota();
                long notifySize;
                long.TryParse(ConfigurationManager.AppSettings["web.tariff-notify.storage"] ?? "314572800", out notifySize); //300 MB
                if (notifySize > 0 && quota.MaxTotalSize - TenantStatisticsProvider.GetUsedSize() < notifySize)
                {
                    var head = string.Format(Resource.TariffExceedLimit, FileSizeComment.FilesSizeToString(quota.MaxTotalSize));
                    var text = String.Format(Resource.TariffExceedLimitInfoText, "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>");
                    return(new Tuple <string, string>(head, text));
                }
            }

            if (tariff.State == TariffState.Delay)
            {
                var text = String.Format(Resource.TariffPaymentDelayText,
                                         "<a href=\"" + TenantExtra.GetTariffPageLink() + "\">", "</a>",
                                         tariff.DelayDueDate.Date.ToLongDateString());
                return(new Tuple <string, string>(Resource.TariffPaymentDelay, text));
            }

            return(null);
        }
コード例 #18
0
        private void MoveOrCopyFiles(ICollection fileIds, Folder toFolder, bool copy)
        {
            if (fileIds.Count == 0)
            {
                return;
            }

            var toFolderId = toFolder.ID;

            foreach (var fileId in fileIds)
            {
                CancellationToken.ThrowIfCancellationRequested();

                var file = FileDao.GetFile(fileId);
                if (file == null)
                {
                    Error = FilesCommonResource.ErrorMassage_FileNotFound;
                }
                else if (!FilesSecurity.CanRead(file))
                {
                    Error = FilesCommonResource.ErrorMassage_SecurityException_ReadFile;
                }
                else if (Global.EnableUploadFilter &&
                         !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(file.Title)))
                {
                    Error = FilesCommonResource.ErrorMassage_NotSupportedFormat;
                }
                else if (file.ContentLength > SetupInfo.AvailableFileSize &&
                         file.ProviderId != toFolder.ProviderId)
                {
                    Error = string.Format(copy ? FilesCommonResource.ErrorMassage_FileSizeCopy : FilesCommonResource.ErrorMassage_FileSizeMove,
                                          FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize));
                }
                else
                {
                    var parentFolder = FolderDao.GetFolder(file.FolderID);
                    try
                    {
                        var conflict = resolveType == FileConflictResolveType.Duplicate
                                           ? null
                                           : FileDao.GetFile(toFolderId, file.Title);
                        if (conflict != null && !FilesSecurity.CanEdit(conflict))
                        {
                            Error = FilesCommonResource.ErrorMassage_SecurityException;
                        }
                        else if (conflict != null && EntryManager.FileLockedForMe(conflict.ID))
                        {
                            Error = FilesCommonResource.ErrorMassage_LockedFile;
                        }
                        else if (conflict == null)
                        {
                            if (copy)
                            {
                                File newFile = null;
                                try
                                {
                                    newFile = FileDao.CopyFile(file.ID, toFolderId); //Stream copy will occur inside dao
                                    FilesMessageService.Send(file, toFolder, headers, MessageAction.FileCopied, file.Title, parentFolder.Title, toFolder.Title);

                                    if (Equals(newFile.FolderID.ToString(), this.toFolderId))
                                    {
                                        needToMark.Add(newFile);
                                    }

                                    if (ProcessedFile(fileId))
                                    {
                                        Status += string.Format("file_{0}{1}", newFile.ID, SPLIT_CHAR);
                                    }
                                }
                                catch
                                {
                                    if (newFile != null)
                                    {
                                        FileDao.DeleteFile(newFile.ID);
                                    }
                                    throw;
                                }
                            }
                            else
                            {
                                if (EntryManager.FileLockedForMe(file.ID))
                                {
                                    Error = FilesCommonResource.ErrorMassage_LockedFile;
                                }
                                else if (FileTracker.IsEditing(file.ID))
                                {
                                    Error = FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile;
                                }
                                else if (FilesSecurity.CanDelete(file))
                                {
                                    FileMarker.RemoveMarkAsNewForAll(file);

                                    var newFileId = FileDao.MoveFile(file.ID, toFolderId);
                                    FilesMessageService.Send(file, toFolder, headers, MessageAction.FileMoved, file.Title, parentFolder.Title, toFolder.Title);

                                    if (Equals(toFolderId.ToString(), this.toFolderId))
                                    {
                                        needToMark.Add(FileDao.GetFile(newFileId));
                                    }

                                    if (ProcessedFile(fileId))
                                    {
                                        Status += string.Format("file_{0}{1}", newFileId, SPLIT_CHAR);
                                    }
                                }
                                else
                                {
                                    Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFile;
                                }
                            }
                        }
                        else
                        {
                            if (resolveType == FileConflictResolveType.Overwrite)
                            {
                                if (EntryManager.FileLockedForMe(conflict.ID))
                                {
                                    Error = FilesCommonResource.ErrorMassage_LockedFile;
                                }
                                else if (FileTracker.IsEditing(conflict.ID))
                                {
                                    Error = FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile;
                                }
                                else
                                {
                                    var newFile = conflict;
                                    newFile.Version++;
                                    newFile.ContentLength = conflict.ContentLength;

                                    using (var stream = FileDao.GetFileStream(file))
                                    {
                                        newFile = FileDao.SaveFile(newFile, stream);
                                    }

                                    needToMark.Add(newFile);

                                    if (copy)
                                    {
                                        FilesMessageService.Send(file, toFolder, headers, MessageAction.FileCopiedWithOverwriting, file.Title, parentFolder.Title, toFolder.Title);
                                        if (ProcessedFile(fileId))
                                        {
                                            Status += string.Format("file_{0}{1}", newFile.ID, SPLIT_CHAR);
                                        }
                                    }
                                    else
                                    {
                                        if (Equals(file.FolderID.ToString(), toFolderId.ToString()))
                                        {
                                            if (ProcessedFile(fileId))
                                            {
                                                Status += string.Format("file_{0}{1}", newFile.ID, SPLIT_CHAR);
                                            }
                                        }
                                        else
                                        {
                                            if (EntryManager.FileLockedForMe(file.ID))
                                            {
                                                Error = FilesCommonResource.ErrorMassage_LockedFile;
                                            }
                                            else if (FileTracker.IsEditing(file.ID))
                                            {
                                                Error = FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile;
                                            }
                                            else if (FilesSecurity.CanDelete(file))
                                            {
                                                FileDao.DeleteFile(file.ID);
                                                FileDao.DeleteFolder(file.ID);

                                                FilesMessageService.Send(file, toFolder, headers, MessageAction.FileMovedWithOverwriting, file.Title, parentFolder.Title, toFolder.Title);

                                                if (ProcessedFile(fileId))
                                                {
                                                    Status += string.Format("file_{0}{1}", newFile.ID, SPLIT_CHAR);
                                                }
                                            }
                                            else
                                            {
                                                Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFile;
                                            }
                                        }
                                    }
                                }
                            }
                            else if (resolveType == FileConflictResolveType.Skip)
                            {
                                //nothing
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Error = ex.Message;
                        Logger.Error(Error, ex);
                    }
                }
                ProgressStep(fileId: FolderDao.CanCalculateSubitems(fileId) ? null : fileId);
            }
        }
コード例 #19
0
        public File <TTo> PerformCrossDaoFileCopy <TFrom, TTo>(
            TFrom fromFileId, IFileDao <TFrom> fromFileDao, Func <TFrom, TFrom> fromConverter,
            TTo toFolderId, IFileDao <TTo> toFileDao, Func <TTo, TTo> toConverter,
            bool deleteSourceFile)
        {
            //Get File from first dao
            var fromFile = fromFileDao.GetFile(fromConverter(fromFileId));

            if (fromFile.ContentLength > SetupInfo.AvailableFileSize)
            {
                throw new Exception(string.Format(deleteSourceFile ? FilesCommonResource.ErrorMassage_FileSizeMove : FilesCommonResource.ErrorMassage_FileSizeCopy,
                                                  FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
            }

            var securityDao = ServiceProvider.GetService <SecurityDao <TFrom> >();
            var tagDao      = ServiceProvider.GetService <TagDao <TFrom> >();

            var fromFileShareRecords = securityDao.GetPureShareRecords(fromFile).Where(x => x.EntryType == FileEntryType.File);
            var fromFileNewTags      = tagDao.GetNewTags(Guid.Empty, fromFile).ToList();
            var fromFileLockTag      = tagDao.GetTags(fromFile.ID, FileEntryType.File, TagType.Locked).FirstOrDefault();
            var fromFileFavoriteTag  = tagDao.GetTags(fromFile.ID, FileEntryType.File, TagType.Favorite);
            var fromFileTemplateTag  = tagDao.GetTags(fromFile.ID, FileEntryType.File, TagType.Template);

            var toFile = ServiceProvider.GetService <File <TTo> >();

            toFile.Title     = fromFile.Title;
            toFile.Encrypted = fromFile.Encrypted;
            toFile.FolderID  = toConverter(toFolderId);

            fromFile.ID = fromConverter(fromFile.ID);

            var mustConvert = !string.IsNullOrEmpty(fromFile.ConvertedType);

            using (var fromFileStream = mustConvert
                                            ? FileConverter.Exec(fromFile)
                                            : fromFileDao.GetFileStream(fromFile))
            {
                toFile.ContentLength = fromFileStream.CanSeek ? fromFileStream.Length : fromFile.ContentLength;
                toFile = toFileDao.SaveFile(toFile, fromFileStream);
            }

            if (deleteSourceFile)
            {
                if (fromFileShareRecords.Any())
                {
                    fromFileShareRecords.ToList().ForEach(x =>
                    {
                        x.EntryId = toFile.ID;
                        securityDao.SetShare(x);
                    });
                }

                var fromFileTags = fromFileNewTags;
                if (fromFileLockTag != null)
                {
                    fromFileTags.Add(fromFileLockTag);
                }
                if (fromFileFavoriteTag != null)
                {
                    fromFileTags.AddRange(fromFileFavoriteTag);
                }
                if (fromFileTemplateTag != null)
                {
                    fromFileTags.AddRange(fromFileTemplateTag);
                }

                if (fromFileTags.Any())
                {
                    fromFileTags.ForEach(x => x.EntryId = toFile.ID);

                    tagDao.SaveTags(fromFileTags);
                }

                //Delete source file if needed
                fromFileDao.DeleteFile(fromConverter(fromFileId));
            }
            return(toFile);
        }
コード例 #20
0
        private Stream CompressToZip(IServiceScope scope, ItemNameValueCollection entriesPathId)
        {
            var setupInfo           = scope.ServiceProvider.GetService <SetupInfo>();
            var fileConverter       = scope.ServiceProvider.GetService <FileConverter>();
            var filesMessageService = scope.ServiceProvider.GetService <FilesMessageService>();

            var stream = TempStream.Create();

            using (var zip = new ZipOutputStream(stream, true))
            {
                zip.CompressionLevel       = Ionic.Zlib.CompressionLevel.Level3;
                zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.AsNecessary;
                zip.AlternateEncoding      = Encoding.UTF8;

                foreach (var path in entriesPathId.AllKeys)
                {
                    var counter = 0;
                    foreach (var entryId in entriesPathId[path])
                    {
                        if (CancellationToken.IsCancellationRequested)
                        {
                            zip.Dispose();
                            stream.Dispose();
                            CancellationToken.ThrowIfCancellationRequested();
                        }

                        var newtitle = path;

                        File file         = null;
                        var  convertToExt = string.Empty;

                        if (!string.IsNullOrEmpty(entryId))
                        {
                            FileDao.InvalidateCache(entryId);
                            file = FileDao.GetFile(entryId);

                            if (file == null)
                            {
                                Error = FilesCommonResource.ErrorMassage_FileNotFound;
                                continue;
                            }

                            if (file.ContentLength > setupInfo.AvailableFileSize)
                            {
                                Error = string.Format(FilesCommonResource.ErrorMassage_FileSizeZip, FileSizeComment.FilesSizeToString(setupInfo.AvailableFileSize));
                                continue;
                            }

                            if (files.ContainsKey(file.ID.ToString()))
                            {
                                convertToExt = files[file.ID.ToString()];
                                if (!string.IsNullOrEmpty(convertToExt))
                                {
                                    newtitle = FileUtility.ReplaceFileExtension(path, convertToExt);
                                }
                            }
                        }

                        if (0 < counter)
                        {
                            var suffix = " (" + counter + ")";

                            if (!string.IsNullOrEmpty(entryId))
                            {
                                newtitle = 0 < newtitle.IndexOf('.') ? newtitle.Insert(newtitle.LastIndexOf('.'), suffix) : newtitle + suffix;
                            }
                            else
                            {
                                break;
                            }
                        }

                        zip.PutNextEntry(newtitle);

                        if (!string.IsNullOrEmpty(entryId) && file != null)
                        {
                            try
                            {
                                if (fileConverter.EnableConvert(file, convertToExt))
                                {
                                    //Take from converter
                                    using (var readStream = fileConverter.Exec(file, convertToExt))
                                    {
                                        readStream.StreamCopyTo(zip);
                                        if (!string.IsNullOrEmpty(convertToExt))
                                        {
                                            filesMessageService.Send(file, headers, MessageAction.FileDownloadedAs, file.Title, convertToExt);
                                        }
                                        else
                                        {
                                            filesMessageService.Send(file, headers, MessageAction.FileDownloaded, file.Title);
                                        }
                                    }
                                }
                                else
                                {
                                    using var readStream = FileDao.GetFileStream(file);
                                    readStream.StreamCopyTo(zip);
                                    filesMessageService.Send(file, headers, MessageAction.FileDownloaded, file.Title);
                                }
                            }
                            catch (Exception ex)
                            {
                                Error = ex.Message;
                                Logger.Error(Error, ex);
                            }
                        }
                        counter++;
                    }

                    ProgressStep();
                }
            }
            return(stream);
        }
コード例 #21
0
        private void CheckConvertFilesStatus(object _)
        {
            if (Monitor.TryEnter(singleThread))
            {
                using var scope = ServiceProvider.CreateScope();
                var logger          = scope.ServiceProvider.GetService <IOptionsMonitor <ILog> >().CurrentValue;
                var tenantManager   = scope.ServiceProvider.GetService <TenantManager>();
                var userManager     = scope.ServiceProvider.GetService <UserManager>();
                var securityContext = scope.ServiceProvider.GetService <SecurityContext>();
                var daoFactory      = scope.ServiceProvider.GetService <IDaoFactory>();

                try
                {
                    List <File> filesIsConverting;
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);

                        conversionQueue.Where(x => !string.IsNullOrEmpty(x.Value.Processed) &&
                                              (x.Value.Progress == 100 && DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(1) ||
                                               DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(10)))
                        .ToList()
                        .ForEach(x =>
                        {
                            conversionQueue.Remove(x);
                            cache.Remove(GetKey(x.Key));
                        });

                        logger.DebugFormat("Run CheckConvertFilesStatus: count {0}", conversionQueue.Count);

                        if (conversionQueue.Count == 0)
                        {
                            return;
                        }

                        filesIsConverting = conversionQueue
                                            .Where(x => string.IsNullOrEmpty(x.Value.Processed))
                                            .Select(x => x.Key)
                                            .ToList();
                    }

                    var fileSecurity = FileSecurity;
                    foreach (var file in filesIsConverting)
                    {
                        var    fileUri = file.ID.ToString();
                        string convertedFileUrl;
                        int    operationResultProgress;

                        try
                        {
                            int      tenantId;
                            IAccount account;
                            string   password;

                            lock (locker)
                            {
                                if (!conversionQueue.Keys.Contains(file))
                                {
                                    continue;
                                }

                                var operationResult = conversionQueue[file];
                                if (!string.IsNullOrEmpty(operationResult.Processed))
                                {
                                    continue;
                                }

                                operationResult.Processed = "1";
                                tenantId = operationResult.TenantId;
                                account  = operationResult.Account;
                                password = operationResult.Password;

                                //if (HttpContext.Current == null && !WorkContext.IsMono)
                                //{
                                //    HttpContext.Current = new HttpContext(
                                //        new HttpRequest("hack", operationResult.Url, string.Empty),
                                //        new HttpResponse(new StringWriter()));
                                //}

                                cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                            }

                            tenantManager.SetCurrentTenant(tenantId);
                            securityContext.AuthenticateMe(account);

                            var user    = userManager.GetUsers(account.ID);
                            var culture = string.IsNullOrEmpty(user.CultureName) ? TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName);
                            Thread.CurrentThread.CurrentCulture   = culture;
                            Thread.CurrentThread.CurrentUICulture = culture;

                            if (!fileSecurity.CanRead(file) && file.RootFolderType != FolderType.BUNCH)
                            {
                                //No rights in CRM after upload before attach
                                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                            }
                            if (file.ContentLength > SetupInfo.AvailableFileSize)
                            {
                                throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
                            }

                            fileUri = PathProvider.GetFileStreamUrl(file);

                            var toExtension   = FileUtility.GetInternalExtension(file.Title);
                            var fileExtension = file.ConvertedExtension;
                            var docKey        = DocumentServiceHelper.GetDocKey(file);

                            fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri);
                            operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, password, true, out convertedFileUrl);
                        }
                        catch (Exception exception)
                        {
                            var password = exception.InnerException != null &&
                                           (exception.InnerException is DocumentService.DocumentServiceException documentServiceException) &&
                                           documentServiceException.Code == DocumentService.DocumentServiceException.ErrorCode.ConvertPassword;

                            logger.Error(string.Format("Error convert {0} with url {1}", file.ID, fileUri), exception);
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    if (operationResult.Delete)
                                    {
                                        conversionQueue.Remove(file);
                                        cache.Remove(GetKey(file));
                                    }
                                    else
                                    {
                                        operationResult.Progress     = 100;
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Error        = exception.Message;
                                        if (password)
                                        {
                                            operationResult.Result = "password";
                                        }
                                        cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                    }
                                }
                            }
                            continue;
                        }

                        operationResultProgress = Math.Min(operationResultProgress, 100);
                        if (operationResultProgress < 100)
                        {
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];

                                    if (DateTime.Now - operationResult.StartDateTime > TimeSpan.FromMinutes(10))
                                    {
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Error        = FilesCommonResource.ErrorMassage_ConvertTimeout;
                                        logger.ErrorFormat("CheckConvertFilesStatus timeout: {0} ({1})", file.ID, file.ContentLengthString);
                                    }
                                    else
                                    {
                                        operationResult.Processed = "";
                                    }
                                    operationResult.Progress = operationResultProgress;
                                    cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                }
                            }

                            logger.Debug("CheckConvertFilesStatus iteration continue");
                            continue;
                        }

                        File newFile = null;
                        var  operationResultError = string.Empty;

                        try
                        {
                            newFile = SaveConvertedFile(file, convertedFileUrl);
                        }
                        catch (Exception e)
                        {
                            operationResultError = e.Message;

                            logger.ErrorFormat("{0} ConvertUrl: {1} fromUrl: {2}: {3}", operationResultError, convertedFileUrl, fileUri, e);
                            continue;
                        }
                        finally
                        {
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    if (operationResult.Delete)
                                    {
                                        conversionQueue.Remove(file);
                                        cache.Remove(GetKey(file));
                                    }
                                    else
                                    {
                                        if (newFile != null)
                                        {
                                            var folderDao   = daoFactory.FolderDao;
                                            var folder      = folderDao.GetFolder(newFile.FolderID);
                                            var folderTitle = fileSecurity.CanRead(folder) ? folder.Title : null;
                                            operationResult.Result = FileJsonSerializer(newFile, folderTitle);
                                        }

                                        operationResult.Progress     = 100;
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Processed    = "1";
                                        if (!string.IsNullOrEmpty(operationResultError))
                                        {
                                            operationResult.Error = operationResultError;
                                        }
                                        cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                    }
                                }
                            }
                        }

                        logger.Debug("CheckConvertFilesStatus iteration end");
                    }

                    lock (locker)
                    {
                        timer.Change(TIMER_PERIOD, TIMER_PERIOD);
                    }
                }
                catch (Exception exception)
                {
                    logger.Error(exception.Message, exception);
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);
                    }
                }
                finally
                {
                    Monitor.Exit(singleThread);
                }
            }
        }
コード例 #22
0
        public Stream Exec(File file, string toExtension)
        {
            if (!EnableConvert(file, toExtension))
            {
                var fileDao = DaoFactory.FileDao;
                return(fileDao.GetFileStream(file));
            }

            if (file.ContentLength > SetupInfo.AvailableFileSize)
            {
                throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
            }

            var fileUri = PathProvider.GetFileStreamUrl(file);
            var docKey  = DocumentServiceHelper.GetDocKey(file);

            fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri);
            DocumentServiceConnector.GetConvertedUri(fileUri, file.ConvertedExtension, toExtension, docKey, null, false, out var convertUri);

            if (WorkContext.IsMono && ServicePointManager.ServerCertificateValidationCallback == null)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, c, n, p) => true; //HACK: http://ubuntuforums.org/showthread.php?t=1841740
            }
            return(new ResponseStream(((HttpWebRequest)WebRequest.Create(convertUri)).GetResponse()));
        }
コード例 #23
0
        private static void CheckConvertFilesStatus(Object obj)
        {
            lock (LockerTimer)
            {
                _timer.Change(Timeout.Infinite, Timeout.Infinite);
            }
            try
            {
                List <File> filesIsConverting;

                lock (LockerStatus)
                {
                    ConversionFileStatus.Where(x => ((!String.IsNullOrEmpty(x.Value.Processed) &&
                                                      DateTime.Now.Subtract(x.Value.StopDateTime) > TimeSpan.FromMinutes(30))))
                    .ToList().ForEach(x => ConversionFileStatus.Remove(x));

                    filesIsConverting = ConversionFileStatus.Where(x => String.IsNullOrEmpty(x.Value.Processed)).Select(x => x.Key).ToList();
                }

                if (filesIsConverting.Count == 0)
                {
                    lock (LockerTimer)
                    {
                        _timer.Dispose();
                        _timer = null;
                    }
                    return;
                }

                foreach (var file in filesIsConverting)
                {
                    var    fileUri = file.ID.ToString();
                    string convetedFileUrl;
                    int    operationResultProgress;
                    object folderId;
                    var    currentFolder = false;

                    try
                    {
                        int      tenantId;
                        IAccount account;

                        lock (LockerStatus)
                        {
                            var operationResult = ConversionFileStatus[file];
                            if (operationResult == null)
                            {
                                continue;
                            }
                            tenantId = operationResult.TenantId;
                            account  = operationResult.Account;
                        }

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

                        var user    = CoreContext.UserManager.GetUsers(account.ID);
                        var culture = string.IsNullOrEmpty(user.CultureName)
                                          ? CoreContext.TenantManager.GetCurrentTenant().GetCulture()
                                          : CultureInfo.GetCultureInfo(user.CultureName);
                        Thread.CurrentThread.CurrentCulture   = culture;
                        Thread.CurrentThread.CurrentUICulture = culture;

                        var fileSecurity = Global.GetFilesSecurity();
                        if (!fileSecurity.CanRead(file) &&
                            file.RootFolderType != FolderType.BUNCH)    //No rights in CRM after upload before attach
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                        }
                        if (file.ContentLength > SetupInfo.AvailableFileSize)
                        {
                            throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
                        }

                        folderId = Global.FolderMy;
                        using (var folderDao = Global.DaoFactory.GetFolderDao())
                        {
                            var parent = folderDao.GetFolder(file.FolderID);
                            if (parent != null &&
                                fileSecurity.CanCreate(parent))
                            {
                                folderId      = parent.ID;
                                currentFolder = true;
                            }
                        }
                        if (Equals(folderId, 0))
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_FolderNotFound);
                        }

                        fileUri = PathProvider.GetFileStreamUrl(file);

                        var toExtension   = FileUtility.GetInternalExtension(file.Title);
                        var fileExtension = file.ConvertedType ?? FileUtility.GetFileExtension(file.Title);
                        var docKey        = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn);

                        operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, true, out convetedFileUrl);
                    }
                    catch (Exception exception)
                    {
                        lock (LockerStatus)
                        {
                            var operationResult = ConversionFileStatus[file];
                            if (operationResult != null)
                            {
                                if (operationResult.Delete)
                                {
                                    ConversionFileStatus.Remove(file);
                                }
                                else
                                {
                                    operationResult.Result       = FileJsonSerializer(file);
                                    operationResult.Processed    = "1";
                                    operationResult.StopDateTime = DateTime.Now;
                                    operationResult.Error        = exception.Message;
                                }
                            }
                        }

                        var strExc = exception.Message + " in file " + fileUri;
                        Global.Logger.Error(strExc, exception);

                        continue;
                    }

                    if (operationResultProgress < 100)
                    {
                        lock (LockerStatus)
                        {
                            var operationResult = ConversionFileStatus[file];
                            if (operationResult != null)
                            {
                                operationResult.Progress = operationResultProgress;
                            }
                        }
                        continue;
                    }

                    using (var fileDao = Global.DaoFactory.GetFileDao())
                        using (var folderDao = Global.DaoFactory.GetFolderDao())
                        {
                            var newFileTitle = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetInternalExtension(file.Title));

                            File newFile = null;
                            if (FilesSettings.UpdateIfExist && (!currentFolder || !file.ProviderEntry))
                            {
                                newFile = fileDao.GetFile(folderId, newFileTitle);
                                if (newFile != null &&
                                    Global.GetFilesSecurity().CanEdit(newFile) &&
                                    !EntryManager.FileLockedForMe(newFile.ID) &&
                                    !FileTracker.IsEditing(newFile.ID))
                                {
                                    newFile.Version++;
                                }
                                else
                                {
                                    newFile = null;
                                }
                            }

                            if (newFile == null)
                            {
                                newFile = new File {
                                    FolderID = folderId
                                }
                            }
                            ;

                            newFile.Title         = newFileTitle;
                            newFile.ConvertedType = FileUtility.GetInternalExtension(file.Title);

                            var operationResultError = string.Empty;
                            try
                            {
                                var req = (HttpWebRequest)WebRequest.Create(convetedFileUrl);

                                using (var convertedFileStream = new ResponseStream(req.GetResponse()))
                                {
                                    newFile.ContentLength = convertedFileStream.Length;
                                    newFile.Comment       = string.Empty;
                                    newFile = fileDao.SaveFile(newFile, convertedFileStream);
                                }

                                FileMarker.MarkAsNew(newFile);

                                using (var tagDao = Global.DaoFactory.GetTagDao())
                                {
                                    var tags = tagDao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList();
                                    if (tags.Any())
                                    {
                                        tags.ForEach(r => r.EntryId = newFile.ID);
                                        tagDao.SaveTags(tags.ToArray());
                                    }
                                }

                                operationResultProgress = 100;
                            }
                            catch (WebException e)
                            {
                                using (var response = e.Response)
                                {
                                    var httpResponse = (HttpWebResponse)response;
                                    var errorString  = String.Format("Error code: {0}", httpResponse.StatusCode);

                                    if (httpResponse.StatusCode != HttpStatusCode.NotFound)
                                    {
                                        using (var data = response.GetResponseStream())
                                        {
                                            var text = new StreamReader(data).ReadToEnd();
                                            errorString += String.Format(" Error message: {0}", text);
                                        }
                                    }

                                    operationResultError = errorString;

                                    Global.Logger.Error(errorString + "  ConvertUrl : " + convetedFileUrl + "    fromUrl : " + fileUri, e);
                                    throw new Exception(errorString);
                                }
                            }
                            finally
                            {
                                var fileSecurity   = Global.GetFilesSecurity();
                                var removeOriginal = !FilesSettings.StoreOriginalFiles &&
                                                     fileSecurity.CanDelete(file) &&
                                                     currentFolder &&
                                                     !EntryManager.FileLockedForMe(file.ID);

                                var folderTitle = folderDao.GetFolder(newFile.FolderID).Title;

                                lock (LockerStatus)
                                {
                                    var operationResult = ConversionFileStatus[file];

                                    if (operationResult.Delete)
                                    {
                                        ConversionFileStatus.Remove(file);
                                    }
                                    else
                                    {
                                        operationResult.Result       = FileJsonSerializer(newFile, removeOriginal, folderTitle);
                                        operationResult.Processed    = "1";
                                        operationResult.StopDateTime = DateTime.Now;
                                        operationResult.Progress     = operationResultProgress;
                                        if (!string.IsNullOrEmpty(operationResultError))
                                        {
                                            operationResult.Error = operationResultError;
                                        }
                                    }
                                }

                                if (removeOriginal)
                                {
                                    FileMarker.RemoveMarkAsNewForAll(file);
                                    fileDao.DeleteFile(file.ID);
                                }
                            }
                        }
                }

                lock (LockerTimer)
                {
                    _timer.Change(0, TimerConvertPeriod);
                }
            }
            catch (Exception exception)
            {
                Global.Logger.Error(exception.Message, exception);
                lock (LockerTimer)
                {
                    _timer.Dispose();
                    _timer = null;
                }
            }
        }
コード例 #24
0
        public static Stream Exec(File file, string toExtension)
        {
            if (file.ContentLength > SetupInfo.AvailableFileSize)
            {
                throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
            }

            var fileExtension = file.ConvertedExtension;

            var requiredFormat = fileExtension.Trim('.').Equals(toExtension.Trim('.'), StringComparison.OrdinalIgnoreCase);

            if (!EnableConvert(file, toExtension) ||
                requiredFormat)
            {
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    return(fileDao.GetFileStream(file));
                }
            }

            var fileUri = PathProvider.GetFileStreamUrl(file);

            var docKey = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn);

            string convertUri;

            DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, false, out convertUri);

            return(new ResponseStream(WebRequest.Create(convertUri).GetResponse()));
        }
コード例 #25
0
        private static string CreateConvertedFile(string driveFile, Token token)
        {
            var jsonFile = JObject.Parse(driveFile);
            var fileName = GetCorrectTitle(jsonFile);

            fileName = FileUtility.ReplaceFileExtension(fileName, FileUtility.GetInternalExtension(fileName));

            var folderId = (string)jsonFile.SelectToken("parents[0].id");

            Global.Logger.Info("GoogleDriveApp: create copy - " + fileName);

            var ext = GetCorrectExt(jsonFile);

            if (GoogleLoginProvider.GoogleDriveExt.Contains(ext))
            {
                var links = jsonFile["exportLinks"];
                if (links == null)
                {
                    Global.Logger.Error("GoogleDriveApp: exportLinks is null");
                    throw new Exception("exportLinks is null");
                }

                var fileType         = FileUtility.GetFileTypeByExtention(ext);
                var internalExt      = FileUtility.InternalExtension[fileType];
                var requiredMimeType = MimeMapping.GetMimeMapping(internalExt);

                var exportLinks = links.ToObject <Dictionary <string, string> >();
                var downloadUrl = exportLinks[requiredMimeType] ?? "";

                if (string.IsNullOrEmpty(downloadUrl))
                {
                    Global.Logger.Error("GoogleDriveApp: exportLinks without requested mime - " + links);
                    throw new Exception("exportLinks without requested mime");
                }


                var request = (HttpWebRequest)WebRequest.Create(downloadUrl);
                request.Method = "GET";
                request.Headers.Add("Authorization", "Bearer " + token);

                Global.Logger.Debug("GoogleDriveApp: download exportLink - " + downloadUrl);
                try
                {
                    using (var response = request.GetResponse())
                        using (var fileStream = new ResponseStream(response))
                        {
                            driveFile = CreateFile(fileStream, fileName, folderId, token);
                        }
                }
                catch (WebException e)
                {
                    Global.Logger.Error("GoogleDriveApp: Error download exportLink", e);
                    request.Abort();

                    var httpResponse = (HttpWebResponse)e.Response;
                    if (httpResponse.StatusCode == HttpStatusCode.Unauthorized && fileType == FileType.Spreadsheet)
                    {
                        throw new SecurityException(FilesCommonResource.AppDriveSpreadsheetException, e);
                    }
                }
            }
            else
            {
                var downloadUrl = jsonFile.Value <string>("downloadUrl");

                var convertedUrl = ConvertFile(downloadUrl, ext, token);

                if (string.IsNullOrEmpty(convertedUrl))
                {
                    Global.Logger.ErrorFormat("GoogleDriveApp: Error convertUrl. FileSize {0}", FileSizeComment.FilesSizeToString(jsonFile.Value <int>("fileSize")));
                    throw new Exception(FilesCommonResource.ErrorMassage_DocServiceException + " (convert)");
                }

                driveFile = CreateFile(convertedUrl, fileName, folderId, token);
            }

            jsonFile = JObject.Parse(driveFile);
            return(jsonFile.Value <string>("id"));
        }
コード例 #26
0
 protected String GetMaxTotalSpace()
 {
     return(FileSizeComment.FilesSizeToString(TenantExtra.GetTenantQuota().MaxTotalSize));
 }
コード例 #27
0
        public File <T> GetParams <T>(File <T> file, bool lastVersion, FileShare linkRight, bool rightToRename, bool rightToEdit, bool editPossible, bool tryEdit, bool tryCoauth, out Configuration <T> configuration)
        {
            if (file == null)
            {
                throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
            }
            if (!string.IsNullOrEmpty(file.Error))
            {
                throw new Exception(file.Error);
            }

            var rightToReview  = rightToEdit;
            var reviewPossible = editPossible;

            var rightToFillForms  = rightToEdit;
            var fillFormsPossible = editPossible;

            var rightToComment  = rightToEdit;
            var commentPossible = editPossible;

            var rightModifyFilter = rightToEdit;

            if (linkRight == FileShare.Restrict && UserManager.GetUsers(AuthContext.CurrentAccount.ID).IsVisitor(UserManager))
            {
                rightToEdit      = false;
                rightToReview    = false;
                rightToFillForms = false;
                rightToComment   = false;
            }

            var fileSecurity = FileSecurity;

            rightToEdit = rightToEdit &&
                          (linkRight == FileShare.ReadWrite || linkRight == FileShare.CustomFilter ||
                           fileSecurity.CanEdit(file) || fileSecurity.CanCustomFilterEdit(file));
            if (editPossible && !rightToEdit)
            {
                editPossible = false;
            }

            rightModifyFilter = rightModifyFilter &&
                                (linkRight == FileShare.ReadWrite ||
                                 fileSecurity.CanEdit(file));

            rightToRename = rightToRename && rightToEdit && fileSecurity.CanEdit(file);

            rightToReview = rightToReview &&
                            (linkRight == FileShare.Review || linkRight == FileShare.ReadWrite ||
                             fileSecurity.CanReview(file));
            if (reviewPossible && !rightToReview)
            {
                reviewPossible = false;
            }

            rightToFillForms = rightToFillForms &&
                               (linkRight == FileShare.FillForms || linkRight == FileShare.Review || linkRight == FileShare.ReadWrite ||
                                fileSecurity.CanFillForms(file));
            if (fillFormsPossible && !rightToFillForms)
            {
                fillFormsPossible = false;
            }

            rightToComment = rightToComment &&
                             (linkRight == FileShare.Comment || linkRight == FileShare.Review || linkRight == FileShare.ReadWrite ||
                              fileSecurity.CanComment(file));
            if (commentPossible && !rightToComment)
            {
                commentPossible = false;
            }

            if (linkRight == FileShare.Restrict &&
                !(editPossible || reviewPossible || fillFormsPossible || commentPossible) &&
                !fileSecurity.CanRead(file))
            {
                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
            }

            if (file.RootFolderType == FolderType.TRASH)
            {
                throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
            }

            if (file.ContentLength > SetupInfo.AvailableFileSize)
            {
                throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeEdit, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
            }

            string strError = null;

            if ((editPossible || reviewPossible || fillFormsPossible || commentPossible) &&
                LockerManager.FileLockedForMe(file.ID))
            {
                if (tryEdit)
                {
                    strError = FilesCommonResource.ErrorMassage_LockedFile;
                }
                rightToRename    = false;
                rightToEdit      = editPossible = false;
                rightToReview    = reviewPossible = false;
                rightToFillForms = fillFormsPossible = false;
                rightToComment   = commentPossible = false;
            }

            if (editPossible &&
                !FileUtility.CanWebEdit(file.Title))
            {
                rightToEdit = editPossible = false;
            }

            if (file.Encrypted &&
                file.RootFolderType != FolderType.Privacy)
            {
                rightToEdit      = editPossible = false;
                rightToReview    = reviewPossible = false;
                rightToFillForms = fillFormsPossible = false;
                rightToComment   = commentPossible = false;
            }


            if (!editPossible && !FileUtility.CanWebView(file.Title))
            {
                throw new Exception(string.Format("{0} ({1})", FilesCommonResource.ErrorMassage_NotSupportedFormat, FileUtility.GetFileExtension(file.Title)));
            }

            if (reviewPossible &&
                !FileUtility.CanWebReview(file.Title))
            {
                rightToReview = reviewPossible = false;
            }

            if (fillFormsPossible &&
                !FileUtility.CanWebRestrictedEditing(file.Title))
            {
                rightToFillForms = fillFormsPossible = false;
            }

            if (commentPossible &&
                !FileUtility.CanWebComment(file.Title))
            {
                rightToComment = commentPossible = false;
            }

            var rightChangeHistory = rightToEdit && !file.Encrypted;

            if (FileTracker.IsEditing(file.ID))
            {
                rightChangeHistory = false;

                bool coauth;
                if ((editPossible || reviewPossible || fillFormsPossible || commentPossible) &&
                    tryCoauth &&
                    (!(coauth = FileUtility.CanCoAuhtoring(file.Title)) || FileTracker.IsEditingAlone(file.ID)))
                {
                    if (tryEdit)
                    {
                        var editingBy = FileTracker.GetEditingBy(file.ID).FirstOrDefault();
                        strError = string.Format(!coauth
                                                     ? FilesCommonResource.ErrorMassage_EditingCoauth
                                                     : FilesCommonResource.ErrorMassage_EditingMobile,
                                                 Global.GetUserName(editingBy, true));
                    }
                    rightToEdit = editPossible = reviewPossible = fillFormsPossible = commentPossible = false;
                }
            }

            var fileStable = file;

            if (lastVersion && file.Forcesave != ForcesaveType.None && tryEdit)
            {
                var fileDao = DaoFactory.GetFileDao <T>();
                fileStable = fileDao.GetFileStable(file.ID, file.Version);
            }

            var docKey    = GetDocKey(fileStable);
            var modeWrite = (editPossible || reviewPossible || fillFormsPossible || commentPossible) && tryEdit;

            configuration = new Configuration <T>(file, ServiceProvider)
            {
                Document =
                {
                    Key         = docKey,
                    Permissions =
                    {
                        Edit          = rightToEdit && lastVersion,
                        Rename        = rightToRename && lastVersion && !file.ProviderEntry,
                        Review        = rightToReview && lastVersion,
                        FillForms     = rightToFillForms && lastVersion,
                        Comment       = rightToComment && lastVersion,
                        ChangeHistory = rightChangeHistory,
                        ModifyFilter  = rightModifyFilter
                    }
                },
                EditorConfig =
                {
                    ModeWrite = modeWrite,
                },
                ErrorMessage = strError,
            };

            if (!lastVersion)
            {
                configuration.Document.Title += string.Format(" ({0})", file.CreateOnString);
            }

            return(file);
        }
コード例 #28
0
        protected String RenderUsedSpace()
        {
            var used = TenantStatisticsProvider.GetUsedSize();

            return(FileSizeComment.FilesSizeToString(used));
        }
コード例 #29
0
        private Stream CompressToZip(ItemNameValueCollection entriesPathId)
        {
            var stream = TempStream.Create();

            using (var zip = new ionic::Ionic.Zip.ZipOutputStream(stream, true))
            {
                zip.CompressionLevel       = ionic::Ionic.Zlib.CompressionLevel.Level3;
                zip.AlternateEncodingUsage = ionic::Ionic.Zip.ZipOption.AsNecessary;
                zip.AlternateEncoding      = Encoding.GetEncoding(Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage);

                foreach (var path in entriesPathId.AllKeys)
                {
                    if (Canceled)
                    {
                        zip.Dispose();
                        stream.Dispose();
                        return(null);
                    }

                    var counter = 0;
                    foreach (var entryId in entriesPathId[path])
                    {
                        var newtitle = path;

                        File file         = null;
                        var  convertToExt = string.Empty;

                        if (!string.IsNullOrEmpty(entryId))
                        {
                            file = FileDao.GetFile(entryId);

                            if (file.ContentLength > SetupInfo.AvailableFileSize)
                            {
                                Error = string.Format(FilesCommonResource.ErrorMassage_FileSizeZip, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize));
                                continue;
                            }

                            if (_files.ContainsKey(file.ID.ToString()))
                            {
                                if (_quotaDocsEdition)
                                {
                                    convertToExt = _files[file.ID.ToString()];
                                }

                                if (!string.IsNullOrEmpty(convertToExt))
                                {
                                    newtitle = FileUtility.ReplaceFileExtension(path, convertToExt);
                                }
                            }
                        }

                        if (0 < counter)
                        {
                            var suffix = " (" + counter + ")";

                            if (!string.IsNullOrEmpty(entryId))
                            {
                                newtitle = 0 < newtitle.IndexOf('.')
                                               ? newtitle.Insert(newtitle.LastIndexOf('.'), suffix)
                                               : newtitle + suffix;
                            }
                            else
                            {
                                break;
                            }
                        }

                        zip.PutNextEntry(newtitle);

                        if (!string.IsNullOrEmpty(entryId) && file != null)
                        {
                            if (file.ConvertedType != null || !string.IsNullOrEmpty(convertToExt))
                            {
                                //Take from converter
                                try
                                {
                                    using (var readStream = !string.IsNullOrEmpty(convertToExt)
                                                                ? FileConverter.Exec(file, convertToExt)
                                                                : FileConverter.Exec(file))
                                    {
                                        if (readStream != null)
                                        {
                                            readStream.StreamCopyTo(zip);
                                            if (!string.IsNullOrEmpty(convertToExt))
                                            {
                                                FilesMessageService.Send(file, httpRequestHeaders, MessageAction.FileDownloadedAs, file.Title, convertToExt);
                                            }
                                            else
                                            {
                                                FilesMessageService.Send(file, httpRequestHeaders, MessageAction.FileDownloaded, file.Title);
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Error = ex.Message;

                                    Logger.Error(Error, ex);
                                }
                            }
                            else
                            {
                                using (var readStream = FileDao.GetFileStream(file))
                                {
                                    readStream.StreamCopyTo(zip);
                                    FilesMessageService.Send(file, httpRequestHeaders, MessageAction.FileDownloaded, file.Title);
                                }
                            }
                        }
                        counter++;
                    }

                    ProgressStep();
                }
                return(stream);
            }
        }
コード例 #30
0
        private bool CheckStartupEnabled(TenantQuota currentQuota, TenantQuota startupQuota, out string errorMessage)
        {
            errorMessage = string.Empty;

            if (!currentQuota.Trial)
            {
                errorMessage = UserControlsCommonResource.SaasTariffErrorTrial;
                return(false);
            }

            if (TenantStatisticsProvider.GetUsersCount() > startupQuota.ActiveUsers)
            {
                errorMessage = string.Format(UserControlsCommonResource.SaasTariffErrorUsers, startupQuota.ActiveUsers);
                return(false);
            }

            if (TenantStatisticsProvider.GetVisitorsCount() > 0)
            {
                errorMessage = string.Format(UserControlsCommonResource.SaasTariffErrorGuests, 0);
                return(false);
            }

            var currentTenant = CoreContext.TenantManager.GetCurrentTenant();

            var admins = WebItemSecurity.GetProductAdministrators(Guid.Empty);

            if (admins.Any(admin => admin.ID != currentTenant.OwnerId))
            {
                errorMessage = string.Format(UserControlsCommonResource.SaasTariffErrorAdmins, 1);
                return(false);
            }

            if (TenantStatisticsProvider.GetUsedSize() > startupQuota.MaxTotalSize)
            {
                errorMessage = string.Format(UserControlsCommonResource.SaasTariffErrorStorage, FileSizeComment.FilesSizeToString(startupQuota.MaxTotalSize));
                return(false);
            }

            var authServiceList = new AuthorizationKeys().AuthServiceList.Where(x => x.CanSet);

            foreach (var service in authServiceList)
            {
                if (service.Props.Any(r => !string.IsNullOrEmpty(r.Value)))
                {
                    errorMessage = UserControlsCommonResource.SaasTariffErrorThirparty;
                    return(false);
                }
            }

            if (!TenantWhiteLabelSettings.Load().IsDefault)
            {
                errorMessage = UserControlsCommonResource.SaasTariffErrorWhiteLabel;
                return(false);
            }

            if (!string.IsNullOrEmpty(currentTenant.MappedDomain))
            {
                errorMessage = UserControlsCommonResource.SaasTariffErrorDomain;
                return(false);
            }

            var accountLinker = new AccountLinker("webstudio");

            foreach (var user in CoreContext.UserManager.GetUsers(EmployeeStatus.All))
            {
                var linkedAccounts = accountLinker.GetLinkedProfiles(user.ID.ToString());

                if (linkedAccounts.Any())
                {
                    errorMessage = UserControlsCommonResource.SaasTariffErrorOauth;
                    return(false);
                }
            }

            if (SsoSettingsV2.Load().EnableSso)
            {
                errorMessage = UserControlsCommonResource.SaasTariffErrorSso;
                return(false);
            }

            if (ActiveDirectory.Base.Settings.LdapSettings.Load().EnableLdapAuthentication)
            {
                errorMessage = UserControlsCommonResource.SaasTariffErrorLdap;
                return(false);
            }

            using (var service = new BackupServiceClient())
            {
                var scheduleResponse = service.GetSchedule(currentTenant.TenantId);

                if (scheduleResponse != null)
                {
                    errorMessage = UserControlsCommonResource.SaasTariffErrorAutoBackup;
                    return(false);
                }
            }

            return(true);
        }