Exemple #1
0
        public override void PublishChanges(DistributedTask task)
        {
            var thirdpartyTask = ThirdPartyOperation.GetDistributedTask();
            var daoTask        = DaoOperation.GetDistributedTask();

            var error1 = thirdpartyTask.GetProperty <string>(ERROR);
            var error2 = daoTask.GetProperty <string>(ERROR);

            if (!string.IsNullOrEmpty(error1))
            {
                Error = error1;
            }
            else if (!string.IsNullOrEmpty(error2))
            {
                Error = error2;
            }

            successProcessed = thirdpartyTask.GetProperty <int>(PROCESSED) + daoTask.GetProperty <int>(PROCESSED);

            var progressSteps = ThirdPartyOperation.Total + DaoOperation.Total + 1;

            var progress = (int)(successProcessed / (double)progressSteps * 100);

            base.FillDistributedTask();

            TaskInfo.SetProperty(PROGRESS, progress < 100 ? progress : progress);
            TaskInfo.PublishChanges();
        }
Exemple #2
0
        protected LDAPOperation(LDAPSupportSettings settings, Tenant tenant = null, bool?acceptCertificate = null)
        {
            CurrentTenant = tenant ?? CoreContext.TenantManager.GetCurrentTenant();

            _culture = Thread.CurrentThread.CurrentCulture.Name;

            LDAPSettings = settings;

            _ldapSettingsChecker = !WorkContext.IsMono
                                       ? (LdapSettingsChecker) new SystemLdapSettingsChecker()
                                       : new NovellLdapSettingsChecker();

            Source   = "";
            Progress = 0;
            Status   = "";
            Error    = "";
            Source   = "";

            TaskInfo = new DistributedTask();

            if (acceptCertificate.HasValue)
            {
                TaskInfo.SetProperty(CERT_ALLOW, acceptCertificate.Value);
            }
        }
        public override void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            base.RunJob(_, cancellationToken);

            using var scope = ThirdPartyOperation.CreateScope();
            var globalStore      = scope.ServiceProvider.GetService <GlobalStore>();
            var filesLinkUtility = scope.ServiceProvider.GetService <FilesLinkUtility>();

            using var stream = TempStream.Create();
            using (var zip = new ZipOutputStream(stream, true)
            {
                CompressionLevel = Ionic.Zlib.CompressionLevel.Level3,
                AlternateEncodingUsage = ZipOption.AsNecessary,
                AlternateEncoding = Encoding.UTF8,
            })
            {
                (ThirdPartyOperation as FileDownloadOperation <string>).CompressToZip(zip, stream, scope);
                (DaoOperation as FileDownloadOperation <int>).CompressToZip(zip, stream, scope);
            }

            if (stream != null)
            {
                stream.Position = 0;
                const string fileName = FileConstant.DownloadTitle + ".zip";
                var          store    = globalStore.GetStore();
                store.Save(
                    FileConstant.StorageDomainTmp,
                    string.Format(@"{0}\{1}", ((IAccount)Thread.CurrentPrincipal.Identity).ID, fileName),
                    stream,
                    "application/zip",
                    "attachment; filename=\"" + fileName + "\"");
                Status = string.Format("{0}?{1}=bulk", filesLinkUtility.FileHandlerPath, FilesLinkUtility.Action);
            }
        }
Exemple #4
0
        public static ReportState FromTask(
            DistributedTask task,
            IHttpContextAccessor httpContextAccessor,
            int tenantId,
            Guid userId)
        {
            var data = new ReportStateData(
                task.GetProperty <string>("fileName"),
                task.GetProperty <string>("tmpFileName"),
                task.GetProperty <string>("script"),
                task.GetProperty <int>("reportType"),
                task.GetProperty <ReportOrigin>("reportOrigin"),
                null,
                null,
                tenantId,
                userId
                );

            return(new ReportState(null, data, httpContextAccessor)
            {
                Id = task.GetProperty <string>("id"),
                FileId = task.GetProperty <int>("fileId"),
                Status = task.GetProperty <ReportStatus>("status"),
                Exception = task.GetProperty <string>("exception")
            });
        }
        public SmtpOperation(
            SmtpSettingsWrapper smtpSettings,
            int tenant,
            Guid user,
            UserManager userManager,
            SecurityContext securityContext,
            TenantManager tenantManager,
            IConfiguration configuration,
            IOptionsMonitor <ILog> options)
        {
            SmtpSettings    = smtpSettings;
            CurrentTenant   = tenant;
            CurrentUser     = user;
            UserManager     = userManager;
            SecurityContext = securityContext;
            TenantManager   = tenantManager;
            Configuration   = configuration;

            //todo
            //messageSubject = WebstudioNotifyPatternResource.subject_smtp_test;
            //messageBody = WebstudioNotifyPatternResource.pattern_smtp_test;

            Source   = "";
            Progress = 0;
            Status   = "";
            Error    = "";
            Source   = "";

            TaskInfo = new DistributedTask();

            Logger = options.CurrentValue;
        }
Exemple #6
0
        public FileOperation(IServiceProvider serviceProvider)
        {
            principal = serviceProvider.GetService <Microsoft.AspNetCore.Http.IHttpContextAccessor>()?.HttpContext?.User ?? Thread.CurrentPrincipal;
            culture   = Thread.CurrentThread.CurrentCulture.Name;

            TaskInfo = new DistributedTask();
        }
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);
                Thread.CurrentPrincipal               = principal;
                Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo(culture);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);

                FolderDao     = Global.DaoFactory.GetFolderDao();
                FileDao       = Global.DaoFactory.GetFileDao();
                TagDao        = Global.DaoFactory.GetTagDao();
                ProviderDao   = Global.DaoFactory.GetProviderDao();
                FilesSecurity = new FileSecurity(Global.DaoFactory);
                LinkDao       = Global.GetLinkDao();

                Logger = Global.Logger;

                Total = InitTotalProgressSteps();

                Do();
            }
            catch (AuthorizingException authError)
            {
                Error = FilesCommonResource.ErrorMassage_SecurityException;
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (Exception error)
            {
                Error = error is TaskCanceledException || error is OperationCanceledException
                            ? FilesCommonResource.ErrorMassage_OperationCanceledException
                            : error.Message;
                Logger.Error(error, error);
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();

                    FolderDao.Dispose();
                    FileDao.Dispose();
                    TagDao.Dispose();
                    LinkDao.Dispose();

                    if (ProviderDao != null)
                    {
                        ProviderDao.Dispose();
                    }
                }
                catch { /* ignore */ }
            }
        }
Exemple #8
0
        public override void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            ThirdPartyOperation.GetDistributedTask().Publication = PublishChanges;
            ThirdPartyOperation.RunJob(_, cancellationToken);

            DaoOperation.GetDistributedTask().Publication = PublishChanges;
            DaoOperation.RunJob(_, cancellationToken);
        }
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);

                Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo(_culture);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(_culture);

                Logger = LogManager.GetLogger("ASC.Mail.Operation");

                Do();
            }
            catch (AuthorizingException authError)
            {
                Error = "ErrorAccessDenied";
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (TenantQuotaException e)
            {
                Error = "TenantQuotaSettled";
                Logger.Error("TenantQuotaException. {0}", e);
            }
            catch (FormatException e)
            {
                Error = "CantCreateUsers";
                Logger.Error("FormatException error. {0}", e);
            }
            catch (Exception e)
            {
                Error = "InternalServerError";
                Logger.Error("Internal server error. {0}", e);
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();
                }
                catch
                {
                    /* ignore */
                }
            }
        }
        protected FileOperation(List <object> folders, List <object> files, Tenant tenant = null)
        {
            CurrentTenant = tenant ?? CoreContext.TenantManager.GetCurrentTenant();
            principal     = Thread.CurrentPrincipal;
            culture       = Thread.CurrentThread.CurrentCulture.Name;

            Folders = folders ?? new List <object>();
            Files   = files ?? new List <object>();

            TaskInfo = new DistributedTask();
        }
Exemple #11
0
        internal void SendRequest(DistributedTask task, CancellationToken token)
        {
            var result = string.Empty;

            if (stopRequesting)
            {
                Starter(this, result);
                return;
            }
            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);

                httpWebRequest.AllowAutoRedirect          = false;
                httpWebRequest.Timeout                    = 15000;
                httpWebRequest.Method                     = "GET";
                httpWebRequest.Headers["Accept-Language"] = "en"; // get correct en lang

                var       countTry = 0;
                const int maxTry   = 3;
                while (countTry < maxTry)
                {
                    try
                    {
                        countTry++;
                        using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                            using (var stream = httpWebResponse.GetResponseStream())
                                using (var reader = new StreamReader(stream, Encoding.GetEncoding(httpWebResponse.CharacterSet)))
                                {
                                    result = reader.ReadToEnd();
                                    break;
                                }
                    }
                    catch (WebException ex)
                    {
                        if (ex.Status != WebExceptionStatus.Timeout)
                        {
                            throw;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                stopRequesting = true;
                Log.Error(string.Format("HelpCenter is not avaliable by url {0}", Url), e);
            }

            Starter(this, result);
        }
Exemple #12
0
 public ReportState(IServiceProvider serviceProvider, ReportStateData reportStateData, IHttpContextAccessor httpContextAccessor)
 {
     TaskInfo        = new DistributedTask();
     ServiceProvider = serviceProvider;
     FileName        = reportStateData.FileName;
     TmpFileName     = reportStateData.TmpFileName;
     Script          = reportStateData.Script;
     ReportType      = reportStateData.ReportType;
     Origin          = reportStateData.Origin;
     SaveFileAction  = reportStateData.SaveFileAction;
     Obj             = reportStateData.Obj;
     TenantId        = reportStateData.TenantId;
     UserId          = reportStateData.UserId;
     ContextUrl      = httpContextAccessor.HttpContext?.Request.GetUrlRewriter().ToString();
 }
        protected MailOperation(Tenant tenant, IAccount user)
        {
            CurrentTenant = tenant ?? CoreContext.TenantManager.GetCurrentTenant();
            CurrentUser   = user ?? SecurityContext.CurrentAccount;

            _culture = Thread.CurrentThread.CurrentCulture.Name;

            Source   = "";
            Progress = 0;
            Status   = "";
            Error    = "";
            Source   = "";

            TaskInfo = new DistributedTask();
        }
Exemple #14
0
        public ReportState(string fileName, string tmpFileName, string script, int reportType, ReportOrigin origin, Action <ReportState, string> saveFileAction, object obj)
        {
            Id             = DocbuilderReportsUtility.GetCacheKey(origin);
            Origin         = origin;
            FileName       = fileName;
            TmpFileName    = tmpFileName;
            Script         = script;
            ReportType     = reportType;
            SaveFileAction = saveFileAction;
            TaskInfo       = new DistributedTask();
            TenantId       = TenantProvider.CurrentTenantID;
            UserId         = SecurityContext.CurrentAccount.ID;
            ContextUrl     = HttpContext.Current != null?HttpContext.Current.Request.GetUrlRewriter().ToString() : null;

            Obj = obj;
        }
Exemple #15
0
        public override void RunJob(DistributedTask distributedTask, CancellationToken cancellationToken)
        {
            base.RunJob(distributedTask, cancellationToken);

            using var scope = ThirdPartyOperation.CreateScope();
            var scopeClass = scope.ServiceProvider.GetService <FileDownloadOperationScope>();

            var(globalStore, filesLinkUtility, _, _, _) = scopeClass;
            var stream = TempStream.Create();

            (ThirdPartyOperation as FileDownloadOperation <string>).CompressToZip(stream, scope);
            (DaoOperation as FileDownloadOperation <int>).CompressToZip(stream, scope);

            if (stream != null)
            {
                var archiveExtension = "";

                using (var zip = scope.ServiceProvider.GetService <CompressToArchive>())
                {
                    archiveExtension = zip.ArchiveExtension;
                }

                stream.Position = 0;
                string fileName = FileConstant.DownloadTitle + archiveExtension;
                var    store    = globalStore.GetStore();
                var    path     = string.Format(@"{0}\{1}", ((IAccount)Thread.CurrentPrincipal.Identity).ID, fileName);

                if (store.IsFile(FileConstant.StorageDomainTmp, path))
                {
                    store.Delete(FileConstant.StorageDomainTmp, path);
                }

                store.Save(
                    FileConstant.StorageDomainTmp,
                    path,
                    stream,
                    MimeMapping.GetMimeMapping(path),
                    "attachment; filename=\"" + fileName + "\"");
                Result = string.Format("{0}?{1}=bulk&ext={2}", filesLinkUtility.FileHandlerPath, FilesLinkUtility.Action, archiveExtension);

                TaskInfo.SetProperty(PROGRESS, 100);
                TaskInfo.SetProperty(RESULT, Result);
                TaskInfo.SetProperty(FINISHED, true);
            }

            TaskInfo.PublishChanges();
        }
Exemple #16
0
 public static ReportState FromTask(DistributedTask task)
 {
     return(new ReportState(
                task.GetProperty <string>("fileName"),
                task.GetProperty <string>("tmpFileName"),
                task.GetProperty <string>("script"),
                task.GetProperty <int>("reportType"),
                task.GetProperty <ReportOrigin>("reportOrigin"),
                null,
                null)
     {
         Id = task.GetProperty <string>("id"),
         FileId = task.GetProperty <int>("fileId"),
         Status = task.GetProperty <ReportStatus>("status"),
         Exception = task.GetProperty <string>("exception")
     });
 }
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            CoreContext.TenantManager.SetCurrentTenant(TenantId);

            var storageModules = StorageFactory.GetModuleList(string.Empty).ToList();

            foreach (var module in storageModules)
            {
                var storage = StorageFactory.GetStorage(TenantId.ToString(), module);
                storage.ResetQuota("");

                var domains = StorageFactory.GetDomainList(string.Empty, module).ToList();
                foreach (var domain in domains)
                {
                    storage.ResetQuota(domain);
                }
            }
        }
Exemple #18
0
        public SmtpOperation(SmtpSettingsWrapper smtpSettings, int tenant, Guid user)
        {
            SmtpSettings  = smtpSettings;
            CurrentTenant = tenant;
            CurrentUser   = user;

            messageSubject = Web.Studio.Core.Notify.WebstudioNotifyPatternResource.subject_smtp_test;
            messageBody    = Web.Studio.Core.Notify.WebstudioNotifyPatternResource.pattern_smtp_test;

            Source   = "";
            Progress = 0;
            Status   = "";
            Error    = "";
            Source   = "";

            TaskInfo = new DistributedTask();

            Logger = LogManager.GetLogger("ASC");
        }
Exemple #19
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            using var scope = ServiceProvider.CreateScope();
            var scopeClass = scope.ServiceProvider.GetService <QuotaSyncScope>();

            var(tenantManager, storageFactoryConfig, storageFactory) = scopeClass;
            tenantManager.SetCurrentTenant(TenantId);

            var storageModules = storageFactoryConfig.GetModuleList(string.Empty).ToList();

            foreach (var module in storageModules)
            {
                var storage = storageFactory.GetStorage(TenantId.ToString(), module);
                storage.ResetQuota("");

                var domains = storageFactoryConfig.GetDomainList(string.Empty, module).ToList();
                foreach (var domain in domains)
                {
                    storage.ResetQuota(domain);
                }
            }
        }
Exemple #20
0
        protected LdapOperation(LdapSettings settings, Tenant tenant, LdapOperationType operationType, LdapLocalization resource = null)
        {
            CurrentTenant = tenant;

            OperationType = operationType;

            _culture = Thread.CurrentThread.CurrentCulture.Name;

            LDAPSettings = settings;

            Source   = "";
            Progress = 0;
            Status   = "";
            Error    = "";
            Source   = "";

            TaskInfo = new DistributedTask();

            Resource = resource ?? new LdapLocalization();

            LDAPUserManager = new LdapUserManager(Resource);
        }
        public override void RunJob(DistributedTask distributedTask, CancellationToken cancellationToken)
        {
            base.RunJob(distributedTask, cancellationToken);

            using var scope = ThirdPartyOperation.CreateScope();
            var scopeClass = scope.ServiceProvider.GetService <FileDownloadOperationScope>();

            var(globalStore, filesLinkUtility, _, _, _) = scopeClass;
            using var stream = TempStream.Create();

            var writerOptions = new ZipWriterOptions(CompressionType.Deflate);

            writerOptions.ArchiveEncoding.Default = Encoding.UTF8;
            writerOptions.DeflateCompressionLevel = SharpCompress.Compressors.Deflate.CompressionLevel.Level3;

            using (var zip = WriterFactory.Open(stream, ArchiveType.Zip, writerOptions))
            {
                (ThirdPartyOperation as FileDownloadOperation <string>).CompressToZip(zip, stream, scope);
                (DaoOperation as FileDownloadOperation <int>).CompressToZip(zip, stream, scope);
            }

            if (stream != null)
            {
                stream.Position = 0;
                const string fileName = FileConstant.DownloadTitle + ".zip";
                var          store    = globalStore.GetStore();
                store.Save(
                    FileConstant.StorageDomainTmp,
                    string.Format(@"{0}\{1}", ((IAccount)Thread.CurrentPrincipal.Identity).ID, fileName),
                    stream,
                    "application/zip",
                    "attachment; filename=\"" + fileName + "\"");
                Status = string.Format("{0}?{1}=bulk", filesLinkUtility.FileHandlerPath, FilesLinkUtility.Action);
            }

            FillDistributedTask();
            TaskInfo.PublishChanges();
        }
Exemple #22
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);

                Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo(_culture);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(_culture);

                Logger = LogManager.GetLogger(typeof(LDAPOperation));

                if (LDAPSettings == null)
                {
                    Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                    Logger.Error("Can't save default LDAP settings.");
                    return;
                }

                if (OperationType == LDAPOperationType.Save)
                {
                    SetProgress(1, Resource.LdapSettingsStatusCheckingLdapSettings);

                    PrepareSettings(LDAPSettings);

                    if (!string.IsNullOrEmpty(Error))
                    {
                        return;
                    }

                    Importer = new LDAPUserImporter(LDAPSettings);

                    SetProgress(5, Resource.LdapSettingsStatusLoadingBaseInfo);

                    var acceptCertificate = TaskInfo.GetProperty <bool>(CERT_ALLOW);

                    var result = _ldapSettingsChecker.CheckSettings(Importer, acceptCertificate);

                    if (result == LdapSettingsChecker.CERTIFICATE_REQUEST)
                    {
                        TaskInfo.SetProperty(FINISHED, true);

                        TaskInfo.SetProperty(CERT_REQUEST, ((NovellLdapSettingsChecker)_ldapSettingsChecker).CertificateConfirmRequest);

                        SetProgress(0, Resource.LdapSettingsStatusCertificateVerification);

                        return;
                    }

                    var error = GetError(result);
                    if (!string.IsNullOrEmpty(error))
                    {
                        Error = error;
                        return;
                    }

                    SetProgress(10, Resource.LdapSettingsStatusSavingSettings);

                    LDAPSettings.IsDefault = LDAPSettings.Equals(LDAPSettings.GetDefault());

                    if (!SettingsManager.Instance.SaveSettings(LDAPSettings, CurrentTenant.TenantId))
                    {
                        Logger.Error("Can't save LDAP settings.");
                        Error = Resource.LdapSettingsErrorCantSaveLdapSettings;
                        return;
                    }
                }
                else if (OperationType == LDAPOperationType.Sync)
                {
                    Importer = new LDAPUserImporter(LDAPSettings);
                }

                Do();
            }
            catch (AuthorizingException authError)
            {
                Error = Resource.ErrorAccessDenied;
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (TenantQuotaException e)
            {
                Error = Resource.LdapSettingsTenantQuotaSettled;
                Logger.ErrorFormat("TenantQuotaException. {0}", e);
            }
            catch (FormatException e)
            {
                Error = Resource.LdapSettingsErrorCantCreateUsers;
                Logger.ErrorFormat("FormatException error. {0}", e);
            }
            catch (Exception e)
            {
                Error = Resource.LdapSettingsInternalServerError;
                Logger.ErrorFormat("Internal server error. {0}", e);
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();
                }
                catch { /* ignore */ }
            }
        }
Exemple #23
0
 public HelpCenterRequest()
 {
     TaskInfo = new DistributedTask();
 }
Exemple #24
0
        /// <summary>
        /// Method for translation mail operation statuses
        /// </summary>
        /// <param name="op">instance of DistributedTask</param>
        /// <returns>translated status text</returns>
        private static string TranslateMailOperationStatus(DistributedTask op)
        {
            var type   = op.GetProperty <MailOperationType>(MailOperation.OPERATION_TYPE);
            var status = op.GetProperty <string>(MailOperation.STATUS);

            //TODO: Move strings to Resource file
            switch (type)
            {
            case MailOperationType.RemoveMailbox:
            {
                var progress = op.GetProperty <MailOperationRemoveMailboxProgress>(MailOperation.PROGRESS);
                switch (progress)
                {
                case MailOperationRemoveMailboxProgress.Init:
                    return("Setup tenant and user");

                case MailOperationRemoveMailboxProgress.RemoveFromDb:
                    return("Remove mailbox from Db");

                case MailOperationRemoveMailboxProgress.FreeQuota:
                    return("Decrease newly freed quota space");

                case MailOperationRemoveMailboxProgress.RecalculateFolder:
                    return("Recalculate folders counters");

                case MailOperationRemoveMailboxProgress.ClearCache:
                    return("Clear accounts cache");

                case MailOperationRemoveMailboxProgress.Finished:
                    return("Finished");

                default:
                    return(status);
                }
            }

            case MailOperationType.RecalculateFolders:
            {
                var progress = op.GetProperty <MailOperationRecalculateMailboxProgress>(MailOperation.PROGRESS);
                switch (progress)
                {
                case MailOperationRecalculateMailboxProgress.Init:
                    return("Setup tenant and user");

                case MailOperationRecalculateMailboxProgress.CountUnreadMessages:
                    return("Calculate unread messages");

                case MailOperationRecalculateMailboxProgress.CountTotalMessages:
                    return("Calculate total messages");

                case MailOperationRecalculateMailboxProgress.CountUreadConversation:
                    return("Calculate unread conversations");

                case MailOperationRecalculateMailboxProgress.CountTotalConversation:
                    return("Calculate total conversations");

                case MailOperationRecalculateMailboxProgress.UpdateFoldersCounters:
                    return("Update folders counters");

                case MailOperationRecalculateMailboxProgress.Finished:
                    return("Finished");

                default:
                    return(status);
                }
            }

            default:
                return(status);
            }
        }
Exemple #25
0
        public void GenerateReport(DistributedTask task, CancellationToken cancellationToken)
        {
            using var scope = ServiceProvider.CreateScope();
            var scopeClass = scope.ServiceProvider.GetService <ReportStateScope>();

            var(options, tenantManager, authContext, securityContext, documentServiceConnector) = scopeClass;
            var logger = options.CurrentValue;

            try
            {
                tenantManager.SetCurrentTenant(TenantId);

                Status = ReportStatus.Started;
                PublishTaskInfo(logger);

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

                tenantManager.SetCurrentTenant(TenantId);
                securityContext.AuthenticateMe(UserId);

                BuilderKey = documentServiceConnector.DocbuilderRequest(null, Script, true, out var urls);

                while (true)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        throw new OperationCanceledException();
                    }

                    Task.Delay(1500, cancellationToken).Wait(cancellationToken);
                    var builderKey = documentServiceConnector.DocbuilderRequest(BuilderKey, null, true, out urls);
                    if (builderKey == null)
                    {
                        throw new NullReferenceException();
                    }

                    if (urls != null && !urls.Any())
                    {
                        throw new Exception("Empty response");
                    }

                    if (urls != null && urls.ContainsKey(TmpFileName))
                    {
                        break;
                    }
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    throw new OperationCanceledException();
                }

                SaveFileAction(this, urls[TmpFileName]);

                Status = ReportStatus.Done;
            }
            catch (Exception e)
            {
                logger.Error("DocbuilderReportsUtility error", e);
                Exception = e.Message;
                Status    = ReportStatus.Failed;
            }

            PublishTaskInfo(logger);
        }
Exemple #26
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

                SecurityContext.AuthenticateMe(Core.Configuration.Constants.CoreSystem);

                Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo(_culture);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(_culture);

                Logger = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Log4Net, "MailOperation");

                //TODO: Check any settings
                switch (OperationType)
                {
                case MailOperationType.RecalculateFolders:
                    break;

                case MailOperationType.RemoveMailbox:
                    break;

                default:
                    throw new InvalidOperationException();
                }

                Do();
            }
            catch (AuthorizingException authError)
            {
                Error = "ErrorAccessDenied";
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (TenantQuotaException e)
            {
                Error = "TenantQuotaSettled";
                Logger.Error("TenantQuotaException. {0}", e);
            }
            catch (FormatException e)
            {
                Error = "CantCreateUsers";
                Logger.Error("FormatException error. {0}", e);
            }
            catch (Exception e)
            {
                Error = "InternalServerError";
                Logger.Error("Internal server error. {0}", e);
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();
                }
                catch
                {
                    /* ignore */
                }
            }
        }
Exemple #27
0
        public void GenerateReport(DistributedTask task, CancellationToken cancellationToken)
        {
            try
            {
                Status = ReportStatus.Started;
                PublishTaskInfo();

                if (HttpContext.Current == null && !WorkContext.IsMono && !string.IsNullOrEmpty(ContextUrl))
                {
                    HttpContext.Current = new HttpContext(
                        new HttpRequest("hack", ContextUrl, string.Empty),
                        new HttpResponse(new System.IO.StringWriter()));
                }

                CoreContext.TenantManager.SetCurrentTenant(TenantId);
                SecurityContext.CurrentUser = UserId;

                Dictionary <string, string> urls;
                BuilderKey = DocumentServiceConnector.DocbuilderRequest(null, Script, true, out urls);

                while (true)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        throw new OperationCanceledException();
                    }

                    Task.Delay(1500, cancellationToken).Wait(cancellationToken);
                    var builderKey = DocumentServiceConnector.DocbuilderRequest(BuilderKey, null, true, out urls);
                    if (builderKey == null)
                    {
                        throw new NullReferenceException();
                    }

                    if (urls != null && !urls.Any())
                    {
                        throw new Exception("Empty response");
                    }

                    if (urls != null && urls.ContainsKey(TmpFileName))
                    {
                        break;
                    }
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    throw new OperationCanceledException();
                }

                SaveFileAction(this, urls[TmpFileName]);

                Status = ReportStatus.Done;
            }
            catch (Exception e)
            {
                Global.Logger.Error("DocbuilderReportsUtility error", e);
                Exception = e.Message;
                Status    = ReportStatus.Failed;
            }

            PublishTaskInfo();
        }
Exemple #28
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

                SecurityContext.AuthenticateMe(Core.Configuration.Constants.CoreSystem);

                Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo(_culture);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(_culture);

                Logger = LogManager.GetLogger("ASC");

                if (LDAPSettings == null)
                {
                    Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                    Logger.Error("Can't save default LDAP settings.");
                    return;
                }

                switch (OperationType)
                {
                case LdapOperationType.Save:
                case LdapOperationType.SaveTest:

                    Logger.InfoFormat("Start '{0}' operation",
                                      Enum.GetName(typeof(LdapOperationType), OperationType));

                    SetProgress(1, Resource.LdapSettingsStatusCheckingLdapSettings);

                    Logger.Debug("PrepareSettings()");

                    PrepareSettings(LDAPSettings);

                    if (!string.IsNullOrEmpty(Error))
                    {
                        Logger.DebugFormat("PrepareSettings() Error: {0}", Error);
                        return;
                    }

                    Importer = new NovellLdapUserImporter(LDAPSettings, Resource);

                    if (LDAPSettings.EnableLdapAuthentication)
                    {
                        var ldapSettingsChecker = new NovellLdapSettingsChecker(Importer);

                        SetProgress(5, Resource.LdapSettingsStatusLoadingBaseInfo);

                        var result = ldapSettingsChecker.CheckSettings();

                        if (result != LdapSettingsStatus.Ok)
                        {
                            if (result == LdapSettingsStatus.CertificateRequest)
                            {
                                TaskInfo.SetProperty(CERT_REQUEST,
                                                     ldapSettingsChecker.CertificateConfirmRequest);
                            }

                            Error = GetError(result);

                            Logger.DebugFormat("ldapSettingsChecker.CheckSettings() Error: {0}", Error);

                            return;
                        }
                    }

                    break;

                case LdapOperationType.Sync:
                case LdapOperationType.SyncTest:
                    Logger.InfoFormat("Start '{0}' operation",
                                      Enum.GetName(typeof(LdapOperationType), OperationType));

                    Importer = new NovellLdapUserImporter(LDAPSettings, Resource);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                Do();
            }
            catch (AuthorizingException authError)
            {
                Error = Resource.ErrorAccessDenied;
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (TenantQuotaException e)
            {
                Error = Resource.LdapSettingsTenantQuotaSettled;
                Logger.ErrorFormat("TenantQuotaException. {0}", e);
            }
            catch (FormatException e)
            {
                Error = Resource.LdapSettingsErrorCantCreateUsers;
                Logger.ErrorFormat("FormatException error. {0}", e);
            }
            catch (Exception e)
            {
                Error = Resource.LdapSettingsInternalServerError;
                Logger.ErrorFormat("Internal server error. {0}", e);
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();
                    Dispose();
                    SecurityContext.Logout();
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("LdapOperation finalization problem. {0}", ex);
                }
            }
        }
Exemple #29
0
 public QuotaSync(int tenantId, IServiceProvider serviceProvider)
 {
     TenantId        = tenantId;
     TaskInfo        = new DistributedTask();
     ServiceProvider = serviceProvider;
 }
Exemple #30
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                SetProgress(5, "Setup tenant");

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

                SetProgress(10, "Setup user");

                SecurityContext.AuthenticateMe(CurrentUser); //Core.Configuration.Constants.CoreSystem);

                SetProgress(15, "Find user data");

                var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

                SetProgress(20, "Create mime message");

                var toAddress = new MailboxAddress(currentUser.UserName, currentUser.Email);

                var fromAddress = new MailboxAddress(SmtpSettings.SenderDisplayName, SmtpSettings.SenderAddress);

                var mimeMessage = new MimeMessage
                {
                    Subject = messageSubject
                };

                mimeMessage.From.Add(fromAddress);

                mimeMessage.To.Add(toAddress);

                var bodyBuilder = new BodyBuilder
                {
                    TextBody = messageBody
                };

                mimeMessage.Body = bodyBuilder.ToMessageBody();

                mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");

                using (var client = GetSmtpClient())
                {
                    SetProgress(40, "Connect to host");

                    client.Connect(SmtpSettings.Host, SmtpSettings.Port.GetValueOrDefault(25),
                                   SmtpSettings.EnableSSL ? SecureSocketOptions.Auto : SecureSocketOptions.None, cancellationToken);

                    if (SmtpSettings.EnableAuth)
                    {
                        SetProgress(60, "Authenticate");

                        client.Authenticate(SmtpSettings.CredentialsUserName,
                                            SmtpSettings.CredentialsUserPassword, cancellationToken);
                    }

                    SetProgress(80, "Send test message");

                    client.Send(FormatOptions.Default, mimeMessage, cancellationToken);
                }
            }
            catch (AuthorizingException authError)
            {
                Error = Resources.Resource.ErrorAccessDenied; // "No permissions to perform this action";
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (SocketException ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            catch (AuthenticationException ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            catch (Exception ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();

                    SecurityContext.Logout();
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("LdapOperation finalization problem. {0}", ex);
                }
            }
        }