Пример #1
0
 //
 // GET: /Project/Delete/1
 public ActionResult Delete(Project p)
 {
     if (p == null) {
         return HttpNotFound();
     }
     return View(p);
 }
Пример #2
0
        public static void MyClassInitialize(TestContext testContext)
        {
            // Test doc 0
            string docText = "This my new and fabulous blog where i would love to write about my dog called Fido!\n" +
                             "Fido is a really nice dog which sadly only has 3 legs, because one time where i was really angry, and i had this saw, well never mind.\n" +
                             "I love my dog above anything else in this world, and i thought i would dedicate this document to him!\n" +
                             "This is Fido: <img src=\"Fido.gif\" alt=\"My Dog\">";

            testDoc = new Document(docText, "Fido", new User("Karsten"));
            testDoc.Path = "root/cuteanimalsxoxo";

            // Test doc 1
            string docText1 = "New text\n" +
                             "more text";

            testDoc1 = new Document(docText1, "Herp", new User("Kewin"));
            testDoc1.Path = "root";

            // Test doc 2
            string docText2 = "Interesting facts about crocodiles: \n" +
                              "They bite hard: \n"+
                              "and thats it.";

            testDoc2= new Document(docText2, "Crocoman", new User("Karsten"));
            testDoc2.Path = "root/cuteanimalsxoxo/reptiles";

            testproject = new Project("Projekt", new User("Kewin"), new List<User>(){new User("Karsten") });
            testproject2 = new Project("Projekt2", new User("Karsten"), new List<User>() { new User("Kewin") });
        }
Пример #3
0
        public static void Main(String[] args)
        {
            Thread.Sleep(1000);
            using (SliceOfPieServiceClient serviceClient = new SliceOfPieServiceClient())
            {
                Project p = new Project("SERVERTEST", new User("servertestuserman"), new List<User>());

                //var derp = serviceClient.SyncAll(new List<Document>());

                //List<Project> list = Storage.ServerGetAllProjects();
                //List<SliceOfPie.Project> list = serviceClient.GetAllProjectsOnServer();
                //var herp = serviceClient.GetHierachy("p663555625Crelde");

                Project bool1 = serviceClient.StartSync(new User("Crelde"), "p663555625Crelde");
                //Project fool2 = serviceClient.StartSync(new User("Creldz"), "p663555625Crelde");
                //Project fool3 = serviceClient.StartSync(new User("Crelde"), "p3555625Crelde");
                //Project bool4 = serviceClient.StartSync(new User("Motor-Bjarne"), "p663555625Crelde");

                serviceClient.SendDocument(new Document("", "Document first", new User("Crelde")));
                serviceClient.SendDocument(new Document("", "Document 2", new User("Crelde")));
                serviceClient.SendDocument(new Document("", "Document third", new User("Crelde")));
                serviceClient.SendDocument(new Document("", "4th document", new User("Crelde")));
                serviceClient.SendDocument(new Document("", "half tenth doc", new User("Crelde")));
                serviceClient.SendDocument(new Document("", "sexy doc", new User("Crelde")));
                serviceClient.SendDocument(new Document("", "doc triple 7", new User("Crelde")));

                Console.ReadKey();
            }
        }
Пример #4
0
        public override Project AddProject(string title, string userMail, int id = 0, bool db = false)
        {
            if (title == null || userMail == null) throw new ArgumentNullException();

            Project p = new Project() {
                Title = title
            };
            using (var dbContext = new sliceofpieEntities2()) { //Insert project
                dbContext.Projects.AddObject(p);
                dbContext.SaveChanges();
            }
            User u = new User() {
                Email = userMail
            };
            ProjectUser pu = new ProjectUser() {
                UserEmail = userMail,
                ProjectId = p.Id
            };
            using (var dbContext = new sliceofpieEntities2()) { //Insert projectUser
                if (dbContext.Users.Count(dbUser => dbUser.Email.Equals(u.Email)) < 1) throw new ArgumentException("No user with email " + u.Email + " exists!");
                dbContext.ProjectUsers.AddObject(pu);
                dbContext.SaveChanges();
            }
            return new Project() {
                Title = p.Title,
                Id = p.Id
            };
        }
Пример #5
0
        private bool modified; // Does this document have unsaved changes?

        #endregion Fields

        #region Constructors

        public EditWindow(Project proj, Document doc, User user)
        {
            currentProj = proj;
            currentDoc = doc;
            currentUser = user;

            InitializeComponent();
        }
Пример #6
0
 public ActionResult DeleteConfirmed(Project p)
 {
     controller.RemoveProject(p);
     if (p == null) {
         return HttpNotFound();
     }
     return RedirectToAction("Overview");
 }
Пример #7
0
        public ActionResult Create(Project project)
        {
            if (ModelState.IsValid)
            {
                Project result = controller.CreateProject(project.Title, User.Identity.Name);
                return RedirectToAction("Index", result);
            }

            return View(project);
        }
Пример #8
0
        /**
         * Shares the changes the user have made in a project
         * to the server, and the server shares changes from other
         * users back. This synchronization is done through a series
         * of method calls to the server.
         */
        public static void SyncWithServer(Project project, User user)
        {
            // Preparing transfer data
            // finding all modified documents to send
            List<DocumentStruct> docs = new List<DocumentStruct>();
            Folder.GetAllStructs(project, docs); // fill up the list

            List<DocumentStruct> docsToSend = new List<DocumentStruct>();
            foreach (DocumentStruct d in docs)
            {
                if (d.Modified)
                    docsToSend.Add(d);
            }

            // Call the server
            using (SliceOfPieServiceClient serviceClient = new SliceOfPieServiceClient())
            {
                // Tell the server who we are and what project we want to sync
                Project newProj = serviceClient.StartSync(user, project.Id);

                // If null is returned, means that the project was deleted
                // or you've lost access to this project, so we delete it
                if (newProj == null)
                    Controller.DeleteProject(project.Id);
                else
                {
                    // Send all modified documents one at a time
                    foreach (DocumentStruct d in docsToSend)
                    {
                        Document document = Controller.OpenDocument(project.Id, d.Id);
                        serviceClient.SendDocument(document);
                        if (document.Deleted)
                            Controller.DeleteDocument(project.Id, document.Id);
                    }

                    // Keep getting new documents from server until there are none remaining
                    while (true)
                    {
                        // Grab a new document from the server
                        Document newDoc = serviceClient.GetUpdatedDocument();

                        // if null is returned, means that there are no new docs left
                        if (newDoc == null)
                            break;

                        // Delete the old copy and write the new one instead
                        Storage.DeleteDocument(project.Id, newDoc.Id);
                        Storage.WriteToFile(newProj, newDoc, true);
                    }

                    // We're done syncing, close the session with the server
                    serviceClient.StopSync();
                }
            }
        }
Пример #9
0
 public static void SaveDocument(Project proj, Document doc, User user, bool fromServer = false)
 {
     // If the document exists in the storage, merge old version with newer verion.
     // Otherwise just save it to the storage.
     Document docInStorage = Storage.ReadFromFile(proj.Id, doc.Id);
     if (docInStorage == null)
         Storage.WriteToFile(proj, doc, fromServer);
     else
     {
         docInStorage.MergeWith(doc, user);
         Storage.WriteToFile(proj, docInStorage, fromServer);
     }
 }
Пример #10
0
        /**
         * Get all documents of a project one by one from the server
         */
        public static List<Document> GetAllProjectDocuments(Project p)
        {
            List<DocumentStruct> allDocs = new List<DocumentStruct>();
            Folder.GetAllStructs(p, allDocs); // get all document reference structs out

            List<Document> result = new List<Document>();

            // ask server for documents
            using (SliceOfPieServiceClient serviceClient = new SliceOfPieServiceClient())
            {
                foreach (DocumentStruct d in allDocs)
                {
                    result.Add(serviceClient.OpenDocumentOnServer(p.Id, d.Id));
                }
            }

            return result;
        }
Пример #11
0
        /// <summary>
        /// Upload all files and folders to db for specific user.
        /// </summary>
        /// <param name="email"></param>
        public void UploadStructure(string email)
        {
            // Projects
            string[] folders = Directory.GetDirectories(AppPath);
            foreach (string folderName in folders) {
                Project dbProject = null;
                using (var dbContext = new sliceofpieEntities2()) {
                    string pathName = Path.GetFileName(folderName);
                    string[] parts = pathName.Split('-');
                    int id = int.Parse(parts[0]);
                    string title = pathName.Replace(parts[0] + "-", "");

                    var dbProjects = from dProject in dbContext.Projects
                                     where dProject.Id == id
                                     select dProject;
                    if (id > 0 && dbProjects.Count() == 0) {
                        if (Directory.Exists(Path.Combine(AppPath, Helper.GenerateName(id, title)))) {
                            Directory.Move(Path.Combine(AppPath, Helper.GenerateName(id, title)), Path.Combine(AppPath, Helper.GenerateName(0, title)));
                        }
                        id = 0;
                    }
                    if (id > 0) {
                        // Updating project
                        dbProject = dbProjects.First();
                        dbProject.Title = title;
                    } else {
                        // Creating project
                        dbProject = new Project {
                            Title = title
                        };
                        dbContext.Projects.AddObject(dbProject);
                    }
                    dbContext.SaveChanges();
                }
                // Rename project directory
                string projectPath = Path.Combine(AppPath, Helper.GenerateName(dbProject.Id, dbProject.Title));
                if (Directory.Exists(Path.Combine(AppPath, Helper.GenerateName(0, dbProject.Title)))) {
                    Directory.Move(Path.Combine(AppPath, Helper.GenerateName(0, dbProject.Title)), projectPath);
                }
                // Create project user
                using (var dbContext = new sliceofpieEntities2()) {
                    var dbProjectUsers = from dProjectUser in dbContext.ProjectUsers
                                         where dProjectUser.ProjectId == dbProject.Id && dProjectUser.UserEmail == email
                                         select dProjectUser;
                    if (dbProjectUsers.Count() == 0) {
                        dbContext.ProjectUsers.AddObject(new ProjectUser {
                            ProjectId = dbProject.Id,
                            UserEmail = email
                        });
                        dbContext.SaveChanges();
                    }
                }

                // Upload folders and documents
                var path = Path.Combine(AppPath, Helper.GenerateName(dbProject.Id, dbProject.Title));
                UploadFolders(path, dbProject.Id, Container.Project);
                UploadDocuments(path, dbProject.Id, Container.Project);
            }
        }
Пример #12
0
 public override void RemoveProject(Project project)
 {
     if (Projects.Count() == 1) {
         throw new ArgumentException("You cannot delete all projects");
     }
     if (!Directory.Exists(project.GetPath())) {
         throw new ArgumentException("Project folder does not exist (" + project.GetPath() + ")");
     }
     Document[] removeDocuments = project.Documents.ToArray();
     foreach (Document document in removeDocuments) {
         RemoveDocument(document);
     }
     Folder[] removeFolders = project.Folders.ToArray();
     foreach (Folder subFolder in removeFolders) {
         RemoveFolder(subFolder);
     }
     Directory.Delete(project.GetPath());
     Projects.Remove(project);
 }
Пример #13
0
 /// <summary>
 /// Rename project both in file system and internal system.
 /// </summary>
 /// <param name="project"></param>
 /// <param name="title"></param>
 public void RenameProject(Project project, string title)
 {
     string projectPath = Path.Combine(AppPath, Helper.GenerateName(project.Id, GetAvailableName(title, project.Id, AppPath)));
     try {
         Directory.Move(project.GetPath(), projectPath);
     } catch (IOException e) {
         // Should not be accesible
         Console.WriteLine(e.Message);
     }
     project.Title = title;
 }
Пример #14
0
 /**
  * Saves an existing project
  */
 public static void UpdateProject(Project p)
 {
     Storage.SaveProjectToFile(p);
 }
Пример #15
0
        /// <summary>
        /// Find all projects in file system and create them in internal system.
        /// </summary>
        public void FindProjects()
        {
            Projects = new List<Project>();

            string[] folders = Directory.GetDirectories(AppPath);
            foreach (string folderName in folders) {
                string pathName = Path.GetFileName(folderName);
                string[] parts = pathName.Split('-');
                Project project = new Project {
                    Id = int.Parse(parts[0]),
                    Title = pathName.Replace(parts[0] + "-", ""),
                    AppPath = AppPath
                };
                Projects.Add(project);

                FindFolders(project);
                FindDocuments(project);
            }
        }
Пример #16
0
 public static void CreateProject(string title, User owner, List<User> sharedWith)
 {
     Project project = new Project(title, owner, sharedWith);
     UpdateProject(project);
 }
Пример #17
0
 public void SaveDocumentOnServer(Project p, Document d, User user)
 {
     Console.WriteLine("{0} saved document {1} to project {2}", user, d.Title, p.Title);
     // If the document exists in the storage, merge old version with newer verion.
     // Otherwise just save it to the storage.
     Document docInStorage = Storage.ReadFromFile(p.Id, d.Id);
     if (docInStorage == null)
         Storage.WriteToFile(p, d);
     else
     {
         docInStorage.MergeWith(d, user);
         Storage.WriteToFile(p, docInStorage);
     }
 }
Пример #18
0
        /**
         * This is called when an user from the offline client
         * wants to start syncronizing a project with the server.
         * We also make sure the users copy of the project info is up to date
         */
        public Project StartSync(User user, string projectId)
        {
            Console.WriteLine("New user connected to sync offline content");
            currentUser = user;
            currentProj = Storage.GetHierachy(projectId);
            if (currentProj != null)
            {
                if (currentProj.Owner.Equals(user) || currentProj.SharedWith.Contains(user))
                {
                    Console.WriteLine("{0} is now syncing with project: {1},",user,projectId);
                    return currentProj;
                }
            }

            Console.WriteLine("Access Denied: {0} wanted to sync with: {1},"
                +"\n\tMaking client delete local copy of project", user, projectId);
            return null;
        }
Пример #19
0
 public static void CreateDocument(User user, string path, Project proj, string title)
 {
     // Save the document to the storage.
     Document newDocument = new Document("Insert your text here.", title, path, user);
     SaveDocument(proj, newDocument, user);
 }
Пример #20
0
 /// <summary>
 /// Share the project with other users (per email).
 /// </summary>
 /// <param name="p">Project to share</param>
 /// <param name="commaSeperatedEmailList">Emails as a comma-seperated string.</param>
 public void ShareProject(Project p, string commaSeparatedEmailList)
 {
     ShareProject(p, commaSeparatedEmailList.Split(','));
 }
Пример #21
0
        /// <summary>
        /// Starts sharing a project using APM.
        /// </summary>
        /// <param name="p">Project to share</param>
        /// <param name="emails">Emails to share the project with</param>
        /// <param name="callback">Callback called upon conclusion of sharing</param>
        /// <param name="stateObject">state object woopdashoopfloop</param>
        /// <returns>IAsyncResult for EnShareProject</returns>
        /// <seealso cref="EndShareProject"/>
        public IAsyncResult BeginShareProject(Project p, IEnumerable<string> emails, AsyncCallback callback, object stateObject)
        {
            AsyncResultNoResult<Project, IEnumerable<string>> ar = new AsyncResultNoResult<Project, IEnumerable<string>>(callback, stateObject, p, emails);
            ThreadPool.QueueUserWorkItem(ShareProjectAsyncHelper, ar);

            return ar;
        }
Пример #22
0
 /// <summary> 
 /// Add project to system. If db is set to true, only create folder.
 /// </summary>
 /// <param name="title"></param>
 /// <param name="db"></param>
 /// <returns></returns>
 public override Project AddProject(string title, string userMail, int id = 0, bool db = false)
 {
     if (!db) title = GetAvailableName(title, id, AppPath);
     string projectPath = Path.Combine(AppPath, Helper.GenerateName(id, title));
     try {
         Directory.CreateDirectory(projectPath);
     } catch (IOException e) {
         // Should not be accesible
         Console.WriteLine(e.Message);
     }
     if (db) return null;
     Project project = new Project();
     project.Title = title;
     project.AppPath = AppPath;
     Projects.Add(project);
     return project;
 }
Пример #23
0
        public override void RemoveProject(Project project)
        {
            if (project == null) throw new ArgumentNullException();
            IEnumerable<Document> documents;
            IEnumerable<Folder> folders;
            using (var dbContext = new sliceofpieEntities2()) {
                Project projectToGetFrom = dbContext.Projects.First(proj => project.Id == proj.Id);
                documents = projectToGetFrom.Documents.ToList();
                folders = projectToGetFrom.Folders.ToList();
            }

            foreach (Document d in documents) {
                RemoveDocument(d);
            }

            foreach (Folder f in folders) {
                RemoveFolder(f);
            }

            using (var dbContext = new sliceofpieEntities2()) {
                Project p = dbContext.Projects.First(proj => project.Id == proj.Id);
                ProjectUser pu = dbContext.ProjectUsers.First(user => project.Id == user.ProjectId);
                dbContext.ProjectUsers.DeleteObject(pu);
                dbContext.Projects.DeleteObject(p);
                dbContext.SaveChanges();
            }
        }
Пример #24
0
 public override Project GetProject(int id)
 {
     Project result;
     using (var dbContext = new sliceofpieEntities2()) {
         Project dbProj = dbContext.Projects.First(p => p.Id == id);
         result = new Project() {
             Id = dbProj.Id,
             Title = dbProj.Title
         };
     }
     GetFolders(result);
     GetDocuments(result);
     return result;
 }
Пример #25
0
        /// <summary>
        /// Remove a project asynchronously, according to the APM (Asynchrnonous Programming Model).
        /// </summary>
        /// <param name="p">Project to remove</param>
        /// <param name="callback">Callback called upon finish</param>
        /// <param name="state">State object, passed to callback.</param>
        /// <returns>IAsyncResult used by EndRemoveProject</returns>
        /// <seealso cref="EndRemoveProject"/>
        public IAsyncResult BeginRemoveProject(Project p, AsyncCallback callback, object state)
        {
            AsyncResultNoResult<Project> ar = new AsyncResultNoResult<Project>(callback, state, p);
            ThreadPool.QueueUserWorkItem(RemoveProjectAsyncHelper, ar);

            return ar;
        }
Пример #26
0
        // Saves a project to the file system if it doesnt already exist.
        // If it is already there, update its MetaInfo file.
        public static void SaveProjectToFile(Project p)
        {
            // The path the project should be saved to.
            string path = p.Id;

            // Check if the project exists, if it doesnt, create it.
            if (!Directory.Exists(p.Id))
            {
                // Create the MetaInfo file, which contains the Title of the project,
                // the owner and the users the project is shared with.
                Directory.CreateDirectory(path);
                using (TextWriter tw = new StreamWriter(path + "\\MetaInfo.txt", false))
                {

                    // Write title
                    tw.WriteLine(p.Title);
                    // Write owner.
                    tw.WriteLine(p.Owner.ToString());
                    // Write users the project is ahred with
                    List<User> userList = p.SharedWith;
                    User[] users = userList.ToArray();
                    string[] userNames = new string[users.Length];

                    int i = 0;
                    foreach (User u in users)
                    {
                        userNames[i] = u.ToString();
                        i++;
                    }
                    StringBuilder sb = new StringBuilder();
                    int j = 1;
                    foreach (string s in userNames)
                    {
                        if (!(j == userNames.Length))
                        {
                            sb.AppendFormat(s + ", ");
                        }
                        else
                        {
                            sb.AppendFormat(s);
                        }
                        j++;
                    }
                    tw.WriteLine(sb.ToString());
                }
            }
            else
            {
                // If the project already exists, overwrite the MetaInfoFile with the new information.
                using (TextWriter tw = new StreamWriter(path + "\\MetaInfo.txt", false))
                {
                    tw.WriteLine(p.Title);
                    tw.WriteLine(p.Owner.ToString());

                    List<User> userList = p.SharedWith;
                    User[] users = userList.ToArray();
                    string[] userNames = new string[users.Length];

                    int i = 0;
                    foreach (User u in users)
                    {
                        userNames[i] = u.ToString();
                        i++;
                    }
                    StringBuilder sb = new StringBuilder();
                    int j = 1;
                    foreach (string s in userNames)
                    {
                        if (!(j == userNames.Length))
                        {
                            sb.AppendFormat(s + ", ");
                        }
                        else
                        {
                            sb.AppendFormat(s);
                        }
                        j++;
                    }
                    tw.WriteLine(sb.ToString());
                    tw.Close();
                }
            }
        }
Пример #27
0
 /// <summary>
 /// Remove the specified project from the system.
 /// </summary>
 /// <param name="p">Project to remove.</param>
 /// <seealso cref="BeginRemoveProject"/>
 public void RemoveProject(Project p)
 {
     fileModel.RemoveProject(p);
 }
Пример #28
0
        /*
         * This method creates a new document based on the document given as a parameter, in the format:
         * First line: The user who created the document
         * Second line: The users the document is shared with
         * The rest is the text
         */
        // Second parameter is optional for now, chooses where to put the file
        public static void WriteToFile(Project pro, Document doc, bool fromServer = false)
        {
            // If a document is about to be saved, assume it's been modified since last time
            // unless it's a document freshly recieved from the server
            if (!fromServer)
                doc.Modified = true;

            string path = pro.Id;
            string fileName;

            fileName = path + "\\" + doc.Id + ".txt";

            // False means that it will overwrite an existing file with the same id.
            using (TextWriter tw = new StreamWriter(fileName, false))
            {
                // Writes the first line in the document file which should be the title
                tw.WriteLine(doc.Title);

                // Writes the second line in the document which should be the path (for gui representation)
                tw.WriteLine(doc.Path);

                // Writes the third line in the file which is the owner of the document
                tw.WriteLine(doc.Owner.ToString());

                // Writes the 4th line, which is the pictures that are attached to the docmuent.
                // If the pictures are not saved already, save them.
                IEnumerable<string> filesInRoot = Directory.EnumerateFiles(path);
                StringBuilder imageLineBuilder = new StringBuilder();
                for (int i = 0; i < doc.Images.Count; i++)
                {
                    string picPath = pro.Id + @"\" + doc.Images[i].Id + ".JPG";
                    string currentDir = Directory.GetCurrentDirectory();
                    if (!(filesInRoot.Contains(picPath)))
                        SavePictureToFile(doc.Images[i], currentDir + @"\" + picPath);
                    if (i == doc.Images.Count - 1)
                        imageLineBuilder.AppendFormat(doc.Images[i].Id);
                    else
                        imageLineBuilder.AppendFormat(doc.Images[i].Id + ",");
                }

                tw.WriteLine(imageLineBuilder.ToString());

                // Write the modified boolean
                tw.WriteLine(doc.Modified.ToString());

                // Write the deleted boolean
                tw.WriteLine(doc.Deleted.ToString());

                // Write the documents log
                tw.WriteLine("");
                tw.Write(doc.Log);

                // Writes the users text into the document
                tw.WriteLine("");
                tw.Write(doc.Text);
            }
        }
Пример #29
0
 /// <summary>
 /// Share the project with other users (per email).
 /// </summary>
 /// <param name="p">Project to share</param>
 /// <param name="emails">Emails as an iterable of strings</param>
 public void ShareProject(Project p, IEnumerable<string> emails)
 {
     foreach (string email in emails) {
         userModel.ShareProject(p.Id, email);
     }
 }
Пример #30
0
        public static Project GetHierachy(string pid)
        {
            // Path of the project
            string folderPath = pid;

            if (Directory.Exists(folderPath))
            {
                List<string> distinctFolders = new List<string>();
                List<Folder> folders = new List<Folder>();
                List<string> potentialFoldersInRoot = new List<string>();
                List<string> toBeFolders = new List<string>();
                // Get an Enumerable of all the files in the Project.
                IEnumerable<string> filesInRoot = Directory.EnumerateFiles(folderPath);
                List<DocumentStruct> structs = new List<DocumentStruct>();

                foreach (string s in filesInRoot)
                {
                    // If the file is not the MetaInfo file, or an image, it's a document
                    // that should be made as a DocumentStruct.
                    if (!(s.Contains("MetaInfo.txt")) && (!(s.Contains(".JPG"))))
                    {
                        using (TextReader tr = new StreamReader(s))
                        {
                            // Read the title
                            string title = tr.ReadLine();
                            // Read the Path
                            string path = tr.ReadLine();
                            // Read the User
                            User user = new User(tr.ReadLine());
                            // Add all folders the path contains to the list of toBeFolders.
                            string[] filePath = path.Split('/');
                            foreach (string st in filePath)
                            {
                                toBeFolders.Add(st);

                            }
                            // Read the modified and deleted booleans
                            tr.ReadLine();
                            bool modified = Boolean.Parse(tr.ReadLine());
                            bool deleted = Boolean.Parse(tr.ReadLine());

                            // Get the files name, which is the documents id.
                            string id = Path.GetFileNameWithoutExtension(s);
                            // Add the struct to the list of structs.
                            structs.Add(new DocumentStruct(title, user, id, path, modified, deleted));
                        }
                    }

                }
                // Of all the folders added to the toBeFolders, get each distinct one, and create
                // a Folder object by that name.
                foreach (string foldername in toBeFolders)
                {
                    if (!(distinctFolders.Contains(foldername)))
                        distinctFolders.Add(foldername);
                }
                foreach (string folderName in distinctFolders)
                {
                    folders.Add(new Folder(folderName));
                    // Add it as a potential folder in root of the project.
                    potentialFoldersInRoot.Add(folderName);
                }

                foreach (DocumentStruct d in structs)
                {
                    // Figure out which folder the struct should be in.
                    string[] folder = d.Path.Split('/');
                    foreach (Folder fo in folders)
                    {
                        if (fo.Title.Equals(folder.Last()))
                        {
                            fo.AddChild(d);
                        }
                    }
                }

                foreach (string s in filesInRoot)
                {
                    // We check that the folder isn't root
                    if (!(s.Contains("MetaInfo.txt")) && (!(s.Contains(".JPG"))))
                    {
                        using (TextReader tr = new StreamReader(s))
                        {
                            // Gets to the correct line where the paths are located
                            tr.ReadLine();
                            string path = tr.ReadLine();
                            string[] splitPath = path.Split('/');
                            // Reverse for loop to put the folders together in a "backwards"-fashion
                            for (int i = splitPath.Length; i != 0; i--)
                            {

                                foreach (Folder fol in folders)
                                {
                                    // takes the lower levels first
                                    // it checks if its the top level
                                    if (!splitPath[i - 1].Equals(splitPath[0]))
                                    {

                                        if (fol.Title.Equals(splitPath[i - 1]))
                                        {
                                            // We use linq to find the correct folders
                                            var result1 = from f in folders
                                                          where f.Title.Equals(splitPath[i - 1])
                                                          select f;

                                            var result2 = from f in folders
                                                          where f.Title.Equals(splitPath[i - 2])
                                                          select f;

                                            // We put the folders in their respectible folder
                                            List<IFileSystemComponent> ParentFolder = result2.FirstOrDefault().Children;
                                            Folder Child = result1.FirstOrDefault();
                                            if (!ParentFolder.Contains(Child) && !ParentFolder.Equals(Child))
                                            {
                                                result2.FirstOrDefault().AddChild(result1.FirstOrDefault());
                                                Folder fold = (Folder)result1.FirstOrDefault();
                                                // Remove the folder from the list of potential root folders, as it was added
                                                // to another folder.
                                                potentialFoldersInRoot.Remove(fold.ToString());
                                            }

                                        }
                                    }

                                }
                            }
                        }
                    }
                }
                // Read the info from the MetaInfo file.
                Project finalProject;
                using (TextReader mr = new StreamReader(folderPath + "\\MetaInfo.txt"))
                {
                    // Read title.
                    string ti = mr.ReadLine();
                    // Read owner.
                    User us = new User(mr.ReadLine());
                    // Read list of users the project is shared with.
                    List<User> sha = new List<User>();
                    string[] userNames = (mr.ReadLine().Split(','));
                    foreach (string str in userNames)
                    {
                        sha.Add(new User(str.Trim()));
                    }
                    // Create the project object with the paramerters read.
                    finalProject = new Project(ti, us, sha, Path.GetFileNameWithoutExtension(folderPath));

                    // Add all remaining folders to root of project, and add all
                    // structs with "" as their folder to root as well.
                    foreach (Folder fol in folders)
                    {
                        if (potentialFoldersInRoot.Contains(fol.ToString()))
                        {
                            if (String.Compare(fol.Title, "") == 0)
                            {
                                // Add the documentstruct.
                                foreach (IFileSystemComponent component in fol.Children)
                                    finalProject.AddChild(component);

                            }
                            // Add the folder.
                            else
                                finalProject.AddChild(fol);
                        }
                    }

                    if (finalProject.Children.Count == 0)
                    {
                        Document doc = new Document("Here is your new project", "Welcome", us);
                        WriteToFile(finalProject, doc);
                        finalProject.Children.Add(new DocumentStruct("Welcome", us, doc.Id, "", true, false));
                    }

                    return finalProject;
                }

            }

            Console.WriteLine("No Project exists by that id");

            return null;
        }