public void TestCollectionPutDelete() { string endPoint = String.Format(endpointLocator, serviceUrl, "sandbox/apitest"); HttpWebRequest request = CreateRequest(endPoint, "PUT"); Stream requestStream = request.GetRequestStream(); DataContractJsonSerializer requestSerializer = new DataContractJsonSerializer(typeof(Chronozoom.Entities.Collection)); Chronozoom.Entities.Collection newCollection = new Chronozoom.Entities.Collection() { Title = "API Test Collection" }; requestSerializer.WriteObject(requestStream, newCollection); WebResponse response = request.GetResponse(); Stream responseStream = response.GetResponseStream(); //string responseText = new StreamReader(response.GetResponseStream()).ReadToEnd(); DataContractJsonSerializer guidSerializer = new DataContractJsonSerializer(typeof(Guid)); Guid collectionId = (Guid)guidSerializer.ReadObject(responseStream); Assert.IsNotNull(collectionId); request = CreateRequest(endPoint, "DELETE"); request.GetResponse(); }
public Collection<TimelineShortcut> GetUserFeatured(string guid) { return ApiOperation<Collection<TimelineShortcut>>(delegate(User user, Storage storage) { Guid userGuid; // If GUID is not given then get supervisor's GUID. Otherwise parse the given GUID. if (guid.Equals("default")) { string aps = ConfigurationManager.AppSettings["FeaturedTimelinesSupervisorGuid"]; userGuid = String.IsNullOrEmpty(aps) ? Guid.Empty : Guid.Parse(aps); } else if (!Guid.TryParse(guid, out userGuid)) { return null; } var cacheKey = string.Format(CultureInfo.InvariantCulture, "UserFeatured - {0}", userGuid); if (Cache.Contains(cacheKey)) { return (Collection<TimelineShortcut>)Cache.Get(cacheKey); } var triple = storage.GetTriplet(String.Format("czusr:{0}", userGuid), "czpred:featured").FirstOrDefault(); if (triple == null) return null; var elements = new Collection<TimelineShortcut>(); foreach (var t in triple.Objects) { var objName = TripleName.Parse(t.Object); if (objName.Prefix == "cztimeline") { var g = new Guid(objName.Name); var timeline = storage.Timelines.Where(x => x.Id == g) .Include("Collection") .Include("Collection.User") .Include("Collection.SuperCollection") .Include("Exhibits") .Include("Exhibits.ContentItems") .FirstOrDefault(); if (timeline != null) elements.Add(storage.GetTimelineShortcut(timeline)); } } Cache.Add(cacheKey, elements); return elements; }); }
protected static Uri UrlForCollection(SuperCollection superCollection, Collection collection) { if (superCollection == null || collection == null || string.IsNullOrEmpty(superCollection.Title) || string.IsNullOrEmpty(collection.Title)) return null; string path = _hostPath.Value + "/" + FriendlyUrl.FriendlyUrlEncode(superCollection.Title) + "/"; if (string.CompareOrdinal(superCollection.Title, collection.Title) != 0) { path += FriendlyUrl.FriendlyUrlEncode(collection.Title) + "/"; } return new Uri(path); }
public Collection<TimelineShortcut> GetUserFavorites() { return ApiOperation<Collection<TimelineShortcut>>(delegate(User user, Storage storage) { #if RELEASE if (user == null) { return null; } #endif Guid userId = user == null || user.Id == null ? Guid.Empty : user.Id; var cacheKey = string.Format(CultureInfo.InvariantCulture, "UserFavorites - {0}", userId); if (Cache.Contains(cacheKey)) { return (Collection<TimelineShortcut>)Cache.Get(cacheKey); } var triple = storage.GetTriplet(String.Format("czusr:{0}", user != null ? user.Id : Guid.Empty), "czpred:favorite").FirstOrDefault(); if (triple == null) return null; var elements = new Collection<TimelineShortcut>(); foreach (var t in triple.Objects) { var objName = TripleName.Parse(t.Object); if (objName.Prefix == "cztimeline") { var g = new Guid(objName.Name); var timeline = storage.Timelines.Where(x => x.Id == g) .Include("Collection") .Include("Collection.User") .Include("Collection.SuperCollection") .Include("Exhibits") .Include("Exhibits.ContentItems") .FirstOrDefault(); if (timeline != null) elements.Add(storage.GetTimelineShortcut(timeline)); } } Cache.Add(cacheKey, elements); return elements; }); }
public Collection<TimelineShortcut> GetUserTimelines(string superCollection, string Collection) { return ApiOperation<Collection<TimelineShortcut>>(delegate(User user, Storage storage) { if (user == null) return null; //#if RELEASE // if (user == null) // { // return null; // } //#endif Timeline roottimeline = GetTimelines(superCollection, Collection, null, null, null, null, null, null); var elements = new Collection<TimelineShortcut>(); var timeline = storage.Timelines.Where(x => x.Id == roottimeline.Id) .Include("Collection") .Include("Collection.SuperCollection") .Include("Collection.User") .Include("Exhibits") .Include("Exhibits.ContentItems") .FirstOrDefault(); if (timeline != null) elements.Add(storage.GetTimelineShortcut(timeline)); if (roottimeline.ChildTimelines != null) { foreach (var t in roottimeline.ChildTimelines) { timeline = storage.Timelines.Where(x => x.Id == t.Id) .Include("Collection") .Include("Collection.SuperCollection") .Include("Collection.User") .Include("Exhibits") .Include("Exhibits.ContentItems") .FirstOrDefault(); if (timeline != null) elements.Add(storage.GetTimelineShortcut(timeline)); } } return elements; }); }
/// <summary> /// Documented under IChronozoomSVC /// </summary> /// <param name="includeMine"></param> /// <returns></returns> public Collection<TimelineShortcut> GetEditableTimelines(bool includeMine = false) { Trace.TraceInformation("GetEditableTimelines"); return ApiOperation<Collection<TimelineShortcut>>(delegate(User user, Storage storage) { Collection<TimelineShortcut> rv = new Collection<TimelineShortcut>(); List<Collection> collections; if (includeMine) { // Collections where others can edit and user is in edit list, or user is collection owner. collections = storage.Collections .Where(c => c.User.Id == user.Id || (c.Members.Any(m => m.User.Id == user.Id) && c.MembersAllowed)) .Include("SuperCollection") .OrderByDescending(c => c.User.Id == user.Id) .ThenBy(c => c.User.DisplayName).ThenBy(c => c.Title) .ToList(); } else { // Collections where others can edit and user is in edit list, but user is not collection owner. collections = storage.Collections .Where(c => c.Members.Any(m => m.User.Id == user.Id) && c.MembersAllowed && c.User.Id != user.Id) .Include("SuperCollection") .OrderBy(c => c.User.DisplayName).ThenBy(c => c.Title) .ToList(); } foreach (Collection collection in collections) { Collection<TimelineShortcut> collectionTimelines = GetUserTimelines(collection.SuperCollection.Title, collection.Title); foreach (TimelineShortcut collectionTimeline in collectionTimelines) { rv.Add(collectionTimeline); } } return rv; }); }
public string ImportCollection( Guid collectionId, string collectionTitle, string collectionTheme, List<FlatTimeline> timelines, List<Tour> tours, bool makeDefault = false, bool forcePublic = false, bool keepOldGuids = false, string forceUserDisplayName = null ) { int titleCount = 1; string titleAppend = ""; string path = Regex.Replace(collectionTitle.Trim(), @"[^A-Za-z0-9\-]+", "").ToLower(); string type; Guid GUID; Guid newGUID; Dictionary<Guid, Guid> newGUIDs = new Dictionary<Guid, Guid>(); DateTime timestamp = DateTime.UtcNow; User user = _user; // ensure user logged in or provided in override if (forceUserDisplayName != null) user = _storage.Users.Where(u => u.DisplayName == forceUserDisplayName).FirstOrDefault(); if (user == null) { return "In order to import a collection, you must first be logged in."; } // ensure collection title is unique for user while ( _storage.Collections.Where(c => c.User.Id == user.Id && c.Path == path + titleAppend).FirstOrDefault() != null ) { titleCount++; titleAppend = "-" + titleCount; } if ((path + titleAppend).Length > 50) { return "Either the name of the collection to be imported is too long, or a collecton with this name already exists."; } // create new collection under existing user's supercollection SuperCollection superCollection = _storage.SuperCollections.Where(s => s.User.Id == user.Id).Include("User").Include("Collections").FirstOrDefault(); if (superCollection == null) { return "The collection could not be imported as you are not properly logged in. Please log out then log back in again first."; } Collection collection = new Collection { Id = keepOldGuids ? collectionId : Guid.NewGuid(), SuperCollection = superCollection, Default = makeDefault, Path = path + titleAppend, Title = collectionTitle.Trim() + titleAppend, Theme = collectionTheme == "" ? null : collectionTheme, MembersAllowed = false, Members = null, PubliclySearchable = forcePublic, User = user }; superCollection.Collections.Add(collection); // iterate through each timeline foreach (FlatTimeline flat in timelines) { // keep cross-reference between old and new timelineIds so child timelines can maintain a pointer to their parents if (!keepOldGuids) { newGUID = Guid.NewGuid(); newGUIDs.Add(flat.timeline.Id, newGUID); flat.timeline.Id = newGUID; if (flat.parentTimelineId != null) // not root timeline { flat.parentTimelineId = newGUIDs[(Guid)flat.parentTimelineId]; } } flat.timeline.Collection = collection; // iterate through each exhibit in the timeline - change last updated to now with current user for (int eachExhibit = 0; eachExhibit < flat.timeline.Exhibits.Count; eachExhibit++) { // also keep cross-references for exhibits if new GUIDs are assigned if (!keepOldGuids) { newGUID = Guid.NewGuid(); newGUIDs.Add(flat.timeline.Exhibits[eachExhibit].Id, newGUID); flat.timeline.Exhibits[eachExhibit].Id = newGUID; } flat.timeline.Exhibits[eachExhibit].Collection = collection; flat.timeline.Exhibits[eachExhibit].UpdatedBy = user; flat.timeline.Exhibits[eachExhibit].UpdatedTime = timestamp; // iterate through each content item in the exhibit for (int eachItem = 0; eachItem < flat.timeline.Exhibits[eachExhibit].ContentItems.Count; eachItem++) { // also keep cross-references for content items if new GUIDs are assigned if (!keepOldGuids) { newGUID = Guid.NewGuid(); newGUIDs.Add(flat.timeline.Exhibits[eachExhibit].ContentItems[eachItem].Id, newGUID); flat.timeline.Exhibits[eachExhibit].ContentItems[eachItem].Id = newGUID; } flat.timeline.Exhibits[eachExhibit].ContentItems[eachItem].Collection = collection; } } // add timeline to database if (flat.parentTimelineId == null) { _storage.Timelines.Add(flat.timeline); } else { Timeline parentTimeline = _storage.Timelines.Where(t => t.Id == flat.parentTimelineId) .Include("ChildTimelines.Exhibits.ContentItems") .FirstOrDefault(); parentTimeline.ChildTimelines.Add(flat.timeline); } // commit creations try { _storage.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } return "Sorry, we were unable to fully import this collection due to an unexpected error, but it may have partially been imported. Please click on My Collections to check."; } } // iterate through each tour foreach (Tour tour in tours) { tour.Collection = collection; // if using new GUIDs, create new ids for tour components and replace url guid parts using old to new GUID mapping if (!keepOldGuids) { tour.Id = Guid.NewGuid(); // iterate through each tour stop for (int eachBookmark = 0; eachBookmark < tour.Bookmarks.Count; eachBookmark++) { tour.Bookmarks[eachBookmark].Id = Guid.NewGuid(); // breakdown each tour stop url segment into parts string[] parts = tour.Bookmarks[eachBookmark].Url.Split('/'); // iterate through each part, replacing the GUID fraction of the part with the new GUID that was mapped earlier during the timelines population for (int eachPart = 1; eachPart < parts.Length; eachPart++) { if (parts[eachPart].Length == 37) { // part has two components type = parts[eachPart].Substring(0, 1); // first character in part is type GUID = new Guid(parts[eachPart].Remove(0, 1)); // rest of part is GUID } else { // part has one component type = ""; GUID = new Guid(parts[eachPart]); // entire part is GUID } GUID = newGUIDs[GUID]; // lookup the earlier mapped GUID parts[eachPart] = type + GUID.ToString(); // and replace the old GUID with mapped } // rejoin all the tour stop url segment parts back together tour.Bookmarks[eachBookmark].Url = String.Join("/", parts); } } // add the tour _storage.Tours.Add(tour); // commit tour to database try { _storage.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } return "We imported all of the timelines, exhibits and content items but we wre unable to fully import tours. Please click on My Collections to check."; } } return "The collection has been imported as \"" + collection.Title + "\". Please click on \"My Collections\" in order to see your new collection."; }
/// <summary>Get owner of the collection</summary> /// <param name="collection">Collection object. May be null.</param> /// <returns>String representation of owning user ID</returns> public string GetCollectionOwner(Collection collection) { if (collection == null) return null; Entry(collection).Reference(c => c.User).Load(); return collection.User != null ? collection.User.Id.ToString() : null; }
/// <summary> /// Returns shortest URL path to a collection. /// For example, excluding the collection path from the URL if it is the default collection. /// If the collection is the default collection in the default supercollection then returns "/". /// </summary> private string GetURLPath(Collection collection, string defaultSuperCollection) { string superCollectionPath = "/" + collection.SuperCollection.Title; string collectionPath = "/" + collection.Path; if (collection.Default) { collectionPath = ""; if (collection.SuperCollection.Title == defaultSuperCollection) { superCollectionPath = "/"; } } return (superCollectionPath + collectionPath).ToLower(); }
private static void ParseJIssues(JArray issuesArray) { if (issuesArray != null && issuesArray.Count > 0) { foreach (JObject obj in issuesArray) { try { Collection new_coll = null; JObject temp = (JObject)obj["title"]; String coll_title = (string)temp["name"]; String title = (string)temp["name"] + "," + (String)obj["date_issued"]; var coll = dbInst.Collections.Where(c => c.Title == coll_title); foreach (Collection c in coll) { new_coll = c; } //adding this newspapers collection if it does not already exist if (new_coll == null) { new_coll = new Collection(); new_coll.Id = Guid.NewGuid(); new_coll.Title = coll_title; dbInst.Collections.Add(new_coll); if (my_sc.Collections == null) my_sc.Collections = new System.Collections.ObjectModel.Collection<Collection>(); my_sc.Collections.Add(new_coll); dbInst.SaveChanges(); } string pagesurl = basebatchurl + (string)obj["local_url"]; StreamReader reader = new StreamReader(pagesurl); string s = reader.ReadToEnd(); reader.Close(); JObject jobj = JObject.Parse(s); JArray pagesArray = (JArray)jobj["pages"]; //Creating the parent timeline Timeline parent = new Timeline(); parent.Id = Guid.NewGuid(); parent.Height = null; //todo parent.Regime = "Humanity"; //todo parent.Sequence = 100; //todo parent.Threshold = "8. Origins of modern world"; //todo parent.Title = title; parent.Collection = new_coll; parent.UniqueId = my_timeline_count++; parent.ChildTimelines = new System.Collections.ObjectModel.Collection<Timeline>(); //Creating the child timelines for (int i = 0; i < pagesArray.Count; i++) { Timeline j = new Timeline(); j.Id = Guid.NewGuid(); j.Title = title + ", Pg" + (i + 1); //Newspaper name,date,pagenumber j.Threshold = "8. Origins of modern world"; //todo j.Regime = "Humanity"; //todo j.Sequence = null; //todo j.FromTimeUnit = "ce"; //to be changed for a different source String dateString = (string)obj["date_issued"]; Decimal year = Decimal.Parse(dateString.Substring(0, 4)); j.FromMonth = int.Parse(dateString.Substring(5, 2)); j.FromDay = int.Parse(dateString.Substring(8, 2)); j.FromYear = convertToDecimalYear(j.FromDay, j.FromMonth, year, j.FromTimeUnit); j.ToTimeUnit = j.FromTimeUnit; j.ToDay = j.FromDay; j.ToMonth = j.FromMonth; j.ToYear = j.FromYear; j.Start = j.FromYear; j.End = j.ToYear; j.UniqueId = my_timeline_count++; if (parent.FromYear == 0) { parent.FromTimeUnit = "ce"; parent.ToTimeUnit = "ce"; parent.FromDay = j.FromDay; parent.FromMonth = j.FromMonth; parent.FromYear = j.FromYear; parent.ToDay = j.ToDay; parent.ToMonth = j.ToMonth; parent.ToYear = j.ToYear; parent.Start = parent.FromYear; parent.End = parent.ToYear; } j.Sequence = 100; //todo j.Height = null; //todo j.Collection = new_coll; String temp2 = (String)(pagesArray[i])["url"]; String URLofData = temp2.Remove(temp2.LastIndexOf(".json")) + "/seq-" + (i + 1); j.Exhibits = new System.Collections.ObjectModel.Collection<Exhibit>(); j.Exhibits.Add(createExhibit(j, URLofData, new_coll)); parent.ChildTimelines.Add(j); //adding j to db dbInst.Timelines.Add(j); if ((my_timeline_count % 10000) == 0) Console.WriteLine("Timelines completed " + my_timeline_count + " " + DateTime.Now.ToShortTimeString()); } //adding parent to db dbInst.Timelines.Add(parent); dbInst.SaveChanges(); } catch (Exception e) { continue; } } } }
//used if creating timeline objects instead of flat json objects private static Exhibit createExhibit(Timeline j, String URL, Collection col) { Exhibit e = new Exhibit(); e.Id = Guid.NewGuid(); e.Title = j.Title + " - Exhibit"; //todo e.Threshold = "8. Origins of modern world"; //todo e.Regime = "Humanity"; //todo e.TimeUnit = "ce"; e.Day = j.FromDay; e.Month = j.FromMonth; e.Year = j.FromYear; e.Sequence = 100; e.UniqueId = my_exhibit_count++; e.Collection = col; e.ContentItems = new System.Collections.ObjectModel.Collection<ContentItem>(); for (int i = 0; i < 4; i++) { ContentItem c = new ContentItem(); c.Id = Guid.NewGuid(); c.UniqueId = my_contentitem_count++; c.Title = j.Title + "- ContentItem"; c.Threshold = "8. Origins of modern world"; c.Regime = "Humanity"; c.TimeUnit = "ce"; c.Year = j.ToYear; c.Order = 1; //todo c.HasBibliography = false; //todo c.MediaSource = "Library of Congress"; //todo c.Attribution = "Library of Congress"; //todo c.Collection = col; switch (i) { case 0: { c.Caption = j.Title + "- JP2"; c.MediaType = "JP2"; c.Uri = URL + ".jp2"; break; } case 1: { c.Caption = j.Title + "- TXT"; c.MediaType = "TXT"; c.Uri = URL + "/ocr.txt"; break; } case 2: { c.Caption = j.Title + "- PDF"; c.MediaType = "PDF"; c.Uri = URL + ".pdf"; break; } case 3: { c.Caption = j.Title + "- OCR"; c.MediaType = "OCR"; c.Uri = URL + "/ocr.xml"; break; } } // Insert into db here dbInst.ContentItems.Add(c); e.ContentItems.Add(c); } dbInst.Exhibits.Add(e); return e; }
public IEnumerable<TimelineRaw> TimelineSubtreeQuery(Guid collectionId, Guid? leastCommonAncestor, decimal startTime, decimal endTime, decimal minSpan, int maxElements) { IEnumerable<TimelineRaw> result; Dictionary<Guid?, TimelineRaw> map = new Dictionary<Guid?, TimelineRaw>(); if (System.Configuration.ConfigurationManager.ConnectionStrings[0].ProviderName.Equals("System.Data.SqlClient")) { result = Database.SqlQuery<TimelineRaw>("EXEC TimelineSubtreeQuery {0}, {1}, {2}, {3}, {4}, {5}", collectionId, leastCommonAncestor, minSpan, startTime, endTime, maxElements); } else { bool return_entire_subtree = false; result = new Collection<TimelineRaw>(); if (leastCommonAncestor != null) { Timeline root = Timelines.Where(r => r.Id == leastCommonAncestor).FirstOrDefault(); if (root != null && root.SubtreeSize <= maxElements) { for (Timeline c = Timelines.Where(_c => _c.Id == root.FirstNodeInSubtree).FirstOrDefault(); c != root; c = Timelines.Where(_c => _c.Id == c.Successor).FirstOrDefault()) { ((Collection<TimelineRaw>)result).Add(new TimelineRaw(c)); } return_entire_subtree = true; } } if (!return_entire_subtree) { Queue<TimelineRaw> q = new Queue<TimelineRaw>(); var init_timelines = leastCommonAncestor == null ? Database.SqlQuery<TimelineRaw>("SELECT * FROM [Timelines] WHERE [Depth] = 0 AND CollectionID = {0}", collectionId) : Database.SqlQuery<TimelineRaw>("SELECT * FROM [Timelines] WHERE [Id] = {0}", leastCommonAncestor); // select the root element foreach (TimelineRaw t in init_timelines) //under normal circumstances this result should only contain a single timeline { q.Enqueue(t); } while (q.Count > 0 && maxElements > 0) { bool childGreaterThanMinspan = false; TimelineRaw t = q.Dequeue(); var childTimelines = Database.SqlQuery<TimelineRaw>("SELECT * FROM [Timelines] WHERE [Timeline_ID] = {0}", t.Id); foreach (TimelineRaw c in childTimelines) { if (c.ToYear - c.FromYear > minSpan) { childGreaterThanMinspan = true; break; } } ((Collection<TimelineRaw>)result).Add(t); --maxElements; if (childGreaterThanMinspan) { if (maxElements >= t.ChildTimelines.Count()) { foreach (TimelineRaw c in childTimelines) { --maxElements; if ((c.FromYear >= startTime && c.FromYear <= endTime) || (c.ToYear >= startTime && c.ToYear <= endTime) || (c.FromYear <= startTime && c.ToYear >= endTime) || (c.FromYear >= startTime && c.ToYear <= endTime)) { //if c overlaps with current viewport, then c may be further expanded q.Enqueue(c); } } } } } } } foreach (TimelineRaw t in result) // note: results are ordered by depth in ascending order { map.Add(t.Id, t); } foreach (TimelineRaw t in result) // note: results are ordered by depth in ascending order { if (t.Timeline_ID != null && map.ContainsKey(t.Timeline_ID)) { if (map[t.Timeline_ID].ChildTimelines == null) { map[t.Timeline_ID].ChildTimelines = new Collection<Timeline>(); } map[t.Timeline_ID].ChildTimelines.Add(t); } } return result; }
public void SetUserTimelinesAsNotFavorite(Collection<Chronozoom.Entities.Timeline> timelines) { Logger.Log("<- imput timelines count: " + timelines.Count); foreach (var timeline in timelines) { ExecuteJavaScript("CZ.Service.deleteUserFavorite('" + timeline.Id + "');"); } Logger.Log("->"); }
public Guid[] SelectAllTimelinesAsFavorites(Collection<Chronozoom.Entities.Timeline> timelines) { Logger.Log("<-"); List<Guid> list = new List<Guid>(); foreach (Chronozoom.Entities.Timeline timeline in timelines) { ExecuteJavaScript("CZ.Service.putUserFavorite('" + timeline.Id + "');"); Sleep(1); list.Add(timeline.Id); } Logger.Log("-> Selected as favorite timelines: " + string.Join(",", list)); return list.ToArray(); }