private void DeleteService(int id)
        {
            SocialTFSEntities db = new SocialTFSEntities();
            bool isDeleted;

            try
            {
                var delInst = db.ServiceInstance.Where(si => si.pk_id == id);
                foreach (ServiceInstance s in delInst)
                {
                    db.ServiceInstance.DeleteObject(s);
                }
                //db.ServiceInstance.DeleteAllOnSubmit(db.ServiceInstance.Where(si => si.pk_id == id));
                db.SaveChanges();
                isDeleted = true;
            }
            catch (Exception)
            {
                isDeleted = false;
            }

            XDocument xml = new XDocument(
                            new XElement("Root",
                                new XElement("Deleted", isDeleted)));
            Response.Clear();
            Response.ContentType = "text/xml";
            Response.Write(xml);
            Response.End();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Session.Clear();

            string username = Request.Form["ctl00$MainContent$UsernameTB"];
            string password = Request.Form["ctl00$MainContent$PasswordTB"];

            if (username != null)
            {
                SocialTFSEntities db = new SocialTFSEntities();
                if (Signup(db, username, password))
                {
                    Session["Username"] = username;
                    if (db.Setting.Any(s => s.key == "SmtpServer"))
                        Response.Redirect("Default.aspx");
                    else
                        Response.Redirect("Settings.aspx");
                }
                else
                {
                    errorLB.Attributes.Add("class", "error");
                    errorLB.InnerText = "The username or the password is not correct";
                }
            }
            else if (Request.QueryString["type"] == "error")
            {
                errorLB.Attributes.Add("class", "error");
                errorLB.InnerHtml = Request.QueryString["message"];
            }
            else if (Request.QueryString["type"] == "confirm")
            {
                errorLB.Attributes.Add("class", "confirm");
                errorLB.InnerText = Request.QueryString["message"];
            }
        }
        private void SaveWeights()
        {
            SocialTFSEntities db = new SocialTFSEntities();
            bool isSaved;

            XmlDocument requestXml = new XmlDocument();
            requestXml.Load(new XmlTextReader(new StreamReader(Request.InputStream)));
            try
            {
                foreach (XmlNode item in requestXml.SelectNodes("//weights/item"))
                {
                    FeatureScore featureScore = db.FeatureScore.Where(fs => fs.ServiceInstance.name == item.SelectSingleNode("service").InnerText && fs.pk_fk_feature == item.SelectSingleNode("feature").InnerText).Single();
                    featureScore.score = Int32.Parse(item.SelectSingleNode("weight").InnerText);
                }
                db.SaveChanges();
                isSaved = true;
            }
            catch (Exception)
            {
                isSaved = false;
            }

            XDocument xml = new XDocument(
                            new XElement("Root",
                                new XElement("Saved", isSaved)));
            Response.Clear();
            Response.ContentType = "text/xml";
            Response.Write(xml);
            Response.End();
        }
        private bool Signup(SocialTFSEntities db, string username, string password)
        {
            IEnumerable<User> users = db.User.Where(u => u.isAdmin && u.username == username && u.password == (password));

            if (users.Count() >= 1)
                return true;
            else
                return false;
        }
        private void SaveService()
        {
            if (!String.IsNullOrEmpty(NameTB.Attributes["required"]) && String.IsNullOrEmpty(Request.Params["ctl00$MainContent$NameTB"]))
                Response.Redirect("Services.aspx");
            if (!String.IsNullOrEmpty(HostTB.Attributes["required"]) && String.IsNullOrEmpty(Request.Params["ctl00$MainContent$HostTB"]))
                Response.Redirect("Services.aspx");
            if (!String.IsNullOrEmpty(ConsumerKeyTB.Attributes["required"]) && String.IsNullOrEmpty(Request.Params["ctl00$MainContent$ConsumerKeyTB"]))
                Response.Redirect("Services.aspx");
            if (!String.IsNullOrEmpty(ConsumerSecretTB.Attributes["required"]) && String.IsNullOrEmpty(Request.Params["ctl00$MainContent$ConsumerSecretTB"]))
                Response.Redirect("Services.aspx");

            SocialTFSEntities db = new SocialTFSEntities();

            ServiceInstance service =
                   (from serin in db.ServiceInstance
                    where serin.pk_id == Int32.Parse(Request.QueryString["id"])
                    select serin).Single();

            IService iService = ServiceFactory.getService(service.Service.name);

            if (iService.GetPrivateFeatures().Contains(FeaturesType.Labels))
            {
                if (String.IsNullOrEmpty(Request.Params["ctl00$MainContent$GitHubLabelTB"]))
                {
                    System.Diagnostics.Debug.WriteLine("label nulla");
                    ServiceFactory.GitHubLabels = String.Empty;
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("labels associate " + Request.Params["ctl00$MainContent$GitHubLabelTB"]);
                    ServiceFactory.GitHubLabels = Request.Params["ctl00$MainContent$GitHubLabelTB"];
                }
            }
            else
            {
                service.name = Request.Params["ctl00$MainContent$NameTB"];
                service.host = Request.Params["ctl00$MainContent$HostTB"];
                if (iService.GetPrivateFeatures().Contains(FeaturesType.OAuth1))
                {
                    service.consumerKey = Request.Params["ctl00$MainContent$ConsumerKeyTB"];
                    service.consumerSecret = Request.Params["ctl00$MainContent$ConsumerSecretTB"];
                }
                else if (iService.GetPrivateFeatures().Contains(FeaturesType.TFSAuthenticationWithDomain))
                {
                    service.consumerKey = Request.Params["ctl00$MainContent$UsernameTB"];
                    service.consumerSecret = Request.Params["ctl00$MainContent$PasswordTB"];
                }

                db.SaveChanges();
            }

            Response.Redirect("Services.aspx");
        }
        private void PopulateServices()
        {
            ServiceSE.Items.Add(new ListItem());
            SocialTFSEntities db = new SocialTFSEntities();

            foreach (Service item in db.Service.Where(s => s.name != "SocialTFS"))
            {
                IService iService = ServiceFactory.getService(item.name);
                if (iService.GetPrivateFeatures().Contains(FeaturesType.MoreInstance) ||
                    (!db.ServiceInstance.Select(si => si.fk_service).Contains(item.pk_id)))
                    ServiceSE.Items.Add(new ListItem(item.name, item.pk_id.ToString()));
            }
        }
        private void LoadServices()
        {
            SocialTFSEntities db = new SocialTFSEntities();

            foreach (var item in db.ServiceInstance.Where(s => s.Service.name != "SocialTFS"))
            {
                HtmlTableCell name = new HtmlTableCell();
                HtmlTableCell service = new HtmlTableCell();
                HtmlTableCell host = new HtmlTableCell();
                HtmlTableCell edit = new HtmlTableCell();
                HtmlTableCell delete = new HtmlTableCell();

                name.InnerText = item.name;
                service.InnerText = item.Service.name;
                host.InnerText = item.host;

                IService iService = ServiceFactory.getService(item.Service.name);

                if (iService.GetPrivateFeatures().Contains(FeaturesType.MoreInstance) || iService.GetPrivateFeatures().Contains(FeaturesType.Labels))
                {
                    HtmlInputButton editBT = new HtmlInputButton();
                    editBT.Attributes.Add("title", "Edit " + item.name);
                    editBT.Attributes.Add("class", "edit");
                    editBT.Value = item.pk_id.ToString();
                    edit.Attributes.Add("class", "center");
                    edit.Controls.Add(editBT);
                }

                HtmlInputButton deleteBT = new HtmlInputButton();
                deleteBT.Attributes.Add("title", "Delete " + item.name);
                deleteBT.Attributes.Add("class", "delete");
                deleteBT.Value = item.pk_id.ToString();
                delete.Attributes.Add("class", "center");
                delete.Controls.Add(deleteBT);

                HtmlTableRow tr = new HtmlTableRow();
                tr.ID = "Row" + item.pk_id;
                tr.Cells.Add(name);
                tr.Cells.Add(service);
                tr.Cells.Add(host);
                tr.Cells.Add(edit);
                tr.Cells.Add(delete);

                ServiceTable.Rows.Add(tr);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            SocialTFSEntities db = new SocialTFSEntities();

            Series userSeries = RegisteredUser.Series[0];
            userSeries["PieLabelStyle"] = "Outside";
            userSeries.Points.Clear();
            userSeries.Points.AddXY("Registered", db.User.Where(u => u.active && !u.isAdmin).Count());
            userSeries.Points.AddXY("Unregistered", db.User.Where(u => !u.active && !u.isAdmin).Count());

            Series serviceSeries = RegisteredService.Series[0];
            serviceSeries["PieLabelStyle"] = "Outside";
            serviceSeries.Points.Clear();

            foreach(ServiceInstance item in db.ServiceInstance.Where(si => si.name != "SocialTFS"))
                serviceSeries.Points.AddXY(item.name, item.Registration.Count);
        }
        private void PopulateService()
        {
            SocialTFSEntities db = new SocialTFSEntities();

            ServiceInstance service =
                   (from serin in db.ServiceInstance
                    where serin.pk_id == Int32.Parse(Request.QueryString["id"])
                    select serin).Single();

            IService iService = ServiceFactory.getService(service.Service.name);

            if (!iService.GetPrivateFeatures().Contains(FeaturesType.MoreInstance) && !iService.GetPrivateFeatures().Contains(FeaturesType.Labels))
                Response.Redirect("Services.aspx");

            Id.Value = service.pk_id.ToString();
            ServiceTB.Value = service.Service.name;
            NameTB.Value = service.name;
            HostTB.Value = service.host;
            if (iService.GetPrivateFeatures().Contains(FeaturesType.OAuth1))
            {
                ConsumerKeyTB.Value = service.consumerKey;
                ConsumerSecretTB.Value = service.consumerSecret;
            }
            else
            {
                ConsumerKeyTB.Attributes["required"] = String.Empty;
                ConsumerSecretTB.Attributes["required"] = String.Empty;
                ConsumerKeyRW.Visible = false;
                ConsumerSecretRW.Visible = false;
            }

            if (!iService.GetPrivateFeatures().Contains(FeaturesType.Labels))
            {
                GitHubLabelRW.Visible = false;
                ErrGitHubLabelRW.Visible = false;
            }
            else
            {
                ServiceTB.Disabled = true;
                NameTB.Disabled = true;
                HostTB.Disabled = true;
                GitHubLabelTB.Value = ServiceFactory.GitHubLabels;
                ErrGitHubLabelRW.Visible = true;
            }
        }
        private void SaveUsers()
        {
            SocialTFSEntities db = new SocialTFSEntities();

            XmlDocument requestXml = new XmlDocument();
            requestXml.Load(new XmlTextReader(new StreamReader(Request.InputStream)));

            List<string> mailError = new List<string>();

            foreach (XmlNode item in requestXml.SelectNodes("//users/user"))
            {
                try
                {
                    String passwd = Membership.GeneratePassword(10, 2);

                    User user = new User()
                    {
                        username = item.InnerText,
                        email = item.InnerText,
                        //password = (passwd)
                        password = (passwd)
                    };
                    db.User.AddObject(user);

                    if (WebUtility.SendEmail(item.InnerText, "SocialTFS invitation", GetBody(item.InnerText, passwd), true))
                        db.SaveChanges();
                    else
                        mailError.Add(item.InnerText);
                }
                catch
                {
                    mailError.Add(item.InnerText);
                }
            }

            XElement root = new XElement("Root");
            foreach (string item in mailError)
                root.Add(new XElement("NotSent", item));

            Response.Clear();
            Response.ContentType = "text/xml";
            Response.Write(new XDocument(root));
            Response.End();
        }
        private void ChangeAdminSettings()
        {
            string username = Request.Params["ctl00$MainContent$AdminUsernameTB"];
            string email = Request.Params["ctl00$MainContent$AdminEmailTB"];
            string password = Request.Params["ctl00$MainContent$PasswordTB"];
            string confirm = Request.Params["ctl00$MainContent$ConfirmTB"];

            SocialTFSEntities db = new SocialTFSEntities();

            User admin = db.User.Where(u => u.isAdmin).Single();
            bool changePassword = true;

            if (ChangePasswordCB.Checked)
                if (password.Equals(confirm))
                    admin.password = (password);
                else
                {
                    ErrorPA.Attributes.Add("class", "error");
                    ErrorPA.InnerText = "Passwords do not match.";
                    changePassword = false;
                }

            if (changePassword)
            {
                if (!db.User.Any(u => (u.username == username || u.email == email) && !u.isAdmin))
                {
                    admin.username = username;
                    admin.email = email;

                    db.SaveChanges();
                    ErrorPA.Attributes.Add("class", "confirm");
                    ErrorPA.InnerText = "Data stored";
                }
                else
                {
                    ErrorPA.Attributes.Add("class", "error");
                    ErrorPA.InnerText = "Username or email already exist.";
                }
            }
        }
        /// <summary>
        /// Send an email.
        /// </summary>
        /// <param name="to">Addressee.</param>
        /// <param name="subject">Sunject.</param>
        /// <param name="body">Message.</param>
        /// <param name="isBodyHtml">True if the message is wrote in HTML.</param>
        /// <returns>True if the email is correctly sended, false otherwise.</returns>
        public static bool SendEmail(String to, String subject, String body, bool isBodyHtml)
        {
            try
            {
                SocialTFSEntities db = new SocialTFSEntities();

                MailMessage message = new MailMessage();
                message.To.Add(new MailAddress(to));
                message.From = new MailAddress(db.Setting.Where(s => s.key == "MailAddress").Single().value,"SocialTFS");
                message.Subject = subject;
                message.IsBodyHtml = isBodyHtml;
                message.Body = body;
                SmtpClient smtp = new SmtpClient(db.Setting.Where(s => s.key == "SmtpServer").Single().value, Int32.Parse(db.Setting.Where(s => s.key == "SmtpPort").Single().value));
                switch (db.Setting.Where(s => s.key == "SmtpSecurity").Single().value)
                {
                    case "None":
                        break;
                    case "SSL/TLS":
                        smtp.UseDefaultCredentials = false;
                        smtp.EnableSsl = true;
                        //smtp.Credentials = new NetworkCredential(db.Setting.Where(s => s.key == "MailAddress").Single().value, db.EncDecRc4("key",db.Setting.Where(s => s.key == "MailPassword").Single().value));
                        smtp.Credentials = new NetworkCredential(db.Setting.Where(s => s.key == "MailAddress").Single().value, db.Setting.Where(s => s.key == "MailPassword").Single().value);
                        break;
                    case "STARTTLS":
                        smtp.UseDefaultCredentials = false;
                        smtp.EnableSsl = true;
                        //smtp.Credentials = new NetworkCredential(db.Setting.Where(s => s.key == "MailAddress").Single().value, db.EncDecRc4("key",db.Setting.Where(s => s.key == "MailPassword").Single().value), "");
                        smtp.Credentials = new NetworkCredential(db.Setting.Where(s => s.key == "MailAddress").Single().value, db.Setting.Where(s => s.key == "MailPassword").Single().value);
                        break;
            }
                smtp.Send(message);
                return true;
            }
            catch
            {
                return false;
            }
        }
        private void LoadWeights()
        {
            SocialTFSEntities db = new SocialTFSEntities();

            foreach (var item in db.FeatureScore)
            {
                HtmlTableCell service = new HtmlTableCell();
                HtmlTableCell feature = new HtmlTableCell();
                HtmlTableCell weight = new HtmlTableCell();

                service.InnerText = item.ServiceInstance.name;
                feature.InnerText = item.pk_fk_feature;
                weight.InnerText = item.score.ToString();
                weight.Attributes.Add("class", "center");
                weight.Attributes.Add("contenteditable", "true");

                HtmlTableRow tr = new HtmlTableRow();
                tr.Cells.Add(service);
                tr.Cells.Add(feature);
                tr.Cells.Add(weight);

                WeightTable.Rows.Add(tr);
            }
        }
        private void ChangeSmtpSettings()
        {
            SocialTFSEntities db = new SocialTFSEntities();

            try
            {
                bool changePassword = true;
                if (ChangeMailPasswordCB.Checked)
                    if (Request.Params["ctl00$MainContent$MailPasswordTB"].Equals(Request.Params["ctl00$MainContent$MailConfirmTB"]))
                        //db.Setting.Where(s => s.key == "MailPassword").Single().value = db.EncDecRc4("key",Request.Params["ctl00$MainContent$MailPasswordTB"]);
                        db.Setting.Where(s => s.key == "MailPassword").Single().value = Request.Params["ctl00$MainContent$MailPasswordTB"];
                    else
                    {
                        ErrorPA.Attributes.Add("class", "error");
                        ErrorPA.InnerText = "Passwords do not match.";
                        changePassword = false;
                    }

                if (changePassword)
                {
                    db.Setting.Where(s => s.key == "SmtpServer").Single().value = Request.Params["ctl00$MainContent$SmtpServerTB"];
                    db.Setting.Where(s => s.key == "SmtpPort").Single().value = Request.Params["ctl00$MainContent$SmtpPortTB"];
                    db.Setting.Where(s => s.key == "SmtpSecurity").Single().value = Request.Params["ctl00$MainContent$SmtpSecuritySE"];
                    db.Setting.Where(s => s.key == "MailAddress").Single().value = Request.Params["ctl00$MainContent$MailAddressTB"];

                    db.SaveChanges();
                    ErrorPA.Attributes.Add("class", "confirm");
                    ErrorPA.InnerText = "Data stored.";
                }
            }
            catch
            {
                try
                {
                    var list = new List<Setting>(){
                        new Setting () {
                            key = "SmtpServer",
                            value = Request.Params["ctl00$MainContent$SmtpServerTB"]
                        },
                        new Setting () {
                            key = "SmtpPort",
                            value = Request.Params["ctl00$MainContent$SmtpPortTB"]
                        },
                        new Setting () {
                            key = "SmtpSecurity",
                            value = Request.Params["ctl00$MainContent$SmtpSecuritySE"]
                        },
                        new Setting () {
                            key = "MailAddress",
                            value = Request.Params["ctl00$MainContent$MailAddressTB"]
                        },
                        new Setting () {
                            key = "MailPassword",
                            //value = db.EncDecRc4("key",Request.Params["ctl00$MainContent$MailPasswordTB"])
                            value = Request.Params["ctl00$MainContent$MailPasswordTB"]
                        }
                    };
                    foreach(Setting s in list)
                    {
                        db.Setting.AddObject(s);
                    }
                    /*
                    db.Setting.InsertAllOnSubmit(new List<Setting>(){
                        new Setting () {
                            key = "SmtpServer",
                            value = Request.Params["ctl00$MainContent$SmtpServerTB"]
                        },
                        new Setting () {
                            key = "SmtpPort",
                            value = Request.Params["ctl00$MainContent$SmtpPortTB"]
                        },
                        new Setting () {
                            key = "SmtpSecurity",
                            value = Request.Params["ctl00$MainContent$SmtpSecuritySE"]
                        },
                        new Setting () {
                            key = "MailAddress",
                            value = Request.Params["ctl00$MainContent$MailAddressTB"]
                        },
                        new Setting () {
                            key = "MailPassword",
                            value = db.EncDecRc4("key",Request.Params["ctl00$MainContent$MailPasswordTB"])
                        }
                    });
                     * */
                    db.SaveChanges();
                    ErrorPA.Attributes.Add("class", "confirm");
                    ErrorPA.InnerText = "Data stored.";
                }
                catch
                {
                    ErrorPA.Attributes.Add("class", "error");
                    ErrorPA.InnerText = "Something was wrong. Please try again later.";
                }
            }
        }
 private void FillSmtpSettings()
 {
     SocialTFSEntities db = new SocialTFSEntities();
     try
     {
         SmtpServerTB.Value = db.Setting.Where(s => s.key == "SmtpServer").Single().value;
         SmtpPortTB.Value = db.Setting.Where(s => s.key == "SmtpPort").Single().value;
         SmtpSecuritySE.Value = db.Setting.Where(s => s.key == "SmtpSecurity").Single().value;
         MailAddressTB.Value = db.Setting.Where(s => s.key == "MailAddress").Single().value;
     }
     catch { }
 }
 private void FillAdminSettings()
 {
     SocialTFSEntities db = new SocialTFSEntities();
     User admin = db.User.Where(u => u.isAdmin).Single();
     AdminUsernameTB.Value = admin.username;
     AdminEmailTB.Value = admin.email;
 }
 private void CheckUsername(string username)
 {
     SocialTFSEntities db = new SocialTFSEntities();
     XDocument xml = new XDocument(
              new XElement("Root",
                  new XElement("IsAviable", !db.User.Any(u => u.username == username && !u.isAdmin))));
     Response.Clear();
     Response.ContentType = "text/xml";
     Response.Write(xml);
     Response.End();
 }
        private void ServiceFields()
        {
            SocialTFSEntities db = new SocialTFSEntities();
            try
            {
                //Request.QueryString["id"])).Single().name;
                //Request.QueryString["id"]

                int id = Int32.Parse(Request.QueryString["id"]);

                IService iService = ServiceFactory.getService(db.Service.Where(s => s.pk_id == id).Single().name);

                XDocument xml = new XDocument(
                    new XElement("Root",
                        new XElement("CanHaveMoreInstance", iService.GetPrivateFeatures().Contains(FeaturesType.MoreInstance)),
                        new XElement("NeedOAuth", iService.GetPrivateFeatures().Contains(FeaturesType.OAuth1)),
                        new XElement("NeedGitHubLabel", iService.Name.Equals("GitHub"))));
                Response.Clear();
                Response.ContentType = "text/xml";
                Response.Write(xml);
                Response.End();
            }
            catch (TargetInvocationException)
            {
                XDocument xml = new XDocument(
                       new XElement("Root",
                           new XElement("CanHaveMoreInstance", false),
                           new XElement("NeedOAuth", false),
                           new XElement("NeedGitHubLabel", false)));
                Response.Clear();
                Response.ContentType = "text/xml";
                Response.Write(xml);
                Response.End();
            }
            catch (InvalidOperationException)
            {
                Response.Redirect("Services.aspx");
            }
        }
        private void SaveService()
        {
            SocialTFSEntities db = new SocialTFSEntities();
            Service service = new Service();
            int id = Int32.Parse(Request.Params["ctl00$MainContent$ServiceSE"]);
            try
            {
                service = db.Service.Where(s => s.pk_id == id).Single();
            }
            catch
            {
                ErrorPA.Style.Remove("display");
            }

            IService iService = ServiceFactory.getService(service.name);
            ServiceInstance serviceInstance = new ServiceInstance();
            if (!iService.GetPrivateFeatures().Contains(FeaturesType.MoreInstance))
            {
                PreregisteredService preser = db.PreregisteredService.Where(ps => ps.service == service.pk_id).Single();

                serviceInstance.name = preser.name;
                serviceInstance.host = preser.host;
                serviceInstance.fk_service = preser.service;
                serviceInstance.consumerKey = preser.consumerKey;
                serviceInstance.consumerSecret = preser.consumerSecret;
                db.ServiceInstance.AddObject(serviceInstance);
            }
            else
            {
                string consumerKey = null, consumerSecret = null;
                string host = Request.Params["ctl00$MainContent$HostTB"];

                if (host.EndsWith(@"/"))
                    host = host.Remove(host.Length - 1);

                if (iService.GetPrivateFeatures().Contains(FeaturesType.OAuth1))
                {
                    consumerKey = Request.Params["ctl00$MainContent$ConsumerKeyTB"];
                    consumerSecret = Request.Params["ctl00$MainContent$ConsumerSecretTB"];
                }

                serviceInstance.name = Request.Params["ctl00$MainContent$NameTB"];
                serviceInstance.host = host;
                serviceInstance.Service = service;
                serviceInstance.consumerKey = consumerKey;
                serviceInstance.consumerSecret = consumerSecret;

                db.ServiceInstance.AddObject(serviceInstance);
            }

            db.SaveChanges();

            if (iService.GetPrivateFeatures().Contains(FeaturesType.Labels))
            {
                iService.Get(FeaturesType.Labels, Request.Params["ctl00$MainContent$GitHubLabelTB"]);
            }

            foreach (FeaturesType featureType in iService.GetScoredFeatures())
            {
                db.FeatureScore.AddObject(new FeatureScore()
                {

                    pk_fk_serviceInstance = serviceInstance.pk_id,
                    pk_fk_feature = featureType.ToString(),
                    score = 1
                });
            }
            //TODO update the new version (leave comment from the next line)
            //dbService.version = newServiceVersion;
            db.SaveChanges();

            Response.Redirect("Services.aspx");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            SocialTFSEntities db = new SocialTFSEntities();

            String token = Request.QueryString["token"];
            Setting recoveringToken = null;
            Setting recoveringTime = null;

            try
            {
                recoveringTime = db.Setting.Where(s => s.key == "RecoveringTime").Single();
                recoveringToken = db.Setting.Where(s => s.key == "RecoveringToken").Single();
            }
            catch { }

            if (Request.RequestType == "GET")
            {
                if (String.IsNullOrEmpty(token))
                {
                    if (recoveringTime == null || DateTime.Parse(recoveringTime.value) < DateTime.UtcNow - new TimeSpan(0, 5, 0))
                    {
                        String newToken = GenerateToken();

                        if (WebUtility.SendEmail(db.User.Where(u => u.isAdmin).Single().email, "Password recovering", GetBody(newToken), true))
                        {
                            if (recoveringToken != null)
                            {
                                recoveringToken.value = newToken;
                                recoveringTime.value = DateTime.UtcNow.ToString();
                            }
                            else
                            {
                                var list = new List<Setting>(){
                                new Setting () {
                                    key = "RecoveringToken",
                                    value = newToken
                                },
                                new Setting () {
                                    key = "RecoveringTime",
                                    value = DateTime.UtcNow.ToString()
                                }};
                                foreach(Setting s in list)
                                {
                                    db.Setting.AddObject(s);
                                }
                                /*
                                db.Setting.AddObject(
                                    new List<Setting>(){
                                new Setting () {
                                    key = "RecoveringToken",
                                    value = newToken
                                },
                                new Setting () {
                                    key = "RecoveringTime",
                                    value = DateTime.UtcNow.ToString()
                                }});
                                 * */
                            }
                            db.SaveChanges();
                            Response.Redirect("Login.aspx?type=confirm&message=Email sent, check your email inbox.");
                        }
                        else
                            Response.Redirect("Login.aspx?type=error&message=Is not possible recover the password, the smtp server is not set.");
                    }
                    else
                        Response.Redirect("Login.aspx?type=error&message=You have sent a request less than 5 minutes ago. Please, try again later.");
                }
                else
                {
                    if (recoveringToken == null || recoveringToken.value != token)
                        Response.Redirect("Login.aspx?type=error&message=Wrong token.");
                }
            }
            else if (Request.RequestType == "POST")
            {
                db.User.Where(u => u.isAdmin).Single().password = (Request.Params["ctl00$MainContent$PasswordTB"]);
                var set = db.Setting.Where(s => s.key == "RecoveringToken" || s.key == "RecoveringTime");
                foreach (Setting s in set)
                {
                    db.Setting.DeleteObject(s);
                }
                //db.Setting.DeleteAllOnSubmit(db.Setting.Where(s => s.key == "RecoveringToken" || s.key == "RecoveringTime"));
                db.SaveChanges();
                Response.Redirect("Login.aspx?type=confirm&message=Password changed successfully.");
            }
        }