public ActionResult TestSuccessfulBuild(int Id)
        {
            var user = database.Users.First(u => u.UserName == User.Identity.Name);
            var project = database.Projects.FirstOrDefault(p => p.ProjectId == Id && user.UserId == p.User.UserId);

            Notification n = new Notification()
            {
                application = new Application()
                {
                    name = project.ProjectName

                },
                build = new Build()
                {
                    commit = new Commit()
                    {
                        id = Guid.NewGuid().ToString(),
                        message = "A successful build test from TweetHarbor"
                    },
                    status = "succeeded"
                }
            };

            NotifyController c = new NotifyController(database, twitterService, textMessageService);
            var res = c.New(user.UserName, user.UniqueId, n);

            //TODO: Make a real post work
            //var notificationValue = JsonConvert.SerializeObject(n);
            //string url = Request.Url.Scheme + "://"
            //    + Request.Url.Host
            //    + (Request.Url.Host.ToLower() == "localhost" ? ":" + Request.Url.Port : "")
            //    + "/notify/new/" + user.UserName + "?token=" + user.UniqueId;

            //WebRequest wr = WebRequest.Create(url);
            //string parms = "notification=" + notificationValue;
            //wr.Method = "POST";
            //byte[] data = System.Text.Encoding.UTF8.GetBytes(parms);
            //wr.ContentLength = data.Length;
            //wr.ContentType = "application/json";

            //var sw = wr.GetRequestStream();
            //sw.Write(data, 0, data.Length);
            //sw.Close();

            //var response = wr.GetResponse();
            //StreamReader sr = new StreamReader(response.GetResponseStream());
            //var val = sr.ReadToEnd();
            //sr.Close();

            return RedirectToAction("Index", new { Controller = "Account" });
        }
        public JsonResult New(string Id, string token, Notification notification)
        {
            // Get the User based on supplied Id
            // * Token must match *
            var user = database.Users
                .Include("Projects")
                .Include("Projects.TwitterAccounts")
                .Include("Projects.MessageRecipients")
                .Include("Projects.TextMessageRecipients")
                .FirstOrDefault(usr => usr.UserName == Id && usr.UniqueId == token);
            // If Id or Token is invalid, user will not be found
            // TODO: Allow users to reset the token
            if (null != user)
            {
                // Locate or create our project
                var project = CreateProjectIfNecessary(notification, user);
                if (null != project)
                {
                    SaveNotification(notification, project);

                    // If the message ends with a dash, we are NOT notifying anyone of the push
                    if (notification.build.commit.message.Trim().EndsWith("-") == false)
                    {
                        // start our connection to twitter
                        var twitterAccount = project.TwitterAccounts != null ? project.TwitterAccounts.FirstOrDefault() : null;
                        if (null == twitterAccount)
                            twitterAccount = user.AuthenticationAccounts.FirstOrDefault(a => a.AccountProvider.ToLower() == "twitter");
                        //TODO: Ensure we HAVE a twitter account
                        twitter.AuthenticateWith(twitterAccount.OAuthToken, twitterAccount.OAuthTokenSecret);

                        // Format and send appropriate messages
                        if (notification.build.status == "succeeded")
                        {
                            // Get the Success Template (or default)
                            var strSuccessUpdate = string.IsNullOrEmpty(project.SuccessTemplate) ?
                                Properties.Settings.Default.DefaultSuccessTemplate : project.SuccessTemplate;

                            // Replace tokens
                            strSuccessUpdate = DeTokenizeString(strSuccessUpdate, project, notification);

                            if (strSuccessUpdate.Length > 140)
                                strSuccessUpdate = strSuccessUpdate.Substring(0, 136) + "...";

                            // ensure we're 'authorized' to send the tweet
                            if (project.SendPrivateTweetOnSuccess && user.SendPrivateTweet)
                            {
                                SendDirectMessages(project, strSuccessUpdate);
                            }
                            if (project.SendPublicTweetOnSuccess && user.SendPublicTweet)
                            {
                                TwitterStatus pubRes = twitter.SendTweet(strSuccessUpdate);
                            }
                            if (project.SendTextOnSuccess && user.SendSMS)
                            {
                                SendSmsMessages(project, strSuccessUpdate);
                            }
                        }
                        else
                        {
                            // Get the Failure Template (or default)
                            var strFailureUpdate = string.IsNullOrEmpty(project.FailureTemplate) ?
                                Properties.Settings.Default.DefaultFailureTemplate : project.FailureTemplate;

                            // Replace tokens & clean up
                            strFailureUpdate = DeTokenizeString(strFailureUpdate, project, notification);

                            if (strFailureUpdate.Length > 140)
                                strFailureUpdate = strFailureUpdate.Substring(0, 136) + "...";

                            // ensure we're 'authorized' to send the tweet
                            if (project.SendPrivateTweetOnFailure && user.SendPrivateTweet)
                            {
                                SendDirectMessages(project, strFailureUpdate);
                            }
                            if (project.SendPublicTweetOnFailure && user.SendPublicTweet)
                            {
                                var pubRes = twitter.SendTweet(strFailureUpdate);
                            }
                            if (project.SendTextOnFailure && user.SendSMS)
                            {
                                SendSmsMessages(project, strFailureUpdate);
                            }
                        }
                    }

                    return Json(new JsonResultModel() { Success = true });
                }
                else
                {
                    return Json(new JsonResultModel() { Success = false, Error = "Unable to locate or create project" });
                }
            }
            else
            {
                return Json(new JsonResultModel() { Success = false, Error = "NotAuthorized" });
            }
        }
 public static string DeTokenizeString(string input, Project project, Notification notification)
 {
     return input.Replace("{application:name}", project.ProjectName)
                     .Replace("{build:commit:message}", notification.build.commit.message)
                     .Replace("{build:commit:id}", notification.build.commit.id.Substring(0, 7));
 }
 private void SaveNotification(Notification notification, Project project)
 {
     ProjectNotification projNotification = new ProjectNotification();
     projNotification.NotificationDate = DateTime.Now;
     projNotification.Build = notification.build;
     project.ProjectNotifications.Add(projNotification);
     database.SaveChanges();
 }
 private Project CreateProjectIfNecessary(Notification notification, Models.User user)
 {
     var project = user.Projects.FirstOrDefault(p => p.ProjectName == notification.application.name);
     if (null == project)
     {
         project = new Project()
         {
             ProjectName = notification.application.name,
             FailureTemplate = "",
             SuccessTemplate = "",
             User = user
         };
         user.Projects.Add(project);
         //TODO: Add logging to prevent these errors from being swallowed
         database.SaveChanges();
     }
     return project;
 }
        public void TestDeTokenizeString()
        {
            string Input = "{application:name} is being tested on @TweetHarbor 'cause it rocks the {build:commit:id} magic {build:commit:message}";
            Notification n = new Notification()
            {
                application = new Application()
                {
                    name = "TestApp",
                },
                build = new Build()
                {
                    BuildId = 10,
                    commit = new Commit()
                    {
                        id = Guid.NewGuid().ToString(),
                        message = "Some testin' goin' on"
                    },
                    status = "succeeded"
                }
            };

            Project p = new Project()
            {
                DateCreated = DateTime.Now.AddDays(-1),
                ProjectName = "TestApp"
            };

            var result = NotifyController.DeTokenizeString(Input, p, n);

            Assert.AreEqual("TestApp is being tested on @TweetHarbor 'cause it rocks the " + n.build.commit.id.Substring(0, 7) + " magic Some testin' goin' on", result);
        }