// POST api/<controller>
        public HttpResponseMessage Post(FormDataCollection form)
        {
            var command = new InboundMail();
            command.Sender = form.Get("sender");
            command.Body = form.Get("body-plain");
            command.Stripped = form.Get("stripped-text");

            string token;

            using (var db = new UsersContext())
            {
                var user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == command.Sender.ToLower());

                if (user == null)
                    return Request.CreateResponse(HttpStatusCode.BadRequest);

                if (user.BasecampCredentials == null || string.IsNullOrWhiteSpace(user.BasecampCredentials.AccessToken))
                    return Request.CreateResponse(HttpStatusCode.BadRequest);

                token = user.BasecampCredentials.AccessToken;
            }

            var basecamp = new BasecampClient();

            var lookfor = "I will complete";
            var rx = new Regex(@"(\S.+?[.!?])(?=\s+|$)");
            foreach (Match match in rx.Matches(command.Body))
            {
                var index = match.Value.IndexOf(lookfor);

                if (index >= 0)
                {
                    var msg = match.Value.Replace(lookfor, "Complete");

                    var notice = "task created ok";
                    try
                    {
                        basecamp.CreateTask(msg, token);
                    }
                    catch (System.Exception e)
                    {
                        notice = e.ToString();
                    }

            //					SendSimpleMessage(command.Sender, notice);
                    break;
                }
            }

            return Request.CreateResponse(HttpStatusCode.Accepted);
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(new MigrateDatabaseToLatestVersion<UsersContext, Configuration>());

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        //
        // GET: /Account/Manage
        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
                : "";
            var userid = WebSecurity.GetUserId(User.Identity.Name);
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(userid);
            using (UsersContext db = new UsersContext())
            {
                ViewBag.HasBasecampCredentials = db.UserProfiles.First(x => x.UserId == userid).BasecampCredentials != null;
            }

            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
        public ActionResult Process(HttpContextBase context, AuthenticateCallbackData model)
        {
            using (var db = new UsersContext())
            {
                var userId = WebSecurity.GetUserId(HttpContext.Current.User.Identity.Name);
                var user = db.UserProfiles.First(u => u.UserId == userId);
                user.BasecampCredentials = user.BasecampCredentials ?? new BasecampCredentials();
                user.BasecampCredentials.AccessToken = model.AuthenticatedClient.AccessToken.PublicToken;
                user.BasecampCredentials.RefreshToken = model.AuthenticatedClient.AccessToken.SecretToken;

                db.SaveChanges();
            }

            var route = new RouteValueDictionary()
            {
                {"action", "Manage"},
                {"controller", "Account"}
            };
            return new RedirectToRouteResult(route);
            return new ContentResult
            {
                Content = model.AuthenticatedClient.UserInformation.Name
            };
            return new ViewResult
            {
                ViewName = "Home",
                ViewData = new ViewDataDictionary(new AuthenticateCallbackViewModel
                {
                    AuthenticatedClient = model.AuthenticatedClient,
                    Exception = model.Exception,
                    ReturnUrl = model.ReturnUrl
                })
            };
        }