public static void AddBookmark(string username, string title, string url, string[] tags, string notes) { BookmarksEntities context = new BookmarksEntities(); Bookmark newBookmark = new Bookmark(); newBookmark.User = CreateOrLoadUser(context, username); newBookmark.Title = title; newBookmark.URL = url; newBookmark.Notes = notes; foreach (var tagName in tags) { Tag tag = CreateOrLoadTag(context, tagName); newBookmark.Tags.Add(tag); } string[] titleTags = Regex.Split(title, @"[,'!\. ;?-]+"); foreach (var titleTagName in titleTags) { Tag titleTag = CreateOrLoadTag(context, titleTagName); newBookmark.Tags.Add(titleTag); } context.Bookmarks.Add(newBookmark); context.SaveChanges(); }
// Problem 3 public static void ImportXmlIntoDatabase(string xmlPath) { TransactionScope tranScope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.RepeatableRead }); using (tranScope) { BookmarksEntities context = new BookmarksEntities(); using (context) { XmlDocument doc = new XmlDocument(); doc.Load(xmlPath); string xpathQuery = "bookmarks/bookmark"; XmlNodeList bookmarksList = doc.SelectNodes(xpathQuery); foreach (XmlNode node in bookmarksList) { string username = node.SelectSingleNode("username").InnerText; string title = node.SelectSingleNode("title").InnerText; string url = node.SelectSingleNode("url").InnerText; string notes = null; string[] tags = { }; string[] tagsFromTitle = { }; HashSet <string> allTags = new HashSet <string>(); XmlNode notesNode = node.SelectSingleNode("notes"); if (notesNode != null) { notes = notesNode.InnerText; } XmlNode tagsNode = node.SelectSingleNode("tags"); if (tagsNode != null) { string tagsAsText = tagsNode.InnerText; tags = tagsAsText.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries); foreach (var tag in tags) { allTags.Add(tag.ToLower().Trim()); } } tagsFromTitle = title.Split(new char[] { ',', '!', '.', ';', '?', '-', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (var tagFromTitle in tagsFromTitle) { allTags.Add(tagFromTitle.ToLower().Trim()); } bool wasCreated = false; User user = CreateOrLoadUser(context, username, out wasCreated); if (wasCreated) { context.Users.Add(user); } Bookmark bookmark = new Bookmark(); bookmark.User = user; bookmark.Notes = notes; bookmark.Title = title; bookmark.URL = url; Dictionary <string, Tag> existingTags = GetExistingTags(context); foreach (var tag in allTags) { if (!existingTags.ContainsKey(tag)) { Tag newTag = new Tag(); newTag.Text = tag; bookmark.Tags.Add(newTag); context.Tags.Add(newTag); } else { bookmark.Tags.Add(existingTags[tag]); } } context.Bookmarks.Add(bookmark); context.SaveChanges(); } } tranScope.Complete(); } }