PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/BindSolution/Controllers/HomeController.cs

https://gitlab.com/bindsolution/bindsolution
C# | 278 lines | 238 code | 34 blank | 6 comment | 18 complexity | 261dc873a1f59f82869d0fdae3bd21f5 MD5 | raw file
  1. // //-----------------------------------------------------------------------
  2. // // <copyright file="HomeController.cs" company="Bind Solution">
  3. // // Copyright (c) Bind Solution. All rights reserved.
  4. // // </copyright>
  5. // // <author></author>
  6. // //-----------------------------------------------------------------------
  7. namespace BindSolution.Controllers
  8. {
  9. #region usings
  10. using System;
  11. using System.Collections.Generic;
  12. using System.ComponentModel;
  13. using System.ServiceModel.Syndication;
  14. using Data.Extensions;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Net;
  18. using System.Xml;
  19. using System.Xml.Linq;
  20. #if DEBUG
  21. using Framework;
  22. #else
  23. using System.IO;
  24. using System.Xml;
  25. using System.Net;
  26. using System.Xml.Linq;
  27. using Framework;
  28. using System.Linq;
  29. #endif
  30. using System.Web.Mvc;
  31. using Data.Infra;
  32. using Framework.Domain;
  33. using Framework.Service;
  34. using Framework.Web;
  35. using Framework.Web.Filters;
  36. using Framework.Web.ViewModel;
  37. using Service;
  38. using ViewModel;
  39. #endregion
  40. public class HomeController : BindAsyncController
  41. {
  42. private readonly IEmailSend _emailSend;
  43. private readonly IUserService _userService;
  44. private readonly IProjectService _projectService;
  45. #region Constructor
  46. public HomeController(IUserService userService, IEmailSend emailSend, IProjectService projectService)
  47. {
  48. _userService = userService;
  49. _emailSend = emailSend;
  50. _projectService = projectService;
  51. }
  52. #endregion
  53. #region Actions
  54. public ActionResult Index()
  55. {
  56. return View();
  57. }
  58. public ActionResult Contact()
  59. {
  60. return View();
  61. }
  62. [HttpPost]
  63. [ValidateAntiForgeryToken]
  64. public ActionResult Contact(ContactViewModel model)
  65. {
  66. if (ModelState.IsValid)
  67. {
  68. _emailSend.SendContactEmail(model.Name, model.Email, model.Menssage);
  69. return AjaxResult(model, "Mensagem enviada com sucesso!", "Em breve entraremos em contato.");
  70. }
  71. return AjaxResult(model);
  72. }
  73. public ActionResult Plus()
  74. {
  75. return View();
  76. }
  77. public ActionResult PlusBusiness()
  78. {
  79. return View();
  80. }
  81. public ActionResult PlusTech()
  82. {
  83. return View();
  84. }
  85. public ActionResult Why()
  86. {
  87. return View();
  88. }
  89. #endregion
  90. #region Partials
  91. [ChildActionOnly]
  92. [CustomOutputCache(CacheProfile = "InternalResource")]
  93. public PartialViewResult ProjectList()
  94. {
  95. var projects = _projectService.Repository.Query()
  96. .OnlyPublishedProjects()
  97. .WithDefaultOrdered()
  98. .Take(3);
  99. return PartialView("_Projects", projects.ToList());
  100. }
  101. [ChildActionOnly]
  102. [OnlyIfNonJava]
  103. [CustomOutputCache(CacheProfile = "ExternalResource")]
  104. public void BlogRssAsync(int page = 0)
  105. {
  106. AsyncManager.OutstandingOperations.Increment(1);
  107. var bg = new BackgroundWorker();
  108. bg.DoWork += (o, e) =>
  109. {
  110. int pg;
  111. if (e.Argument != null && int.TryParse(e.Argument.ToString(), out pg))
  112. AsyncManager.Parameters["items"] = e.Result = GetFeeds(pg);
  113. else
  114. AsyncManager.Parameters["items"] = e.Result = GetFeeds();
  115. };
  116. bg.RunWorkerCompleted += (o, e) => AsyncManager.OutstandingOperations.Decrement();
  117. bg.RunWorkerAsync(page);
  118. }
  119. [ChildActionOnly]
  120. [CustomOutputCache(CacheProfile = "ExternalResource")]
  121. public PartialViewResult BlogRssCompleted(IEnumerable<SyndicationItem> items)
  122. {
  123. return PartialView("_BlogRss", items);
  124. }
  125. [ChildActionOnly]
  126. [OnlyIfNonJava]
  127. [CustomOutputCache(CacheProfile = "ExternalResource")]
  128. public void TwitterAsync()
  129. {
  130. AsyncManager.OutstandingOperations.Increment(1);
  131. var bg = new BackgroundWorker();
  132. bg.DoWork += (o, e) => AsyncManager.Parameters["items"] = e.Result = GetTwitters();
  133. bg.RunWorkerCompleted += (o, e) => AsyncManager.OutstandingOperations.Decrement();
  134. bg.RunWorkerAsync();
  135. }
  136. [ChildActionOnly]
  137. [CustomOutputCache(CacheProfile = "ExternalResource")]
  138. public PartialViewResult TwitterCompleted(List<TwitterDataViewModel> items)
  139. {
  140. return PartialView("_Twitter", items);
  141. }
  142. [NonAction]
  143. public IEnumerable<SyndicationItem> GetFeeds(int page = 0)
  144. {
  145. try
  146. {
  147. using (var reader = XmlReader.Create("http://blog.bindsolution.com/rss"))
  148. {
  149. var rssData = SyndicationFeed.Load(reader);
  150. if (rssData != null)
  151. {
  152. return (from item in rssData.Items
  153. orderby item.PublishDate descending
  154. select item).Take(3).Skip(3 * page).ToList();
  155. }
  156. return null;
  157. }
  158. }
  159. catch (WebException wex)
  160. {
  161. Elmah.ErrorSignal.FromCurrentContext().Raise(wex);
  162. return null;
  163. }
  164. }
  165. #endregion
  166. [NonAction]
  167. public IEnumerable<TwitterDataViewModel> GetTwitters()
  168. {
  169. var request = WebRequest.Create("http://search.twitter.com/search.atom?q=bindsolution&rpp=5") as HttpWebRequest;
  170. if (request != null)
  171. {
  172. using (var response = request.GetResponse() as HttpWebResponse)
  173. {
  174. using (var reader = new StreamReader(response.GetResponseStream()))
  175. {
  176. var document = XDocument.Parse(reader.ReadToEnd());
  177. XNamespace xmlns = "http://www.w3.org/2005/Atom";
  178. return (from entry in document.Descendants(xmlns + "entry")
  179. let content = entry.Element(xmlns + "content")
  180. where content != null
  181. let update = entry.Element(xmlns + "updated")
  182. where update != null
  183. let author = entry.Element(xmlns + "author")
  184. where author != null
  185. let name = author.Element(xmlns + "name")
  186. where name != null
  187. let uri = author.Element(xmlns + "uri")
  188. where uri != null
  189. let id = entry.Element(xmlns + "id")
  190. where id != null
  191. select new TwitterDataViewModel
  192. {
  193. Content = content.Value,
  194. Updated = DateTime.Parse(update.Value).PrettyFormat(),
  195. AuthorName = name.Value,
  196. AuthorUri = uri.Value,
  197. TwitterID = id.Value,
  198. Link = (from o in entry.Descendants(xmlns + "link")
  199. let xAttribute = o.Attribute("rel")
  200. where xAttribute != null && xAttribute.Value == "image"
  201. let attribute = o.Attribute("href")
  202. where attribute != null
  203. select new { Val = attribute.Value }).First().Val
  204. }).ToList();
  205. }
  206. }
  207. }
  208. return null;
  209. }
  210. [Authorize(Roles = RoleConstants.Administrators)]
  211. public ActionResult ThrowError()
  212. {
  213. throw new ApplicationException("Forced error!!");
  214. }
  215. [Authorize(Roles = RoleConstants.Administrators)]
  216. public JsonResult AddUser(string user, string email, string pass)
  217. {
  218. try
  219. {
  220. var userObj = new User
  221. {
  222. Name = user
  223. ,
  224. Password = pass.Sha1Hash()
  225. ,
  226. IsApproved = true
  227. ,
  228. IsBlock = false
  229. ,
  230. Email = email
  231. };
  232. _userService.Repository.Add(userObj);
  233. return Json(_userService.Repository.Save() > 0
  234. ? new { success = true, message = "Usuário cadastrado com sucesso!" }
  235. : new { success = false, message = "Não foi possível realizar o cadastro do usuário." },
  236. JsonRequestBehavior.AllowGet);
  237. }
  238. catch (Exception ex)
  239. {
  240. return Json(new { success = false, message = ex.GetInnerException().Message });
  241. }
  242. }
  243. }
  244. }