private void DeleteUser(int id)
        {
            ConnectorDataContext db = new ConnectorDataContext();
            bool isDeleted;
            string errorMessage = String.Empty;

            try
            {
                Stopwatch w = Stopwatch.StartNew();
                db.InteractiveFriends.DeleteAllOnSubmit(db.InteractiveFriends.Where(q => q.user == id));
                db.SubmitChanges();
                w.Stop();
                ILog log = LogManager.GetLogger("QueryLogger");
                log.Info(" Elapsed time: " + w.Elapsed + ", remove all interactive friends of an user");
                Stopwatch w2 = Stopwatch.StartNew();
                db.DynamicFriends.DeleteAllOnSubmit(db.DynamicFriends.Where(q => q.user == id));
                db.SubmitChanges();
                w2.Stop();
                ILog log2 = LogManager.GetLogger("QueryLogger");
                log2.Info(" Elapsed time: " + w2.Elapsed + ", remove all dynamic friends of an user");
                Stopwatch w3 = Stopwatch.StartNew();
                db.StaticFriends.DeleteAllOnSubmit(db.StaticFriends.Where(q => q.user == id));
                db.SubmitChanges();
                w3.Stop();
                ILog log3 = LogManager.GetLogger("QueryLogger");
                log3.Info(" Elapsed time: " + w3.Elapsed + ", remove all static friends of an user");
                Stopwatch w4 = Stopwatch.StartNew();
                db.Suggestions.DeleteAllOnSubmit(db.Suggestions.Where(q => q.user == id));
                db.SubmitChanges();
                w4.Stop();
                ILog log4 = LogManager.GetLogger("QueryLogger");
                log4.Info(" Elapsed time: " + w4.Elapsed + ", remove all suggestions of an user");
                Stopwatch w1 = Stopwatch.StartNew();
                db.Users.DeleteAllOnSubmit(db.Users.Where(u => u.id == id));
                db.SubmitChanges();
                w1.Stop();
                ILog log1 = LogManager.GetLogger("QueryLogger");
                log1.Info(" Elapsed time: " + w1.Elapsed + ", remove the user");
                isDeleted = true;
            }
            catch (Exception e)
            {

                errorMessage = e.Message;
               // errorMessage = e.StackTrace;
                isDeleted = false;
            }

            XDocument xml = new XDocument(
                            new XElement("Root",
                                new XElement("Deleted", isDeleted),
                                new XElement("Errors", errorMessage)));
            Response.Clear();
            Response.ContentType = "text/xml";
            Response.Write(xml);
            Response.End();
        }
        private void DeleteService(int id)
        {
            ConnectorDataContext db = new ConnectorDataContext();
            bool isDeleted;

            try
            {
                Stopwatch w1 = Stopwatch.StartNew();
                db.ServiceInstances.DeleteAllOnSubmit(db.ServiceInstances.Where(si => si.id == id));
                db.SubmitChanges();
                w1.Stop();
                ILog log1 = LogManager.GetLogger("QueryLogger");
                log1.Info(" Elapsed time: " + w1.Elapsed + ", remove all service instances");
                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();
        }
        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"];

            ConnectorDataContext db = new ConnectorDataContext();

            Stopwatch w = Stopwatch.StartNew();
            User admin = db.Users.Where(u => u.isAdmin).Single();
            w.Stop();
            ILog log = LogManager.GetLogger("QueryLogger");
            log.Info(" Elapsed time: " + w.Elapsed + ", select the admin to change his settings");
            bool changePassword = true;

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

            if (changePassword)
            {
                Stopwatch w2 = Stopwatch.StartNew();
                bool usr = db.Users.Any(u => (u.username == username || u.email == email) && !u.isAdmin);
                w2.Stop();
                ILog log2 = LogManager.GetLogger("QueryLogger");
                log2.Info(" Elapsed time: " + w2.Elapsed + ", check if there is an user with admin's username or email");
                if (!usr)
                {
                    admin.username = username;
                    admin.email = email;

                    Stopwatch w3 = Stopwatch.StartNew();
                    db.SubmitChanges();
                    w3.Stop();
                    ILog log3 = LogManager.GetLogger("QueryLogger");
                    log3.Info(" Elapsed time: " + w3.Elapsed + ", change admin settings");
                    ErrorPA.Attributes.Add("class", "confirm");
                    ErrorPA.InnerText = "Data stored";
                }
                else
                {
                    ErrorPA.Attributes.Add("class", "error");
                    ErrorPA.InnerText = "Username or email already exist.";
                }
            }
        }
        private void SaveUsers()
        {
            ConnectorDataContext db = new ConnectorDataContext();

            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 = db.Encrypt(passwd)
                    };
                    Stopwatch w = Stopwatch.StartNew();
                    db.Users.InsertOnSubmit(user);
                    w.Stop();
                    ILog log = LogManager.GetLogger("QueryLogger");
                    log.Info(" Elapsed time: " + w.Elapsed + ", insert the user in a pending state");

                    if (WebUtility.SendEmail(item.InnerText, "SocialCDE invitation", GetBody(item.InnerText, passwd), true))
                    {
                        Stopwatch w1 = Stopwatch.StartNew();
                        db.SubmitChanges();
                        w1.Stop();
                        ILog log1 = LogManager.GetLogger("QueryLogger");
                        log1.Info(" Elapsed time: " + w1.Elapsed + ", send mail for registration");
                    }
                    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 SaveWeights()
        {
            ConnectorDataContext db = new ConnectorDataContext();
            bool isSaved;

            XmlDocument requestXml = new XmlDocument();
            requestXml.Load(new XmlTextReader(new StreamReader(Request.InputStream)));
            try
            {
                foreach (XmlNode item in requestXml.SelectNodes("//weights/item"))
                {
                    Stopwatch w = Stopwatch.StartNew();
                    FeatureScore featureScore = db.FeatureScores.Where(fs => fs.ServiceInstance.name == item.SelectSingleNode("service").InnerText && fs.feature == item.SelectSingleNode("feature").InnerText).Single();
                    w.Stop();
                    ILog log = LogManager.GetLogger("QueryLogger");
                    log.Info(" Elapsed time: " + w.Elapsed + ", select feature scores");
                    featureScore.score = Int32.Parse(item.SelectSingleNode("weight").InnerText);
                }
                Stopwatch w1 = Stopwatch.StartNew();
                db.SubmitChanges();
                w1.Stop();
                ILog log1 = LogManager.GetLogger("QueryLogger");
                log1.Info(" Elapsed time: " + w1.Elapsed + ", save weights");
                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 void UpdateInteractiveFriend(User user)
        {
            ConnectorDataContext db = new ConnectorDataContext();

            Stopwatch w = Stopwatch.StartNew();
            List<ChosenFeature> cFeature = db.ChosenFeatures.Where(cf => cf.user == user.id && cf.feature == FeaturesType.InteractiveNetwork.ToString()).ToList();
            w.Stop();
            ILog log = LogManager.GetLogger("QueryLogger");
            log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + user.id + ", feature's name: " + FeaturesType.InteractiveNetwork.ToString() + ", select all chosen features of an author and his feature 'interactive network'");

            foreach (ChosenFeature chosenFeature in cFeature)
            {
                Stopwatch w2 = Stopwatch.StartNew();
                ChosenFeature temp = db.ChosenFeatures.Where(cf => cf.id == chosenFeature.id).Single();
                w2.Stop();
                ILog log2 = LogManager.GetLogger("QueryLogger");
                log2.Info(" Elapsed time: " + w2.Elapsed + ", chosen feature's id: " + chosenFeature.id + ", select a chosen feature");
                if (temp.lastDownload > DateTime.UtcNow - _interactiveSpan)
                    continue;
                else
                    temp.lastDownload = DateTime.UtcNow;

                try
                {
                    Stopwatch w1 = Stopwatch.StartNew();
                    db.SubmitChanges();
                    w1.Stop();
                    ILog log1 = LogManager.GetLogger("QueryLogger");
                    log1.Info(" Elapsed time: " + w1.Elapsed + ", update the chosen feature according to the date(interactive friend)");
                }
                catch { continue; }

                IService service;
                if (temp.Registration.ServiceInstance.Service.name.Equals("GitHub"))
                {
                    service = ServiceFactory.getServiceOauth(temp.Registration.ServiceInstance.Service.name, temp.Registration.ServiceInstance.host, temp.Registration.ServiceInstance.consumerKey, temp.Registration.ServiceInstance.consumerSecret, temp.Registration.accessToken, null);
                }
                else
                {
                    //submit new friendship for the current chosen feature
                    service = ServiceFactory.getService(
                       temp.Registration.ServiceInstance.Service.name,
                       temp.Registration.nameOnService,
                       db.EncDecRc4("key", temp.Registration.accessToken),
                       temp.Registration.accessSecret,
                       temp.Registration.ServiceInstance.host);
                }
                //this line must be before the deleting
                SCollection[] collections = (SCollection[])service.Get(FeaturesType.InteractiveNetwork);
                try
                {
                    //vecchio metodo
                    Stopwatch w3 = Stopwatch.StartNew();
                    db.InteractiveFriends.DeleteAllOnSubmit(db.InteractiveFriends.Where(intFr => intFr.chosenFeature == temp.id));
                    db.SubmitChanges();
                    w3.Stop();
                    ILog log3 = LogManager.GetLogger("QueryLogger");
                    log3.Info(" Elapsed time: " + w3.Elapsed + ", chosen feature's id: " + temp.id + ", remove all old interactive friends according to the chosen feature");

                    foreach (SCollection collection in collections)
                    {
                        foreach (SWorkItem workitem in collection.WorkItems)
                        {
                            Stopwatch w4 = Stopwatch.StartNew();
                            IEnumerable<int> friendsInDb = db.Registrations.Where(r => workitem.InvolvedUsers.Contains(r.nameOnService) || workitem.InvolvedUsers.Contains(r.accessSecret + "\\" + r.nameOnService)).Select(r => r.user);
                            w4.Stop();
                            ILog log4 = LogManager.GetLogger("QueryLogger");
                            log4.Info(" Elapsed time: " + w4.Elapsed + ", select all users that are working on the same workitem");
                            foreach (int friendInDb in friendsInDb)
                            {
                                Stopwatch w5 = Stopwatch.StartNew();
                                db.InteractiveFriends.InsertOnSubmit(new InteractiveFriend()
                                {
                                    user = friendInDb,
                                    chosenFeature = temp.id,
                                    collection = collection.Uri,
                                    interactiveObject = workitem.Name,
                                    objectType = "WorkItem"
                                });
                                w5.Stop();
                                ILog log5 = LogManager.GetLogger("QueryLogger");
                                log5.Info(" Elapsed time: " + w5.Elapsed + ", user id: " + friendInDb + ", chosen feature: " + temp.id + ", collection uri: " + collection.Uri + ", interactive object: " + workitem.Name + ", insert an interactive friend which is working on a workitem in a pending state");
                            }
                        }
                        foreach (SFile file in collection.Files)
                        {
                            Stopwatch w6 = Stopwatch.StartNew();
                            IEnumerable<int> friendsInDb = db.Registrations.Where(r => file.InvolvedUsers.Contains(r.nameOnService) || file.InvolvedUsers.Contains(r.accessSecret + "\\" + r.nameOnService)).Select(r => r.user);
                            w6.Stop();
                            ILog log6 = LogManager.GetLogger("QueryLogger");
                            log6.Info(" Elapsed time: " + w6.Elapsed + ", select all users that are working on the same file");
                            foreach (int friendInDb in friendsInDb)
                            {
                                Stopwatch w7 = Stopwatch.StartNew();
                                db.InteractiveFriends.InsertOnSubmit(new InteractiveFriend()
                                {
                                    user = friendInDb,
                                    chosenFeature = temp.id,
                                    collection = collection.Uri,
                                    interactiveObject = file.Name,
                                    objectType = "File"
                                });
                                w7.Stop();
                                ILog log7 = LogManager.GetLogger("QueryLogger");
                                log7.Info(" Elapsed time: " + w7.Elapsed + ", user id: " + friendInDb + ", chosen feature: " + temp.id + ", collection uri: " + collection.Uri + ", interactive object: " + file.Name + ", insert an interactive friend which is working on a file in a pending state");
                            }
                        }
                    }

                    Stopwatch w8 = Stopwatch.StartNew();
                    db.SubmitChanges();
                    w8.Stop();
                    ILog log8 = LogManager.GetLogger("QueryLogger");
                    log8.Info(" Elapsed time: " + w8.Elapsed + ", insert the interactive friend");
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.StackTrace);
                }
            }
        }
        public bool SaveAvatar(string username, string password, Uri avatar)
        {
            Contract.Requires(!String.IsNullOrEmpty(username));
            Contract.Requires(!String.IsNullOrEmpty(password));

            ConnectorDataContext db = new ConnectorDataContext();
            User user = CheckCredentials(db, username, password);
            if (user == null)
                return false;

            Stopwatch w = Stopwatch.StartNew();
            user.avatar = avatar.AbsoluteUri;
            db.SubmitChanges();
            w.Stop();
            ILog log = LogManager.GetLogger("QueryLogger");
            log.Info(" Elapsed time: " + w.Elapsed + ", uri: " + avatar.AbsoluteUri + ", save avatar");

            return true;
        }
        /// <summary>
        /// This static constructor is called only one time, when the application is started. 
        /// It synchronizes the features available for each service with the features available in the database.
        /// </summary>
        static SocialTFSProxy()
        {
            ConnectorDataContext db = new ConnectorDataContext();
            XmlConfigurator.Configure(new Uri(System.Web.Hosting.HostingEnvironment.MapPath("~/log4net.config")));

            //add the completely new features
            IEnumerable<FeaturesType> features = FeaturesManager.GetFeatures();
            foreach (FeaturesType featureType in features)
            {
                Stopwatch w = Stopwatch.StartNew();
                bool feat = db.Features.Contains(new Feature() { name = featureType.ToString() });
                w.Stop();
                ILog log = LogManager.GetLogger("QueryLogger");
                log.Info(" Elapsed time: " + w.Elapsed + ", feature's name: " + featureType.ToString() + ", check if the feature is available when the application is started");
                if (!feat)
                {
                    Stopwatch w1 = Stopwatch.StartNew();
                    db.Features.InsertOnSubmit(new Feature()
                    {
                        name = featureType.ToString(),
                        description = FeaturesManager.GetFeatureDescription(featureType),
                        @public = FeaturesManager.IsPublicFeature(featureType)
                    });
                    w1.Stop();
                    ILog log1 = LogManager.GetLogger("QueryLogger");
                    log1.Info(" Elapsed time: " + w1.Elapsed + ", feature's name: " + featureType.ToString() + ", description: " + FeaturesManager.GetFeatureDescription(featureType) + ", public: " + FeaturesManager.IsPublicFeature(featureType) + ", insert a feature in a pending state");
                }
            }
            Stopwatch w2 = Stopwatch.StartNew();
            db.SubmitChanges();
            w2.Stop();
            ILog log2 = LogManager.GetLogger("QueryLogger");
            log2.Info(" Elapsed time: " + w2.Elapsed + ", insert the feature");
        }
        private void DownloadOlderPost(int author)
        {
            ConnectorDataContext db = new ConnectorDataContext();

            Stopwatch w = Stopwatch.StartNew();
            List<ChosenFeature> chosenFeatures = db.ChosenFeatures.Where(cf =>
                cf.Registration.user == author &&
                cf.feature == FeaturesType.UserTimeline.ToString()).ToList();
            w.Stop();
            ILog log = LogManager.GetLogger("QueryLogger");
            log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + author + ", feature's name: " + FeaturesType.UserTimeline.ToString() + ", select all chosen features of an author and his feature 'user timeline'(old post)");

            foreach (ChosenFeature item in chosenFeatures)
            {
                long maxId;
                DateTime maxDate = new DateTime();
                try
                {
                    Stopwatch w1 = Stopwatch.StartNew();
                    Post maxPost = db.Posts.Where(p => p.chosenFeature == item.id).OrderBy(p => p.createAt).First();
                    w1.Stop();
                    ILog log1 = LogManager.GetLogger("QueryLogger");
                    log1.Info(" Elapsed time: " + w1.Elapsed + ", chosen feature's id: " + item.id + ", select the oldest post");
                    maxId = maxPost.idOnService.GetValueOrDefault();
                    maxDate = maxPost.createAt;
                }
                catch (InvalidOperationException)
                {
                    maxId = 0;
                }

                IService service = ServiceFactory.getServiceOauth(
                    item.Registration.ServiceInstance.Service.name,
                    item.Registration.ServiceInstance.host,
                    item.Registration.ServiceInstance.consumerKey,
                    item.Registration.ServiceInstance.consumerSecret,
                    item.Registration.accessToken,
                    item.Registration.accessSecret);

                IPost[] timeline = null;
                if (service.Name.Equals("Facebook"))
                {
                    timeline = (IPost[])service.Get(FeaturesType.UserTimelineOlderPosts, long.Parse(item.Registration.idOnService), maxId, maxDate);
                }
                else
                {
                    timeline = (IPost[])service.Get(FeaturesType.UserTimelineOlderPosts, int.Parse(item.Registration.idOnService), maxId, maxDate);
                }
                Stopwatch w2 = Stopwatch.StartNew();
                IEnumerable<long?> postInDb = db.Posts.Where(p => p.chosenFeature == item.id).Select(p => p.idOnService);
                w2.Stop();
                ILog log2 = LogManager.GetLogger("QueryLogger");
                log2.Info(" Elapsed time: " + w2.Elapsed + ", chosen feature's id: " + item.id + ", select id on service of the oldest post");

                foreach (IPost post in timeline)
                {
                    if (!postInDb.Contains(post.Id))
                    {
                        Stopwatch w3 = Stopwatch.StartNew();
                        db.Posts.InsertOnSubmit(new Post
                        {
                            chosenFeature = item.id,
                            idOnService = post.Id,
                            message = post.Text,
                            createAt = post.CreatedAt
                        });
                        w3.Stop();
                        ILog log3 = LogManager.GetLogger("QueryLogger");
                        log3.Info(" Elapsed time: " + w3.Elapsed + ", chosen feature's id: " + item.id + ", id on service: " + post.Id + ", message: " + post.Text + ", date time of creation: " + post.CreatedAt + ", preparing to insert the oldest post");
                    }
                }
            }
            Stopwatch w4 = Stopwatch.StartNew();
            db.SubmitChanges();
            w4.Stop();
            ILog log4 = LogManager.GetLogger("QueryLogger");
            log4.Info(" Elapsed time: " + w4.Elapsed + ", actually inserting the oldest post");
        }
        private void DownloadNewerPost(int author)
        {
            ConnectorDataContext db = new ConnectorDataContext();

            Stopwatch w = Stopwatch.StartNew();
            List<ChosenFeature> chosenFeatures = db.ChosenFeatures.Where(cf =>
                cf.Registration.user == author &&
                cf.feature == FeaturesType.UserTimeline.ToString()).ToList();
            w.Stop();
            ILog log = LogManager.GetLogger("QueryLogger");
            log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + author + ", feature's name: " + FeaturesType.UserTimeline.ToString() + ", select all chosen features of an author and his feature 'user timeline'(new post)");

            foreach (ChosenFeature item in chosenFeatures)
            {
                Stopwatch w1 = Stopwatch.StartNew();
                ChosenFeature cfTemp = db.ChosenFeatures.Where(cf => cf.id == item.id).Single();
                w1.Stop();
                ILog log1 = LogManager.GetLogger("QueryLogger");
                log1.Info(" Elapsed time: " + w1.Elapsed + ", chosen feature's id: " + item.id + ", select a chosen feature");
                if (cfTemp.lastDownload >= DateTime.UtcNow - _postSpan)
                    continue;
                else
                    cfTemp.lastDownload = DateTime.UtcNow;

                try
                {
                    Stopwatch w6 = Stopwatch.StartNew();
                    db.SubmitChanges();
                    w6.Stop();
                    ILog log6 = LogManager.GetLogger("QueryLogger");
                    log6.Info(" Elapsed time: " + w6.Elapsed + ", update the chosen feature according to the date(download newer post)");
                }
                catch { continue; }

                long sinceId;
                DateTime sinceDate = new DateTime();
                try
                {
                    Stopwatch w2 = Stopwatch.StartNew();
                    Post sincePost = db.Posts.Where(p => p.chosenFeature == cfTemp.id).OrderByDescending(p => p.createAt).First();
                    w2.Stop();
                    ILog log2 = LogManager.GetLogger("QueryLogger");
                    log2.Info(" Elapsed time: " + w2.Elapsed + ", chosen feature's id: " + cfTemp.id + ", select the most recent post");
                    sinceId = sincePost.idOnService.GetValueOrDefault();
                    sinceDate = sincePost.createAt;
                }
                catch (InvalidOperationException)
                {
                    sinceId = 0;
                }

                IService service = ServiceFactory.getServiceOauth(
                    cfTemp.Registration.ServiceInstance.Service.name,
                    cfTemp.Registration.ServiceInstance.host,
                    cfTemp.Registration.ServiceInstance.consumerKey,
                    cfTemp.Registration.ServiceInstance.consumerSecret,
                    cfTemp.Registration.accessToken,
                    cfTemp.Registration.accessSecret);
                IPost[] timeline = new IPost[0];

                if (service.Name.Equals("Facebook"))
                {
                    timeline = (IPost[])service.Get(FeaturesType.UserTimeline, long.Parse(cfTemp.Registration.idOnService), sinceId, sinceDate);
                }
                else
                {
                    timeline = (IPost[])service.Get(FeaturesType.UserTimeline, int.Parse(cfTemp.Registration.idOnService), sinceId, sinceDate);
                }

                Stopwatch w3 = Stopwatch.StartNew();
                IEnumerable<long?> postInDb = db.Posts.Where(p => p.chosenFeature == item.id).Select(p => p.idOnService);
                w3.Stop();
                ILog log3 = LogManager.GetLogger("QueryLogger");
                log3.Info(" Elapsed time: " + w3.Elapsed + ", chosen feature's id: " + item.id + ", select id on service of the newer post");

                if (timeline != null)
                    foreach (IPost post in timeline)
                    {
                        if (!postInDb.Contains(post.Id))
                        {
                            Stopwatch w4 = Stopwatch.StartNew();
                            db.Posts.InsertOnSubmit(new Post
                            {
                                chosenFeature = cfTemp.id,
                                idOnService = post.Id,
                                message = post.Text,
                                createAt = post.CreatedAt
                            });
                            w4.Stop();
                            ILog log4 = LogManager.GetLogger("QueryLogger");
                            log4.Info(" Elapsed time: " + w4.Elapsed + ", chosen feature's id: " + cfTemp.id + ", id on service: " + post.Id + ", message: " + post.Text + ", date time of creation: " + post.CreatedAt + ", preparing to insert the newer post");
                        }
                    }
            }
            try
            {
                Stopwatch w5 = Stopwatch.StartNew();
                db.SubmitChanges();
                w5.Stop();
                ILog log5 = LogManager.GetLogger("QueryLogger");
                log5.Info(" Elapsed time: " + w5.Elapsed + ", actually inserting the newer post");
            }
            catch (Exception e)
            {

            }
        }
        public bool UpdateHiddenUser(string username, string password, int userId, bool suggestions, bool dynamic, bool interactive)
        {
            Contract.Requires(!String.IsNullOrEmpty(username));
            Contract.Requires(!String.IsNullOrEmpty(password));

            ConnectorDataContext db = new ConnectorDataContext();
            User user = CheckCredentials(db, username, password);
            if (user == null)
                return false;

            try
            {
                Stopwatch w = Stopwatch.StartNew();
                db.Hiddens.DeleteAllOnSubmit(db.Hiddens.Where(h => h.user == user.id && h.friend == userId));
                db.SubmitChanges();
                w.Stop();
                ILog log = LogManager.GetLogger("QueryLogger");
                log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + user.id + ", friend's id: " + userId + ", remove all hidden friends of an user");

                if (suggestions)
                {
                    Stopwatch w2 = Stopwatch.StartNew();
                    db.Hiddens.InsertOnSubmit(new Hidden()
                    {
                        user = user.id,
                        friend = userId,
                        timeline = HiddenType.Suggestions.ToString()
                    });
                    w2.Stop();
                    ILog log2 = LogManager.GetLogger("QueryLogger");
                    log2.Info(" Elapsed time: " + w2.Elapsed + ", user id: " + user.id + ", friend's id: " + userId + ", timeline: " + HiddenType.Suggestions.ToString() + ", insert a hidden friend in the suggestion timeline in a pending state");
                }
                if (dynamic)
                {
                    Stopwatch w3 = Stopwatch.StartNew();
                    db.Hiddens.InsertOnSubmit(new Hidden()
                    {
                        user = user.id,
                        friend = userId,
                        timeline = HiddenType.Dynamic.ToString()
                    });
                    w3.Stop();
                    ILog log3 = LogManager.GetLogger("QueryLogger");
                    log3.Info(" Elapsed time: " + w3.Elapsed + ", user id: " + user.id + ", friend's id: " + userId + ", timeline: " + HiddenType.Dynamic.ToString() + ", insert a hidden friend in the dynamic timeline in a pending state");
                }
                if (interactive)
                {
                    Stopwatch w4 = Stopwatch.StartNew();
                    db.Hiddens.InsertOnSubmit(new Hidden()
                    {
                        user = user.id,
                        friend = userId,
                        timeline = HiddenType.Interactive.ToString()
                    });
                    w4.Stop();
                    ILog log4 = LogManager.GetLogger("QueryLogger");
                    log4.Info(" Elapsed time: " + w4.Elapsed + ", user id: " + user.id + ", friend's id: " + userId + ", timeline: " + HiddenType.Interactive.ToString() + ", insert a hidden friend in the interactive timeline in a pending state");
                }
                Stopwatch w5 = Stopwatch.StartNew();
                db.SubmitChanges();
                w5.Stop();
                ILog log5 = LogManager.GetLogger("QueryLogger");
                log5.Info(" Elapsed time: " + w5.Elapsed + ", insert a hidden friend according to the timeline");
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool UpdateChosenFeatures(string username, string password, int serviceInstanceId, string[] chosenFeatures)
        {
            Contract.Requires(!String.IsNullOrEmpty(username));
            Contract.Requires(!String.IsNullOrEmpty(password));

            ConnectorDataContext db = new ConnectorDataContext();
            bool suggestion = false, dynamic = false, interactive = false;

            User user = CheckCredentials(db, username, password);
            if (user == null)
                return false;

            //remove the old chosen features
            Stopwatch w4 = Stopwatch.StartNew();
            IEnumerable<ChosenFeature> chosenFeaturesToDelete = db.ChosenFeatures.Where(c => c.user == user.id
                && !chosenFeatures.Contains(c.feature) && c.serviceInstance == serviceInstanceId);
            w4.Stop();
            ILog log4 = LogManager.GetLogger("QueryLogger");
            log4.Info(" Elapsed time: " + w4.Elapsed + ", user id: " + user.id + ", service instance: " + serviceInstanceId + ", select all chosen features of an user");
            Stopwatch w = Stopwatch.StartNew();
            db.ChosenFeatures.DeleteAllOnSubmit(chosenFeaturesToDelete);
            db.SubmitChanges();
            w.Stop();
            ILog log = LogManager.GetLogger("QueryLogger");
            log.Info(" Elapsed time: " + w.Elapsed + ", remove the old chosen features");

            //add the new chosen features
            foreach (string chosenFeature in chosenFeatures)
            {
                Stopwatch w1 = Stopwatch.StartNew();
                bool cFeature = db.ChosenFeatures.Where(c => c.user == user.id && c.feature == chosenFeature && c.serviceInstance == serviceInstanceId).Any();
                w1.Stop();
                ILog log1 = LogManager.GetLogger("QueryLogger");
                log1.Info(" Elapsed time: " + w1.Elapsed + ", user id: " + user.id + ", feature's name: " + chosenFeature + ", service instance's id: " + serviceInstanceId + ", check if there is a chosen feature with these parameters");
                if (!cFeature)
                {
                    if (chosenFeature == FeaturesType.Followers.ToString()
                        || chosenFeature == FeaturesType.Followings.ToString()
                        || chosenFeature == FeaturesType.TFSTeamProject.ToString()
                        || chosenFeature == FeaturesType.TFSTeamProject.ToString())
                        suggestion = true;
                    else if (chosenFeature == FeaturesType.IterationNetwork.ToString())
                        dynamic = true;
                    else if (chosenFeature == FeaturesType.InteractiveNetwork.ToString())
                        interactive = true;
                    Stopwatch w2 = Stopwatch.StartNew();
                    db.ChosenFeatures.InsertOnSubmit(new ChosenFeature()
                    {
                        user = user.id,
                        serviceInstance = serviceInstanceId,
                        feature = chosenFeature,
                        lastDownload = new DateTime(1900, 1, 1)
                    });
                    w2.Stop();
                    ILog log2 = LogManager.GetLogger("QueryLogger");
                    log2.Info(" Elapsed time: " + w2.Elapsed + ", user id: " + user.id + ", service instance's id: " + serviceInstanceId + ", feature: " + chosenFeature + ", last download: " + new DateTime(1900, 1, 1) + ", insert a new chosen feature in a pending state");
                }
            }
            Stopwatch w3 = Stopwatch.StartNew();
            db.SubmitChanges();
            w3.Stop();
            ILog log3 = LogManager.GetLogger("QueryLogger");
            log3.Info(" Elapsed time: " + w3.Elapsed + ", insert the chosen feature");

            if (suggestion)
                new Thread(thread => UpdateSuggestion(user)).Start();

            if (dynamic)
                new Thread(thread => UpdateDynamicFriend(user)).Start();

            if (interactive)
                new Thread(thread => UpdateInteractiveFriend(user)).Start();

            return true;
        }
        public bool Unfollow(string username, string password, int followId)
        {
            Contract.Requires(!String.IsNullOrEmpty(username));
            Contract.Requires(!String.IsNullOrEmpty(password));

            ConnectorDataContext db = new ConnectorDataContext();

            User user = CheckCredentials(db, username, password);
            if (user == null)
                return false;

            try
            {
                Stopwatch w = Stopwatch.StartNew();
                StaticFriend friend = db.StaticFriends.Where(f => f.user == user.id && f.friend == followId).Single();
                w.Stop();
                ILog log = LogManager.GetLogger("QueryLogger");
                log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + user.id + ", friend's id: " + followId + ", select a static friend of a user");

                Stopwatch w1 = Stopwatch.StartNew();
                db.StaticFriends.DeleteOnSubmit(friend);
                db.SubmitChanges();
                w1.Stop();
                ILog log1 = LogManager.GetLogger("QueryLogger");
                log1.Info(" Elapsed time: " + w1.Elapsed + ", unfollow an user");

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        private void UpdateSuggestion(User user)
        {
            ConnectorDataContext db = new ConnectorDataContext();
            Dictionary<int, HashSet<int>> logFriends = new Dictionary<int, HashSet<int>>();
            bool needToLog = false;

            Stopwatch w = Stopwatch.StartNew();
            IEnumerable<ChosenFeature> chosenFeatures = db.ChosenFeatures.Where(
                cf => (cf.feature.Equals(FeaturesType.Followings.ToString()) ||
                    cf.feature.Equals(FeaturesType.Followers.ToString()) ||
                    cf.feature.Equals(FeaturesType.TFSCollection.ToString()) ||
                    cf.feature.Equals(FeaturesType.TFSTeamProject.ToString())) && cf.user == user.id);
            w.Stop();
            ILog log = LogManager.GetLogger("QueryLogger");
            log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + user.id + ", select all chosen features of an author and his feature 'followings' or 'followers' or 'TFSCollection' or 'TFSTeamProject'");

            foreach (ChosenFeature chosenFeature in chosenFeatures)
            {
                Stopwatch w2 = Stopwatch.StartNew();
                ChosenFeature temp = db.ChosenFeatures.Where(cf => cf.id == chosenFeature.id).Single();
                w2.Stop();
                ILog log2 = LogManager.GetLogger("QueryLogger");
                log2.Info(" Elapsed time: " + w2.Elapsed + ", chosen feature's id: " + chosenFeature.id + ", select a chosen feature");
                if (temp.lastDownload > DateTime.UtcNow - _suggestionSpan)
                    continue;
                else
                    temp.lastDownload = DateTime.UtcNow;

                try
                {
                    Stopwatch w1 = Stopwatch.StartNew();
                    db.SubmitChanges();
                    w1.Stop();
                    ILog log1 = LogManager.GetLogger("QueryLogger");
                    log1.Info(" Elapsed time: " + w1.Elapsed + ", update the chosen feature according to the date(suggestion)");
                    needToLog = true;
                }
                catch
                {
                    continue;
                }

                IService service = null;

                if (chosenFeature.feature.Equals(FeaturesType.Followings.ToString()) ||
                    chosenFeature.feature.Equals(FeaturesType.Followers.ToString()))
                    service = ServiceFactory.getServiceOauth(
                        chosenFeature.Registration.ServiceInstance.Service.name,
                        chosenFeature.Registration.ServiceInstance.host,
                        chosenFeature.Registration.ServiceInstance.consumerKey,
                        chosenFeature.Registration.ServiceInstance.consumerSecret,
                        chosenFeature.Registration.accessToken,
                        chosenFeature.Registration.accessSecret);
                else if (chosenFeature.feature.Equals(FeaturesType.TFSCollection.ToString()) ||
                    chosenFeature.feature.Equals(FeaturesType.TFSTeamProject.ToString()))
                {
                    if (temp.Registration.ServiceInstance.Service.name.Equals("GitHub"))
                    {
                        service = ServiceFactory.getServiceOauth(temp.Registration.ServiceInstance.Service.name, temp.Registration.ServiceInstance.host, temp.Registration.ServiceInstance.consumerKey, temp.Registration.ServiceInstance.consumerSecret, temp.Registration.accessToken, null);
                    }
                    else
                    {
                        service = ServiceFactory.getService(
                            chosenFeature.Registration.ServiceInstance.Service.name,
                            chosenFeature.Registration.nameOnService,
                            db.EncDecRc4("key", chosenFeature.Registration.accessToken),
                            chosenFeature.Registration.accessSecret,
                            chosenFeature.Registration.ServiceInstance.host);
                    }
                }

                string[] friends = null;

                if (chosenFeature.feature.Equals(FeaturesType.Followings.ToString()))
                    friends = (string[])service.Get(FeaturesType.Followings, null);
                else if (chosenFeature.feature.Equals(FeaturesType.Followers.ToString()))
                    friends = (string[])service.Get(FeaturesType.Followers, null);
                else if (chosenFeature.feature.Equals(FeaturesType.TFSCollection.ToString()))
                    friends = (string[])service.Get(FeaturesType.TFSCollection, null);
                else if (chosenFeature.feature.Equals(FeaturesType.TFSTeamProject.ToString()))
                    friends = (string[])service.Get(FeaturesType.TFSTeamProject, null);

                if (friends != null)
                {
                    //Delete suggestions for this chosen feature in the database
                    Stopwatch w3 = Stopwatch.StartNew();
                    db.Suggestions.DeleteAllOnSubmit(db.Suggestions.Where(s => s.chosenFeature == chosenFeature.id));
                    db.SubmitChanges();
                    w3.Stop();
                    ILog log3 = LogManager.GetLogger("QueryLogger");
                    log3.Info(" Elapsed time: " + w3.Elapsed + ", chosen feature's id: " + chosenFeature.id + ", delete suggestions for this chosen feature");

                    foreach (string friend in friends)
                    {
                        Stopwatch w4 = Stopwatch.StartNew();
                        IEnumerable<User> friendInSocialTfs = db.Registrations.Where(r => r.idOnService == friend &&
                            r.serviceInstance == chosenFeature.serviceInstance).Select(r => r.User);
                        w4.Stop();
                        ILog log4 = LogManager.GetLogger("QueryLogger");
                        log4.Info(" Elapsed time: " + w4.Elapsed + ", user id: " + friend + ", feature's name: " + chosenFeature.serviceInstance + ", select all users that can be possible friends in SocialTFS");
                        if (friendInSocialTfs.Count() == 1)
                        {
                            User suggestedFriend = friendInSocialTfs.First();

                            if (friend != chosenFeature.Registration.idOnService)
                            {
                                Stopwatch w5 = Stopwatch.StartNew();
                                db.Suggestions.InsertOnSubmit(new Suggestion()
                                {
                                    user = suggestedFriend.id,
                                    chosenFeature = chosenFeature.id
                                });
                                w5.Stop();
                                ILog log5 = LogManager.GetLogger("QueryLogger");
                                log5.Info(" Elapsed time: " + w5.Elapsed + ", user id: " + suggestedFriend.id + ", chosen feature: " + chosenFeature.id + ", insert a suggestion in a pending state");

                                if (!logFriends.ContainsKey(suggestedFriend.id))
                                    logFriends[suggestedFriend.id] = new HashSet<int>();
                                logFriends[suggestedFriend.id].Add(temp.Registration.serviceInstance);
                            }
                        }
                    }
                    try
                    {
                        Stopwatch w6 = Stopwatch.StartNew();
                        db.SubmitChanges();
                        w6.Stop();
                        ILog log6 = LogManager.GetLogger("QueryLogger");
                        log6.Info(" Elapsed time: " + w6.Elapsed + ", insert a suggestion");
                    }
                    catch { }
                }
            }

            if (needToLog)
            {
                ILog log7 = LogManager.GetLogger("NetworkLogger");
                log7.Info(user.id + ",S,[" + GetFriendString(user.id, logFriends) + "]");
            }
        }
        private void DownloadSkills(User currentUser, ConnectorDataContext db)
        {
            Stopwatch w = Stopwatch.StartNew();
            List<ChosenFeature> chosenFeatures = db.ChosenFeatures.Where(cf => cf.user == currentUser.id &&
                cf.feature == FeaturesType.Skills.ToString() &&
                cf.lastDownload < DateTime.UtcNow - _skillSpan).ToList();
            w.Stop();
            ILog log = LogManager.GetLogger("QueryLogger");
            log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + currentUser.id + ", feature's name: " + FeaturesType.Skills.ToString() + ", select all chosen features of an user and his feature 'skills'");

            foreach (ChosenFeature item in chosenFeatures)
            {
                //delete the user's skills in the database
                Stopwatch w1 = Stopwatch.StartNew();
                db.Skills.DeleteAllOnSubmit(item.Skills);
                db.SubmitChanges();
                w1.Stop();
                ILog log1 = LogManager.GetLogger("QueryLogger");
                log1.Info(" Elapsed time: " + w1.Elapsed + ", delete user's skills");

                Registration registration = item.Registration;
                IService service = ServiceFactory.getServiceOauth(
                    registration.ServiceInstance.Service.name,
                    registration.ServiceInstance.host,
                    registration.ServiceInstance.consumerKey,
                    registration.ServiceInstance.consumerSecret,
                    registration.accessToken,
                    registration.accessSecret);

                string[] userSkills = (string[])service.Get(FeaturesType.Skills, null);

                //insert skills in the database
                foreach (string userSkill in userSkills)
                {
                    Stopwatch w2 = Stopwatch.StartNew();
                    db.Skills.InsertOnSubmit(new Skill()
                    {
                        chosenFeature = item.id,
                        skill = userSkill
                    });
                    w2.Stop();
                    ILog log2 = LogManager.GetLogger("QueryLogger");
                    log2.Info(" Elapsed time: " + w2.Elapsed + ", chosen feature: " + item.id + ", skill: " + userSkill + ", preparing to insert skills");
                }

                item.lastDownload = DateTime.UtcNow;

                Stopwatch w3 = Stopwatch.StartNew();
                db.SubmitChanges();
                w3.Stop();
                ILog log3 = LogManager.GetLogger("QueryLogger");
                log3.Info(" Elapsed time: " + w3.Elapsed + ", actually inserting skills");
            }
        }
        public bool Follow(string username, string password, int followId)
        {
            Contract.Requires(!String.IsNullOrEmpty(username));
            Contract.Requires(!String.IsNullOrEmpty(password));

            ConnectorDataContext db = new ConnectorDataContext();

            User user = CheckCredentials(db, username, password);
            if (user == null)
                return false;

            try
            {
                Stopwatch w = Stopwatch.StartNew();
                db.StaticFriends.InsertOnSubmit(new StaticFriend()
                {
                    user = user.id,
                    friend = followId
                });
                db.SubmitChanges();
                w.Stop();
                ILog log = LogManager.GetLogger("QueryLogger");
                log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + user.id + ", static friend's id: " + followId + ", insert an user as static friend");

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public bool ChangePassword(String username, String oldPassword, String newPassword)
        {
            Contract.Requires(!String.IsNullOrEmpty(username));
            Contract.Requires(!String.IsNullOrEmpty(oldPassword));
            Contract.Requires(!String.IsNullOrEmpty(newPassword));

            ConnectorDataContext db = new ConnectorDataContext();

            User user = CheckCredentials(db, username, oldPassword);
            if (user == null)
                return false;

            Stopwatch w = Stopwatch.StartNew();
            user.password = db.Encrypt(newPassword);
            db.SubmitChanges();
            w.Stop();
            ILog log = LogManager.GetLogger("QueryLogger");
            log.Info(" Elapsed time: " + w.Elapsed + ", change password");
            return true;
        }
        public bool Post(String username, String password, String message)
        {
            Contract.Requires(!String.IsNullOrEmpty(username));
            Contract.Requires(!String.IsNullOrEmpty(password));
            Contract.Requires(!String.IsNullOrEmpty(message));

            ConnectorDataContext db = new ConnectorDataContext();

            User user = CheckCredentials(db, username, password);
            if (user == null)
                return false;

            ILog log = LogManager.GetLogger("PanelLogger");
            log.Info(user.id + ",P");

            Stopwatch w1 = Stopwatch.StartNew();
            int service = db.ServiceInstances.Where(si => si.Service.name == "SocialTFS").Single().id;
            w1.Stop();
            ILog log1 = LogManager.GetLogger("QueryLogger");
            log1.Info(" Elapsed time: " + w1.Elapsed + ", select service instance's id of the service 'SocialTFS'");

            long chosenFeature = -1;

            try
            {
                Stopwatch w2 = Stopwatch.StartNew();
                chosenFeature = db.ChosenFeatures.Where(cf => cf.user == user.id && cf.serviceInstance == service && cf.feature == FeaturesType.Post.ToString()).First().id;
                w2.Stop();
                ILog log2 = LogManager.GetLogger("QueryLogger");
                log2.Info(" Elapsed time: " + w2.Elapsed + ", user id: " + user.id + ", service instance: " + service + ", feature's name: " + FeaturesType.Post.ToString() + ", select chosen feature's id");
            }
            catch (InvalidOperationException)
            {
                try
                {
                    Stopwatch w3 = Stopwatch.StartNew();
                    db.Registrations.Where(r => r.user == user.id && r.serviceInstance == service).Single();
                    w3.Stop();
                    ILog log3 = LogManager.GetLogger("QueryLogger");
                    log3.Info(" Elapsed time: " + w3.Elapsed + ", user id: " + user.id + ", service instance: " + service + ", select registration of a service");
                }
                catch
                {
                    Registration registration = new Registration()
                    {
                        User = user,
                        serviceInstance = db.ServiceInstances.Where(si => si.Service.name == "SocialTFS").Single().id,  //considerata poco sopra per il log
                        nameOnService = username,
                        idOnService = username
                    };
                    Stopwatch w4 = Stopwatch.StartNew();
                    db.Registrations.InsertOnSubmit(registration);
                    db.SubmitChanges();
                    w4.Stop();
                    ILog log4 = LogManager.GetLogger("QueryLogger");
                    log4.Info(" Elapsed time: " + w4.Elapsed + ", insert a registration");
                }

                ChosenFeature newChoseFeature = new ChosenFeature()
                {
                    Registration = db.Registrations.Where(r => r.user == user.id && r.serviceInstance == service).Single(), //considerata poco sopra per il log
                    feature = FeaturesType.Post.ToString(),
                    lastDownload = new DateTime(1900, 1, 1)
                };
                Stopwatch w5 = Stopwatch.StartNew();
                db.ChosenFeatures.InsertOnSubmit(newChoseFeature);
                db.SubmitChanges();
                w5.Stop();
                ILog log5 = LogManager.GetLogger("QueryLogger");
                log5.Info(" Elapsed time: " + w5.Elapsed + ", feature's name: " + FeaturesType.Post.ToString() + ", last download: " + new DateTime(1900, 1, 1) + ", insert a new chosen feature");
                chosenFeature = newChoseFeature.id;
            }

            Stopwatch w6 = Stopwatch.StartNew();
            db.Posts.InsertOnSubmit(new Post
            {
                chosenFeature = chosenFeature,
                message = message,
                createAt = DateTime.UtcNow
            });

            db.SubmitChanges();
            w6.Stop();
            ILog log6 = LogManager.GetLogger("QueryLogger");
            log6.Info(" Elapsed time: " + w6.Elapsed + ", message: " + message + ", date time: " + DateTime.UtcNow + ", insert the post");

            return true;
        }
        private void GetUsersIssuesInvolved(User user, string collectionUri, string issueId)
        {
            ConnectorDataContext db = new ConnectorDataContext();
            Boolean flag = false;
            IService service = null;
            ChosenFeature temp = null;
            Stopwatch w = Stopwatch.StartNew();
            List<ChosenFeature> cFeatures = db.ChosenFeatures.Where(cf => cf.user == user.id && cf.feature == FeaturesType.InteractiveNetwork.ToString()).ToList();
            w.Stop();
            ILog log = LogManager.GetLogger("QueryLogger");
            log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + user.id + ", feature: " + FeaturesType.InteractiveNetwork.ToString() + ", select all chosen features of an user with feature 'InteractiveNetwork'");
            foreach (ChosenFeature chosenFeature in cFeatures)
            {
                Stopwatch w1 = Stopwatch.StartNew();
                temp = db.ChosenFeatures.Where(cf => cf.id == chosenFeature.id).Single();
                w1.Stop();
                ILog log1 = LogManager.GetLogger("QueryLogger");
                log1.Info(" Elapsed time: " + w1.Elapsed + ", chosen feature's id: " + chosenFeature.id + ", select a chosen feature to get users' issues involved");
                if (temp.Registration.ServiceInstance.Service.name.Equals("GitHub"))
                {
                    service = ServiceFactory.getServiceOauth(temp.Registration.ServiceInstance.Service.name, temp.Registration.ServiceInstance.host, temp.Registration.ServiceInstance.consumerKey, temp.Registration.ServiceInstance.consumerSecret, temp.Registration.accessToken, null);
                    flag = true;
                }
            }

            if (flag)
            {
                //obtaining users involved in the issue
                String[] users = (String[])service.Get(FeaturesType.UsersIssuesInvolved, new Object[2] { collectionUri, issueId });

                SWorkItem workitem = new SWorkItem()
                {
                    Name = issueId,
                    InvolvedUsers = users
                };

                Stopwatch w2 = Stopwatch.StartNew();
                db.InteractiveFriends.DeleteAllOnSubmit(db.InteractiveFriends.Where(intFr => intFr.chosenFeature == temp.id && intFr.objectType == "WorkItem"));
                db.SubmitChanges();
                w2.Stop();
                ILog log2 = LogManager.GetLogger("QueryLogger");
                log2.Info(" Elapsed time: " + w2.Elapsed + ", chosen feature's id: " + temp.id + ", delete all interactive friends according to the feature and objecttype 'WorkItem'");
                Stopwatch w3 = Stopwatch.StartNew();
                IEnumerable<int> friendsInDb = db.Registrations.Where(r => workitem.InvolvedUsers.Contains(r.nameOnService) || workitem.InvolvedUsers.Contains(r.accessSecret + "\\" + r.nameOnService)).Select(r => r.user);
                w3.Stop();
                ILog log3 = LogManager.GetLogger("QueryLogger");
                log3.Info(" Elapsed time: " + w3.Elapsed + ", select all users that are working on the same workitem(GetUsersIssuesInvolved)");
                foreach (int friendInDb in friendsInDb)
                {
                    Stopwatch w4 = Stopwatch.StartNew();
                    db.InteractiveFriends.InsertOnSubmit(new InteractiveFriend()
                    {
                        user = friendInDb,
                        chosenFeature = temp.id,
                        collection = collectionUri,
                        interactiveObject = workitem.Name,
                        objectType = "WorkItem"
                    });
                    w4.Stop();
                    ILog log4 = LogManager.GetLogger("QueryLogger");
                    log4.Info(" Elapsed time: " + w4.Elapsed + ", user id: " + friendInDb + ", chosen feature: " + temp.id + ", collection uri: " + collectionUri + ", interactive object: " + workitem.Name + ", insert an interactive friend which is working on a workitem in a pending state");
                }

                Stopwatch w8 = Stopwatch.StartNew();
                db.SubmitChanges();
                w8.Stop();
                ILog log8 = LogManager.GetLogger("QueryLogger");
                log8.Info(" Elapsed time: " + w8.Elapsed + ", insert the interactive friend");
            }
        }
        public int SubscribeUser(String email, String password, String username)
        {
            Contract.Requires(!String.IsNullOrEmpty(email));
            Contract.Requires(!String.IsNullOrEmpty(password));
            Contract.Requires(!String.IsNullOrEmpty(username));

            ConnectorDataContext db = new ConnectorDataContext();
            User user;
            try
            {
                Stopwatch w = Stopwatch.StartNew();
                user = db.Users.Where(u => u.email == email).Single();
                w.Stop();
                ILog log = LogManager.GetLogger("QueryLogger");
                log.Info(" Elapsed time: " + w.Elapsed + ", user email: " + email + ", select the user to subscribe him");
            }
            catch (InvalidOperationException)
            {
                return 1;
            }

            if (user.password != db.Encrypt(password))
                return 2;

            if (!IsAvailable(username))
                return 3;

            user.username = username;
            user.active = true;

            Stopwatch w1 = Stopwatch.StartNew();
            int sInstance = db.ServiceInstances.Where(si => si.Service.name == "SocialTFS").Single().id;
            w1.Stop();
            ILog log1 = LogManager.GetLogger("QueryLogger");
            log1.Info(" Elapsed time: " + w1.Elapsed + ", select the service instance with name 'SocialTFS'");

            Registration registration = new Registration()
            {
                User = user,
                serviceInstance = sInstance,
                nameOnService = username,
                idOnService = username
            };
            Stopwatch w2 = Stopwatch.StartNew();
            db.Registrations.InsertOnSubmit(registration);
            db.SubmitChanges();
            w2.Stop();
            ILog log2 = LogManager.GetLogger("QueryLogger");
            log2.Info(" Elapsed time: " + w2.Elapsed + ", service instance's id: " + sInstance + ", name and id on service: " + username + ", insert a new registration");

            Stopwatch w3 = Stopwatch.StartNew();
            db.ChosenFeatures.InsertOnSubmit(new ChosenFeature()
            {
                Registration = registration,
                feature = FeaturesType.Post.ToString(),
                lastDownload = new DateTime(1900, 1, 1)
            });
            db.SubmitChanges();
            w3.Stop();
            ILog log3 = LogManager.GetLogger("QueryLogger");
            log3.Info(" Elapsed time: " + w3.Elapsed + ", feature: " + FeaturesType.Post.ToString() + ", last download: " + new DateTime(1900, 1, 1) + ", insert a new Chosen feature");

            return 0;
        }
        private bool RegisterUserOnAService(ConnectorDataContext db, User user, ServiceInstance serviceInstance, IUser iUser, String accessToken, String accessSecret)
        {
            try
            {
                Registration reg = new Registration();

                reg.user = user.id;
                reg.ServiceInstance = serviceInstance;
                reg.nameOnService = iUser.UserName != null ? iUser.UserName : iUser.Id;
                reg.idOnService = iUser.Id.ToString();
                reg.accessToken = accessToken;
                reg.accessSecret = accessSecret;

                Stopwatch w = Stopwatch.StartNew();
                db.Registrations.InsertOnSubmit(reg);
                db.SubmitChanges();
                w.Stop();
                ILog log = LogManager.GetLogger("QueryLogger");
                log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + user.id + ", id on service: " + iUser.Id.ToString() + ", access token: " + accessToken + ", access secret: " + accessSecret + ", register user on a service");
                return true;
            }
            catch (ChangeConflictException)
            {
                return false;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            ConnectorDataContext db = new ConnectorDataContext();

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

            try
            {
                Stopwatch w = Stopwatch.StartNew();
                recoveringTime = db.Settings.Where(s => s.key == "RecoveringTime").Single();
                w.Stop();
                ILog log = LogManager.GetLogger("QueryLogger");
                log.Info(" Elapsed time: " + w.Elapsed + ", select the 'recovering time' key from settings");
                Stopwatch w1 = Stopwatch.StartNew();
                recoveringToken = db.Settings.Where(s => s.key == "RecoveringToken").Single();
                w1.Stop();
                ILog log1 = LogManager.GetLogger("QueryLogger");
                log1.Info(" Elapsed time: " + w1.Elapsed + ", select the 'recovering token' key from settings");
            }
            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();

                        Stopwatch w2 = Stopwatch.StartNew();
                        String to = db.Users.Where(u => u.isAdmin).Single().email;
                        w2.Stop();
                        ILog log2 = LogManager.GetLogger("QueryLogger");
                        log2.Info(" Elapsed time: " + w2.Elapsed + ", select the admin's email");

                        if (WebUtility.SendEmail(to, "Password recovering", GetBody(newToken), true))
                        {
                            if (recoveringToken != null)
                            {
                                recoveringToken.value = newToken;
                                recoveringTime.value = DateTime.UtcNow.ToString();
                            }
                            else
                            {
                                Stopwatch w3 = Stopwatch.StartNew();
                                db.Settings.InsertAllOnSubmit(
                                    new List<Setting>(){
                                new Setting () {
                                    key = "RecoveringToken",
                                    value = newToken
                                },
                                new Setting () {
                                    key = "RecoveringTime",
                                    value = DateTime.UtcNow.ToString()
                                }});
                                w3.Stop();
                                ILog log3 = LogManager.GetLogger("QueryLogger");
                                log3.Info(" Elapsed time: " + w3.Elapsed + ", insert new setting in a pending state(password recovering)");
                            }
                            Stopwatch w4 = Stopwatch.StartNew();
                            db.SubmitChanges();
                            w4.Stop();
                            ILog log4 = LogManager.GetLogger("QueryLogger");
                            log4.Info(" Elapsed time: " + w4.Elapsed + ", insert new settings");
                            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")
            {
                Stopwatch w5 = Stopwatch.StartNew();
                db.Users.Where(u => u.isAdmin).Single().password = db.Encrypt(Request.Params["ctl00$MainContent$PasswordTB"]);
                w5.Stop();
                ILog log5 = LogManager.GetLogger("QueryLogger");
                log5.Info(" Elapsed time: " + w5.Elapsed + ", select admin's password");
                Stopwatch w6 = Stopwatch.StartNew();
                db.Settings.DeleteAllOnSubmit(db.Settings.Where(s => s.key == "RecoveringToken" || s.key == "RecoveringTime"));
                db.SubmitChanges();
                w6.Stop();
                ILog log6 = LogManager.GetLogger("QueryLogger");
                log6.Info(" Elapsed time: " + w6.Elapsed + ", password changed");
                Response.Redirect("Login.aspx?type=confirm&message=Password changed successfully.");
            }
        }
        private void UpdateDynamicFriend(User user)
        {
            ConnectorDataContext db = new ConnectorDataContext();
            Dictionary<int, HashSet<int>> logFriends = new Dictionary<int, HashSet<int>>();
            bool needToLog = false;

            Stopwatch w = Stopwatch.StartNew();
            List<ChosenFeature> cFeature = db.ChosenFeatures.Where(cf => cf.user == user.id && cf.feature == FeaturesType.IterationNetwork.ToString()).ToList();
            w.Stop();
            ILog log = LogManager.GetLogger("QueryLogger");
            log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + user.id + ", feature's name: " + FeaturesType.IterationNetwork.ToString() + ", select all chosen feature of an author and his feature 'Iteration Network'");

            foreach (ChosenFeature chosenFeature in cFeature)
            {
                Stopwatch w1 = Stopwatch.StartNew();
                ChosenFeature temp = db.ChosenFeatures.Where(cf => cf.id == chosenFeature.id).Single();
                w1.Stop();
                ILog log1 = LogManager.GetLogger("QueryLogger");
                log1.Info(" Elapsed time: " + w1.Elapsed + ", chosen feature's id: " + chosenFeature.id + ", select a chosen feature to update");
                if (temp.lastDownload > DateTime.UtcNow - _dynamicSpan)
                    continue;
                else
                    temp.lastDownload = DateTime.UtcNow;

                try
                {
                    Stopwatch w3 = Stopwatch.StartNew();
                    db.SubmitChanges();
                    w3.Stop();
                    ILog log3 = LogManager.GetLogger("QueryLogger");
                    log3.Info(" Elapsed time: " + w3.Elapsed + ", update the chosen feature according to the date(dynamic friend)");
                    needToLog = true;
                }
                catch
                {
                    continue;
                }

                IService service;
                //submit new friendship for the current chosen feature
                if (temp.Registration.ServiceInstance.Service.name.Equals("GitHub"))
                {
                    service = ServiceFactory.getServiceOauth(temp.Registration.ServiceInstance.Service.name, temp.Registration.ServiceInstance.host, temp.Registration.ServiceInstance.consumerKey, temp.Registration.ServiceInstance.consumerSecret, temp.Registration.accessToken, null);
                }
                else
                {
                    service = ServiceFactory.getService(
                        temp.Registration.ServiceInstance.Service.name,
                        temp.Registration.nameOnService,
                        db.EncDecRc4("key", temp.Registration.accessToken),
                        temp.Registration.accessSecret,
                        temp.Registration.ServiceInstance.host);
                }
                //this line must be before the deleting
                String[] dynamicFriends = (String[])service.Get(FeaturesType.IterationNetwork, null);

                //delete old friendship for the current chosen feature
                Stopwatch w4 = Stopwatch.StartNew();
                db.DynamicFriends.DeleteAllOnSubmit(db.DynamicFriends.Where(df => df.chosenFeature == temp.id));
                db.SubmitChanges();
                w4.Stop();
                ILog log4 = LogManager.GetLogger("QueryLogger");
                log4.Info(" Elapsed time: " + w4.Elapsed + ", chosen feature's id: " + temp.id + ", delete old friendship for the current chosen feature");

                foreach (String dynamicFriend in dynamicFriends)
                {
                    Stopwatch w5 = Stopwatch.StartNew();
                    IEnumerable<int> friendsInDb = db.Registrations.Where(r => r.nameOnService == dynamicFriend && r.serviceInstance == temp.serviceInstance).Select(r => r.user);
                    w5.Stop();
                    ILog log5 = LogManager.GetLogger("QueryLogger");
                    log5.Info(" Elapsed time: " + w5.Elapsed + ", : dynamic friend" + dynamicFriend + ", service instance: " + temp.serviceInstance + ", select user to add as dynamic friend");
                    foreach (int friendInDb in friendsInDb)
                    {
                        Stopwatch w6 = Stopwatch.StartNew();
                        db.DynamicFriends.InsertOnSubmit(new DynamicFriend()
                        {
                            chosenFeature = temp.id,
                            user = friendInDb
                        });
                        w6.Stop();
                        ILog log6 = LogManager.GetLogger("QueryLogger");
                        log6.Info(" Elapsed time: " + w6.Elapsed + ", chosen feature's id: " + temp.id + ", friend id: " + friendInDb + ", insert a new dynamic friend in a pending state");

                        if (!logFriends.ContainsKey(friendInDb))
                            logFriends[friendInDb] = new HashSet<int>();
                        logFriends[friendInDb].Add(temp.Registration.serviceInstance);
                    }
                }
                try
                {
                    Stopwatch w7 = Stopwatch.StartNew();
                    db.SubmitChanges();
                    w7.Stop();
                    ILog log7 = LogManager.GetLogger("QueryLogger");
                    log7.Info(" Elapsed time: " + w7.Elapsed + ", insert a dynamic friend");
                }
                catch { }
            }

            if (needToLog)
            {
                ILog log8 = LogManager.GetLogger("NetworkLogger");
                log8.Info(user.id + ",I,[" + GetFriendString(user.id, logFriends) + "]");
            }
        }
        private void SaveService()
        {
            ConnectorDataContext db = new ConnectorDataContext();
            Service service = new Service();
            try
            {
                Stopwatch w3 = Stopwatch.StartNew();
                service = db.Services.Where(s => s.id == Int32.Parse(Request.Params["ctl00$MainContent$ServiceSE"])).Single();
                w3.Stop();
                ILog log3 = LogManager.GetLogger("QueryLogger");
                log3.Info(" Elapsed time: " + w3.Elapsed + ", select the service to save it");
            }
            catch
            {
                ErrorPA.Style.Remove("display");
            }

            IService iService = ServiceFactory.getService(service.name);
            ServiceInstance serviceInstance = new ServiceInstance();
            if (!iService.GetPrivateFeatures().Contains(FeaturesType.MoreInstance))
            {
                Stopwatch w4 = Stopwatch.StartNew();
                PreregisteredService preser = db.PreregisteredServices.Where(ps => ps.service == service.id).Single();
                w4.Stop();
                ILog log4 = LogManager.GetLogger("QueryLogger");
                log4.Info(" Elapsed time: " + w4.Elapsed + ", select the preregistered service to save the service");

                serviceInstance.name = preser.name;
                serviceInstance.host = preser.host;
                serviceInstance.service = preser.service;
                serviceInstance.consumerKey = preser.consumerKey;
                serviceInstance.consumerSecret = preser.consumerSecret;

                Stopwatch w5 = Stopwatch.StartNew();
                db.ServiceInstances.InsertOnSubmit(serviceInstance);
                w5.Stop();
                ILog log5 = LogManager.GetLogger("QueryLogger");
                log5.Info(" Elapsed time: " + w5.Elapsed + ", insert the service instance in a pending state");
            }
            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.id;
                serviceInstance.consumerKey = consumerKey;
                serviceInstance.consumerSecret = consumerSecret;

                Stopwatch w6 = Stopwatch.StartNew();
                db.ServiceInstances.InsertOnSubmit(serviceInstance);
                w6.Stop();
                ILog log6 = LogManager.GetLogger("QueryLogger");
                log6.Info(" Elapsed time: " + w6.Elapsed + ", insert the service instance in a pending state");
            }

            Stopwatch w7 = Stopwatch.StartNew();
            db.SubmitChanges();
            w7.Stop();
            ILog log7 = LogManager.GetLogger("QueryLogger");
            log7.Info(" Elapsed time: " + w7.Elapsed + ", insert the service ");

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

            foreach (FeaturesType featureType in iService.GetScoredFeatures())
            {
                Stopwatch w8 = Stopwatch.StartNew();
                db.FeatureScores.InsertOnSubmit(new FeatureScore()
                {
                    serviceInstance = serviceInstance.id,
                    feature = featureType.ToString(),
                    score = 1
                });
                w8.Stop();
                ILog log8 = LogManager.GetLogger("QueryLogger");
                log8.Info(" Elapsed time: " + w8.Elapsed + ", insert the relative feature score in a pending state");
            }
            //TODO update the new version (leave comment from the next line)
            //dbService.version = newServiceVersion;
            Stopwatch w9 = Stopwatch.StartNew();
            db.SubmitChanges();
            w9.Stop();
            ILog log9 = LogManager.GetLogger("QueryLogger");
            log9.Info(" Elapsed time: " + w9.Elapsed + ", insert the feature score");

            Response.Redirect("Services.aspx");
        }
        public bool DeleteRegistredService(String username, String password, int service)
        {
            Contract.Requires(!String.IsNullOrEmpty(username));
            Contract.Requires(!String.IsNullOrEmpty(password));

            ConnectorDataContext db = new ConnectorDataContext();

            User user = CheckCredentials(db, username, password);
            if (user == null)
                return false;

            try
            {
                Stopwatch w = Stopwatch.StartNew();
                db.Registrations.DeleteAllOnSubmit(db.Registrations.Where(r => r.user == user.id && r.serviceInstance == service));
                db.SubmitChanges();
                w.Stop();
                ILog log = LogManager.GetLogger("QueryLogger");
                log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + user.id + ", service id: " + service + ", unsubscribe service");
            }
            catch (ChangeConflictException)
            {
                return false;
            }
            return true;
        }
        private void ChangeSmtpSettings()
        {
            ConnectorDataContext db = new ConnectorDataContext();

            try
            {
                bool changePassword = true;
                if (ChangeMailPasswordCB.Checked)
                {
                    if (Request.Params["ctl00$MainContent$MailPasswordTB"].Equals(Request.Params["ctl00$MainContent$MailConfirmTB"]))
                    {
                        Stopwatch w2 = Stopwatch.StartNew();
                        db.Settings.Where(s => s.key == "MailPassword").Single().value = db.EncDecRc4("key", Request.Params["ctl00$MainContent$MailPasswordTB"]);
                        w2.Stop();
                        ILog log2 = LogManager.GetLogger("QueryLogger");
                        log2.Info(" Elapsed time: " + w2.Elapsed + ", select the value of 'MailPassword' key from settings");
                    }
                    else
                    {
                        ErrorPA.Attributes.Add("class", "error");
                        ErrorPA.InnerText = "Passwords do not match.";
                        changePassword = false;
                    }
                }
                if (changePassword)
                {
                    Stopwatch w3 = Stopwatch.StartNew();
                    db.Settings.Where(s => s.key == "SmtpServer").Single().value = Request.Params["ctl00$MainContent$SmtpServerTB"];
                    w3.Stop();
                    ILog log3 = LogManager.GetLogger("QueryLogger");
                    log3.Info(" Elapsed time: " + w3.Elapsed + ", set the value of 'Smtp Server' key");
                    Stopwatch w4 = Stopwatch.StartNew();
                    db.Settings.Where(s => s.key == "SmtpPort").Single().value = Request.Params["ctl00$MainContent$SmtpPortTB"];
                    w4.Stop();
                    ILog log4 = LogManager.GetLogger("QueryLogger");
                    log4.Info(" Elapsed time: " + w4.Elapsed + ", set the value of 'Smtp Port' key");
                    Stopwatch w5 = Stopwatch.StartNew();
                    db.Settings.Where(s => s.key == "SmtpSecurity").Single().value = Request.Params["ctl00$MainContent$SmtpSecuritySE"];
                    w5.Stop();
                    ILog log5 = LogManager.GetLogger("QueryLogger");
                    log5.Info(" Elapsed time: " + w5.Elapsed + ", set the value of 'Smtp Security' key");
                    Stopwatch w6 = Stopwatch.StartNew();
                    db.Settings.Where(s => s.key == "MailAddress").Single().value = Request.Params["ctl00$MainContent$MailAddressTB"];
                    w6.Stop();
                    ILog log6 = LogManager.GetLogger("QueryLogger");
                    log6.Info(" Elapsed time: " + w6.Elapsed + ", set the value of 'MailAddress' key");

                    Stopwatch w7 = Stopwatch.StartNew();
                    db.SubmitChanges();
                    w7.Stop();
                    ILog log7 = LogManager.GetLogger("QueryLogger");
                    log7.Info(" Elapsed time: " + w7.Elapsed + ", change smtp settings");
                    ErrorPA.Attributes.Add("class", "confirm");
                    ErrorPA.InnerText = "Data stored.";
                }
            }
            catch
            {
                try
                {
                    Stopwatch w8 = Stopwatch.StartNew();
                    db.Settings.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.SubmitChanges();
                    w8.Stop();
                    ILog log8 = LogManager.GetLogger("QueryLogger");
                    log8.Info(" Elapsed time: " + w8.Elapsed + ", insert new settings");
                    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 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");

            ConnectorDataContext db = new ConnectorDataContext();

            Stopwatch w = Stopwatch.StartNew();
            ServiceInstance service =
                   (from serin in db.ServiceInstances
                    where serin.id == Int32.Parse(Request.QueryString["id"])
                    select serin).Single();
            w.Stop();
            ILog log = LogManager.GetLogger("QueryLogger");
            log.Info(" Elapsed time: " + w.Elapsed + ", select the service instances to save");

            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"];
                }

                Stopwatch w1 = Stopwatch.StartNew();
                db.SubmitChanges();
                w1.Stop();
                ILog log1 = LogManager.GetLogger("QueryLogger");
                log1.Info(" Elapsed time: " + w1.Elapsed + ", edit service");
            }

            Response.Redirect("Services.aspx");
        }