Пример #1
0
        protected PostCollection GetTaggedPosts(string tagName)
        {
            PostCollection pc = ZCache.Get <PostCollection>("Tags-ForRSS-" + tagName);

            if (pc == null)
            {
                pc = Post.FetchPostsByTag(TagName);

                PostCollection permissionsFiltered = new PostCollection();
                foreach (Post post in pc)
                {
                    permissionsFiltered.Add(post);
                }
                permissionsFiltered.AddRange(pc);
                foreach (Post p in pc)
                {
                    if (!RolePermissionManager.GetPermissions(p.Category.Id, GraffitiUsers.Current).Read)
                    {
                        permissionsFiltered.Remove(p);
                    }
                }
                pc.Clear();
                int ctr = 0;
                foreach (Post post in permissionsFiltered)
                {
                    if (ctr < Util.PageSize)
                    {
                        pc.Add(post);
                        ctr++;
                    }
                }
                ZCache.InsertCache("Tags-ForRSS-" + tagName, pc, 120);
            }
            return(pc);
        }
Пример #2
0
        /// <summary>
        /// Gets all tags
        /// </summary>
        /// <returns></returns>
        public TagCollection GetAllTags()
        {
            TagCollection tc = ZCache.Get <TagCollection>("AllTags");

            if (tc == null)
            {
                tc = new TagCollection();

                TagCollection temp = TagCollection.FetchAll();

                foreach (Tag t in temp)
                {
                    Tag tag = tc.Find(
                        delegate(Tag tempTag)
                    {
                        return(tempTag.Name == t.Name);
                    });

                    if (tag == null)
                    {
                        tc.Add(t);
                    }
                }

                ZCache.InsertCache("AllTags", tc, 90);
            }

            return(tc);
        }
Пример #3
0
        public override string RenderData()
        {
            if (PostIds == null || PostIds.Length == 0)
            {
                return(string.Empty);
            }

            PostCollection pc = ZCache.Get <PostCollection>(DataCacheKey);

            if (pc == null)
            {
                pc = new PostCollection();
                foreach (int i in PostIds)
                {
                    Post p = new Post(i);
                    if (!p.IsNew && !p.IsDeleted && p.IsPublished)
                    {
                        pc.Add(p);
                    }
                }

                ZCache.InsertCache(DataCacheKey, pc, 180);
            }

            StringBuilder sb = new StringBuilder("<ul>");

            foreach (Post p in pc)
            {
                sb.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", p.Url, p.Title);
            }

            sb.Append("</ul>");

            return(sb.ToString());
        }
Пример #4
0
        /// <summary>
        ///     Manages a single instance of GraffitiApplication which controls the events to be invoked
        /// </summary>
        public static GraffitiApplication Instance()
        {
            GraffitiApplication ga = ZCache.Get <GraffitiApplication>("GraffitiApplication");

            if (ga == null)
            {
                lock (lockedOnly)
                {
                    ga = ZCache.Get <GraffitiApplication>("GraffitiApplication");
                    if (ga == null)
                    {
                        ga = new GraffitiApplication();

                        var details = GetEvents();

                        foreach (EventDetails detail in details)
                        {
                            if (detail.Enabled)
                            {
                                detail.Event.Init(ga);
                            }
                        }

                        ZCache.InsertCache("GraffitiApplication", ga, 1800);
                    }
                }
            }
            return(ga);
        }
Пример #5
0
        public static T Get <T>(string name) where T : class, new()
        {
            string cacheKey = "object-" + name;
            T      t        = ZCache.Get <T>(cacheKey);

            if (t == null)
            {
                ObjectStore os = ObjectStore.FetchByColumn(ObjectStore.Columns.Name, name);
                if (os.IsLoaded)
                {
                    t = ConvertToObject <T>(os.Data);
                }
                else
                {
                    t = new T();
                }

                if (t == null)
                {
                    throw new Exception("Type " + typeof(T) + " could not be found or created");
                }

                ZCache.MaxCache(cacheKey, t);
            }

            return(t);
        }
Пример #6
0
        /// <summary>
        /// Returns all categories along with the uncategorized category
        /// </summary>
        /// <returns></returns>
        public CategoryCollection GetAllCachedCategories()
        {
            CategoryCollection cc = ZCache.Get <CategoryCollection>(CacheKey);

            if (cc == null)
            {
                cc = CategoryCollection.FetchAll();

                bool foundUncategorized = false;
                foreach (Category c in cc)
                {
                    if (c.Name == UncategorizedName)
                    {
                        foundUncategorized = true;
                        break;
                    }
                }

                if (!foundUncategorized)
                {
                    Category uncategorizedCategory = new Category();
                    uncategorizedCategory.Name     = UncategorizedName;
                    uncategorizedCategory.LinkName = "uncategorized";
                    uncategorizedCategory.Save();
                    cc.Add(uncategorizedCategory);
                }

                ZCache.InsertCache(CacheKey, cc, 90);
            }
            return(cc);
        }
Пример #7
0
        /// <summary>
        /// Returns a Graffiti User Object, which is a wrapper around the ASP.Net membership system.
        ///
        /// Users are cached for 2 minutes using a lower case version of the username.
        /// </summary>
        /// <returns></returns>
        public static IGraffitiUser GetUser(string username, bool isOnline)
        {
            username = username.ToLower();
            IGraffitiUser user = ZCache.Get <IGraffitiUser>("user-" + username);

            if (user == null)
            {
                user = controller.GetUser(username);
                if (user != null)
                {
                    ZCache.InsertCache("user-" + username, user, 120);
                }
            }

            if (isOnline)
            {
                HttpContext context = HttpContext.Current;
                if (context != null)
                {
                    context.Items["Current.GraffitiUser"] = user;
                }
            }

            return(user);
        }
Пример #8
0
        /// <summary>
        ///     Returns all the users for a given role
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public static List <IGraffitiUser> GetUsers(string role)
        {
            var userList = ZCache.Get <string[]>("usersByRole-" + role);

            if (userList == null)
            {
                if (role != "*")
                {
                    userList = controller.GetUsersInRole(role);
                }
                else
                {
                    StringCollection sc = new StringCollection();

                    foreach (RolePermissions rp in RolePermissionManager.GetRolePermissions())
                    {
                        var users = controller.GetUsersInRole(rp.RoleName);
                        foreach (string u in users)
                        {
                            if (!sc.Contains(u))
                            {
                                sc.Add(u.ToLower());
                            }
                        }
                    }

                    var admimUsers = controller.GetUsersInRole(AdminRole);
                    foreach (string u in admimUsers)
                    {
                        if (!sc.Contains(u))
                        {
                            sc.Add(u.ToLower());
                        }
                    }

                    userList = new string[sc.Count];
                    sc.CopyTo(userList, 0);
                }

                ZCache.InsertCache("usersByRole-" + role, userList, 180);
            }

            var the_users = new List <IGraffitiUser>();

            foreach (string username in userList)
            {
                the_users.Add(GetUser(username));
            }

            the_users.Sort(delegate(IGraffitiUser u1, IGraffitiUser u2)
            {
                return
                (Comparer <string> .Default.Compare(
                     u1.ProperName, u2.ProperName));
            });

            return(the_users);
        }
Пример #9
0
        public PostCollection PostsByCategory(Category category, int numberOfPosts, bool filterHome)
        {
            if (category == null)
            {
                return(null);
            }

            const string CacheKey = "Posts-Categories-P:{0}-C:{1}-T:{2}-PS:{3}";

            PostCollection pc =
                ZCache.Get <PostCollection>(string.Format(CacheKey, 1, category.Id, category.SortOrder, numberOfPosts));

            if (pc == null)
            {
                pc = new PostCollection();
                Query q = PostCollection.DefaultQuery(1, numberOfPosts, category.SortOrder);

                if (Category.IncludeChildPosts)
                {
                    if (category.ParentId > 0)
                    {
                        q.AndWhere(Post.Columns.CategoryId, category.Id);
                    }
                    else
                    {
                        var ids = new List <int>(category.Children.Count + 1);
                        foreach (Category child in category.Children)
                        {
                            ids.Add(child.Id);
                        }

                        ids.Add(category.Id);

                        q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                    }
                }
                else
                {
                    q.AndWhere(Post.Columns.CategoryId, category.Id);
                }

                if (filterHome)
                {
                    string where = GraffitiContext.Current["where"] as string;
                    if (!string.IsNullOrEmpty(where) && where == "home" && Site.UseCustomHomeList)
                    {
                        q.AndWhere(Post.Columns.IsHome, true);
                    }
                }

                pc.LoadAndCloseReader(q.ExecuteReader());
                ZCache.InsertCache(string.Format(CacheKey, 1, category.Id, category.SortOrder, numberOfPosts), pc, 60);
            }

            return(pc);
        }
Пример #10
0
        public static Post GetCachedPost(int id)
        {
            Post post = ZCache.Get <Post>("Post-" + id);

            if (post == null)
            {
                post = new Post(id);
                ZCache.InsertCache("Post-" + id, post, 10);
            }

            return(post);
        }
Пример #11
0
        /// <summary>
        /// Gets all Posts by the specified tag
        /// </summary>
        /// <param name="tagName"></param>
        /// <returns></returns>
        public PostCollection PostsByTag(string tagName)
        {
            string         TagName = Util.CleanForUrl(tagName);
            PostCollection pc      = ZCache.Get <PostCollection>("Tags-" + TagName);

            if (pc == null)
            {
                pc = Post.FetchPostsByTag(TagName);
                ZCache.InsertCache("Tags-" + TagName, pc, 60);
            }

            return(pc);
        }
Пример #12
0
        public List <MigratorComment> GetComments(int postID)
        {
            var comments = ZCache.Get <List <MigratorComment> >("MigratorComments");

            if (comments == null)
            {
                throw new Exception("The comment cache has expired. Please restart your import.");
            }

            var postComments = comments.FindAll(
                delegate(MigratorComment c) { return(c.PostID == postID); });

            return(postComments);
        }
Пример #13
0
        /// <summary>
        /// Gets the last x amount of comments from the specified category Id
        /// </summary>
        /// <param name="numberOfComments"></param>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public CommentCollection RecentComments(int numberOfComments, int categoryId)
        {
            CommentCollection cc = ZCache.Get <CommentCollection>("Comments-Recent-" + numberOfComments + "c:" + categoryId);

            if (cc == null)
            {
                cc = new CommentCollection();
                Query q = Comment.CreateQuery();
                q.AndWhere(Comment.Columns.IsDeleted, false);
                q.AndWhere(Comment.Columns.IsPublished, true);
                if (categoryId > 0)
                {
                    Category category = new CategoryController().GetCachedCategory(categoryId, true);
                    if (category != null)
                    {
                        if (category.ParentId > 0)
                        {
                            q.AndWhere(Post.Columns.CategoryId, categoryId);
                        }
                        else
                        {
                            List <int> ids = new List <int>(category.Children.Count + 1);
                            foreach (Category child in category.Children)
                            {
                                ids.Add(child.Id);
                            }

                            ids.Add(category.Id);

                            q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                        }
                    }
                    else
                    {
                        //this should result in no data, but it will signal to
                        //the end user to edit/remove this widget
                        q.AndWhere(Post.Columns.CategoryId, categoryId);
                    }
                }
                q.Top = numberOfComments.ToString();
                q.OrderByDesc(Comment.Columns.Id);

                cc.LoadAndCloseReader(q.ExecuteReader());

                ZCache.InsertCache("Comments-Recent-" + numberOfComments + "c:" + categoryId, cc, 60);
            }

            return(cc);
        }
Пример #14
0
        private static string LoadFile(string path)
        {
            string fileContent = ZCache.Get <string>(path);

            if (fileContent == null)
            {
                using (StreamReader sr = new StreamReader(path))
                {
                    fileContent = sr.ReadToEnd();
                }

                ZCache.MaxCache(path, fileContent, new CacheDependency(path));
            }

            return(fileContent);
        }
Пример #15
0
        /// <summary>
        /// Gets x amount of popular posts from the specified category Id
        /// </summary>
        /// <param name="numberOfPosts"></param>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public PostCollection PopularPosts(int numberOfPosts, int categoryId)
        {
            PostCollection pc = ZCache.Get <PostCollection>("Posts-Popular-" + numberOfPosts + "c:" + categoryId);

            if (pc == null)
            {
                Query q = PostCollection.DefaultQuery();

                if (categoryId > 0)
                {
                    Category category = new CategoryController().GetCachedCategory(categoryId, true);
                    if (category != null)
                    {
                        if (category.ParentId > 0)
                        {
                            q.AndWhere(Post.Columns.CategoryId, categoryId);
                        }
                        else
                        {
                            List <int> ids = new List <int>(category.Children.Count + 1);
                            foreach (Category child in category.Children)
                            {
                                ids.Add(child.Id);
                            }

                            ids.Add(category.Id);

                            q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                        }
                    }
                    else
                    {
                        //this should result in no data, but it will signal to
                        //the end user to edit/remove this widget
                        q.AndWhere(Post.Columns.CategoryId, categoryId);
                    }
                }

                q.Orders.Clear();
                q.OrderByDesc(Post.Columns.Views);
                q.Top = numberOfPosts.ToString();
                pc    = PostCollection.FetchByQuery(q);
                ZCache.InsertCache("Posts-Popular-" + numberOfPosts + "c:" + categoryId, pc, 60);
            }
            return(pc);
        }
Пример #16
0
        protected virtual object GetCategoryPosts(string key, GraffitiContext graffitiContext)
        {
            Category       category = new CategoryController().GetCachedCategory(CategoryID, false);
            int            pageSize = SiteSettings.Get().PageSize;
            PostCollection pc       =
                ZCache.Get <PostCollection>(string.Format(CacheKey, PageIndex, CategoryID, category.SortOrder, pageSize));

            if (pc == null)
            {
                pc = new PostCollection();
                Query q = PostCollection.DefaultQuery(PageIndex, pageSize, category.SortOrder);

                if (Category.IncludeChildPosts)
                {
                    if (category.ParentId > 0)
                    {
                        q.AndWhere(Post.Columns.CategoryId, CategoryID);
                    }
                    else
                    {
                        var ids = new List <int>(category.Children.Count + 1);
                        foreach (Category child in category.Children)
                        {
                            ids.Add(child.Id);
                        }

                        ids.Add(category.Id);

                        q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                    }
                }
                else
                {
                    q.AndWhere(Post.Columns.CategoryId, CategoryID);
                }
                pc.LoadAndCloseReader(q.ExecuteReader());
                ZCache.InsertCache(string.Format(CacheKey, PageIndex, CategoryID, category.SortOrder, pageSize), pc, 60);
            }

            graffitiContext.TotalRecords = category.PostCount;
            graffitiContext.PageIndex    = PageIndex;
            graffitiContext.PageSize     = SiteSettings.Get().PageSize;

            return(pc);
        }
Пример #17
0
        /// <summary>
        /// Gets the post feedback from the specified postId
        /// </summary>
        /// <param name="PostId"></param>
        /// <returns></returns>
        public CommentCollection PostFeedback(int PostId)
        {
            CommentCollection cc = ZCache.Get <CommentCollection>("Feedback-" + PostId);

            if (cc == null)
            {
                cc = new CommentCollection();
                Query q = Comment.CreateQuery();
                q.AndWhere(Comment.Columns.PostId, PostId);
                q.AndWhere(Comment.Columns.IsPublished, true);
                q.AndWhere(Comment.Columns.IsDeleted, false);
                q.OrderByAsc(Comment.Columns.Published);
                cc.LoadAndCloseReader(q.ExecuteReader());
                ZCache.InsertCache("Feedback-" + PostId, cc, 10);
            }

            return(cc);
        }
Пример #18
0
        /// <summary>
        ///     Gets all posts by the specified user in the specified category name
        /// </summary>
        /// <param name="user"></param>
        /// <param name="category"></param>
        /// <param name="numberOfPosts"></param>
        public PostCollection PostsByUserAndCategory(IGraffitiUser user, Category category, int numberOfPosts)
        {
            if (category == null || user == null)
            {
                return(null);
            }

            const string CacheKey = "Posts-Users-Categories-P:{0}-U:{1}-C:{2}-T:{3}-PS:{4}";

            PostCollection pc =
                ZCache.Get <PostCollection>(string.Format(CacheKey, 1, user.UniqueId, category.Id, category.SortOrder, numberOfPosts));

            if (pc == null)
            {
                pc = new PostCollection();
                Query q = PostCollection.DefaultQuery(1, numberOfPosts, category.SortOrder);
                q.AndWhere(Post.Columns.UserName, user.Name);
                if (Category.IncludeChildPosts)
                {
                    if (category.ParentId > 0)
                    {
                        q.AndWhere(Post.Columns.CategoryId, category.Id);
                    }
                    else
                    {
                        var ids = new List <int>(category.Children.Count + 1);
                        foreach (Category child in category.Children)
                        {
                            ids.Add(child.Id);
                        }
                        ids.Add(category.Id);
                        q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                    }
                }
                else
                {
                    q.AndWhere(Post.Columns.CategoryId, category.Id);
                }
                pc.LoadAndCloseReader(q.ExecuteReader());
                ZCache.InsertCache(string.Format(CacheKey, 1, user.UniqueId, category.Id, category.SortOrder, numberOfPosts), pc, 60);
            }

            return(pc);
        }
Пример #19
0
        /// <summary>
        /// Gets all the widgets from the ObjectStore (match ContentType = "xml/widget"
        /// </summary>
        /// <returns></returns>
        public static List <Widget> FetchAll()
        {
            List <Widget> the_Widgets = ZCache.Get <List <Widget> >(cacheKey);

            if (the_Widgets == null)
            {
                ObjectStoreCollection osc = new ObjectStoreCollection();
                Query oquery = ObjectStore.CreateQuery();
                oquery.AndWhere(ObjectStore.Columns.ContentType, "xml/widget");
                osc.LoadAndCloseReader(oquery.ExecuteReader());

                the_Widgets = new List <Widget>(osc.Count);
                foreach (ObjectStore os in osc)
                {
                    try
                    {
                        Widget widget = ObjectManager.ConvertToObject(os.Data, Type.GetType(os.Type)) as Widget;

                        if (widget != null)
                        {
                            the_Widgets.Add(widget);
                        }
                        else
                        {
                            Log.Warn("Widgets",
                                     "The widget of type {0} (Widget Id:{1}, ObjetStore id: {2}) could not be loaded. Please check with the widget developer for help",
                                     os.Type, os.Name, os.Id);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("Widget",
                                  "An exception was raised invoking the following widget type {0}. Exception: {1} Details: {2}",
                                  os.Type, ex.Message, ex.StackTrace);
                    }
                }

                ZCache.InsertCache(cacheKey, the_Widgets, 120);
            }
            return(the_Widgets);
        }
Пример #20
0
        public static TagWeightCollection FetchTags(int minWeight, int maxItems)
        {
            TagWeightCollection twc = ZCache.Get <TagWeightCollection>("TagCloud:" + minWeight + "|" + maxItems);

            if (twc == null)
            {
                Query q = TagWeight.CreateQuery();

                if (minWeight > 0)
                {
                    q.AndWhere(TagWeight.Columns.Weight, minWeight, Comparison.GreaterOrEquals);
                }

                if (maxItems > 0)
                {
                    q.Top = maxItems.ToString();
                }

                //q.OrderByAsc(TagWeight.Columns.Weight);
                q.Orders.Add(DataService.Provider.QuoteName(TagWeight.Columns.Weight.Alias) + " DESC");

                twc = TagWeightCollection.FetchByQuery(q);

                double mean = 0;
                double std  = StdDev(twc, out mean);

                foreach (TagWeight tag in twc)
                {
                    tag.FontFactor = NormalizeWeight(tag.Count, mean, std);
                    tag.FontSize   = _fontSizes[tag.FontFactor - 1];
                }

                twc.Sort(delegate(TagWeight t1, TagWeight t2) { return(Comparer <string> .Default.Compare(t1.Name, t2.Name)); });

                ZCache.InsertCache("TagCloud:" + minWeight + "|" + maxItems, twc, 120);
            }

            return(twc);
        }
Пример #21
0
        public static Dictionary <Guid, Feed> GetFeeds()
        {
            Dictionary <Guid, Feed> feeds = ZCache.Get <Dictionary <Guid, Feed> >("Feed-Objects");

            if (feeds == null)
            {
                feeds = new Dictionary <Guid, Feed>();
                ObjectStoreCollection osc = new ObjectStoreCollection();
                Query q = ObjectStore.CreateQuery();
                q.AndWhere(ObjectStore.Columns.ContentType, "feed/xml");
                osc.LoadAndCloseReader(q.ExecuteReader());

                foreach (ObjectStore os in osc)
                {
                    Feed feed = ObjectManager.ConvertToObject <Feed>(os.Data);
                    feeds.Add(feed.Id, feed);
                }

                ZCache.InsertCache("Feed-Objects", feeds, 300);
            }

            return(feeds);
        }
Пример #22
0
        public static int GetPostIdByName(string name)
        {
            object id = ZCache.Get <object>("PostIdByName-" + name);

            if (id == null)
            {
                string postName;
                string categoryName = null;

                if (name.Contains("/"))
                {
                    string[] parts = name.Split('/');

                    for (int i = 0; i < parts.Length; i++)
                    {
                        parts[i] = Util.CleanForUrl(parts[i]);
                    }

                    switch (parts.Length)
                    {
                    case 2:
                        categoryName = parts[0];
                        postName     = parts[1];
                        break;

                    case 3:
                        categoryName = parts[0] + "/" + parts[1];
                        postName     = parts[2];
                        break;

                    default:
                        return(-1);
                    }
                }
                else
                {
                    postName = Util.CleanForUrl(name);
                }

                int categoryId = -1;
                if (categoryName != null)
                {
                    CategoryCollection the_categories = categories.GetCachedCategories();

                    foreach (Category category in the_categories)
                    {
                        if (category.LinkName == categoryName)
                        {
                            categoryId = category.Id;
                        }
                    }

                    if (categoryId == -1)
                    {
                        return(-1);
                    }
                }

                List <Parameter> parameters = Post.GenerateParameters();

                /* this is supposed to be TOP 1, but the ExecuteScalar will pull only the first one */
                QueryCommand cmd = new QueryCommand("Select Id FROM graffiti_Posts Where Name = " + DataService.Provider.SqlVariable("Name") + " and IsDeleted = 0");
                cmd.Parameters.Add(Post.FindParameter(parameters, "Name")).Value = postName;

                if (categoryId > -1)
                {
                    cmd.Sql += " and CategoryId = " + DataService.Provider.SqlVariable("CategoryId");
                    cmd.Parameters.Add(Post.FindParameter(parameters, "CategoryId")).Value = categoryId;
                }

                cmd.Sql += " order by CategoryId asc";

                object postobj = DataService.ExecuteScalar(cmd);
                if (postobj != null)
                {
                    id = postobj;
                    ZCache.InsertCache("PostIdByName-" + name, (int)id, 60);
                }
                else
                {
                    id = -1;
                }
            }
            return((int)id);
        }
Пример #23
0
        /// <summary>
        ///     Returns a list of all known events based the assemblies in the bin directory
        /// </summary>
        /// <returns></returns>
        public static List <EventDetails> GetEvents()
        {
            var details = ZCache.Get <List <EventDetails> >("EventDetails");

            if (details == null)
            {
                details = new List <EventDetails>();

                ObjectStoreCollection osc =
                    ObjectStoreCollection.FetchByColumn(ObjectStore.Columns.ContentType, "eventdetails/xml");

                // Can't log errors until after Events have been fully loaded
                var warnings = new List <String>();

                var assemblies =
                    Directory.GetFileSystemEntries(HttpRuntime.BinDirectory, "*.dll");
                for (int i = 0; i < assemblies.Length; i++)
                {
                    try
                    {
                        Assembly asm = Assembly.LoadFrom(assemblies[i]);
                        foreach (Type type in asm.GetTypes())
                        {
                            try
                            {
                                if (type.IsClass && !type.IsAbstract && type.IsSubclassOf(typeof(GraffitiEvent)))
                                {
                                    string the_Type = type.AssemblyQualifiedName;
                                    the_Type = the_Type.Substring(0, the_Type.IndexOf(", Version="));
                                    EventDetails ed = null;
                                    foreach (ObjectStore os in osc)
                                    {
                                        if (os.Name == the_Type)
                                        {
                                            ed = LoadEventDetailsFromObjectStore(os);
                                            break;
                                        }
                                    }

                                    if (ed == null)
                                    {
                                        ed = CreateNewEventFromTypeName(the_Type);
                                    }

                                    details.Add(ed);
                                }
                            }
                            catch (Exception exType)
                            {
                                warnings.Add(String.Format("Failed to load type {0}. Reason: {1}", type.FullName, exType.Message));
                            }
                        }
                    }
                    catch (ReflectionTypeLoadException rtle)
                    {
                        if (assemblies[i].IndexOf("DataBuddy") == -1 && assemblies[i].IndexOf("RssToolkit") == -1)
                        {
                            warnings.Add(String.Format("Failed to load assembly {0}. Reason: {1}", assemblies[i], rtle.Message));
                        }
                    }

                    catch (Exception exAssembly)
                    {
                        warnings.Add(String.Format("Failed to load assembly {0}. Reason: {1}", assemblies[i], exAssembly.Message));
                    }
                }

                ZCache.InsertCache("EventDetails", details, 300);

                // Now we can log errors
                foreach (var warning in warnings)
                {
                    Log.Warn("Plugin", warning);
                }
            }

            return(details);
        }
Пример #24
0
        public IEnumerable Query(IDictionary paramaters)
        {
            string type = paramaters["type"] as string;

            if (type != null)
            {
                paramaters.Remove("type");
            }
            else
            {
                type = "post";
            }

            switch (type)
            {
            case "post":

                Query postQuery = Post.CreateQuery();
                SetLimits(postQuery, paramaters);

                string categoryName = paramaters["category"] as string;
                if (categoryName != null)
                {
                    paramaters.Remove("category");
                }

                if (categoryName == "none")
                {
                    categoryName = CategoryController.UncategorizedName;
                }

                if (categoryName != null)
                {
                    paramaters["categoryid"] = new CategoryController().GetCachedCategory(categoryName, false).Id;
                }

                if (paramaters["isDeleted"] == null)
                {
                    paramaters["isDeleted"] = false;
                }

                if (paramaters["isPublished"] == null)
                {
                    paramaters["isPublished"] = true;
                }

                string orderBy = paramaters["orderby"] as string;
                if (orderBy != null)
                {
                    paramaters.Remove("orderBy");
                }
                else
                {
                    orderBy = "Published DESC";
                }

                postQuery.Orders.Add(orderBy);

                string cacheKey = "Posts-";
                foreach (string key in paramaters.Keys)
                {
                    Column col = GetPostColumn(key);
                    postQuery.AndWhere(col, paramaters[key]);
                    cacheKey += "|" + col.Name + "|" + paramaters[key];
                }

                PostCollection pc = ZCache.Get <PostCollection>(cacheKey);
                if (pc == null)
                {
                    pc = new PostCollection();
                    pc.LoadAndCloseReader(postQuery.ExecuteReader());
                    ZCache.InsertCache(cacheKey, pc, 90);
                }
                return(pc);

            case "comment":

                break;

            case "category":

                break;
            }

            return(null);
        }
Пример #25
0
        public List <MigratorComment> GetComments(int postID)
        {
            string dbConnString = ZCache.Get <string>("MigratorConnectionString");

            if (String.IsNullOrEmpty(dbConnString))
            {
                throw new Exception("The database connection string has expired. Please restart your import.");
            }

            var comments = new List <MigratorComment>();

            using (SqlConnection conn = new SqlConnection(dbConnString))
            {
                conn.Open();

                using (
                    SqlCommand cmd =
                        new SqlCommand(
                            "select p.PostID, p.FormattedBody, p.PostDate, p.IPAddress, p.ApplicationPostType, p.PropertyNames, p.PropertyValues, p.IsApproved, p.SpamScore, IsNull(u.Email, '') as Email from cs_Posts p LEFT OUTER JOIN cs_Users u ON p.UserID = u.UserID where ParentID = @parentid and PostLevel > 1 and ApplicationPostType in (4,8) order by PostID asc",
                            conn))
                {
                    cmd.Parameters.Add(new SqlParameter("@parentid", postID));

                    using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        while (rdr.Read())
                        {
                            MigratorComment comment = new MigratorComment();

                            comment.PostID      = postID;
                            comment.PublishedOn = Convert.ToDateTime(rdr["PostDate"]);
                            comment.IPAddress   = rdr["IPAddress"] as string;

                            // Remove <p> tags from comment body, as Graffiti will add these back in when saving the comment
                            comment.Body = rdr["FormattedBody"] as string;
                            if (!string.IsNullOrEmpty(comment.Body))
                            {
                                comment.Body = comment.Body.Replace("<p>", "").Replace("</p>", "");
                            }

                            NameValueCollection nvc =
                                ConvertToNameValueCollection(rdr["PropertyNames"] as string,
                                                             rdr["PropertyValues"] as string);

                            comment.IsPublished = Convert.ToBoolean(rdr["IsApproved"]);
                            comment.SpamScore   = Convert.ToInt32(rdr["SpamScore"]);
                            comment.WebSite     = nvc["TitleUrl"];

                            // ApplicationPostType:  Comment = 4; Trackback = 8;
                            Int32 applicationPostType = Convert.ToInt32(rdr["ApplicationPostType"]);

                            if (applicationPostType == 8)
                            {
                                comment.UserName    = !string.IsNullOrEmpty(nvc["trackbackName"]) ? nvc["trackbackName"] : "TrackBack";
                                comment.IsTrackback = true;
                            }
                            else
                            {
                                comment.Email       = rdr["Email"] as string;
                                comment.UserName    = nvc["SubmittedUserName"];
                                comment.IsTrackback = false;
                            }


                            comments.Add(comment);
                        }

                        rdr.Close();
                    }
                }

                conn.Close();
            }

            return(comments);
        }
Пример #26
0
        protected override void OnLoad(EventArgs e)
        {
            Initialize();

            SiteSettings settings = SiteSettings.Get();

            string baseUrl = SiteSettings.BaseUrl;

            if (string.IsNullOrEmpty(TagName))
            {
                Category category = null;
                if (CategoryID > -1)
                {
                    category = new CategoryController().GetCachedCategory(CategoryID, false);
                }

                if (category == null)
                {
                    if (!string.IsNullOrEmpty(settings.ExternalFeedUrl) &&
                        Request.UserAgent.IndexOf("FeedBurner", StringComparison.InvariantCultureIgnoreCase) == -1)
                    {
                        Context.Response.RedirectLocation = settings.ExternalFeedUrl;
                        Context.Response.StatusCode       = 301;
                        Context.Response.End();
                    }
                }
                else if (!string.IsNullOrEmpty(category.FeedUrlOverride) &&
                         Request.UserAgent.IndexOf("FeedBurner", StringComparison.InvariantCultureIgnoreCase) == -1)
                {
                    Context.Response.RedirectLocation = category.FeedUrlOverride;
                    Context.Response.StatusCode       = 301;
                    Context.Response.End();
                }
                else if (CategoryName != null && !Util.AreEqualIgnoreCase(CategoryName, category.LinkName))
                {
                    Context.Response.RedirectLocation = new Uri(Context.Request.Url, category.Url).ToString();
                    Context.Response.StatusCode       = 301;
                    Context.Response.End();
                }

                string cacheKey = CategoryID > -1
                                                          ? "Posts-Index-" + Util.PageSize + "-" + CategoryID.ToString()
                                                          : string.Format("Posts-Categories-P:{0}-C:{1}-T:{2}-PS:{3}", 1, CategoryID,
                                                                          SortOrderType.Descending, Util.PageSize);

                PostCollection pc = ZCache.Get <PostCollection>(cacheKey);

                if (pc == null)
                {
                    Query q = PostCollection.DefaultQuery();
                    q.Top = Util.PageSize.ToString();

                    if (SiteSettings.Get().IncludeChildPosts&& macros.IsNotNull(category))
                    {
                        if (category.ParentId > 0)
                        {
                            q.AndWhere(Post.Columns.CategoryId, CategoryID);
                        }
                        else
                        {
                            var ids = new List <int>(category.Children.Count + 1);
                            foreach (Category child in category.Children)
                            {
                                ids.Add(child.Id);
                            }

                            ids.Add(category.Id);

                            q.AndInWhere(Post.Columns.CategoryId, ids.ToArray());
                        }
                    }
                    else
                    {
                        if (CategoryID > 0)
                        {
                            q.AndWhere(Post.Columns.CategoryId, CategoryID);
                        }
                    }

                    pc = new PostCollection();
                    pc.LoadAndCloseReader(q.ExecuteReader());

                    PostCollection permissionsFiltered = new PostCollection();

                    permissionsFiltered.AddRange(pc);

                    foreach (Post p in pc)
                    {
                        if (!RolePermissionManager.GetPermissions(p.CategoryId, GraffitiUsers.Current).Read)
                        {
                            permissionsFiltered.Remove(p);
                        }
                    }

                    ZCache.InsertCache(cacheKey, permissionsFiltered, 90);
                    pc = permissionsFiltered;
                }

                ValidateAndSetHeaders(pc, settings, Context);

                StringWriter sw = new StringWriter();
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
                XmlTextWriter writer = new XmlTextWriter(sw);

                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                writer.WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");
                writer.WriteAttributeString("xmlns:slash", "http://purl.org/rss/1.0/modules/slash/");

                // Allow plugins to add additional xml namespaces
                Core.Events.Instance().ExecuteRssNamespace(writer);

                writer.WriteStartElement("channel");
                WriteChannel(writer, category, settings);

                // Allow plugins to add additional xml to the <channel>
                Core.Events.Instance().ExecuteRssChannel(writer);

                foreach (Post p in pc)
                {
                    writer.WriteStartElement("item");
                    WriteItem(writer, p, settings, baseUrl);

                    // Allow plugins to add additional xml to the <item>
                    Core.Events.Instance().ExecuteRssItem(writer, p);

                    writer.WriteEndElement();                     // End Item
                }

                writer.WriteEndElement();                 // End Channel
                writer.WriteEndElement();                 // End Document

                // save XML into response
                Context.Response.ContentEncoding = Encoding.UTF8;
                Context.Response.ContentType     = "application/rss+xml";
                Context.Response.Write(sw.ToString());
            }
            else
            {
                PostCollection pc = GetTaggedPosts(TagName);

                ValidateAndSetHeaders(pc, settings, Context);

                StringWriter sw = new StringWriter();
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
                XmlTextWriter writer = new XmlTextWriter(sw);

                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                writer.WriteAttributeString("xmlns:dc", "http://purl.org/dc/elements/1.1/");
                writer.WriteAttributeString("xmlns:slash", "http://purl.org/rss/1.0/modules/slash/");

                Core.Events.Instance().ExecuteRssNamespace(writer);

                writer.WriteStartElement("channel");
                WriteChannel(writer, TagName, settings);

                // Allow plugins to add additional xml to the <channel>
                Core.Events.Instance().ExecuteRssChannel(writer);

                foreach (Post p in pc)
                {
                    writer.WriteStartElement("item");
                    WriteItem(writer, p, settings, baseUrl);

                    Core.Events.Instance().ExecuteRssItem(writer, p);

                    writer.WriteEndElement();                     // End Item
                }

                writer.WriteEndElement();                 // End Channel
                writer.WriteEndElement();                 // End Document

                Context.Response.ContentEncoding = Encoding.UTF8;
                Context.Response.ContentType     = "application/rss+xml";
                Context.Response.Write(sw.ToString());
            }
        }