PageRenderTime 32ms CodeModel.GetById 1ms app.highlight 25ms RepoModel.GetById 1ms app.codeStats 0ms

/BlogEngine/BlogEngine.NET/default.aspx.cs

#
C# | 307 lines | 252 code | 31 blank | 24 comment | 60 complexity | 0b6294c79128cc9798b9aedbbceab40f MD5 | raw file
  1#region Using
  2
  3using System;
  4using System.Globalization;
  5using System.Text.RegularExpressions;
  6using System.Web;
  7using System.Xml;
  8using System.Collections.Generic;
  9using BlogEngine.Core;
 10using System.Web.UI;
 11
 12
 13#endregion
 14
 15//TODO  Remove All URL redirects to Business layer? To speed up page loading instead of having the most visited page handling so many tasks
 16public partial class _default : BlogEngine.Core.Web.Controls.BlogBasePage
 17{
 18
 19    bool SearchEngine = false;
 20	protected void Page_Load(object sender, EventArgs e)
 21	{
 22        //Check to see if Client is a SearchEngine or Bot trying to craw the website
 23        CheckBrowserCaps();
 24
 25
 26		if (Page.IsCallback)
 27			return;
 28
 29        // If Client is a SearchEngine or Bot Start the Processing of SearchEngine 
 30        if (SearchEngine == true)
 31        {
 32            ProcessSearchEngine();
 33        }
 34
 35		if (Request.RawUrl.ToLowerInvariant().Contains("/category/"))
 36		{
 37			DisplayCategories();
 38		}
 39
 40            else if (Request.RawUrl.ToLowerInvariant().Contains("/author/"))
 41            {
 42                DisplayAuthors();
 43            }
 44            else if (Request.RawUrl.ToLowerInvariant().Contains("?tag="))
 45            {
 46                DisplayTags();
 47            }
 48            else if (Request.QueryString["year"] != null || Request.QueryString["date"] != null || Request.QueryString["calendar"] != null)
 49            {
 50                if (Request.RawUrl.Contains("year="))
 51                    Redirect();
 52                else
 53                    DisplayDateRange();
 54
 55                // base.AddMetaTag("description", Server.HtmlEncode(BlogSettings.Instance.Description));    This only should be for default.aspx page once.
 56                //TODO Removing all BlogSettings.Instance.Description AddMetaTags so that each page and post has unique description 
 57            }
 58            else if (Request.QueryString["apml"] != null)
 59            {
 60                DisplayApmlFiltering();
 61            }
 62            else
 63            {
 64                if (!BlogSettings.Instance.UseBlogNameInPageTitles)
 65                    Page.Title = BlogSettings.Instance.Name + " | ";
 66
 67                if (!string.IsNullOrEmpty(BlogSettings.Instance.Description))
 68                    Page.Title += Server.HtmlEncode(BlogSettings.Instance.Description);
 69
 70                base.AddMetaTag("description", Server.HtmlEncode(BlogSettings.Instance.Description));
 71            }
 72
 73		AddMetaKeywords();
 74		base.AddMetaTag("author", Server.HtmlEncode(BlogSettings.Instance.AuthorName));		
 75	}
 76
 77    void CheckBrowserCaps()
 78    {
 79        System.Web.HttpBrowserCapabilities myBrowserCaps = Request.Browser;
 80        if (((System.Web.Configuration.HttpCapabilitiesBase)myBrowserCaps).Crawler)
 81        {
 82            SearchEngine = true;
 83        }
 84
 85    }
 86       /// <summary>
 87       ///   Blocks SearchEngine and Bots from indexing Human Only webpages
 88       ///   pager,keywords,tags,categories,search and archive page
 89       /// </summary>
 90    private void ProcessSearchEngine ()
 91       {
 92           string CrawlerUrl = Request.RawUrl.ToLowerInvariant();
 93                       
 94           if (CrawlerUrl.Contains("/category/") ||
 95               CrawlerUrl.Contains("?tag") ||
 96               CrawlerUrl.Contains("?page=") ||
 97               // Post with Date has format http://MainWebsite.com/post/2014/02/13/post-2
 98               CrawlerUrl.Contains(Utils.RelativeWebRoot + "/2013/", StringComparison.OrdinalIgnoreCase) ||   //Stops Calendar from being indexed 
 99               CrawlerUrl.Contains(Utils.RelativeWebRoot + "/2014/", StringComparison.OrdinalIgnoreCase) ||   
100               CrawlerUrl.StartsWith(Utils.RelativeWebRoot + "search.aspx", StringComparison.OrdinalIgnoreCase) ||
101               CrawlerUrl.StartsWith(Utils.RelativeWebRoot + "archive.aspx", StringComparison.OrdinalIgnoreCase))
102           {
103               base.AddMetaTag("ROBOT", "NOINDEX, NOFOLLOW");
104               //Sends SearchEngine or Bot to the default page
105               Response.RedirectPermanent(Utils.RelativeWebRoot); 
106           }
107       }
108
109	private void DisplayApmlFiltering()
110	{
111		Uri url = null;
112		if (Uri.TryCreate(Request.QueryString["apml"], UriKind.Absolute, out url))
113		{
114			Page.Title = Resources.labels.apmlFilteredList;
115			try
116			{
117				Dictionary<Uri, XmlDocument> docs = Utils.FindSemanticDocuments(url, "apml");
118				if (docs.Count > 0)
119				{
120					foreach (Uri key in docs.Keys)
121					{
122                        PostList1.ContentBy = ServingContentBy.Apml;
123						PostList1.Posts = Search.ApmlMatches(docs[key], 30).FindAll(delegate(IPublishable p) { return p is Post; });
124						PostList1.Posts.Sort(delegate(IPublishable ip1, IPublishable ip2) { return ip2.DateCreated.CompareTo(ip1.DateCreated); });
125						Page.Title += Resources.labels.per + Server.HtmlEncode(key.Host);
126						break;
127					}
128				}
129				else
130				{
131					divError.InnerHtml = "<h1 style=\"text-align:center\">"+Resources.labels.apmlNotFoundDesc+"</h1><br /><br />";
132					Page.Title = Resources.labels.apmlNotFound;
133				}
134			}
135			catch (NotSupportedException)
136			{
137				divError.InnerHtml = "<h1 style=\"text-align:center\">"+Resources.labels.apmlNoInfoWebsite+"</h1><br /><br />";
138				Page.Title = Resources.labels.apmlNotFound;
139			}
140			catch (System.Net.WebException)
141			{
142				divError.InnerHtml = "<h1 style=\"text-align:center\">"+Resources.labels.apmlNoConnWebsite+"</h1><br /><br />";
143				Page.Title = Resources.labels.apmlAddrInvalid;
144			}
145			catch (XmlException)
146			{
147				divError.InnerHtml = "<h1 style=\"text-align:center\">"+Resources.labels.apmlInvalidXml+"</h1><br /><br />";
148				Page.Title = Resources.labels.apmlDocErr;
149			}
150		}
151		else if (PostList1.Posts == null || PostList1.Posts.Count == 0)
152		{
153			divError.InnerHtml = "<h1 style=\"text-align:center\">"+Resources.labels.apmlInvalidUrl+"</h1><br /><br />";
154			Page.Title = Resources.labels.apmlNotFound;
155		}
156	}
157	
158    //TODO Does the old URL redirect still needed with BE 2.9 and above?
159	/// <summary>
160	/// Permanently redirects to the correct URL format if the page is requested with
161	/// the old URL: /default.aspx?year=2007&month=12
162	/// <remarks>
163	/// The redirection is important so that we don't end up having 2 URLs 
164	/// to the same resource. It's for SEO purposes.
165	/// </remarks>
166	/// </summary>
167	private void Redirect()
168	{
169		string year = Request.QueryString["year"];
170		string month = Request.QueryString["month"];
171		string date = Request.QueryString["date"];
172		string page = string.IsNullOrEmpty(Request.QueryString["page"]) ? string.Empty : "?page=" + Request.QueryString["page"];
173		string rewrite = null;
174
175		if (!string.IsNullOrEmpty(date))
176		{
177			DateTime dateParsed = DateTime.Parse(date);
178			rewrite = Utils.RelativeWebRoot + dateParsed.Year + "/" + dateParsed.Month + "/" + dateParsed.Day + "/default.aspx";
179		}
180		else if (!string.IsNullOrEmpty(year) && !string.IsNullOrEmpty(month))
181		{
182			rewrite = Utils.RelativeWebRoot + year + "/" + month + "/default.aspx"; 
183		}
184		else if (!string.IsNullOrEmpty(year))
185		{
186			rewrite = Utils.RelativeWebRoot + year + "/default.aspx";
187		}
188
189		if (rewrite != null)
190		{
191            //TODO Replace this Block of code with Response.RedirectPermanent?  Since Asp.net 4.0 has new method saves on code.
192			Response.Clear();
193			Response.StatusCode = 301;
194			Response.AppendHeader("location", rewrite + page);
195			Response.End();
196		}
197	}
198
199	private static readonly Regex YEAR_MONTH = new Regex("/([0-9][0-9][0-9][0-9])/([0-1][0-9])", RegexOptions.IgnoreCase | RegexOptions.Compiled);
200	private static readonly Regex YEAR_MONTH_DAY = new Regex("/([0-9][0-9][0-9][0-9])/([0-1][0-9])/([0-3][0-9])", RegexOptions.IgnoreCase | RegexOptions.Compiled);
201
202	/// <summary>
203	/// Adds the post's tags as meta keywords.
204	/// </summary>
205	private void AddMetaKeywords()
206	{
207		if (Category.Categories.Count > 0)
208		{
209			string[] categories = new string[Category.Categories.Count];
210			for (int i = 0; i < Category.Categories.Count; i++)
211			{
212				categories[i] = Category.Categories[i].Title;
213			}
214
215			string metakeywords = Server.HtmlEncode(string.Join(",", categories));
216			System.Web.UI.HtmlControls.HtmlMeta tag = null;
217			foreach (Control c in Page.Header.Controls)
218			{
219				if (c is System.Web.UI.HtmlControls.HtmlMeta && (c as System.Web.UI.HtmlControls.HtmlMeta).Name.ToLower() == "keywords")
220				{
221					tag = c as System.Web.UI.HtmlControls.HtmlMeta;
222					tag.Content += ", " + metakeywords;
223					break;
224				}
225			}
226			if (tag == null)
227			{
228				base.AddMetaTag("keywords", metakeywords);
229			} 
230		}
231	}
232
233	private void DisplayCategories()
234	{
235		if (!String.IsNullOrEmpty(Request.QueryString["id"]))
236		{
237			Guid categoryId = new Guid(Request.QueryString["id"]);
238            PostList1.ContentBy = ServingContentBy.Category;
239            Category category = Category.GetCategory(categoryId, Blog.CurrentInstance.IsSiteAggregation);
240			PostList1.Posts = Post.GetPostsByCategory(category).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
241            Page.Title = category.Title;
242            base.AddMetaTag("description", string.IsNullOrWhiteSpace(category.Description) ? Server.HtmlEncode(category.Title) : category.Description);
243        }
244	}
245
246	private void DisplayAuthors()
247	{
248		if (!string.IsNullOrEmpty(Request.QueryString["name"]))
249		{
250			string author = Server.UrlDecode(Request.QueryString["name"]);
251            PostList1.ContentBy = ServingContentBy.Author;
252			PostList1.Posts = Post.GetPostsByAuthor(author).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
253			Title = Resources.labels.AllPostsBy +" " + Server.HtmlEncode(author);
254            base.AddMetaTag("description", Server.HtmlEncode(Title));
255		}
256	}
257
258	private void DisplayTags()
259	{
260		if (!string.IsNullOrEmpty(Request.QueryString["tag"]))
261		{
262            PostList1.ContentBy = ServingContentBy.Tag;
263			PostList1.Posts = Post.GetPostsByTag(Request.QueryString["tag"].Substring(1)).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
264			base.Title = Resources.labels.AllPostsTagged + " '" + Request.QueryString["tag"].Substring(1) + "'";
265            base.AddMetaTag("description", Server.HtmlEncode(base.Title));
266		}
267	}
268
269	private void DisplayDateRange()
270	{
271		string year = Request.QueryString["year"];
272		string month = Request.QueryString["month"];
273		string specificDate = Request.QueryString["date"];
274
275		if (!string.IsNullOrEmpty(year) && !string.IsNullOrEmpty(month))
276		{
277			DateTime dateFrom = DateTime.Parse(year + "-" + month + "-01", CultureInfo.InvariantCulture);
278			DateTime dateTo = dateFrom.AddMonths(1).AddMilliseconds(-1);
279            PostList1.ContentBy = ServingContentBy.DateRange;
280			PostList1.Posts = Post.GetPostsByDate(dateFrom, dateTo).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
281			Title = dateFrom.ToString("MMMM yyyy");
282		}
283		else if (!string.IsNullOrEmpty(year))
284		{
285			DateTime dateFrom = DateTime.Parse(year + "-01-01", CultureInfo.InvariantCulture);
286			DateTime dateTo = dateFrom.AddYears(1).AddMilliseconds(-1);
287            PostList1.ContentBy = ServingContentBy.DateRange;
288			PostList1.Posts = Post.GetPostsByDate(dateFrom, dateTo).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; })); ;
289			Title = dateFrom.ToString("yyyy");
290		}
291		else if (!string.IsNullOrEmpty(specificDate) && specificDate.Length == 10)
292		{
293			DateTime date = DateTime.Parse(specificDate, CultureInfo.InvariantCulture);
294            PostList1.ContentBy = ServingContentBy.DateRange;
295			PostList1.Posts = Post.GetPostsByDate(date, date).ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; })); ;
296			Title = date.ToString("MMMM d. yyyy");
297		}
298		else if (!string.IsNullOrEmpty(Request.QueryString["calendar"]))
299		{
300			calendar.Visible = true;
301			PostList1.Visible = false;
302			Title = Server.HtmlEncode(Resources.labels.calendar);
303		}
304	}
305
306
307}