예제 #1
0
        private void ChangeStateToExpiredItems()
        {
            var implicitExpire = persister.Repository
                                 .Find(Parameter.LessOrEqual("Expires", Utility.CurrentTime())
                                       & Parameter.Equal("State", ContentState.Published))
                                 .ToList();

            for (int i = 0; i < implicitExpire.Count; i++)
            {
                try
                {
                    // reset status on expired items
                    var item = implicitExpire[i];
                    changer.ChangeTo(item, ContentState.Unpublished);
                    persister.Save(item);
                }
                catch (Exception ex)
                {
                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                    }
                    logger.Error(ex);
                }
            }
        }
예제 #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            btnCancel.NavigateUrl = Selection.SelectedItem.FindPath(PathData.DefaultAction).GetRewrittenUrl();

            ContentItem toMove = Selection.MemorizedItem;

            if (toMove == null)
            {
                return;
            }

            if (!IsPostBack)
            {
                pnlNewName.Visible = false;

                try
                {
                    PerformMove(toMove);
                }
                catch (NameOccupiedException ex)
                {
                    SetErrorMessage(cvMove, ex);
                    pnlNewName.Visible = true;
                }
                catch (DestinationOnOrBelowItselfException ex)
                {
                    SetErrorMessage(cvMove, ex);
                    btnMove.Enabled = false;
                }
                catch (PermissionDeniedException ex)
                {
                    SetErrorMessage(cvMove, ex);
                    btnMove.Enabled = false;
                }
                catch (NotAllowedParentException ex)
                {
                    SetErrorMessage(cvMove, ex);
                    btnMove.Enabled = false;
                }
                catch (NullReferenceException ex)
                {
                    logger.Error(ex);
                    SetErrorMessage(cvException, "Nothing to move");
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                    SetErrorMessage(cvMove, ex);
                }

                txtNewName.Text = toMove.Name;
            }

            LoadDefaultsAndInfo(toMove, Selection.SelectedItem);
        }
예제 #3
0
 private void WriteToIndex(int itemID, Document doc)
 {
     if (doc == null)
     {
         return;
     }
     lock (accessor)
     {
         var iw = accessor.GetWriter();
         try
         {
             iw.UpdateDocument(new Term(TextExtractor.Properties.ID, itemID.ToString()), doc);
             iw.PrepareCommit();
             iw.Commit();
         }
         catch (AlreadyClosedException ex)
         {
             logger.Error(ex);
             try
             {
                 iw = accessor.GetWriter();
                 iw.UpdateDocument(new Term(TextExtractor.Properties.ID, itemID.ToString()), doc);
                 iw.PrepareCommit();
                 iw.Commit();
             }
             catch (Exception ex2)
             {
                 logger.Error(ex2);
                 iw.Dispose();
                 accessor.ClearLock();
             }
         }
         catch (ThreadAbortException ex)
         {
             logger.Warn(ex);
             iw.Rollback();
             iw.Dispose(waitForMerges: false);
             accessor.ClearLock();
             throw;
         }
         catch (Exception ex)
         {
             logger.Error(ex);
             iw.Rollback();
             iw.Dispose();
             accessor.ClearLock();
         }
         finally
         {
             iw.Dispose(waitForMerges: true);
             accessor.RecreateSearcher();
         }
     }
 }
예제 #4
0
        private bool UpdateVersion(DatabaseStatus status)
        {
            try
            {
                status.DatabaseVersion = 0;
                sessionProvider.OpenSession.Session.CreateQuery("select ci.ID from " + typeof(ContentItem).Name + " ci").SetMaxResults(1).List();
                status.DatabaseVersion = 1;

                // checking for properties added between version 1 and 2
                sessionProvider.OpenSession.Session.CreateQuery("select ci.AncestralTrail from " + typeof(ContentItem).Name + " ci").SetMaxResults(1).List();
                status.DatabaseVersion = 2;

                // checking for properties added between version 2 and 3
                sessionProvider.OpenSession.Session.CreateQuery("select ci.AlteredPermissions from " + typeof(ContentItem).Name + " ci").SetMaxResults(1).List();
                status.DatabaseVersion = 3;

                // checking for properties added between version 3 and 4
                sessionProvider.OpenSession.Session.CreateQuery("select ci.TemplateKey from " + typeof(ContentItem).Name + " ci").SetMaxResults(1).List();
                status.DatabaseVersion = 4;

                // checking for properties added between 4 and 5
                sessionProvider.OpenSession.Session.CreateQuery("select ci.ChildState from " + typeof(ContentItem).Name + " ci").SetMaxResults(1).List();
                status.DatabaseVersion = 5;

                // checking for properties added between 5 and 6
                sessionProvider.OpenSession.Session.CreateQuery("select cd.Meta from " + typeof(ContentDetail).Name + " cd").SetMaxResults(1).List();
                status.DatabaseVersion = 6;

                // checking for properties added between 6 and 7
                sessionProvider.OpenSession.Session.CreateQuery("select cv.FuturePublish from " + typeof(ContentVersion).Name + " cv").SetMaxResults(1).List();
                status.DatabaseVersion = 7;

                if (isDatabaseFileSystemEnbled)
                {
                    // checking file system table (if enabled)
                    sessionProvider.OpenSession.Session.CreateQuery("select ci from " + typeof(N2.Edit.FileSystem.NH.FileSystemItem).Name + " ci").SetMaxResults(1).List();
                    status.DatabaseVersion = 8;
                }

                // checking persistable properties added in application
                sessionProvider.OpenSession.Session.CreateQuery("select ci from " + typeof(ContentItem).Name + " ci").SetMaxResults(1).List();
                status.DatabaseVersion = DatabaseStatus.RequiredDatabaseVersion;
                return(true);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(false);
            }
        }
        public override SiteMapNode FindSiteMapNode(string rawUrl)
        {
            FileSiteMapNode fsmn = null;

            try
            {
                string[] pageQueryPair = rawUrl.Split('?');
                if (pageQueryPair.Length > 1)
                {
                    NameValueCollection nvc = HttpUtility.ParseQueryString(pageQueryPair[1]);
                    if (!string.IsNullOrEmpty(nvc["fileUrl"]))
                    {
                        fsmn = NewNode(nvc["fileUrl"]);
                    }
                }
                else
                {
                    fsmn = NewNode(rawUrl);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return(fsmn);
        }
예제 #6
0
        public void WriteTo(TextWriter writer)
        {
            if (Context.Displayable == null || Context.Content == null)
            {
                return;
            }

            Context.IsEditable = isEditable && ControlPanelExtensions.GetControlPanelState(Context.Html).IsFlagSet(ControlPanelState.DragDrop);

            var renderer = Context.Html.ResolveService <DisplayableRendererSelector>();

            if (swallowExceptions)
            {
                try
                {
                    renderer.Render(Context, writer);
                }
                catch (System.Exception ex)
                {
                    logger.Error(ex);
                }
            }
            else
            {
                renderer.Render(Context, writer);
            }
        }
예제 #7
0
 private void InitMaxFileSize()
 {
     try
     {
         var config = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
         maxFileSize = config.MaxRequestLength * 1024 - 10000;
     }
     catch (Exception ex)
     {
         logger.Error(ex);
     }
 }
예제 #8
0
        private IEnumerable <RssAggregatorModel.RssItem> GetNewsItems(string url)
        {
            try
            {
                var xml = XDocument.Load(url).ToString();

                foreach (var formatter in new SyndicationFeedFormatter[] { new Rss20FeedFormatter(), new Atom10FeedFormatter() })
                {
                    using (var reader = new XmlTextReader(new StringReader(xml)))
                    {
                        if (!formatter.CanRead(reader))
                        {
                            continue;
                        }

                        formatter.ReadFrom(reader);
                        return(formatter.Feed.Items.Select(i => new RssAggregatorModel.RssItem
                        {
                            Title = i.Title.Text,
                            Introduction = i.Summary != null ? i.Summary.Text : "",
                            Published = i.PublishDate,
                            Url = i.Links.Where(l => l.MediaType == "text/html").Select(l => l.Uri.ToString()).FirstOrDefault()
                                  ?? i.Links.Select(l => l.Uri.ToString()).FirstOrDefault()
                        }));
                    }
                }
            }
            catch (SecurityException)
            {
                // Cannot use this in Medium Trust
                return(GetCannotLoadItem(Resources.RssAggregator.CannotLoadCauseSecurity));
            }
            catch (SocketException)
            {
                //Feed Is Offline or inaccessible
                return(GetCannotLoadItem("Could not load RSS feed due to network connectivity failure."));
            }
            catch (WebException)
            {
                //invalid feed address?
                return(GetCannotLoadItem("Could not load RSS feed, possible failure resolving remote host."));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            return(GetCannotLoadItem(""));
        }
예제 #9
0
파일: Client.cs 프로젝트: bourgeoisor/topaz
        public void HandleMessages()
        {
            NetIncomingMessage msg;

            while ((msg = _client.ReadMessage()) != null)
            {
                if (msg.PeekString() != "")
                {
                    LastNetMessage = msg.PeekString();
                }

                switch (msg.MessageType)
                {
                case NetIncomingMessageType.StatusChanged:
                    _logger.Info("StatusChanged received: " + msg.SenderConnection.Status);
                    break;

                case NetIncomingMessageType.Data:
                    LastNetMessage = (MessageType)msg.PeekInt32() + "";
                    HandleIncomingData(msg);
                    break;

                case NetIncomingMessageType.ConnectionLatencyUpdated:
                    LastLatency = (int)Math.Round(msg.ReadFloat() * 1000);
                    break;

                case NetIncomingMessageType.VerboseDebugMessage:
                case NetIncomingMessageType.DebugMessage:
                    _logger.Debug(msg.ReadString());
                    break;

                case NetIncomingMessageType.WarningMessage:
                    _logger.Warn(msg.ReadString());
                    break;

                case NetIncomingMessageType.ErrorMessage:
                    _logger.Error(msg.ReadString());
                    break;

                default:
                    _logger.Warn("Unhandled MessageType: " + msg.MessageType);
                    break;
                }

                _client.Recycle(msg);
            }
        }
예제 #10
0
 public virtual Items.User GetUser(string username)
 {
     try
     {
         IList <Items.User> users = GetUsers(username, 0, 1);
         if (users.Count == 0)
         {
             return(null);
         }
         return(users[0]);
     }
     catch (Exception ex)
     {
         logger.Error(ex);
         return(null);
     }
 }
예제 #11
0
        protected override void OnInit(EventArgs e)
        {
            try
            {
                selectedPath = Selection.SelectedItem.Path;
                selectedUrl  = Engine.GetContentAdapter <NodeAdapter>(Selection.SelectedItem).GetPreviewUrl(Selection.SelectedItem);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Response.Redirect(N2.Web.Url.ResolveTokens(Engine.Resolve <EditSection>().Installer.WelcomeUrl));
            }

            Resources.Register.JQueryUi(Page);
            Resources.Register.JQueryPlugins(Page);

            base.OnInit(e);
        }
예제 #12
0
파일: Server.cs 프로젝트: bourgeoisor/topaz
        public void ServerThread()
        {
            NetIncomingMessage msg;

            while (Engine.Core.Instance.State == Engine.Core.EngineState.Running)
            {
                Thread.Sleep(5);
                while ((msg = _server.ReadMessage()) != null)
                {
                    switch (msg.MessageType)
                    {
                    case NetIncomingMessageType.StatusChanged:
                        _logger.Info("StatusChanged received: " + msg.SenderConnection.Status);
                        HandleStatusChanged(msg);
                        break;

                    case NetIncomingMessageType.Data:
                        HandleIncomingData(msg);
                        break;

                    case NetIncomingMessageType.VerboseDebugMessage:
                    case NetIncomingMessageType.DebugMessage:
                        _logger.Debug(msg.ReadString());
                        break;

                    case NetIncomingMessageType.WarningMessage:
                        _logger.Warn(msg.ReadString());
                        break;

                    case NetIncomingMessageType.ErrorMessage:
                        _logger.Error(msg.ReadString());
                        break;

                    default:
                        _logger.Warn("Unhandled MessageType: " + msg.MessageType);
                        break;
                    }
                    _server.Recycle(msg);
                }
            }

            _logger.Info("Terminated.");
        }
예제 #13
0
        protected void btnEnable_Click(object sender, EventArgs args)
        {
            try
            {
                System.Configuration.Configuration cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

                EngineSection engineConfiguration = (EngineSection)cfg.GetSection("n2/engine");
                engineConfiguration.Globalization.Enabled = true;

                cfg.Save();

                cvLanguageRoots.IsValid = Engine.Resolve <ILanguageGateway>().GetAvailableLanguages().GetEnumerator().MoveNext();
                Initialize();
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                cvEnable.IsValid = false;
            }
        }
예제 #14
0
        /// <summary>Executes the supplied command</summary>
        /// <param name="command">The command to execute.</param>
        /// <param name="context">The context passed to the command</param>
        public virtual void Execute(CommandBase <CommandContext> command, CommandContext context)
        {
            var args = new CommandProcessEventArgs {
                Command = command, Context = context
            };

            if (CommandExecuting != null)
            {
                CommandExecuting.Invoke(this, args);
            }

            logger.Info(args.Command.Name + " processing " + args.Context);
            using (var tx = persister.Repository.BeginTransaction())
            {
                try
                {
                    args.Command.Process(args.Context);
                    Utility.FindEmpty(args.Context.Content);
                    tx.Commit();

                    if (CommandExecuted != null)
                    {
                        CommandExecuted.Invoke(this, args);
                    }
                }
                catch (StopExecutionException)
                {
                    tx.Rollback();
                }
                catch (Exception ex)
                {
                    tx.Rollback();
                    logger.Error(ex);
                    throw;
                }
                finally
                {
                    logger.Info(" -> " + args.Context);
                }
            }
        }
예제 #15
0
 protected override void OnInit(EventArgs args)
 {
     Response.Status = "500 Internal Server Error";
     try
     {
         N2.ContentItem page = N2.Templates.Find.StartPage.ErrorPage;
         if (page != null)
         {
             var wc = N2.Context.Current.Resolve <N2.Web.IWebContext>();
             wc.CurrentPage = page;
             Server.Execute(Url.Parse(page.FindPath(PathData.DefaultAction).GetRewrittenUrl()).AppendQuery("postback", page.Url));
             Response.End();
             return;
         }
     }
     catch (Exception ex)
     {
         logger.Error(ex.ToString());
     }
     Response.Write("<html><body><h1>500 Internal Server Error</h1></body></html>");
     Response.End();
 }
예제 #16
0
        private void SendEmail(string subject, string body)
        {
            string from     = ConfigurationManager.AppSettings["Demo.From"];
            string to       = ConfigurationManager.AppSettings["Demo.To"];
            string serverUn = ConfigurationManager.AppSettings["Demo.SmtpUN"];
            string serverPw = ConfigurationManager.AppSettings["Demo.SmtpPW"];

            try
            {
                MailMessage mm = new MailMessage(from, to);
                mm.Subject = subject;
                mm.Body    = string.Format(body, body);
                SmtpClient sc = new SmtpClient();
                if (!string.IsNullOrEmpty(serverUn))
                {
                    sc.Credentials = new System.Net.NetworkCredential(serverUn, serverPw);
                }
                sc.Send(mm);
            }
            catch (Exception ex)
            {
                logger.Error(subject + Environment.NewLine + body + Environment.NewLine + ex);
            }
        }
예제 #17
0
        internal void Render(RenderingContext context, TextWriter writer)
        {
            string text = context.Content[context.PropertyName] as string;

            if (text == null)
            {
                return;
            }

            var tokens = context.Content.GetDetailCollection(context.PropertyName + CollectionSuffix, false);

            if (tokens != null)
            {
                int lastFragmentEnd = 0;

                foreach (var detail in tokens.Details)
                {
                    var token = detail.ExtractToken();

                    if (lastFragmentEnd < token.Index)
                    {
                        writer.Write(text.Substring(lastFragmentEnd, token.Index - lastFragmentEnd));
                    }

                    ViewEngineResult vr = null;
                    if (context.Html.ViewContext.HttpContext.IsCustomErrorEnabled)
                    {
                        try
                        {
                            vr = ViewEngines.Engines.FindPartialView(context.Html.ViewContext, "TokenTemplates/" + token.Name);
                        }
                        catch (System.Exception ex)
                        {
                            logger.Error(ex);
                        }
                    }
                    else
                    {
                        vr = ViewEngines.Engines.FindPartialView(context.Html.ViewContext, "TokenTemplates/" + token.Name); // duplicated to preserve stack trace
                    }

                    if (vr != null && vr.View != null)
                    {
                        var viewData = new ViewDataDictionary(token.Value)
                        {
                            { "ParentViewContext", context.Html.ViewContext }
                        };
                        viewData[RenderingExtensions.ContextKey] = context;
                        viewData[RenderingExtensions.TokenKey]   = token;
                        var vc = new ViewContext(context.Html.ViewContext, vr.View, viewData, context.Html.ViewContext.TempData, writer);
                        vr.View.Render(vc, writer);
                    }
                    else
                    {
                        writer.Write(detail.StringValue);
                    }

                    lastFragmentEnd = token.Index + detail.StringValue.Length;
                }

                if (lastFragmentEnd < text.Length)
                {
                    writer.Write(text.Substring(lastFragmentEnd, text.Length - lastFragmentEnd));
                }
            }
            else
            {
                writer.Write(text);
            }
        }
예제 #18
0
        /// <summary>Executes the scheduled actions that are scheduled for executions.</summary>
        public void ExecuteActions()
        {
            if (!enabled)
            {
                return;
            }

            if (Debugger.IsAttached && !runWhileDebuggerAttached)
            {
                return;
            }

            for (int i = 0; i < actions.Count; i++)
            {
                ScheduledAction action = actions[i];
                if (action.ShouldExecute())
                {
                    Action work = delegate
                    {
                        try
                        {
                            var config = ((System.Web.Configuration.GlobalizationSection)System.Configuration.ConfigurationManager.GetSection("system.web/globalization"));
                            if (!string.IsNullOrEmpty(config.Culture))
                            {
                                Thread.CurrentThread.CurrentCulture = new CultureInfo(config.Culture);
                            }
                            if (!string.IsNullOrEmpty(config.UICulture))
                            {
                                Thread.CurrentThread.CurrentUICulture = new CultureInfo(config.UICulture);
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.Warn(ex);
                        }

                        try
                        {
                            logger.Debug("Executing " + action.GetType().Name);
                            action.Engine = engine;
                            action.Execute();
                            action.ErrorCount = 0;
                        }
                        catch (Exception ex)
                        {
                            action.ErrorCount++;
                            action.LastError = ex;
                            try
                            {
                                logger.Error("Exception executing scheduled action: ", ex);
                                action.OnError(ex);                                     // wayne: call custom action error handler
                            }
                            catch (Exception ex2)
                            {
                                logger.Error("Exception handling error: ", ex2);
                            }
                        }
                        finally
                        {
                            try
                            {
                                IClosable closable = action as IClosable;
                                if (closable != null)
                                {
                                    closable.Dispose();
                                }
                            }
                            catch (Exception ex)
                            {
                                errorHandler.Notify(ex);
                            }
                        }
                        action.LastExecuted = Utility.CurrentTime();
                        action.IsExecuting  = false;

                        try
                        {
                            context.Close();
                        }
                        catch (Exception ex)
                        {
                            errorHandler.Notify(ex);
                        }
                    };

                    action.IsExecuting = true;
                    if (asyncActions)
                    {
                        worker.DoWork(work);
                    }
                    else
                    {
                        work();
                    }

                    if (action.Repeat == Repeat.Once)
                    {
                        actions.RemoveAt(i);
                        --i;
                    }
                }
            }
        }
예제 #19
0
        /// <summary>Finds the path associated with an url.</summary>
        /// <param name="url">The url to the template to locate.</param>
        /// <param name="startNode">The node to start finding path from if none supplied will start from StartNode</param>
        /// <param name="remainingPath">The remaining path to search</param>
        /// <returns>A PathData object. If no template was found the object will have empty properties.</returns>
        public PathData FindPath(Url url, ContentItem startNode = null, string remainingPath = null)
        {
            if (url == null)
            {
                return(PathData.Empty);
            }
            if (!IsOnline)
            {
                return(PathData.Empty);
            }

            Url         requestedUrl = url;
            ContentItem item         = TryLoadingFromQueryString(requestedUrl, PathData.ItemQueryKey);
            ContentItem page         = TryLoadingFromQueryString(requestedUrl, PathData.PageQueryKey);

            if (page != null)
            {
                var directPath = page.FindPath(requestedUrl["action"] ?? PathData.DefaultAction)
                                 .SetArguments(requestedUrl["arguments"])
                                 .UpdateParameters(requestedUrl.GetQueries());

                var directData = UseItemIfAvailable(item, directPath);
                // check whether to rewrite requests with page in query string since this might be already rewritten
                directData.IsRewritable &= !string.Equals(url.ApplicationRelativePath, directData.TemplateUrl, StringComparison.InvariantCultureIgnoreCase);
                return(directData);
            }

            ContentItem startPage = startNode ?? GetStartPage(requestedUrl);

            if (startPage == null)
            {
                return(PathData.Empty);
            }

            string   path = remainingPath ?? Url.ToRelative(requestedUrl.Path).TrimStart('~');
            PathData data = startPage.FindPath(path).UpdateParameters(requestedUrl.GetQueries());

            if (data.IsEmpty())
            {
                if (!string.IsNullOrEmpty(DefaultDocument) && path.EndsWith(DefaultDocument, StringComparison.OrdinalIgnoreCase))
                {
                    // Try to find path without default document.
                    data = StartPage
                           .FindPath(StripDefaultDocument(path))
                           .UpdateParameters(requestedUrl.GetQueries());
                }

                if (data.IsEmpty())
                {
                    // Allow user code to set path through event
                    if (PageNotFound != null)
                    {
                        PageNotFoundEventArgs args = new PageNotFoundEventArgs(requestedUrl);
                        args.AffectedPath = data;
                        PageNotFound(this, args);
                        data = args.AffectedPath;
                    }
                }
            }

            try
            {
                if (webContext.HttpContext != null)
                {
                    data.Ignore = !IgnoreExisting(webContext.HttpContext.Request.PhysicalPath);
                }

                data = UseItemIfAvailable(item, data);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                throw;
            }

            return(data);
        }