Ejemplo n.º 1
0
        public static IRepositoryBuilder UseMailProvider(this IRepositoryBuilder repositoryBuilder, MailProvider mailProvider)
        {
            Providers.Instance.SetProvider(typeof(MailProvider), mailProvider);
            SnLog.WriteInformation($"MailProvider created: {mailProvider?.GetType().FullName}");

            return(repositoryBuilder);
        }
Ejemplo n.º 2
0
        private ContentListType ManageContentListType(Dictionary <string, FieldDescriptor> fieldInfoList, Dictionary <string, List <string> > oldBindings, bool modify, out List <FieldSetting> fieldSettings)
        {
            var attempts = 0;

            while (true)
            {
                try
                {
                    return(ManageContentListTypeOneAttempt(fieldInfoList, oldBindings, modify, out fieldSettings));
                }
                catch (Exception e)
                {
                    if (!e.Message.Contains("Storage schema is out of date") || attempts++ >= 42)
                    {
                        throw;
                    }
                }
                var timer = Stopwatch.StartNew();
                ActiveSchema.Reload();
                ContentTypeManager.Reload();
                timer.Stop();
                var d          = timer.Elapsed;
                var timeString = $"{d.Minutes}:{d.Seconds}.{d.Milliseconds}";
                SnLog.WriteInformation(
                    $"Type system is reloaded because it was out of date during managing a list type. Attempt: {attempts}, reloading time: {timeString}",
                    EventId.RepositoryRuntime);
            }
        }
Ejemplo n.º 3
0
        private static void CheckCulture()
        {
            var calendar = Thread.CurrentThread.CurrentCulture.DateTimeFormat.Calendar;

            if (calendar.MinSupportedDateTime <= _dateTimeMinValue && calendar.MaxSupportedDateTime >= _dateTimeMaxValue)
            {
                return;
            }

            var logMsg = Thread.CurrentThread.CurrentCulture.Name + ": " + calendar + " is changed to ";

            Calendar[] optCals = Thread.CurrentThread.CurrentCulture.OptionalCalendars;
            foreach (var cal in optCals)
            {
                if (cal.MinSupportedDateTime <= _dateTimeMinValue && cal.MaxSupportedDateTime >= _dateTimeMaxValue)
                {
                    Thread.CurrentThread.CurrentCulture.DateTimeFormat.Calendar   = cal;
                    Thread.CurrentThread.CurrentUICulture.DateTimeFormat.Calendar = cal;
                    SnLog.WriteInformation(logMsg + cal);
                    return;
                }
            }
            SnLog.WriteWarning("This locale cannot be used: " + Thread.CurrentThread.CurrentCulture.Name + ". Current culture is assigned to invariant culture.");
            Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
        }
Ejemplo n.º 4
0
        private void RepairSendQueues()
        {
            bool repairHappened = false;

            for (var i = 0; i < _sendQueues.Count; i++)
            {
                if (!_sendQueuesAvailable[i])
                {
                    try
                    {
                        _sendQueues[i]          = RecoverQueue(_sendQueues[i]);
                        _sendQueuesAvailable[i] = true;     // indicate that the queue is up and running
                        repairHappened          = true;
                    }
                    catch (Exception ex)
                    {
                        SnLog.WriteException(ex, EventMessage.Errors.RepairError, EventId.Messaging);
                    }
                }
            }
            if (repairHappened)
            {
                SnLog.WriteInformation("Send queues have been repaired.", EventId.Messaging);
            }
        }
Ejemplo n.º 5
0
        public void Write(ClientLogEntry entry)
        {
            switch (entry.Severity)
            {
            case TraceEventType.Critical:
            case TraceEventType.Error:
                SnLog.WriteError(entry.Message, entry.EventId, entry.Categories, entry.Priority, entry.Title, entry.Properties);
                break;

            case TraceEventType.Warning:
                SnLog.WriteWarning(entry.Message, entry.EventId, entry.Categories, entry.Priority, entry.Title, entry.Properties);
                break;

            case TraceEventType.Verbose:
                // do nothing: verbose log should be written using SnTrace
                break;

            case TraceEventType.Information:
                SnLog.WriteInformation(entry.Message, entry.EventId, entry.Categories, entry.Priority, entry.Title, entry.Properties);
                break;

            default:
                SnLog.WriteInformation(entry.Severity + ": " + entry.Message, entry.EventId, entry.Categories, entry.Priority, entry.Title, entry.Properties);
                break;
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes an instance of the BuiltInBlobProviderSelector
        /// </summary>
        public BuiltInBlobProviderSelector()
        {
            // check if there is a configuration for an external blob provider
            if (string.IsNullOrEmpty(BlobStorage.BlobProviderClassName) || ExternalBlobProvider != null)
            {
                return;
            }

            try
            {
                ExternalBlobProvider = (IBlobProvider)TypeResolver.CreateInstance(BlobStorage.BlobProviderClassName);
                SnLog.WriteInformation("External BlobProvider created by configuration. Type: " + BlobStorage.BlobProviderClassName,
                                       EventId.RepositoryLifecycle);
            }
            catch (Exception ex)
            {
                SnLog.WriteException(ex);
            }

            // We throw an exception in a static constructor (which will prevent this type to work)
            // because if something is wrong with the blob provider configuration, it will affect
            // the whole system and it should be resolved immediately.
            if (ExternalBlobProvider == null)
            {
                throw new ConfigurationErrorsException("Unknown blob provider name in configuration: " + BlobStorage.BlobProviderClassName);
            }
        }
Ejemplo n.º 7
0
        public void EventLogger_Acceptance()
        {
            var logger = new EventLoggerForTests();
            var loggerBackup = SnLog.Instance;
            SnLog.Instance = logger;
            try
            {
                var thisMethodName = MethodBase.GetCurrentMethod().Name;
                var information = (int)TraceEventType.Information;
                var warning = (int)TraceEventType.Warning;

                SnLog.WriteInformation(thisMethodName + "_INFOMESSAGE", 42, null, 61, thisMethodName + "_TITLE");
                SnLog.WriteWarning(thisMethodName + "_WARNINGMESSAGE", 43, null, 61, thisMethodName + "_TITLE");

                var expected =
                    $"{{\"Message\":\"{thisMethodName}_INFOMESSAGE\",\"Categories\":[],\"Priority\":61,\"EventId\":42,\"Severity\":{information},\"Title\":\"{thisMethodName}_TITLE\",\"Properties\":{{}}}}" + Environment.NewLine +
                    $"{{\"Message\":\"{thisMethodName}_WARNINGMESSAGE\",\"Categories\":[],\"Priority\":61,\"EventId\":43,\"Severity\":{warning},\"Title\":\"{thisMethodName}_TITLE\",\"Properties\":{{}}}}";
                var actual = string.Join(Environment.NewLine, logger.Entries.Select(x => x.ToString()));
                Assert.AreEqual(expected, actual);
            }
            finally
            {
                SnLog.Instance = loggerBackup;
            }
        }
Ejemplo n.º 8
0
        internal static void Shutdown()
        {
            if (_instance == null)
            {
                _started = false;

                SnLog.WriteWarning("Repository shutdown has already completed.");
                return;
            }

            lock (_startStopSync)
            {
                if (_instance == null)
                {
                    _started = false;

                    SnLog.WriteWarning("Repository shutdown has already completed.");
                    return;
                }

                SnTrace.Repository.Write("Sending a goodbye message.");

                _instance.ConsoleWriteLine();

                _instance.ConsoleWriteLine("Sending a goodbye message...");
                DistributedApplication.ClusterChannel.ClusterMemberInfo.NeedToRecover = false;
                var pingMessage = new PingMessage();
                pingMessage.SendAsync(CancellationToken.None).GetAwaiter().GetResult();

                foreach (var svc in _instance.serviceInstances)
                {
                    SnTrace.Repository.Write("Shutting down {0}", svc.GetType().Name);
                    svc.Shutdown();
                }

                SnTrace.Repository.Write("Shutting down {0}", DistributedApplication.ClusterChannel.GetType().Name);
                DistributedApplication.ClusterChannel.ShutDownAsync(CancellationToken.None).GetAwaiter().GetResult();

                SnTrace.Repository.Write("Shutting down Security.");
                SecurityHandler.ShutDownSecurity();

                SnTrace.Repository.Write("Shutting down IndexingEngine.");
                IndexManager.ShutDown();

                ContextHandler.Reset();

                var t   = DateTime.UtcNow - _instance._startupInfo.Starting;
                var msg = $"Repository has stopped. Running time: {t.Days}.{t.Hours:d2}:{t.Minutes:d2}:{t.Seconds:d2}";

                SnTrace.Repository.Write(msg);
                SnTrace.Flush();

                _instance.ConsoleWriteLine(msg);
                _instance.ConsoleWriteLine();
                SnLog.WriteInformation(msg);

                _instance = null;
                _started  = false;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// This method deletes orphaned rows from the database physically.
        /// </summary>
        private async Task CleanupFilesDeleteRowsAsync(CancellationToken cancellationToken)
        {
            var deleteCount = 0;

            try
            {
                SnTrace.Database.Write(SnMaintenance.TracePrefix + "Cleanup files: deleting rows...");

                // keep deleting orphaned binary rows while there are any
                while (await BlobStorage.CleanupFilesAsync(cancellationToken).ConfigureAwait(false))
                {
                    deleteCount++;
                }

                if (deleteCount > 0)
                {
                    SnLog.WriteInformation($"{deleteCount} orphaned rows were deleted from the binary table during cleanup.",
                                           EventId.RepositoryRuntime);
                }
            }
            catch (Exception ex)
            {
                SnLog.WriteWarning("Error in file cleanup background process. " + ex, EventId.RepositoryRuntime);
            }
        }
Ejemplo n.º 10
0
        private static void PreloadContentTemplates()
        {
            try
            {
                QueryResult queryResult;

                var timer = new Stopwatch();
                timer.Start();

                using (new SystemAccount())
                {
                    queryResult = ContentQuery.Query(SafeQueries.PreloadContentTemplates, null,
                                                     RepositoryStructure.ContentTemplateFolderPath, RepositoryPath.GetDepth(RepositoryStructure.ContentTemplateFolderPath) + 2);

                    // ReSharper disable once UnusedVariable
                    // this is a preload operation, we do not want to use the result
                    var templates = queryResult.Nodes.ToList();
                }

                timer.Stop();

                SnLog.WriteInformation($"***** Content template preload time: {timer.Elapsed} ******* Count: {queryResult.Count}");
            }
            catch (Exception ex)
            {
                SnLog.WriteException(ex);
            }
        }
Ejemplo n.º 11
0
        // ============================================================ Interface

        public static void Preload()
        {
            if (!SystemStart.WarmupEnabled)
            {
                SnLog.WriteInformation("***** Warmup is not enabled, skipped.");
                return;
            }

            // types
            ThreadPool.QueueUserWorkItem(delegate { PreloadTypes(); });

            // template replacers and resolvers
            ThreadPool.QueueUserWorkItem(delegate { TemplateManager.Init(); });

            // jscript evaluator
            ThreadPool.QueueUserWorkItem(delegate { JscriptEvaluator.Init(); });

            // xslt
            ThreadPool.QueueUserWorkItem(delegate { PreloadXslt(); });

            // content templates
            ThreadPool.QueueUserWorkItem(delegate { PreloadContentTemplates(); });

            // preload controls
            ThreadPool.QueueUserWorkItem(delegate { PreloadControls(); });

            // preload security items
            ThreadPool.QueueUserWorkItem(delegate { PreloadSecurity(); });
        }
Ejemplo n.º 12
0
        private static void LogLine(string msg, EventType eventType)
        {
            switch (eventType)
            {
            case EventType.Error:
                Logger.WriteError(EventId.NotDefined, msg, AdSyncLogCategory);
                break;

            case EventType.Warning:
                SnLog.WriteWarning(msg, categories: AdSyncLogCategory);
                break;

            case EventType.Info:
                SnLog.WriteInformation(msg, categories: AdSyncLogCategory);
                break;

            case EventType.Verbose:
                Logger.WriteVerbose(string.Format("  {0}", msg), AdSyncLogCategory);
                break;
            }

            // log event for subscriber of the current thread
            StringBuilder sb;

            if (Subscribers.TryGetValue(Thread.CurrentThread.GetHashCode(), out sb))
            {
                if (sb != null)
                {
                    sb.AppendLine(GetMsgWithTimeStamp(msg));
                }
            }
        }
Ejemplo n.º 13
0
        private static void Load()
        {
            foreach (var type in TypeResolver.GetTypesByInterface(typeof(IEvaluator)))
            {
                try
                {
                    if (!(type.GetCustomAttributes(typeof(ScriptTagNameAttribute), false).FirstOrDefault() is ScriptTagNameAttribute tagAttribute))
                    {
                        SnLog.WriteWarning($"Evaluator does not have a ScriptTagNameAttribute: {type.FullName} " +
                                           $"(Assembly: {type.Assembly})");
                        continue;
                    }

                    var fullTagName = GetFullTagName(tagAttribute.TagName);

                    // check if we already have an evaluator for this tag
                    if (Providers.Instance.GetProvider <IEvaluator>(fullTagName) != null)
                    {
                        continue;
                    }

                    var engine = (IEvaluator)Activator.CreateInstance(type);

                    Providers.Instance.SetProvider(fullTagName, engine);

                    SnLog.WriteInformation("Evaluator loaded: " + tagAttribute.TagName + ": " + engine);
                }
                catch (Exception ex)
                {
                    SnLog.WriteException(ex, $"Error loading script evaluator class. {type.AssemblyQualifiedName}");
                }
            }
        }
Ejemplo n.º 14
0
        //============================================================================================= Static API

        public static SecuritySystem StartSecurity(ISecurityDataProvider securityDataProvider,
                                                   IMessageProvider messageProvider,
                                                   IMissingEntityHandler missingEntityHandler,
                                                   MessagingOptions messagingOptions)
        {
            var securityConfig = new SecurityConfiguration
            {
                SystemUserId    = Identifiers.SystemUserId,
                VisitorUserId   = Identifiers.VisitorUserId,
                EveryoneGroupId = Identifiers.EveryoneGroupId,
                OwnerGroupId    = Identifiers.OwnersGroupId
            };

            var securitySystem = new SecuritySystem(securityDataProvider, messageProvider, missingEntityHandler,
                                                    securityConfig, messagingOptions);

            securitySystem.Start();

            SnLog.WriteInformation("Security subsystem started in Search service", EventId.RepositoryLifecycle,
                                   properties: new Dictionary <string, object> {
                { "DataProvider", securityDataProvider.GetType().FullName },
                { "MessageProvider", messageProvider.GetType().FullName }
            });

            return(securitySystem);
        }
        internal static void Reset()
        {
            SnLog.WriteInformation("ResourceManager.Reset called.", EventId.RepositoryRuntime,
                properties: new Dictionary<string, object> { { "AppDomain", AppDomain.CurrentDomain.FriendlyName } });

            new ResourceManagerResetDistributedAction().Execute();
        }
Ejemplo n.º 16
0
        static ContentNamingProvider()
        {
            var className = Providers.ContentNamingProviderClassName;

            ContentNamingProvider instance = null;

            if (string.IsNullOrEmpty(className))
            {
                instance = new CharReplacementContentNamingProvider();
            }
            else
            {
                try
                {
                    instance = (ContentNamingProvider)TypeResolver.CreateInstance(className);
                }
                catch (Exception)
                {
                    SnLog.WriteWarning("Error loading ContentNamingProvider type: " + className, EventId.RepositoryLifecycle);
                }
            }

            if (instance == null)
            {
                instance = new CharReplacementContentNamingProvider();
            }

            SnLog.WriteInformation("ContentNamingProvider created: " + instance);

            __instance = instance;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Registers an application through the task management API.
        /// </summary>
        /// <returns>Returns true if the registration was successful.</returns>
        public static bool RegisterApplication()
        {
            var taskManUrl = Url;

            if (string.IsNullOrEmpty(taskManUrl))
            {
                return(false);
            }

            var requestData = new RegisterApplicationRequest
            {
                AppId          = ContentRepository.Storage.Settings.GetValue(Settings.SETTINGSNAME, Settings.TASKMANAGEMENTAPPID, null, Settings.TASKMANAGEMENTDEFAULTAPPID),
                ApplicationUrl = ContentRepository.Storage.Settings.GetValue <string>(Settings.SETTINGSNAME, Settings.TASKMANAGEMENTAPPLICATIONURL)
            };

            // make this a synchron call
            var registered = Instance.RegisterApplicationAsync(taskManUrl, requestData).GetAwaiter().GetResult();

            if (registered)
            {
                SnLog.WriteInformation("Task management app registration was successful.", EventId.TaskManagement.General, properties: new Dictionary <string, object>
                {
                    { "TaskManagementUrl", taskManUrl },
                    { "AppId", requestData.AppId }
                });
            }

            return(registered);
        }
Ejemplo n.º 18
0
        internal static WopiDiscovery GetInstance(string officeOnlineUrl)
        {
            return(Instances.GetOrAdd(officeOnlineUrl.TrimEnd('/'), oosUrl => new Lazy <WopiDiscovery>(() =>
            {
                var discoveryXml = new XmlDocument();

                Retrier.Retry(3, 500, () =>
                {
                    using (var client = new HttpClient())
                    {
                        using (var discoveryStream = client.GetAsync($"{oosUrl}/hosting/discovery")
                                                     .GetAwaiter().GetResult().Content.ReadAsStreamAsync().GetAwaiter().GetResult())
                        {
                            discoveryXml.Load(discoveryStream);
                        }
                    }
                }, (i, ex) => ex == null || i > 3);

                if (discoveryXml.DocumentElement == null)
                {
                    SnLog.WriteWarning($"Could not connect to Office Online Server {oosUrl} for available actions.");
                }
                else
                {
                    SnLog.WriteInformation($"Connected to Office Online Server {oosUrl} for available actions.");
                }


                return FromXmlDocument(discoveryXml);
            })).Value);
        }
Ejemplo n.º 19
0
        private static void InitializeOAuthProviders()
        {
            var providerTypeNames = new List <string>();

            foreach (var providerType in TypeResolver.GetTypesByInterface(typeof(IOAuthProvider)).Where(t => !t.IsAbstract))
            {
                if (!(TypeResolver.CreateInstance(providerType.FullName) is IOAuthProvider provider))
                {
                    continue;
                }

                if (string.IsNullOrEmpty(provider.ProviderName))
                {
                    SnLog.WriteWarning($"OAuth provider type {providerType.FullName} does not expose a valid ProviderName value, therefore cannot be initialized.");
                    continue;
                }
                if (string.IsNullOrEmpty(provider.IdentifierFieldName))
                {
                    SnLog.WriteWarning($"OAuth provider type {providerType.FullName} does not expose a valid IdentifierFieldName value, therefore cannot be initialized.");
                    continue;
                }

                Providers.Instance.SetProvider(OAuthProviderTools.GetProviderRegistrationName(provider.ProviderName), provider);
                providerTypeNames.Add($"{providerType.FullName} ({provider.ProviderName})");
            }

            if (providerTypeNames.Any())
            {
                SnLog.WriteInformation("OAuth providers registered: " + Environment.NewLine +
                                       string.Join(Environment.NewLine, providerTypeNames));
            }
        }
        public bool Start()
        {
            if (Settings.GetValue(MailHelper.MAILPROCESSOR_SETTINGS, MailHelper.SETTINGS_MODE, null, MailProcessingMode.ExchangePull) != MailProcessingMode.ExchangePush)
            {
                return(false);
            }

            // renew subscriptions
            //  1: go through doclibs with email addresses
            var doclibs = ContentQuery.Query("+TypeIs:DocumentLibrary +ListEmail:* -ListEmail:\"\"");

            if (doclibs.Count > 0)
            {
                SnLog.WriteInformation(String.Concat("Exchange subscription service enabled, running subscriptions (", doclibs.Count.ToString(), " found)"), categories: ExchangeHelper.ExchangeLogCategory);
                foreach (var doclib in doclibs.Nodes)
                {
                    try
                    {
                        ExchangeHelper.Subscribe(doclib);
                    }
                    catch (Exception ex)
                    {
                        SnLog.WriteException(ex, categories: ExchangeHelper.ExchangeLogCategory);
                    }
                }
            }
            else
            {
                SnLog.WriteInformation("Exchange subscription service enabled, no subscriptions found.", categories: ExchangeHelper.ExchangeLogCategory);
            }

            return(true);
        }
Ejemplo n.º 21
0
        private static void WriteLog(string name, object provider)
        {
            var message = $"{name} configured: {provider?.GetType().FullName ?? "null"}";

            SnTrace.Repository.Write(message);
            SnLog.WriteInformation(message);
        }
Ejemplo n.º 22
0
            public override SecurityActivity LoadSecurityActivity(int id)
            {
                var activity = base.LoadSecurityActivity(id);

                SnLog.WriteInformation($"LoadMessage: {activity.GetType().Name}#{id}");

                return(activity);
            }
Ejemplo n.º 23
0
 /// <summary>
 /// Reloads the storage schema and distributes a NodeTypeManagerRestart action.
 /// </summary>
 internal void Reset()
 {
     SnLog.WriteInformation("NodeTypeManager.Restart called.", EventId.RepositoryRuntime,
                            properties: new Dictionary <string, object> {
         { "AppDomain", AppDomain.CurrentDomain.FriendlyName }
     });
     new NodeTypeManagerRestartDistributedAction().ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult();
 }
Ejemplo n.º 24
0
        public static void WriteLog(string name, object provider)
        {
            var providerName = provider is string pName ? pName : provider?.GetType().FullName ?? "null";
            var message      = $"{name} configured: {providerName}";

            SnTrace.Repository.Write(message);
            SnLog.WriteInformation(message);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Loads all assemblies from the specified file system path.
        /// </summary>
        /// <param name="path">A file system path where assemblies should be loaded from.</param>
        /// <returns>An array of file names of loaded assemblies in the specified folder.</returns>
        public static string[] LoadAssembliesFrom(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (path.Length == 0)
            {
                throw new ArgumentException("Path cannot be empty.", nameof(path));
            }

            var loaded = new List <string>();
            var badImageFormatMessages = new List <string>();

            using (var op = SnTrace.Repository.StartOperation("Loading assemblies from: " + path))
            {
                _pluginsLoaded = true;

                var assemblies = AppDomain.CurrentDomain.GetAssemblies()
                                 .GroupBy(a => new AssemblyName(a.FullName).Name)
                                 .ToDictionary(grp => grp.Key, grp => grp.Last());

                var dllPaths = Directory.GetFiles(path, "*.dll");

                foreach (var dllPath in dllPaths)
                {
                    try
                    {
                        var asmName     = AssemblyName.GetAssemblyName(dllPath);
                        var asmFullName = asmName.FullName;
                        var asmNameName = asmName.Name;
                        if (assemblies.TryGetValue(asmNameName, out var origAsm))
                        {
                            SnTrace.Repository.Write("ASM Skipped: {0}, {1}", asmFullName, origAsm.Location);
                        }
                        else
                        {
                            var loadedAsm = Assembly.LoadFrom(dllPath);
                            assemblies.Add(asmNameName, loadedAsm);
                            loaded.Add(Path.GetFileName(dllPath));
                            SnTrace.Repository.Write("ASM Loaded: {0}, {1}", asmFullName, dllPath);
                        }
                    }
                    catch (BadImageFormatException e) //logged
                    {
                        badImageFormatMessages.Add(e.Message);
                    }
                }

                op.Successful = true;
            }
            if (badImageFormatMessages.Count > 0)
            {
                SnLog.WriteInformation(
                    $"Skipped assemblies from {path} on start: {Environment.NewLine}{string.Join(Environment.NewLine, badImageFormatMessages)}");
            }
            return(loaded.ToArray());
        }
Ejemplo n.º 26
0
        internal void DoStart()
        {
            ConsoleWriteLine();
            ConsoleWriteLine("Starting Repository...");
            ConsoleWriteLine();

            if (_settings.TraceCategories != null)
            {
                LoggingSettings.SnTraceConfigurator.UpdateCategories(_settings.TraceCategories);
            }
            else
            {
                LoggingSettings.SnTraceConfigurator.UpdateStartupCategories();
            }

            SearchManager.SetSearchEngineSupport(new SearchEngineSupport());

            InitializeLogger();

            RegisterAppdomainEventHandlers();

            if (_settings.IndexPath != null)
            {
                SearchManager.SetIndexDirectoryPath(_settings.IndexPath);
            }

            LoadAssemblies(_settings.IsWebContext);

            InitializeDataProviderExtensions();

            SecurityHandler.StartSecurity(_settings.IsWebContext);

            SnQueryVisitor.VisitorExtensionTypes = new[] { typeof(Sharing.SharingVisitor) };

            // We have to log the access provider here because it cannot be logged
            // during creation as it would lead to a circular reference.
            SnLog.WriteInformation($"AccessProvider created: {AccessProvider.Current?.GetType().FullName}");

            using (new SystemAccount())
                StartManagers();

            if (_settings.TraceCategories != null)
            {
                LoggingSettings.SnTraceConfigurator.UpdateCategories(_settings.TraceCategories);
            }
            else
            {
                LoggingSettings.SnTraceConfigurator.UpdateCategories();
            }

            InitializeOAuthProviders();

            ConsoleWriteLine();
            ConsoleWriteLine("Repository has started.");
            ConsoleWriteLine();

            _startupInfo.Started = DateTime.UtcNow;
        }
Ejemplo n.º 27
0
        public Task ExecuteAsync(CancellationToken cancellationToken)
        {
            if (!_ADSynchIsAvailable.HasValue)
            {
                _ADSynchIsAvailable = Settings.GetSettingsByName <Settings>(ADSyncSettingsName, null) != null;
                SnLog.WriteInformation("Active Directory synch feature is " + (_ADSynchIsAvailable.Value ? string.Empty : "not ") + "available.");
            }
            if (!_ADSynchIsAvailable.Value)
            {
                return(Task.CompletedTask);
            }

            // skip check if the feature is not enabled
            if (!Settings.GetValue(ADSyncSettingsName, "Enabled", null, false))
            {
                return(Task.CompletedTask);
            }

            if (!AdSyncTimeArrived())
            {
                return(Task.CompletedTask);
            }

#pragma warning disable 618
            // fallback for legacy code
            var appId = _taskManagementOptions.ApplicationId;
            if (string.IsNullOrEmpty(appId))
            {
                appId = SnTaskManager.Settings.AppId;
            }
            var appUrl = _taskManagementOptions.ApplicationUrl;
            if (string.IsNullOrEmpty(appUrl))
            {
                appUrl = SnTaskManager.Settings.AppUrl;
            }
#pragma warning restore 618

            var requestData = new RegisterTaskRequest
            {
                Type     = "SyncAD2Portal",
                Title    = "SyncAD2Portal",
                Priority = TaskPriority.Immediately,

                AppId       = appId,
                TaskData    = JsonConvert.SerializeObject(new { SiteUrl = appUrl }),
                Tag         = string.Empty,
                FinalizeUrl = "/odata.svc/('Root')/Ad2PortalSyncFinalizer"
            };

            // Fire and forget: we do not need the result of the register operation.
            // (we have to start a task here instead of calling RegisterTaskAsync
            // directly because the asp.net sync context callback would fail)
            Task.Run(() => _taskManager.RegisterTaskAsync(requestData, cancellationToken), cancellationToken);

            return(Task.CompletedTask);
        }
Ejemplo n.º 28
0
        public static void Subscribe(Node doclibrary, ExchangeService service)
        {
            if (service == null)
            {
                return;
            }

            var address = doclibrary["ListEmail"] as string;

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

            var mailbox     = new Mailbox(address);
            var folderId    = new FolderId(WellKnownFolderName.Inbox, mailbox);
            var servicePath = string.Format(Settings.GetValue <string>(MailHelper.MAILPROCESSOR_SETTINGS, MailHelper.SETTINGS_SERVICEPATH), doclibrary.Path);

            var watermark = ExchangeHelper.GetWaterMark(doclibrary);

            var ps = service.SubscribeToPushNotifications(new List <FolderId> {
                folderId
            }, new Uri(servicePath), Settings.GetValue(MailHelper.MAILPROCESSOR_SETTINGS, MailHelper.SETTINGS_POLLINGINTERVAL, null, 120), watermark, EventType.NewMail);

            var loginfo = string.Concat(" - Path:", doclibrary.Path, ", Email:", address, ", Watermark:", watermark, ", SubscriptionId:", ps.Id);

            SnLog.WriteInformation("Exchange subscription" + loginfo, categories: ExchangeHelper.ExchangeLogCategory);

            // persist subscription id to doclib, so that multiple subscriptions are handled correctly
            var user = User.Current;

            try
            {
                AccessProvider.Current.SetCurrentUser(User.Administrator);

                var retryCount = 3;
                while (retryCount > 0)
                {
                    try
                    {
                        doclibrary["ExchangeSubscriptionId"] = ps.Id;
                        doclibrary.Save();
                        break;
                    }
                    catch (NodeIsOutOfDateException)
                    {
                        retryCount--;
                        doclibrary = Node.LoadNode(doclibrary.Id);
                    }
                }
            }
            finally
            {
                AccessProvider.Current.SetCurrentUser(user);
            }
        }
Ejemplo n.º 29
0
        private static void UpdateTraceCategories()
        {
            foreach (var category in SnTrace.Categories.Where(c => !c.Enabled))
            {
                category.Enabled = Tracing.TraceCategories.Contains(category.Name);
            }

            SnLog.WriteInformation("Trace settings were updated in Search service.", EventId.NotDefined,
                                   properties: SnTrace.Categories.ToDictionary(c => c.Name, c => (object)c.Enabled.ToString()));
        }
        private static void ResetPrivate()
        {
            SnLog.WriteInformation("ResourceManager.Reset executed.", EventId.RepositoryRuntime,
                properties: new Dictionary<string, object> { { "AppDomain", AppDomain.CurrentDomain.FriendlyName } });

            lock (_syncRoot)
            {
                _current = null;
            }
        }