예제 #1
0
파일: AdLog.cs 프로젝트: SenseNet/sn-adsync
        private static void LogLine(string msg, EventType eventType)
        {
            switch (eventType)
            {
            case EventType.Error:
                SnLog.WriteError(msg, categories: AdSyncLogCategory);
                break;

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

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

            case EventType.Verbose:
                SnTrace.Write("{0}: {1}", AdSync, msg);
                break;
            }

            Console.WriteLine(msg);

            // 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));
                }
            }
        }
예제 #2
0
 private static void SendWaitForLockErrorMail()
 {
     if (!string.IsNullOrEmpty(Notification.NotificationSender) && !string.IsNullOrEmpty(Indexing.IndexLockFileRemovedNotificationEmail))
     {
         try
         {
             var smtpClient = new System.Net.Mail.SmtpClient();
             var msgstr     = string.Format(WRITELOCKREMOVEERRORTEMPLATESTR,
                                            Indexing.IndexLockFileWaitForRemovedTimeout,
                                            AppDomain.CurrentDomain.FriendlyName,
                                            AppDomain.CurrentDomain.BaseDirectory);
             var msg = new System.Net.Mail.MailMessage(
                 Notification.NotificationSender,
                 Indexing.IndexLockFileRemovedNotificationEmail.Replace(';', ','),
                 WRITELOCKREMOVEERRORSUBJECTSTR,
                 msgstr);
             smtpClient.Send(msg);
         }
         catch (Exception ex)
         {
             SnLog.WriteException(ex);
         }
     }
     else
     {
         SnLog.WriteError(WRITELOCKREMOVEEMAILERRORSTR);
     }
 }
예제 #3
0
        public virtual void OnTaskFinished(SnTaskResult result)
        {
            // the task was executed successfully without an error message
            if (result.Successful && result.Error == null)
            {
                return;
            }

            try
            {
                if (result.Error != null)
                {
                    // log the error message and details for admins
                    SnLog.WriteError("Task execution error, see the details below.",
                                     EventId.TaskManagement.General,
                                     properties: new Dictionary <string, object>
                    {
                        { "TaskType", result.Task.Type },
                        { "TaskData", result.Task.TaskData },
                        { "ErrorCode", result.Error.ErrorCode },
                        { "ErrorType", result.Error.ErrorType },
                        { "Message", result.Error.Message },
                        { "Details", result.Error.Details },
                        { "CallingContext", result.Error.CallingContext }
                    });
                }
            }
            catch (Exception ex)
            {
                SnLog.WriteException(ex);
            }
        }
예제 #4
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;
            }
        }
예제 #5
0
        private static void SearchServiceChannelOnFaulted(object sender, EventArgs eventArgs)
        {
            SnTrace.Index.WriteError("Centralized search service channel error.");

            // log an error once per minute
            if (_lastErrorLog.AddMinutes(1) < DateTime.UtcNow)
            {
                SnLog.WriteError("Centralized search service channel error.");
                _lastErrorLog = DateTime.UtcNow;
            }
        }
예제 #6
0
        private static void LogTypeLoadException(ReflectionTypeLoadException rtle, string assemblyName = null)
        {
            SnLog.WriteError(rtle.ToString(), properties: new Dictionary <string, object> {
                { "Assembly", assemblyName ?? "unknown" }
            });

            foreach (var exc in rtle.LoaderExceptions)
            {
                SnLog.WriteError(exc);
            }
        }
예제 #7
0
        public void TaskFinished(SnTaskResult taskResult)
        {
            SnTrace.TaskManagement.Write("AgentHub TaskFinished called. Agent: {0} / {1}, taskId: {2}, code: {3}, error: {4}",
                                         taskResult.MachineName, taskResult.AgentName, taskResult.Task.Id, taskResult.ResultCode,
                                         taskResult.Error == null ? "" : taskResult.Error.Message);
            try
            {
                if (string.IsNullOrEmpty(taskResult.Task.AppId))
                {
                    SnLog.WriteWarning($"AppId is empty for task #{taskResult.Task.Id}.",
                                       EventId.TaskManagement.Lifecycle);
                    return;
                }

                var doesApplicationNeedNotification = !string.IsNullOrWhiteSpace(taskResult.Task.GetFinalizeUrl());
                // first we make sure that the app is accessible by sending a ping request
                if (doesApplicationNeedNotification && !ApplicationHandler.SendPingRequest(taskResult.Task.AppId))
                {
                    var app = ApplicationHandler.GetApplication(taskResult.Task.AppId);

                    SnLog.WriteError(string.Format("Ping request to application {0} ({1}) failed when finalizing task #{2}. Task success: {3}, error: {4}",
                                                   taskResult.Task.AppId,
                                                   app == null ? "unknown app" : app.ApplicationUrl,
                                                   taskResult.Task.Id,
                                                   taskResult.Successful,
                                                   taskResult.Error == null ? "-" : taskResult.Error.ToString()),
                                     EventId.TaskManagement.Communication);

                    doesApplicationNeedNotification = false;
                }

                // remove the task from the database first
                TaskDataHandler.FinalizeTask(taskResult);

                SnTrace.TaskManagement.Write("AgentHub TaskFinished: task {0} has been deleted.", taskResult.Task.Id);

                if (doesApplicationNeedNotification)
                {
                    // This method does not need to be awaited, because we do not want to do anything
                    // with the result, only notify the app that the task has been finished.
                    ApplicationHandler.SendFinalizeNotificationAsync(taskResult);
                }

                // notify monitors
                TaskMonitorHub.OnTaskEvent(taskResult.Successful
                    ? SnTaskEvent.CreateDoneEvent(taskResult.Task.Id, taskResult.Task.Title, taskResult.ResultData, taskResult.Task.AppId, taskResult.Task.Tag, taskResult.MachineName, taskResult.AgentName)
                    : SnTaskEvent.CreateFailedEvent(taskResult.Task.Id, taskResult.Task.Title, taskResult.ResultData, taskResult.Task.AppId, taskResult.Task.Tag, taskResult.MachineName, taskResult.AgentName));
            }
            catch (Exception ex)
            {
                SnLog.WriteException(ex, "AgentHub TaskFinished failed.", EventId.TaskManagement.General);
            }
        }
예제 #8
0
        private void Domain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e?.ExceptionObject as Exception;

            if (ex != null)
            {
                SnLog.WriteException(ex, "Domain_UnhandledException", EventId.NotDefined);
            }
            else
            {
                SnLog.WriteError("Domain_UnhandledException. ExceptionObject is " + e?.ExceptionObject ?? "null", EventId.NotDefined);
            }
        }
예제 #9
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            var contentListPath = ContentListPath.Get(context);

            if (string.IsNullOrEmpty(contentListPath))
            {
                SnLog.WriteError("MailPoller activity: ContentList path is empty.");
                return(null);
            }

            var getMessagesDelegate = new Func <string, MailMessage[]>(GetMessages);

            context.UserState = getMessagesDelegate;
            return(getMessagesDelegate.BeginInvoke(contentListPath, callback, state));
        }
예제 #10
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            var pushNotification = PushNotification.Get(context);
            var contentListPath  = ContentListPath.Get(context);

            if (string.IsNullOrEmpty(contentListPath))
            {
                SnLog.WriteError("ExchangePoller activity: ContentList path is empty.", categories: ExchangeHelper.ExchangeLogCategory);
                return(null);
            }

            var GetMessageInfosDelegate = new Func <bool, string, EmailMessage[]>(GetMessageInfos);

            context.UserState = GetMessageInfosDelegate;
            return(GetMessageInfosDelegate.BeginInvoke(pushNotification, contentListPath, callback, state));
        }
예제 #11
0
 private static void WriteError(Exception e, Node node)
 {
     if (e != null)
     {
         SnLog.WriteException(e,
                              node != null
                 ? $"An error occured during extracting text. Version: {node.Version}, path: {node.Path}"
                 : $"An error occured during extracting text.");
     }
     else
     {
         SnLog.WriteError(node != null
             ? $"An error occured during extracting text. Version: {node.Version}, path: {node.Path}"
             : $"An error occured during extracting text.");
     }
 }
예제 #12
0
        public static void Ad2PortalSyncFinalizer(Content content, SnTaskResult result)
        {
            SnTaskManager.OnTaskFinished(result);

            // not enough information
            if (result.Task == null)
            {
                return;
            }

            try
            {
                if (!string.IsNullOrEmpty(result.ResultData))
                {
                    dynamic resultData = JsonConvert.DeserializeObject(result.ResultData);

                    SnLog.WriteInformation("AD sync finished. See details below.", EventId.DirectoryServices,
                                           properties: new Dictionary <string, object>
                    {
                        { "SyncedObjects", resultData.SyncedObjects },
                        { "ObjectErrorCount", resultData.ObjectErrorCount },
                        { "ErrorCount", resultData.ErrorCount },
                        { "ElapsedTime", resultData.ElapsedTime }
                    });
                }
                else
                {
                    SnLog.WriteWarning("AD sync finished with no results.", EventId.DirectoryServices);
                }
            }
            catch (Exception ex)
            {
                SnLog.WriteException(ex, "Error during AD sync finalizer.", EventId.DirectoryServices);
            }

            // the task was executed successfully without an error message
            if (result.Successful && result.Error == null)
            {
                return;
            }

            SnLog.WriteError("Error during AD sync. " + result.Error);
        }
예제 #13
0
        private static void ParseEncoding(string setting)
        {
            if (string.IsNullOrEmpty(setting))
            {
                MessageEncoding = DefaultMessageEncoding;
                return;
            }

            try
            {
                MessageEncoding = Encoding.GetEncoding(setting);
            }
            catch (ArgumentException)
            {
                SnLog.WriteError(
                    $"The configured value: {setting} is not a valid code page name. Default encoding is set: {DefaultMessageEncoding.BodyName}.");
                MessageEncoding = DefaultMessageEncoding;
            }
        }
예제 #14
0
        private void ChannelStopped(string[] stoppedChannels)
        {
            var receiverName = ContentRepository.DistributedApplication.ClusterChannel.ReceiverName;

            var allStoppedChannels = _channels.Where(c => stoppedChannels.Contains(c.Name)).ToArray();
            var brokenChannels     = allStoppedChannels.Where(c => c.NeedToRecover).ToArray();
            var closedChannels     = allStoppedChannels.Where(c => !c.NeedToRecover).ToArray();

            if (brokenChannels.Length > 0)
            {
                var brokenNames = brokenChannels.Select(c => c.Name).ToArray();
                Debug.WriteLine(
                    $"ClusterChannelMonitor> BROKEN CHANNELS ({receiverName}): {string.Join(", ", brokenNames)}, Running channels: {string.Join(", ", _currentResponses)}");
                SnLog.WriteError(
                    $"{brokenChannels.Length} cluster channel stopped: {string.Join(", ", brokenNames)}",
                    EventId.RepositoryLifecycle,
                    MessagingLoggingCategory,
                    properties: new Dictionary <string, object> {
                    { "Name: ", receiverName }, { "Running channels", string.Join(", ", _currentResponses) }
                });
            }
            if (closedChannels.Length > 0)
            {
                var closedNames = closedChannels.Select(c => c.Name).ToArray();
                Debug.WriteLine(
                    $"ClusterChannelMonitor> CLOSED CHANNELS ({receiverName}): {string.Join(", ", closedNames)}, Running channels: {string.Join(", ", _currentResponses)}");
                SnLog.WriteInformation(
                    $"{closedChannels.Length} Message channel stopped: {string.Join(", ", closedNames)}",
                    EventId.RepositoryLifecycle,
                    categories: MessagingLoggingCategory,
                    properties: new Dictionary <string, object> {
                    { "Name: ", receiverName }, { "Running channels", string.Join(", ", _currentResponses) }
                }
                    );
            }

            var channels = _channels.Where(x => stoppedChannels.Contains(x.Name));

            foreach (var channel in channels)
            {
                channel.Running = false;
            }
        }
예제 #15
0
        /// <summary>
        /// Waits for write.lock to disappear for a configured time interval. Timeout: configured with IndexLockFileWaitForRemovedTimeout key.
        /// If timeout is exceeded an error is logged and execution continues. For errors at OnStart an email is also sent to a configured address.
        /// </summary>
        /// <param name="waitType">A parameter that influences the logged error message and email template only.</param>
        public static void WaitForWriterLockFileIsReleased(WaitForLockFileType waitType)
        {
            // check if writer.lock is still there -> if yes, wait for other appdomain to quit or lock to disappear - until a given timeout.
            // after timeout is passed, Repository.Start will deliberately attempt to remove lock file on following startup

            if (!WaitForWriterLockFileIsReleased())
            {
                // lock file was not removed by other or current appdomain for the given time interval (onstart: other appdomain might use it, onend: current appdomain did not release it yet)
                // onstart -> notify operator and start repository anyway
                // onend -> log error, and continue
                var template = waitType == WaitForLockFileType.OnEnd ? WRITELOCKREMOVEERRORONENDTEMPLATESTR : WRITELOCKREMOVEERRORTEMPLATESTR;
                SnLog.WriteError(string.Format(template, Indexing.IndexLockFileWaitForRemovedTimeout,
                                               AppDomain.CurrentDomain.FriendlyName, AppDomain.CurrentDomain.BaseDirectory));

                if (waitType == WaitForLockFileType.OnStart)
                {
                    RepositoryInstance.SendWaitForLockErrorMail();
                }
            }
        }
예제 #16
0
        private void HandleTimeout()
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                return;
            }

            var transactionInfo = GatherLongRunningTransactionInformation();

            var rollbackOk            = true;
            var rollbackExceptionInfo = string.Empty;

            try
            {
                const int         timeOut     = 10 * 1000;
                var               tokenSource = new CancellationTokenSource();
                CancellationToken token       = tokenSource.Token;
                try
                {
                    using (var task = Task.Factory.StartNew(Rollback, token))
                    {
                        if (!task.Wait(timeOut, token))
                        {
                            tokenSource.Cancel();
                            rollbackOk = false;
                        }
                    }
                }
                catch (Exception e)
                {
                    rollbackExceptionInfo = e.ToString();
                }
            }
            finally
            {
                SnLog.WriteError(
                    $@"Transaction #{Id} timed out ({Configuration.Data.TransactionTimeout} sec). Rollback called on it {(rollbackOk ? "and it is executed successfully." : "but that is timed out too. " + rollbackExceptionInfo)}{Environment.NewLine}{transactionInfo}",
                    EventId.Transaction);
            }
        }
예제 #17
0
        public static void StartMessageProcessing()
        {
            if (!_isSmtpConfigured && !TestMode)
            {
                Debug.WriteLine("#Notification> Notification sender is unable to work. Reason: smtp server isn't configured.");
                SnLog.WriteError("Notification sender is unable to work. Reason: smtp server isn't configured.");
                return;
            }

            if (_mailSendingInProgress)
            {
                return;
            }

            _mailSendingInProgress = true;
            Debug.WriteLine("#Notification> _mailSendingInProgress true ");

            var worker = new Thread(ProcessQueuedMessages);

            worker.Name             = "NotificationSenderThread";
            worker.CurrentCulture   = Thread.CurrentThread.CurrentCulture;
            worker.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
            worker.Start();
        }
예제 #18
0
        public async Task TaskFinished(SnTaskResult taskResult)
        {
            SnTrace.TaskManagement.Write("AgentHub TaskFinished called. Agent: {0} / {1}, taskId: {2}, code: {3}, error: {4}",
                                         taskResult.MachineName, taskResult.AgentName, taskResult.Task.Id, taskResult.ResultCode,
                                         taskResult.Error == null ? "" : taskResult.Error.Message);
            try
            {
                if (string.IsNullOrEmpty(taskResult.Task.AppId))
                {
                    SnLog.WriteWarning($"AppId is empty for task #{taskResult.Task.Id}.",
                                       EventId.TaskManagement.Lifecycle);
                    return;
                }

                var app = _applicationHandler.GetApplication(taskResult.Task.AppId);
                var doesApplicationNeedNotification = !string.IsNullOrWhiteSpace(taskResult.Task.GetFinalizeUrl(app));

                // first we make sure that the app is accessible by sending a ping request
                if (doesApplicationNeedNotification && !(await _applicationHandler.SendPingRequestAsync(taskResult.Task.AppId, Context.ConnectionAborted)
                                                         .ConfigureAwait(false)))
                {
                    SnLog.WriteError($"Ping request to application {taskResult.Task.AppId} " +
                                     $"({(app == null ? "unknown app" : app.ApplicationUrl)}) " +
                                     $"failed when finalizing task #{taskResult.Task.Id}. " +
                                     $"Task success: {taskResult.Successful}, " +
                                     $"error: {(taskResult.Error == null ? "-" : taskResult.Error.ToString())}",
                                     EventId.TaskManagement.Communication);

                    doesApplicationNeedNotification = false;
                }

                // remove the task from the database first
                await _dataHandler.FinalizeTaskAsync(taskResult, Context.ConnectionAborted).ConfigureAwait(false);

                SnTrace.TaskManagement.Write("AgentHub TaskFinished: task {0} has been deleted.", taskResult.Task.Id);

                if (doesApplicationNeedNotification)
                {
                    // This method does not need to be awaited, because we do not want to do anything
                    // with the result, only notify the app that the task has been finished.
#pragma warning disable 4014
                    _applicationHandler.SendFinalizeNotificationAsync(taskResult, CancellationToken.None);
#pragma warning restore 4014
                }

                // notify monitors
                var te = taskResult.Successful
                    ? SnTaskEvent.CreateDoneEvent(taskResult.Task.Id, taskResult.Task.Title,
                                                  taskResult.ResultData, taskResult.Task.AppId, taskResult.Task.Tag,
                                                  taskResult.MachineName, taskResult.AgentName)
                    : SnTaskEvent.CreateFailedEvent(taskResult.Task.Id, taskResult.Task.Title,
                                                    taskResult.ResultData, taskResult.Task.AppId, taskResult.Task.Tag,
                                                    taskResult.MachineName, taskResult.AgentName);

                await _monitorHub.OnTaskEvent(te).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                SnLog.WriteException(ex, "AgentHub TaskFinished failed.", EventId.TaskManagement.General);
            }
        }
예제 #19
0
        private static void StartUpdaterAndExit()
        {
            // this switch is monitored by the Work method because it
            // must not ask for a new task if an update has started
            _updateStarted = true;

            SnLog.WriteInformation($"Task#Starting update process on agent {AgentName}.", EventId.TaskManagement.General);

            var updaterToolName       = AgentManager.UPDATER_PROCESSNAME + ".exe";
            var updaterToolPath       = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), updaterToolName);
            var updaterAlreadyRunning = false;

            // the tool should be next to the agent executable
            if (File.Exists(updaterToolPath))
            {
                var startInfo = new ProcessStartInfo(updaterToolName)
                {
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    ErrorDialog            = false,
                    WindowStyle            = ProcessWindowStyle.Hidden,
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                };

                var updaterProcess = new Process
                {
                    EnableRaisingEvents = true,
                    StartInfo           = startInfo
                };

                // listen to what the updater tool writes to the Console
                updaterProcess.OutputDataReceived += delegate(object sender, DataReceivedEventArgs args)
                {
                    if (args == null || args.Data == null)
                    {
                        return;
                    }

                    // the updater notified us that he won
                    if (string.CompareOrdinal(args.Data, "WINNER") == 0)
                    {
                        _updateWinner = true;
                    }
                };

                try
                {
                    updaterProcess.Start();
                    updaterProcess.BeginOutputReadLine();

                    SnLog.WriteInformation($"Task#Updater tool STARTED on agent {Agent.AgentName}",
                                           EventId.TaskManagement.General);

                    // Wait while the updater process exits (because another updater is already running)
                    // or it notifies us that he is the winner and will do the actual update soon.
                    do
                    {
                        updaterProcess.WaitForExit(1000);
                    } while (!updaterProcess.HasExited && !_updateWinner);

                    if (updaterProcess.HasExited)
                    {
                        if (updaterProcess.ExitCode == AgentManager.UPDATER_STATUSCODE_STARTED)
                        {
                            updaterAlreadyRunning = true;

                            // another agent already started the updater tool, simply exit
                            SnLog.WriteInformation($"Task#Updater tool EXITED on agent {AgentName} because another updater is already running.",
                                                   EventId.TaskManagement.General);
                        }
                        else
                        {
                            // unknown error code
                            SnLog.WriteWarning($"Task#Updater tool EXITED on agent {AgentName} with an unexpected code: {updaterProcess.ExitCode}.",
                                               EventId.TaskManagement.General);
                        }
                    }
                    else if (_updateWinner)
                    {
                        // Download the package only if we started the one
                        // and only true updater exe - that has not exited.
                        DownloadUpdatePackage();
                    }
                }
                catch (Exception ex)
                {
                    SnLog.WriteException(ex, "Agent update error.", EventId.TaskManagement.General);
                }
            }
            else
            {
                // the updater tool is missing
                SnLog.WriteError(string.Format("Task#Updater tool not found ({0}), but there is a new version on the server. Please update the TaskManagement folder manually.", updaterToolPath),
                                 EventId.TaskManagement.General);

                // no update will be performed: switch back to working mode
                _updateStarted = false;

                // do not exit if there is no updater: the operator must handle
                // this use-case manually (stop the service and copy the files)
                return;
            }

            // wait for the last task executor to finish
            while (_working)
            {
                Thread.Sleep(1000);
            }

            SnLog.WriteInformation(string.Format(updaterAlreadyRunning
                    ? "Task#Agent {0} exits before updating."
                    : "Task#Agent {0} exits before updating. This is Ripley, last survivor of the Nostromo, signing off.", AgentName), EventId.TaskManagement.General);

            // shut down this agent
            Environment.Exit(0);
        }
예제 #20
0
        // ================================================================================= Helper methods

        private void SendNotification()
        {
            var  parent = Content.Create(this.Parent);
            bool isNotificationEnabled;


            if (bool.TryParse(parent["EnableNotificationMail"].ToString(), out isNotificationEnabled) && isNotificationEnabled)
            {
                var mailTemplate  = this.Parent.GetReference <Node>("MailTemplatePage");
                var senderAddress = parent.Fields["SenderAddress"].GetData().ToString();

                if (mailTemplate != null && !string.IsNullOrEmpty(senderAddress))
                {
                    var evaluators = parent["Evaluators"] as List <Node>;
                    var emailList  = new Dictionary <string, string>();

                    if (evaluators != null)
                    {
                        foreach (var evaluator in evaluators)
                        {
                            var user = evaluator as IUser;

                            if (user != null && !string.IsNullOrEmpty(user.Email) && !emailList.ContainsKey(user.Email))
                            {
                                emailList.Add(user.Email, user.FullName);
                            }
                            else
                            {
                                var group = evaluator as Group;

                                if (group != null)
                                {
                                    foreach (var usr in group.GetAllMemberUsers())
                                    {
                                        if (!string.IsNullOrEmpty(usr.Email) && !emailList.ContainsKey(usr.Email))
                                        {
                                            emailList.Add(usr.Email, usr.FullName);
                                        }
                                    }
                                }
                            }
                        }

                        var mailTemplateCnt = Content.Create(mailTemplate);

                        var mailSubject = new StringBuilder(mailTemplateCnt.Fields["Subtitle"].GetData().ToString());

                        var mailBody = new StringBuilder(mailTemplateCnt.Fields["Body"].GetData().ToString());
                        var linkText = "<a href='{0}?action={1}'>{1}</a>";

                        var url = GetUrl();

                        mailBody = mailBody.Replace("{User}", (this.CreatedBy as IUser).FullName);
                        mailBody = mailBody.Replace("{SurveyName}", parent.DisplayName);
                        mailBody = mailBody.Replace("{Browse}", string.Format(linkText, url, "Browse"));
                        mailBody = mailBody.Replace("{Evaluate}", string.Format(linkText, url, "Evaluate"));
                        mailBody = mailBody.Replace("{Creator}", (this.Parent.CreatedBy as IUser).FullName);

                        foreach (var email in emailList)
                        {
                            mailBody = mailBody.Replace("{Addressee}", email.Value);
                            var mailMessage = new MailMessage(senderAddress, email.Key)
                            {
                                Subject    = mailSubject.ToString(),
                                IsBodyHtml = true,
                                Body       = mailBody.ToString()
                            };

                            try
                            {
                                using (var smtpClient = new SmtpClient())
                                    smtpClient.Send(mailMessage);
                            }
                            catch (Exception ex) // logged
                            {
                                SnLog.WriteException(ex);
                            }
                        }
                    }
                }
                else
                {
                    SnLog.WriteError("Notification e-mail cannot be sent because the template content or the sender address is missing.");
                }
            }
        }
예제 #21
0
        protected override void CreateChildControls()
        {
            if (this.HiddenPropertyCategories == null)
            {
                this.HiddenPropertyCategories = new List <string>();
            }
            this.HiddenPropertyCategories.Add("Cache"); // this is an administrative portlet we don't need to use Cache functionality.
            Controls.Clear();

            _currentUserControl = LoadUserInterface(Page, Configuration.Portlets.ContentAddNewPortletTemplate);

            // 1st allowed types check: if allowed content types list is empty, only administrators should be able to use this portlet
            var parentPath = GetParentPath();

            if (!AllowCreationForEmptyAllowedContentTypes(parentPath))
            {
                Controls.Add(new LiteralControl("Allowed ContentTypes list is empty!"));
                return;
            }


            if (_currentUserControl != null)
            {
                var contentError    = false;
                var contentTypeName = GetRequestedContentType();

                if (this.ContextNode != null && !string.IsNullOrEmpty(parentPath))
                {
                    try
                    {
                        _currentContent = ContentManager.CreateContentFromRequest(contentTypeName, null, parentPath, true);
                    }
                    catch (Exception ex)
                    {
                        SnLog.WriteException(ex);

                        // Something went wrong during content parsing, we should display
                        // an error message instead of simply displaying the type list.
                        contentError = true;
                    }
                }

                if (_currentContent != null)
                {
                    CurrentState = States[1];
                }

                if (!contentError && ContentTypeIsValid())
                {
                    SetControlsByState();

                    try
                    {
                        Controls.Add(_currentUserControl);
                    }
                    catch (Exception ex)
                    {
                        SnLog.WriteException(ex);

                        Controls.Clear();

                        var message = ex.Message.Contains("does not contain Field")
                                          ? string.Format("Content and view mismatch: {0}", ex.Message)
                                          : string.Format("Error: {0}", ex.Message);

                        Controls.Add(new LiteralControl(message));
                    }
                }
                else
                {
                    Controls.Clear();

                    if (_currentContent != null)
                    {
                        contentTypeName = _currentContent.ContentType.Name;
                        parentPath      = _currentContent.ContentHandler.ParentPath;
                    }

                    if (string.IsNullOrEmpty(contentTypeName))
                    {
                        contentTypeName = ContentManager.GetContentTypeNameFromRequest();
                    }

                    SnLog.WriteError($"Forbidden content type ({contentTypeName}) under {parentPath}");

                    Controls.Add(new LiteralControl($"It is not allowed to add a new {contentTypeName} here."));
                }
            }

            ChildControlsCreated = true;
        }
예제 #22
0
        protected override void Execute(NativeActivityContext context)
        {
            var message     = Message.Get(context);
            var parentPath  = ParentPath.Get(context);
            var overwrite   = OverwriteExistingContent.Get(context);
            var displayName = ContentDisplayName.Get(context);
            var name        = ContentName.Get(context);

            if (string.IsNullOrEmpty(name))
            {
                name = ContentNamingProvider.GetNameFromDisplayName(displayName) + ".eml";
            }

            var parent = Node.LoadNode(parentPath);

            if (parent == null)
            {
                throw new ApplicationException("Cannot create content because parent does not exist. Path: " + parentPath);
            }

            // check existing file
            var  node = Node.LoadNode(RepositoryPath.Combine(parentPath, name));
            File file;

            if (node == null)
            {
                // file does not exist, create new one
                file = new File(parent);
                if (!string.IsNullOrEmpty(displayName))
                {
                    file.DisplayName = displayName;
                }
                file.Name = name;
            }
            else
            {
                // file exists
                if (overwrite)
                {
                    // overwrite it, so we open it
                    file = node as File;

                    // node exists and it is not a file -> delete it and create a new one
                    if (file == null)
                    {
                        try
                        {
                            node.ForceDelete();
                        }
                        catch
                        {
                            SnLog.WriteError("Mail processor workflow: content could not be deleted during saving the email. Path: " + node.Path);
                            return;
                        }

                        file = new File(parent);
                    }
                    file.DisplayName = displayName;
                    file.Name        = name;
                }
                else
                {
                    // do not overwrite it
                    file = new File(parent);
                    if (!string.IsNullOrEmpty(displayName))
                    {
                        file.DisplayName = displayName;
                    }
                    file.Name = name;
                    file.AllowIncrementalNaming = true;
                }
            }

            try
            {
                var binaryData = new BinaryData()
                {
                    FileName = name
                };
                binaryData.SetStream(RepositoryTools.GetStreamFromString(message.Body));

                file.Binary = binaryData;
                file.Save();
            }
            catch (Exception ex)
            {
                SnLog.WriteException(ex);
            }
        }
        public SendNotificationResultType SendNotification(SendNotificationResponseType SendNotification1)
        {
            var result = new SendNotificationResultType();
            var rmta   = SendNotification1.ResponseMessages.Items;

            foreach (ResponseMessageType rmt in rmta)
            {
                if (rmt.ResponseCode != ResponseCodeType.NoError)
                {
                    SnLog.WriteError("An error occurred during receiving exchange notifications: " + rmt.MessageText,
                                     categories: ExchangeHelper.ExchangeLogCategory);
                    result.SubscriptionStatus = SubscriptionStatusType.OK;
                    return(result);
                }

                var snrmt        = rmt as SendNotificationResponseMessageType;
                var notification = snrmt.Notification;

                // check if subscription is valid:
                //  1: if it is not the last subscription, unsubscribe, so we don't receive mails twice or more
                //  2: if target email has been deleted, unsubscribe
                var contextNode            = PortalContext.Current.ContextNode;
                var targetEmail            = contextNode["ListEmail"] as string;
                var expectedSubscriptionId = contextNode["ExchangeSubscriptionId"] as string;
                var targetEmailEmpty       = string.IsNullOrEmpty(targetEmail);
                var subscriptiondifferent  = expectedSubscriptionId != notification.SubscriptionId;
                if (subscriptiondifferent || targetEmailEmpty)
                {
                    var loginfo = string.Concat("Exchange unsubscribe: subscriptionId of event and last subscription are different:", (subscriptiondifferent).ToString(), ", targetemail is empty: ", targetEmailEmpty.ToString(), ", path: ", contextNode.Path);
                    SnLog.WriteInformation(loginfo, categories: ExchangeHelper.ExchangeLogCategory);

                    result.SubscriptionStatus = SubscriptionStatusType.Unsubscribe;
                    return(result);
                }

                var items = notification.Items;

                // extract mail ids
                var itemIdsBuilder = new StringBuilder();
                var lastWatermark  = string.Empty;
                for (int i = 0; i < items.Length; i++)
                {
                    var bocet = items[i] as BaseObjectChangedEventType;
                    if (bocet != null)
                    {
                        var loginfo = string.Concat(" - Path:", contextNode.Path, ", Email:", contextNode["ListEmail"], ", Watermark:", bocet.Watermark, ", SubscriptionId:", notification.SubscriptionId);
                        SnLog.WriteInformation(string.Concat("Exchange ", notification.ItemsElementName[i].ToString(), loginfo), categories: ExchangeHelper.ExchangeLogCategory);

                        var itemId = bocet.Item as ItemIdType;
                        if (itemId != null)
                        {
                            itemIdsBuilder.Append(itemId.Id);
                            itemIdsBuilder.Append(";");
                        }
                        lastWatermark = bocet.Watermark;
                    }
                    else
                    {
                        var loginfo = string.Concat(" - Path:", contextNode.Path, ", Email:", contextNode["ListEmail"]);
                        SnLog.WriteInformation(string.Concat("Exchange ", notification.ItemsElementName[i].ToString(), loginfo), categories: ExchangeHelper.ExchangeLogCategory);
                    }
                }

                // persist mail ids under contentlist
                var itemIds = itemIdsBuilder.ToString();
                if (!string.IsNullOrEmpty(itemIds))
                {
                    var parent = SetWatermark(contextNode, lastWatermark);
                    if (parent != null)
                    {
                        using (new SystemAccount())
                        {
                            try
                            {
                                var task = new Task(parent)
                                {
                                    Name = "IncomingEmail",
                                    AllowIncrementalNaming = true,
                                    Description            = itemIds
                                };
                                task.Save();
                            }
                            catch (Exception ex)
                            {
                                SnLog.WriteException(ex);
                            }
                        }
                    }
                }
            }
            result.SubscriptionStatus = SubscriptionStatusType.OK;
            return(result);
        }
예제 #24
0
        /// <summary>
        /// Loads all types that inherit from the specified base type.
        /// </summary>
        /// <param name="baseType">Base type to look for.</param>
        public static Type[] GetTypesByBaseType(Type baseType)
        {
            Type[] temp;
            if (!TypecacheByBase.TryGetValue(baseType, out temp))
            {
                lock (TypeCacheSync)
                {
                    if (!TypecacheByBase.TryGetValue(baseType, out temp))
                    {
                        var list = new List <Type>();
                        foreach (var asm in GetAssemblies())
                        {
                            try
                            {
                                if (asm.IsDynamic)
                                {
                                    continue;
                                }

                                var types = asm.GetTypes();
                                foreach (var type in types)
                                {
                                    try
                                    {
                                        if (type.IsSubclassOf(baseType))
                                        {
                                            list.Add(type);
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        if (!IgnorableException(e))
                                        {
                                            throw TypeDiscoveryError(e, type.FullName, asm);
                                        }
                                    }
                                }
                            }
                            catch (ReflectionTypeLoadException rtle)
                            {
                                SnLog.WriteError(rtle.ToString(), properties: new Dictionary <string, object> {
                                    { "Assembly", asm.FullName }
                                });

                                // Logging each exception
                                foreach (var exc in rtle.LoaderExceptions)
                                {
                                    SnLog.WriteError(exc);
                                }

                                throw;
                            }
                            catch (Exception e)
                            {
                                if (!IgnorableException(e))
                                {
                                    throw TypeDiscoveryError(e, null, asm);
                                }
                            }
                        }
                        temp = list.ToArray();

                        if (!TypecacheByBase.ContainsKey(baseType))
                        {
                            TypecacheByBase.Add(baseType, temp);
                        }
                    }
                }
            }

            var result = new Type[temp.Length];

            temp.CopyTo(result, 0);
            return(result);
        }