PageRenderTime 15ms CodeModel.GetById 2ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 1ms

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