Beispiel #1
0
        /// <summary>
        /// Loads saved connection out of a file
        /// </summary>
        public void LoadConnections(string filename, BackgroundWorker worker = null)
        {
            Dictionary <string, List <Friend> > parsedData;

            data    = new FriendGraph();
            friends = new Addresser();

            // loading raw data about friends to an object in an undesired format
            using (FileStream fs = File.Open(filename, FileMode.Open))
                using (StreamReader sr = new StreamReader(fs))
                    using (JsonTextReader jr = new JsonTextReader(sr)) {
                        JsonSerializer serializer = new JsonSerializer();
                        parsedData = serializer.Deserialize <Dictionary <string, List <Friend> > >(jr);
                    }

            // reporting progress
            if (worker != null)
            {
                worker.ReportProgress(15);
            }

            int i = 0;

            // find all distinct friends and create id->friend addresser
            // friends with no mutual friends with us will get lost (but what would they do inside the graph anyway)
            foreach (KeyValuePair <string, List <Friend> > pair in parsedData)
            {
                if (worker != null && worker.CancellationPending)
                {
                    throw new InterruptedException();
                }

                foreach (Friend f in pair.Value)
                {
                    if (!friends.ContainsKey(f.id))
                    {
                        friends.Add(f.id, f);
                        data.Add(f, new List <Friend>());
                    }
                }

                // reporting progress
                if (worker != null)
                {
                    worker.ReportProgress(15 + (++i * 70) / parsedData.Count);
                }
            }

            i = 0;
            // create the real graph out of the list of connections (connect our addresser)
            foreach (KeyValuePair <string, List <Friend> > pair in parsedData)
            {
                foreach (Friend f in pair.Value)
                {
                    data[friends[pair.Key]].Add(friends[f.id]);                     // we add inside friends[f.id] not f so we unify the pointers
                }                                                                   // (and actually toss away a lot of redundant data)

                // reporting progress
                if (worker != null)
                {
                    worker.ReportProgress(85 + (++i * 15) / parsedData.Count);
                }
            }
        }