/// <summary>
        /// Convert a Post (used for the database) in a WPost (used for the web).
        /// </summary>
        /// <param name="db">Database connector data context.</param>
        /// <param name="user">User that requires the conversion.</param>
        /// <param name="post">The Post to convert.</param>
        /// <returns>A WPost.</returns>
        public static WPost PostToWPost(ConnectorDataContext db, User user, Post post)
        {
            WUser author = Converter.UserToWUser(db, user, post.ChosenFeature.Registration.User, false);

            WService service = Converter.ServiceInstanceToWService(db, user, post.ChosenFeature.Registration.ServiceInstance, false);

            WPost result = new WPost()
            {
                Id = post.id,
                User = author,
                Service = service,
                Message = post.message,
                CreateAt = post.createAt
            };

            return result;
        }
        private void DownloadReputations(User currentUser, SocialTFSEntities db)
        {
            try
            {
                String str = FeaturesType.Reputation.ToString();
                DateTime tempoLimite = DateTime.UtcNow - _reputationSpan;
                List<ChosenFeature> chosenFeatures = db.ChosenFeature.Where(cf => cf.fk_user == currentUser.pk_id &&
                    cf.fk_feature == str).ToList();

                //cf.lastDownload < tempoLimite

                foreach (ChosenFeature item in chosenFeatures)
                {
                    /*
                    foreach (Reputation repu in item.Reputation)
                    {
                        db.Reputation.DeleteObject(repu);
                    }
                    db.SaveChanges();
                     * */

                    #region Get servizio

                    Registration registration = item.Registration;
                    IService service;
                    String currentService = registration.ServiceInstance.name;
                    if (currentService == "Coderwall" || currentService == "Ohloh")
                    {
                        service = ServiceFactory.getService(
                        registration.ServiceInstance.Service.name,
                        registration.nameOnService,
                        registration.User.password,
                        "standard-domain",
                        registration.ServiceInstance.host);
                    }
                    else
                    {
                        service = ServiceFactory.getServiceOauth(
                        registration.ServiceInstance.Service.name,
                        registration.ServiceInstance.host,
                        registration.ServiceInstance.consumerKey,
                        registration.ServiceInstance.consumerSecret,
                        registration.accessToken,
                        registration.accessSecret);
                    }

                    #endregion Get servizio

                    IReputation userReputations = (IReputation)service.Get(FeaturesType.Reputation, null);

                    #region New Reputation

                    // Controllo se la reputazione di un dato servizio e di un dato utente
                    // è presente nel DB
                    // Se esiste, la modifico, se non esiste la creo

                    Reputation testReputation = db.Reputation.FirstOrDefault<Reputation>(
                        r => r.ChosenFeature.fk_user == currentUser.pk_id);

                    //rep = db.Reputation.FirstOrDefault(e => e.pk_id == userReputations.reputationId);

                    if (testReputation == null)
                    {
                        switch (currentService)
                        {
                            case "Coderwall":
                                db.Reputation.AddObject( new Reputation()
                                {
                                    fk_chosenFeature = item.pk_id,
                                    stack_answer = null,
                                    stack_question = null,
                                    stack_bronze = null,
                                    stack_silver = null,
                                    stack_gold = null,
                                    stack_reputationValue = null,
                                    ohloh_kudorank = null,
                                    ohloh_bigCheese = null,
                                    ohloh_fosser = null,
                                    ohloh_orgMan = null,
                                    ohloh_stacker = null,
                                    ohloh_kudoscore = null,
                                    coderwall_endorsements = userReputations.coderwallEndorsements,
                                    linkedin_recommendations = null,
                                    linkedin_recommenders = null
                                });
                                break;

                            case "Ohloh":
                                db.Reputation.AddObject(new Reputation()
                            {

                                fk_chosenFeature = item.pk_id,
                                stack_answer = null,
                                stack_question = null,
                                stack_bronze = null,
                                stack_silver = null,
                                stack_gold = null,
                                stack_reputationValue = null,
                                ohloh_kudorank = userReputations.ohlohKudoRank,
                                ohloh_bigCheese = userReputations.ohlohBigcheese,
                                ohloh_fosser = userReputations.ohlohFosser,
                                ohloh_orgMan = userReputations.ohlohOrgman,
                                ohloh_stacker = userReputations.ohlohStacker,
                                ohloh_kudoscore = userReputations.ohlohKudoScore,
                                coderwall_endorsements = null,
                                linkedin_recommendations = null,
                                linkedin_recommenders = null
                            });
                            break;

                            case "StackOverflow":
                                Reputation r = new Reputation()
                                {
                                    fk_chosenFeature = item.pk_id,
                                    stack_answer = userReputations.stackAnswer,
                                    stack_question = userReputations.stackQuestion,
                                    stack_bronze = userReputations.stackBronze,
                                    stack_silver = userReputations.stackSilver,
                                    stack_gold = userReputations.stackGold,
                                    stack_reputationValue = userReputations.stackReputationValue,
                                    ohloh_kudorank = null,
                                    ohloh_bigCheese = null,
                                    ohloh_fosser = null,
                                    ohloh_orgMan = null,
                                    ohloh_stacker = null,
                                    ohloh_kudoscore = null,
                                    coderwall_endorsements = null,
                                    linkedin_recommendations = null,
                                    linkedin_recommenders = null
                                };
                                db.Reputation.AddObject(r);
                                break;
                        }

                        /*
                        db.Reputation.AddObject(new Reputation()
                        {
                            pk_id = userReputations.reputationId,
                            fk_chosenFeature = item.pk_id,
                            stack_answer = userReputations.stackAnswer,
                            stack_question = userReputations.stackQuestion,
                            stack_bronze = userReputations.stackBronze,
                            stack_silver = userReputations.stackSilver,
                            stack_gold = userReputations.stackGold,
                            stack_reputationValue = userReputations.stackReputationValue,
                            ohloh_kudorank = userReputations.ohlohKudoRank,
                            ohloh_bigCheese = userReputations.ohlohBigcheese,
                            ohloh_fosser = userReputations.ohlohFosser,
                            ohloh_orgMan = userReputations.ohlohOrgman,
                            ohloh_stacker = userReputations.ohlohStacker,
                            ohloh_kudoscore = userReputations.ohlohKudoScore,
                            coderwall_endorsements = userReputations.coderwallEndorsements,
                            linkedin_recommendations = userReputations.linkedinRecommendations,
                            linkedin_recommenders = userReputations.linkedinRecommenders
                        });
                         * */

                        db.SaveChanges();

                    }

                    #endregion New Reputation

                    else

                    #region edit reputation

                    {
                        //aggiornamento tupla
                        //var testReputation = db.Reputation.FirstOrDefault(e => e.pk_id == userReputations.reputationId);
                        if (registration.ServiceInstance.name == "Coderwall")
                        {
                            testReputation.coderwall_endorsements = userReputations.coderwallEndorsements;
                        }
                        else if (registration.ServiceInstance.name == "Ohloh")
                        {
                            testReputation.ohloh_kudorank = userReputations.ohlohKudoRank;
                            testReputation.ohloh_kudoscore = userReputations.ohlohKudoScore;
                            testReputation.ohloh_bigCheese = userReputations.ohlohBigcheese;
                            testReputation.ohloh_fosser = userReputations.ohlohFosser;
                            testReputation.ohloh_orgMan = userReputations.ohlohOrgman;
                            testReputation.ohloh_stacker = userReputations.ohlohStacker;
                        }
                        else if (registration.ServiceInstance.name == "StackOverflow")
                        {
                            testReputation.stack_answer = userReputations.stackAnswer;
                            testReputation.stack_question = userReputations.stackQuestion;
                            testReputation.stack_reputationValue = userReputations.stackReputationValue;
                            testReputation.stack_bronze = userReputations.stackBronze;
                            testReputation.stack_silver = userReputations.stackSilver;
                            testReputation.stack_gold = userReputations.stackGold;
                        }
                        else
                        {
                            throw new NotImplementedException();
                        }

                        db.SaveChanges();

                    }

                    #endregion edit reputation

                    item.lastDownload = DateTime.UtcNow;
                }

            }
            catch (Exception e)
            {
                return;
            }
        }
        private void DownloadPositions(User currentUser, SocialTFSEntities db)
        {
            String str = FeaturesType.Positions.ToString();
            DateTime tempoLimite = DateTime.UtcNow - _positionSpan;
            List<ChosenFeature> chosenFeatures = db.ChosenFeature.Where(cf => cf.fk_user == currentUser.pk_id &&
                cf.fk_feature == str &&
                cf.lastDownload < tempoLimite).ToList();

            foreach (ChosenFeature item in chosenFeatures)
            {
                //delete the user's positions in the database
                //db.Position.DeleteAllOnSubmit(item.Positions);
                foreach (Positions p in item.Positions)
                {
                    db.Positions.DeleteObject(p);
                }

                db.SaveChanges();

                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);

                IPos[] userPositions = (IPos[])service.Get(FeaturesType.Positions, null);
                //String[] poss = (String[])service.Get(FeaturesType.Positions, null);
                //poss = poss;

                try
                {
                    foreach (IPos userPosition in userPositions)
                    {
                        db.Positions.AddObject(new Positions()
                        {
                            fk_chosenFeature = item.pk_id,
                            pk_id = userPosition.posId,
                            title = userPosition.title,
                            name = userPosition.name,
                            industry = userPosition.industry
                        });
                    }
                }
                catch (Exception)
                {

                    return;
                }

                item.lastDownload = DateTime.UtcNow;

                db.SaveChanges();
            }
        }
        /// <summary>
        /// Convert a ServiceInstance (used for the database) in a WService (used for the web).
        /// </summary>
        /// <param name="db">Database connector data context.</param>
        /// <param name="user">User that requires the conversion.</param>
        /// <param name="serviceInstance">The ServiceInstance to convert.</param>
        /// <param name="calculateFeature">True if you need to have all the information about the User, false otherwise.</param>
        /// <returns>A WService.</returns>
        public static WService ServiceInstanceToWService(SocialTFSEntities db, User user, ServiceInstance serviceInstance, bool calculateFeature)
        {
            WService result = null;

            if (calculateFeature)
            {
                bool isRegistered = false;
                IEnumerable<ServiceInstance> myServices = db.Registration.Where(r => r.pk_fk_user == user.pk_id).Select(r => r.ServiceInstance);
                if (myServices.Contains(serviceInstance))
                    isRegistered = true;

                List<FeaturesType> privateFeatures = ServiceFactory.getService(serviceInstance.Service.name).GetPrivateFeatures();
                bool requireOAuth = false;
                int oauthVersion = 0;
                if (privateFeatures.Contains(FeaturesType.OAuth1))
                {
                    requireOAuth = true;
                    oauthVersion = 1;
                }
                else if (privateFeatures.Contains(FeaturesType.OAuth2))
                {
                    requireOAuth = true;
                    oauthVersion = 2;
                }

                bool requireTFSAuthentication = false;
                bool requireTFSDomain = false;
                if (privateFeatures.Contains(FeaturesType.TFSAuthenticationWithDomain))
                {
                    requireTFSAuthentication = true;
                    requireTFSDomain = true;
                }
                else if (privateFeatures.Contains(FeaturesType.TFSAuthenticationWithoutDomain))
                {
                    requireTFSAuthentication = true;
                    requireTFSDomain = false;
                }

                result = new WService()
                {
                    Id = serviceInstance.pk_id,
                    Name = serviceInstance.name,
                    Host = serviceInstance.host,
                    BaseService = serviceInstance.Service.name,
                    Image = serviceInstance.Service.image,
                    Registered = isRegistered,
                    RequireOAuth = requireOAuth,
                    OAuthVersion = oauthVersion,
                    RequireTFSAuthentication = requireTFSAuthentication,
                    RequireTFSDomain = requireTFSDomain
                };
            }
            else
            {
                result = new WService()
                {
                    Id = serviceInstance.pk_id,
                    Name = serviceInstance.name,
                    BaseService = serviceInstance.Service.name,
                    Image = serviceInstance.Service.image
                };
            }

            return result;
        }
        private void UpdateDynamicFriend(User user)
        {
            SocialTFSEntities db = new SocialTFSEntities();

            String str = FeaturesType.IterationNetwork.ToString();
            foreach (ChosenFeature chosenFeature in db.ChosenFeature.Where(cf => cf.fk_user == user.pk_id && cf.fk_feature == str ))
            {
                ChosenFeature temp = db.ChosenFeature.Where(cf => cf.pk_id == chosenFeature.pk_id).Single();
                if (temp.lastDownload > DateTime.UtcNow - _dynamicSpan)
                    continue;
                else
                    temp.lastDownload = DateTime.UtcNow;

                try { db.SaveChanges(); }
                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.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
                var delFriends = db.DynamicFriend.Where(df => df.fk_chosenFeature == temp.pk_id);
                foreach (DynamicFriend s in delFriends)
                {
                    db.DynamicFriend.DeleteObject(s);
                }
                //db.DynamicFriend.DeleteAllOnSubmit(db.DynamicFrien.Where(df => df.chosenFeature == temp.pk_id));
                db.SaveChanges();

                foreach (String dynamicFriend in dynamicFriends)
                {
                    IEnumerable<int> friendsInDb = db.Registration.Where(r => r.nameOnService == dynamicFriend && r.pk_fk_serviceInstance == temp.fk_serviceInstance).Select(r => r.pk_fk_user);
                    foreach (int friendInDb in friendsInDb)
                    {
                        db.DynamicFriend.AddObject(new DynamicFriend()
                        {
                            fk_chosenFeature = temp.pk_id,
                            fk_user = friendInDb
                        });
                    }
                }
                try
                {
                    db.SaveChanges();
                }
                catch { }
            }
        }
        private void UpdateSuggestion(User user)
        {
            SocialTFSEntities db = new SocialTFSEntities();

            String str1 = FeaturesType.Followings.ToString();
            String str2 = FeaturesType.Followers.ToString();
            String str3 = FeaturesType.TFSCollection.ToString();
            String str4 = FeaturesType.TFSTeamProject.ToString();
            IEnumerable<ChosenFeature> chosenFeatures = db.ChosenFeature.Where(
                cf => (cf.fk_feature.Equals(str1) ||
                    cf.fk_feature.Equals(str2) ||
                    cf.fk_feature.Equals(str3) ||
                    cf.fk_feature.Equals(str4)) && cf.fk_user == user.pk_id);

            foreach (ChosenFeature chosenFeature in chosenFeatures)
            {
                ChosenFeature temp = db.ChosenFeature.Where(cf => cf.pk_id == chosenFeature.pk_id).Single();
                if (temp.lastDownload > DateTime.UtcNow - _suggestionSpan)
                    continue;
                else
                    temp.lastDownload = DateTime.UtcNow;

                try { db.SaveChanges(); }
                catch { continue; }

                IService service = null;

                if (chosenFeature.fk_feature.Equals(FeaturesType.Followings.ToString()) ||
                    chosenFeature.fk_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.fk_feature.Equals(FeaturesType.TFSCollection.ToString()) ||
                    chosenFeature.fk_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.accessToken,
                            chosenFeature.Registration.accessSecret,
                            chosenFeature.Registration.ServiceInstance.host);
                    }
                }

                string[] friends = null;

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

                if (friends != null)
                {
                    //Delete suggestions for this chosen feature in the database
                    var sug = db.Suggestion.Where(s => s.fk_chosenFeature == chosenFeature.pk_id);
                    foreach (Suggestion s in sug)
                    {
                        db.Suggestion.DeleteObject(s);
                    }

                    //db.Suggestion.DeleteAllOnSubmit(db.Suggestion.Where(s => s.fk_chosenFeature == chosenFeature.pk_id));
                    db.SaveChanges();

                    foreach (string friend in friends)
                    {
                        IEnumerable<User> friendInSocialTfs = db.Registration.Where(r => r.idOnService == friend &&
                            r.pk_fk_serviceInstance == chosenFeature.fk_serviceInstance).Select(r => r.User);

                        if (friendInSocialTfs.Count() == 1)
                        {
                            User suggestedFriend = friendInSocialTfs.First();

                            if (friend != chosenFeature.Registration.idOnService)
                            {
                                db.Suggestion.AddObject(new Suggestion()
                                {
                                    fk_user = suggestedFriend.pk_id,
                                    fk_chosenFeature = chosenFeature.pk_id
                                });
                            }
                        }
                    }
                    try
                    {
                        db.SaveChanges();
                    }
                    catch { }
                }
            }
        }
        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");
            }
        }
        private WPost[] GetTimeline(SocialTFSEntities db, User user, List<int> authors, long since, long to)
        {
            List<WPost> result = new List<WPost>();

            try
            {
                if (since == 0 && to != 0)
                {
                    //checked if we have enought older posts
                    DateTime lastPostDate = db.Post.Where(tp => tp.pk_id == to).Single().createAt;
                    int olderPostCounter = db.Post.Where(p => authors.Contains(p.ChosenFeature.Registration.pk_fk_user) &&
                        p.createAt < lastPostDate).Count();

                    if (olderPostCounter < postLimit)
                    {
                        foreach (int item in authors)
                            DownloadOlderPost(item);
                    }
                }
                else
                {
                    new Thread(delegate()
                    {
                        foreach (int item in authors)
                            DownloadNewerPost(item);
                    }).Start();
                }
            }
            catch (InvalidOperationException)
            {
                return result.ToArray();
            }

            IEnumerable<Post> posts = new List<Post>();

            if (since == 0 && to == 0)
                posts = db.Post.Where(p => authors.Contains(p.ChosenFeature.Registration.pk_fk_user)).OrderByDescending(p => p.createAt).Take(postLimit);
            else if (since != 0)
                posts = db.Post.Where(p => authors.Contains(p.ChosenFeature.Registration.pk_fk_user) && p.createAt > db.Post.Where(sp => sp.pk_id == since).FirstOrDefault().createAt).OrderByDescending(p => p.createAt).Take(postLimit);
            else
                posts = db.Post.Where(p => authors.Contains(p.ChosenFeature.Registration.pk_fk_user) && p.createAt < db.Post.Where(tp => tp.pk_id == to).FirstOrDefault().createAt).OrderByDescending(p => p.createAt).Take(postLimit);

            IEnumerable<int> followings = db.StaticFriend.Where(f => f.fk_user == user.pk_id).Select(f => f.fk_friend);

            foreach (Post post in posts)
            {
                result.Add(Converter.PostToWPost(db, user, post));
            }
            return result.ToArray();
        }
        private string FindGithubRepository(User user, string interactiveObject)
        {
            ConnectorDataContext db = new ConnectorDataContext();
            Boolean flag = false;
            IService service = null;

            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 user and his feature 'interactive 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 chosen feature's id");

                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)
            {
                return (String)service.Get(FeaturesType.Repository, new Object[1] { interactiveObject });

            }
            else
            {
                return string.Empty;
            }
        }
        private WPost[] GetTimeline(ConnectorDataContext db, User user, List<int> authors, long since, long to)
        {
            List<WPost> result = new List<WPost>();

            try
            {
                if (since == 0 && to != 0)
                {
                    //checked if we have enought older posts
                    Stopwatch w = Stopwatch.StartNew();
                    DateTime lastPostDate = db.Posts.Where(tp => tp.id == to).Single().createAt;
                    w.Stop();
                    ILog log = LogManager.GetLogger("QueryLogger");
                    log.Info(" Elapsed time: " + w.Elapsed + ", post id: " + to + ", select last post");
                    Stopwatch w1 = Stopwatch.StartNew();
                    int olderPostCounter = db.Posts.Where(p => authors.Contains(p.ChosenFeature.Registration.user) &&
                        p.createAt < lastPostDate).Count();
                    w1.Stop();
                    ILog log1 = LogManager.GetLogger("QueryLogger");
                    log1.Info(" Elapsed time: " + w1.Elapsed + ", number of posts before a certain post written by an user using a certain service");

                    if (olderPostCounter < postLimit)
                    {
                        foreach (int item in authors)
                            DownloadOlderPost(item);
                    }
                }
                else
                {
                    new Thread(delegate()
                    {
                        foreach (int item in authors)
                            DownloadNewerPost(item);
                    }).Start();
                }
            }
            catch (InvalidOperationException)
            {
                return result.ToArray();
            }

            IEnumerable<Post> posts = new List<Post>();

            if (since == 0 && to == 0)
            {
                Stopwatch w2 = Stopwatch.StartNew();
                posts = db.Posts.Where(p => authors.Contains(p.ChosenFeature.Registration.user)).OrderByDescending(p => p.createAt).Take(postLimit);
                w2.Stop();
                ILog log2 = LogManager.GetLogger("QueryLogger");
                log2.Info(" Elapsed time: " + w2.Elapsed + ", select top posts of an user");
            }
            else if (since != 0)
            {
                Stopwatch w3 = Stopwatch.StartNew();
                posts = db.Posts.Where(p => authors.Contains(p.ChosenFeature.Registration.user) && p.createAt > db.Posts.Where(sp => sp.id == since).Single().createAt).OrderByDescending(p => p.createAt).Take(postLimit);
                w3.Stop();
                ILog log3 = LogManager.GetLogger("QueryLogger");
                log3.Info(" Elapsed time: " + w3.Elapsed + ", post id: " + since + ", select top posts of an user chronologically written after a certain post");
            }
            else
            {
                Stopwatch w4 = Stopwatch.StartNew();
                posts = db.Posts.Where(p => authors.Contains(p.ChosenFeature.Registration.user) && p.createAt < db.Posts.Where(tp => tp.id == to).Single().createAt).OrderByDescending(p => p.createAt).Take(postLimit);
                w4.Stop();
                ILog log4 = LogManager.GetLogger("QueryLogger");
                log4.Info(" Elapsed time: " + w4.Elapsed + ", post id: " + to + ", select top posts of an user chronologically written before a certain post");
            }
            Stopwatch w5 = Stopwatch.StartNew();
            IEnumerable<int> followings = db.StaticFriends.Where(f => f.user == user.id).Select(f => f.friend);
            w5.Stop();
            ILog log5 = LogManager.GetLogger("QueryLogger");
            log5.Info(" Elapsed time: " + w5.Elapsed + ", user id: " + user.id + ", select all static friends that follow that user"); ;

            foreach (Post post in posts)
            {
                result.Add(Converter.PostToWPost(db, user, post));
            }
            return result.ToArray();
        }
        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");
            }
        }
 /// <summary>
 /// Metodo deprecato per l'aggiunta di un nuovo oggetto all'elemento EntitySet User. Utilizzare il metodo .Add della proprietà associata ObjectSet&lt;T&gt;.
 /// </summary>
 public void AddToUser(User user)
 {
     base.AddObject("User", user);
 }
 /// <summary>
 /// Crea un nuovo oggetto User.
 /// </summary>
 /// <param name="pk_id">Valore iniziale della proprietà pk_id.</param>
 /// <param name="username">Valore iniziale della proprietà username.</param>
 /// <param name="email">Valore iniziale della proprietà email.</param>
 /// <param name="password">Valore iniziale della proprietà password.</param>
 /// <param name="active">Valore iniziale della proprietà active.</param>
 /// <param name="isAdmin">Valore iniziale della proprietà isAdmin.</param>
 public static User CreateUser(global::System.Int32 pk_id, global::System.String username, global::System.String email, global::System.String password, global::System.Boolean active, global::System.Boolean isAdmin)
 {
     User user = new User();
     user.pk_id = pk_id;
     user.username = username;
     user.email = email;
     user.password = password;
     user.active = active;
     user.isAdmin = isAdmin;
     return user;
 }
        private void DownloadSkills(User currentUser, SocialTFSEntities db)
        {
            String str = FeaturesType.Skills.ToString();
            DateTime tempoLimite = DateTime.UtcNow - _skillSpan;

            List<ChosenFeature> chosenFeatures = (from ChosenFeature cf in db.ChosenFeature
                                                  where cf.fk_user == currentUser.pk_id &&
                                                        cf.fk_feature == str && cf.lastDownload < tempoLimite
                                                  select cf).ToList<ChosenFeature>();

            foreach (ChosenFeature item in chosenFeatures)
            {
                foreach (Skills s in item.Skills)
                {
                    db.Skills.DeleteObject(s);
                }

                db.SaveChanges();

                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)
                {
                    db.Skills.AddObject(
                        new Skills()
                        {
                            pk_fk_chosenFeature = item.pk_id,
                            pk_skill_name = userSkill
                        }
                    );
                }

                item.lastDownload = DateTime.UtcNow;

                db.SaveChanges();
            }
        }
        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;
            }
        }
        private string FindGithubRepository(User user, string interactiveObject)
        {
            SocialTFSEntities db = new SocialTFSEntities();
            Boolean flag = false;
            IService service = null;

            foreach (ChosenFeature chosenFeature in db.ChosenFeature.Where(cf => cf.fk_user == user.pk_id && cf.fk_feature == FeaturesType.InteractiveNetwork.ToString()))
            {
                ChosenFeature temp = db.ChosenFeature.Where(cf => cf.pk_id == chosenFeature.pk_id).Single();

                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)
            {
                return (String)service.Get(FeaturesType.Repository, new Object[1] { interactiveObject });

            }
            else
            {
                return string.Empty;
            }
        }
        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 bool RegisterUserOnAService(SocialTFSEntities db, User user, ServiceInstance serviceInstance, IUser iUser, String accessToken, String accessSecret)
        {
            try
            {
                db.Registration.AddObject(new Registration
                {
                    pk_fk_user = user.pk_id,
                    ServiceInstance = serviceInstance,
                    nameOnService = iUser.UserName,
                    idOnService = iUser.Id.ToString(),
                    accessToken = accessToken,
                    accessSecret = accessSecret
                });

                db.SaveChanges();
                return true;
            }
            catch (ChangeConflictException)
            {
                return false;
            }
        }
        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);
                }
            }
        }
        private void UpdateInteractiveFriend(User user)
        {
            SocialTFSEntities db = new SocialTFSEntities();
            String str = FeaturesType.InteractiveNetwork.ToString();

            foreach (ChosenFeature chosenFeature in db.ChosenFeature.Where(cf => cf.fk_user == user.pk_id && cf.fk_feature == str))
            {
                ChosenFeature temp = db.ChosenFeature.Where(cf => cf.pk_id == chosenFeature.pk_id).Single();
                if (temp.lastDownload > DateTime.UtcNow - _interactiveSpan)
                    continue;
                else
                    temp.lastDownload = DateTime.UtcNow;

                try { db.SaveChanges(); }
                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.accessToken,
                       temp.Registration.accessSecret,
                       temp.Registration.ServiceInstance.host);
                }
                //this line must be before the deleting
                SCollection[] collections = (SCollection[])service.Get(FeaturesType.InteractiveNetwork);
                try
                {
                    //delete old friendship for the current chosen feature
                    System.Diagnostics.Debug.WriteLine(" id temp " + temp.pk_id);
                    System.Diagnostics.Debug.WriteLine(" db " + (db.InteractiveFriend == null));
                    System.Diagnostics.Debug.WriteLine(" collections length " + collections.Length);
                    /*
                    foreach (SCollection collection in collections)
                    {
                        System.Diagnostics.Debug.WriteLine(" collection " + collection.Uri);

                        foreach (SFile file in collection.Files)
                        {
                            System.Diagnostics.Debug.WriteLine(" file " + file.Name);

                            foreach (String utente in file.InvolvedUsers)
                            {
                                System.Diagnostics.Debug.WriteLine(" utente " + utente);
                            }
                        }

                    }
                    */
                    /*
                    SocialTFSEntities db2 = new SocialTFSEntities();

                    IQueryable<InteractiveFriend> pr = db2.InteractiveFriends.Where(df => df.chosenFeature == temp.pk_id);

                    try
                    {
                        foreach (InteractiveFriend cf in pr)
                        {
                            System.Diagnostics.Debug.WriteLine(" id selezionato " + cf.pk_id);
                        }
                    }
                    catch
                    {
                        System.Diagnostics.Debug.WriteLine("seconda prova di integrità nulla");

                    }

                    IQueryable<InteractiveFriend> pr3 = db2.InteractiveFriends.Where(u => u.user == 3);
                    IQueryable<ChosenFeature> pr2 = db2.ChosenFeatures.Where(cl => cl.serviceInstance == 2);
                    //prova di integrità CHE FUNZIONA

                    System.Diagnostics.Debug.WriteLine(" righe selezionate chosen feature " + pr2.Count());

                    try
                    {
                        foreach (ChosenFeature cf in pr2)
                        {
                            System.Diagnostics.Debug.WriteLine(" id selezionato " + cf.pk_id);
                        }
                    }
                    catch
                    {
                        System.Diagnostics.Debug.WriteLine(" prova di integrità nulla");
                    }
                    */
                    /*

                    IQueryable<InteractiveFriend> pr3 = db2.InteractiveFriends.Where(u => u.user == 3);

                    //prova di integrità CHE FUNZIONA

                    System.Diagnostics.Debug.WriteLine(" righe selezionate chosen feature " + pr2.Count());

                    try
                    {
                        foreach (ChosenFeature cf in pr2)
                        {
                            System.Diagnostics.Debug.WriteLine(" id selezionato " + cf.pk_id);
                        }
                    }
                    catch
                    {
                        System.Diagnostics.Debug.WriteLine(" prova di integrità nulla");
                    }

                    //prova di integrità 2

                    try
                    {
                        foreach (InteractiveFriend  cf in pr3)
                        {
                            System.Diagnostics.Debug.WriteLine(" id selezionato " + cf.pk_id);
                        }
                    }
                    catch
                    {
                        System.Diagnostics.Debug.WriteLine("seconda prova di integrità nulla");

                    }

                    System.Diagnostics.Debug.WriteLine(" righe selezionate " + pr.Count());

                    try
                    {
                        //1° tentativo
                       foreach(InteractiveFriend fr in pr)
                       {
                            db2.InteractiveFriends.DeleteOnSubmit(fr);
                        }
                    }
                    catch {

                        try
                        {
                            //2° tentativo
                            System.Diagnostics.Debug.WriteLine(" Enum fallito ");
                            List<InteractiveFriend> listfr = pr.ToList<InteractiveFriend>();
                            foreach (InteractiveFriend fr in pr)
                            {
                                db2.InteractiveFriends.DeleteOnSubmit(fr);
                            }
                        }
                        catch
                        {
                            System.Diagnostics.Debug.WriteLine(" List fallito ");

                            try
                            {
                                //3° tentativo
                                var removeItems = (from c in db2.InteractiveFriends where c.chosenFeature == temp.pk_id select c);
                                foreach(var item in removeItems.AsEnumerable())
                                {
                                    db.InteractiveFriend.DeleteOnSubmit(item);
                                }
                            }
                            catch
                            {
                                System.Diagnostics.Debug.WriteLine("Query statica fallita");
                                try
                                {
                                    InteractiveFriend[] fr = pr.ToArray<InteractiveFriend>();
                                    foreach (InteractiveFriend fr1 in pr)
                                    {
                                        db2.InteractiveFriends.DeleteOnSubmit(fr1);
                                    }
                                }
                                catch
                                {
                                    System.Diagnostics.Debug.WriteLine(" Array Fallito");
                                }
                            }

                        }
                    }

                    //ultimo tentativo
                    db2.InteractiveFriends.DeleteAllOnSubmit(pr.AsEnumerable<InteractiveFriend>());
                   //IEnumerable<InteractiveFriend> pr = (from c in db.InteractiveFriend.AsEnumerable()
                    // where c.chosenFeature == temp.pk_id select c).ToList();

                   */

                    //vecchio metodo
                    var inFriends = db.InteractiveFriend.Where(df => df.fk_chosenFeature == temp.pk_id);

                    foreach (InteractiveFriend i in inFriends)
                    {
                        db.InteractiveFriend.DeleteObject(i);
                    }
                    //db.InteractiveFriend.DeleteAllOnSubmit(db.InteractiveFriend.Where(df => df.fk_chosenFeature == temp.pk_id));
                    db.SaveChanges();

                    foreach (SCollection collection in collections)
                    {
                        foreach (SWorkItem workitem in collection.WorkItems)
                        {
                            IEnumerable<int> friendsInDb = db.Registration.Where(r => workitem.InvolvedUsers.Contains(r.nameOnService) || workitem.InvolvedUsers.Contains(r.accessSecret + "\\" + r.nameOnService)).Select(r => r.pk_fk_user);
                            foreach (int friendInDb in friendsInDb)
                                db.InteractiveFriend.AddObject(new InteractiveFriend()
                                {
                                    fk_user = friendInDb,
                                    fk_chosenFeature = temp.pk_id,
                                    collection = collection.Uri,
                                    interactiveObject = workitem.Name,
                                    objectType = "WorkItem"
                                });
                        }
                        foreach (SFile file in collection.Files)
                        {
                            IEnumerable<int> friendsInDb = db.Registration.Where(r => file.InvolvedUsers.Contains(r.nameOnService) || file.InvolvedUsers.Contains(r.accessSecret + "\\" + r.nameOnService)).Select(r => r.pk_fk_user);
                            foreach (int friendInDb in friendsInDb)
                                db.InteractiveFriend.AddObject(new InteractiveFriend()
                                {
                                    fk_user = friendInDb,
                                    fk_chosenFeature = temp.pk_id,
                                    collection = collection.Uri,
                                    interactiveObject = file.Name,
                                    objectType = "File"
                                });
                        }
                    }

                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.StackTrace);
                }
            }
        }
        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) + "]");
            }
        }
        /// <summary>
        /// Convert an User (used for the database) in a WUser (used for the web).
        /// </summary>
        /// <param name="db">Database connector data context.</param>
        /// <param name="user">User that requires the conversion.</param>
        /// <param name="userToConvert">The User to convert.</param>
        /// <param name="calculateInfos">True if you need to have all the information about the User, false otherwise.</param>
        /// <returns>A WUser.</returns>
        public static WUser UserToWUser(ConnectorDataContext db, User user, User userToConvert, bool calculateInfos)
        {
            WUser result = null;

            if (calculateInfos)
            {
                Stopwatch w = Stopwatch.StartNew();
                int stat = db.Posts.Where(p => p.ChosenFeature.user == userToConvert.id).Count();
                w.Stop();
                ILog log = LogManager.GetLogger("QueryLogger");
                log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + userToConvert.id + ", count the number of posts of an user for a certain chosen feature");
                Stopwatch w1 = Stopwatch.StartNew();
                int followings = db.StaticFriends.Where(sf => sf.User == userToConvert).Count();
                w1.Stop();
                ILog log1 = LogManager.GetLogger("QueryLogger");
                log1.Info(" Elapsed time: " + w1.Elapsed + ", count the number of static friends of an user");
                Stopwatch w2 = Stopwatch.StartNew();
                int followers = db.StaticFriends.Where(sf => sf.Friend == userToConvert).Count();
                w2.Stop();
                ILog log2 = LogManager.GetLogger("QueryLogger");
                log2.Info(" Elapsed time: " + w2.Elapsed + ", count the number of users that are static friends of an user");
                Stopwatch w3 = Stopwatch.StartNew();
                int followed = db.StaticFriends.Where(sf => sf.User == user && sf.Friend == userToConvert).Count();
                w3.Stop();
                ILog log3 = LogManager.GetLogger("QueryLogger");
                log3.Info(" Elapsed time: " + w3.Elapsed + ", count the number of users that follow and are followed by an user");
                result = new WUser()
                {
                    Id = userToConvert.id,
                    Username = userToConvert.username,
                    Email = userToConvert.email,
                    Avatar = userToConvert.avatar,
                    Statuses = stat,
                    Followings = followings,
                    Followers = followers,
                    Followed = followed == 1
                };
            }
            else
            {
                result = new WUser()
                {
                    Id = userToConvert.id,
                    Username = userToConvert.username,
                    Email = userToConvert.email,
                    Avatar = userToConvert.avatar,
                    Statuses = -1,
                    Followings = -1,
                    Followers = -1,
                    Followed = false
                };
            }

            return result;
        }
        private void DownloadEducations(User currentUser, SocialTFSEntities db)
        {
            String str = FeaturesType.Educations.ToString();
            DateTime tempoLimite = DateTime.UtcNow - _educationSpan;
            List<ChosenFeature> chosenFeatures = db.ChosenFeature.Where(cf => cf.fk_user == currentUser.pk_id &&
                cf.fk_feature == str &&
                cf.lastDownload < tempoLimite).ToList();

            foreach (ChosenFeature item in chosenFeatures)
            {
                foreach (Educations edu in item.Educations)
                {
                    db.Educations.DeleteObject(edu);
                }

                db.SaveChanges();

                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);

                IEdu[] userEducations = (IEdu[])service.Get(FeaturesType.Educations, null);

                //insert educations in the database
                try
                {
                    foreach (IEdu userEducation in userEducations)
                    {
                        if (db.Educations.FirstOrDefault(e => e.pk_id == userEducation.eduId) == null)
                        {
                            db.Educations.AddObject(new Educations()
                            {
                                pk_id = userEducation.eduId,
                                fk_chosenFeature = item.pk_id,
                                fieldOfStudy = userEducation.fieldOfStudy,
                                schoolName = userEducation.schoolName
                            });
                        }
                    }
                }
                catch (Exception)
                {

                    return;
                }

                item.lastDownload = DateTime.UtcNow;

                db.SaveChanges();
            }
        }
        /// <summary>
        /// Convert a ServiceInstance (used for the database) in a WService (used for the web).
        /// </summary>
        /// <param name="db">Database connector data context.</param>
        /// <param name="user">User that requires the conversion.</param>
        /// <param name="serviceInstance">The ServiceInstance to convert.</param>
        /// <param name="calculateFeature">True if you need to have all the information about the User, false otherwise.</param>
        /// <returns>A WService.</returns>
        public static WService ServiceInstanceToWService(ConnectorDataContext db, User user, ServiceInstance serviceInstance, bool calculateFeature)
        {
            WService result = null;

            if (calculateFeature)
            {
                bool isRegistered = false;
                Stopwatch w = Stopwatch.StartNew();
                IEnumerable<ServiceInstance> myServices = db.Registrations.Where(r => r.user == user.id).Select(r => r.ServiceInstance);
                w.Stop();
                ILog log = LogManager.GetLogger("QueryLogger");
                log.Info(" Elapsed time: " + w.Elapsed + ", user id: " + user.id + ", select all service instances of an user");
                if (myServices.Contains(serviceInstance))
                    isRegistered = true;

                List<FeaturesType> privateFeatures = ServiceFactory.getService(serviceInstance.Service.name).GetPrivateFeatures();
                bool requireOAuth = false;
                int oauthVersion = 0;
                if (privateFeatures.Contains(FeaturesType.OAuth1))
                {
                    requireOAuth = true;
                    oauthVersion = 1;
                }
                else if (privateFeatures.Contains(FeaturesType.OAuth2))
                {
                    requireOAuth = true;
                    oauthVersion = 2;
                }

                bool requireTFSAuthentication = false;
                bool requireTFSDomain = false;
                if (privateFeatures.Contains(FeaturesType.TFSAuthenticationWithDomain))
                {
                    requireTFSAuthentication = true;
                    requireTFSDomain = true;
                }
                else if (privateFeatures.Contains(FeaturesType.TFSAuthenticationWithoutDomain))
                {
                    requireTFSAuthentication = true;
                    requireTFSDomain = false;
                }

                result = new WService()
                {
                    Id = serviceInstance.id,
                    Name = serviceInstance.name,
                    Host = serviceInstance.host,
                    BaseService = serviceInstance.Service.name,
                    Image = serviceInstance.Service.image,
                    Registered = isRegistered,
                    RequireOAuth = requireOAuth,
                    OAuthVersion = oauthVersion,
                    RequireTFSAuthentication = requireTFSAuthentication,
                    RequireTFSDomain = requireTFSDomain
                };
            }
            else
            {
                result = new WService()
                {
                    Id = serviceInstance.id,
                    Name = serviceInstance.name,
                    BaseService = serviceInstance.Service.name,
                    Image = serviceInstance.Service.image
                };
            }

            return result;
        }
        /// <summary>
        /// Convert an User (used for the database) in a WUser (used for the web).
        /// </summary>
        /// <param name="db">Database connector data context.</param>
        /// <param name="user">User that requires the conversion.</param>
        /// <param name="userToConvert">The User to convert.</param>
        /// <param name="calculateInfos">True if you need to have all the information about the User, false otherwise.</param>
        /// <returns>A WUser.</returns>
        public static WUser UserToWUser(SocialTFSEntities db, User user, User userToConvert, bool calculateInfos)
        {
            WUser result = new WUser();

            //result.Statuses = db.Post.Where( p => p.ChosenFeature.fk_user == userToConvert.pk_id ).Count();
            //result.Followings = db.StaticFriend.Where(sf => sf.fk_user == userToConvert.pk_id ).Count();
            //result.Followers = db.StaticFriend.Where(sf => sf.fk_friend == userToConvert.pk_id).Count();
            //result.Followed = db.StaticFriend.Where(sf => sf.fk_user == user.pk_id && sf.fk_friend == userToConvert.pk_id ).Count() == 1;

            if (calculateInfos)
            {
                result = new WUser()
                {
                    Id = userToConvert.pk_id,
                    Username = userToConvert.username,
                    Email = userToConvert.email,
                    Avatar = userToConvert.avatar,
                    Statuses = db.Post.Where( p => p.ChosenFeature.fk_user == userToConvert.pk_id ).Count(),
                    Followings = db.StaticFriend.Where(sf => sf.User.pk_id == userToConvert.pk_id).Count(),
                    Followers = db.StaticFriend.Where(sf => sf.Friend.pk_id == userToConvert.pk_id).Count(),
                    Followed = db.StaticFriend.Where(sf => sf.User.pk_id == user.pk_id && sf.Friend.pk_id == userToConvert.pk_id).Count() == 1
                };
            }
            else
            {
                result = new WUser()
                {
                    Id = userToConvert.pk_id,
                    Username = userToConvert.username,
                    Email = userToConvert.email,
                    Avatar = userToConvert.avatar,
                    Statuses = -1,
                    Followings = -1,
                    Followers = -1,
                    Followed = false
                };
            }

            return result;
        }