public virtual void UpdateGlobal( ) { var getStream = myReceiver.StreamGetAsync(myReceiver.StreamId); getStream.Wait(); NickName = getStream.Result.Stream.Name; Layers = getStream.Result.Stream.Layers.ToList(); // TODO: Implement cache // we can safely omit the displayValue, since this is rhino! this.Message = "Getting objects"; PayloadObjectGetBulk payload = new PayloadObjectGetBulk(); payload.Objects = getStream.Result.Stream.Objects.Where(o => !ObjectCache.ContainsKey(o)); myReceiver.ObjectGetBulkAsync("omit=displayValue", payload).ContinueWith(tres => { // add to cache foreach (var x in tres.Result.Objects) { ObjectCache[x.DatabaseId] = x; } // populate real objects SpeckleObjects.Clear(); foreach (var objId in getStream.Result.Stream.Objects) { SpeckleObjects.Add(ObjectCache[objId]); } this.Message = "Converting objects"; ConvertedObjects = SpeckleCore.Converter.Deserialize(SpeckleObjects); if (ConvertedObjects.Count != SpeckleObjects.Count) { this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Some objects failed to convert."); } this.Message = "Updating..."; UpdateOutputStructure(); Message = "Got data\n@" + DateTime.Now.ToString("hh:mm:ss"); Rhino.RhinoApp.MainApplicationWindow.Invoke(expireComponentAction); }); }
public override void BakeReceiver(string args) { var client = JsonConvert.DeserializeObject <dynamic>(args); var apiClient = new SpeckleApiClient((string)client.account.RestApi) { AuthToken = (string)client.account.Token }; NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = true, loadingBlurb = "Getting stream from server..." })); var previousStream = speckleStreams.FirstOrDefault(s => s.StreamId == (string)client.streamId); var stream = apiClient.StreamGetAsync((string)client.streamId, "").Result.Resource; // If it's the first time we bake this stream, create a local shadow copy if (previousStream == null) { previousStream = new SpeckleStream() { StreamId = stream.StreamId, Objects = new List <SpeckleObject>() }; speckleStreams.Add(previousStream); } LocalContext.GetCachedObjects(stream.Objects, (string)client.account.RestApi); var payload = stream.Objects.Where(o => o.Type == "Placeholder").Select(obj => obj._id).ToArray(); // TODO: Orchestrate & save in cache afterwards! var objects = apiClient.ObjectGetBulkAsync(payload, "").Result.Resources; foreach (var obj in objects) { stream.Objects[stream.Objects.FindIndex(o => o._id == obj._id)] = obj; } }
public virtual void UpdateGlobal( ) { if (IsUpdating) { this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "New update received while update was in progress. Please refresh."); return; } IsUpdating = true; var getStream = Client.StreamGetAsync(Client.StreamId, null).Result; NickName = getStream.Resource.Name; Layers = getStream.Resource.Layers.ToList(); Client.Stream = getStream.Resource; // add or update the newly received stream in the cache. LocalContext.AddOrUpdateStream(Client.Stream, Client.BaseUrl); this.Message = "Getting objects!"; // pass the object list through a cache check LocalContext.GetCachedObjects(Client.Stream.Objects, Client.BaseUrl); // filter out the objects that were not in the cache and still need to be retrieved var payload = Client.Stream.Objects.Where(o => o.Type == "Placeholder").Select(obj => obj._id).ToArray(); // how many objects to request from the api at a time int maxObjRequestCount = 42; // list to hold them into var newObjects = new List <SpeckleObject>(); // jump in `maxObjRequestCount` increments through the payload array for (int i = 0; i < payload.Length; i += maxObjRequestCount) { // create a subset var subPayload = payload.Skip(i).Take(maxObjRequestCount).ToArray(); // get it sync as this is always execed out of the main thread var res = Client.ObjectGetBulkAsync(subPayload, "omit=displayValue").Result; // put them in our bucket newObjects.AddRange(res.Resources); this.Message = JsonConvert.SerializeObject(String.Format("{0}/{1}", i, payload.Length)); } foreach (var obj in newObjects) { var locationInStream = Client.Stream.Objects.FindIndex(o => o._id == obj._id); try { Client.Stream.Objects[locationInStream] = obj; } catch { } } // add objects to cache async Task.Run(() => { foreach (var obj in newObjects) { LocalContext.AddCachedObject(obj, Client.BaseUrl); } }); // set ports UpdateOutputStructure(); this.Message = "Converting..."; SpeckleObjects.Clear(); ConvertedObjects = SpeckleCore.Converter.Deserialise(Client.Stream.Objects); this.Message = "Got data\n@" + DateTime.Now.ToString("hh:mm:ss"); IsUpdating = false; Rhino.RhinoApp.MainApplicationWindow.Invoke(expireComponentAction); }
/// <summary> /// This function will bake the objects in the given receiver. Behaviour: /// 1) Fresh bake: objects are created /// 2) Diff bake: old objects are deleted, any overlapping objects (by applicationId) are either edited or left alone if not marked as having been user modified, new objects are created. /// </summary> /// <param name="args">Serialised client coming from the ui.</param> public override void BakeReceiver(string args) { var client = JsonConvert.DeserializeObject <dynamic>(args); var apiClient = new SpeckleApiClient((string)client.account.RestApi) { AuthToken = (string)client.account.Token }; apiClient.ClientType = "Revit"; //dispatch on the cef window to let progress bar update SpeckleWindow.Dispatcher.Invoke(() => { NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = true, loadingBlurb = "Getting stream from server..." })); }, System.Windows.Threading.DispatcherPriority.Background); var previousStream = LocalState.FirstOrDefault(s => s.StreamId == (string)client.streamId); var stream = apiClient.StreamGetAsync((string)client.streamId, "").Result.Resource; InjectScaleInKits(GetScale((string)stream.BaseProperties.units)); var test = stream.BaseProperties.unitsDictionary; if (test != null) { var secondTest = JsonConvert.DeserializeObject <Dictionary <string, string> >(JsonConvert.SerializeObject(test)); InjectUnitDictionaryInKits(secondTest); } else { InjectUnitDictionaryInKits(null); // make sure it's not there to potentially muddy the waters on other conversions } // If it's the first time we bake this stream, create a local shadow copy if (previousStream == null) { previousStream = new SpeckleStream() { StreamId = stream.StreamId, Objects = new List <SpeckleObject>() }; LocalState.Add(previousStream); } LocalContext.GetCachedObjects(stream.Objects, (string)client.account.RestApi); var payload = stream.Objects.Where(o => o.Type == "Placeholder").Select(obj => obj._id).ToArray(); // TODO: Orchestrate & save in cache afterwards! var objects = apiClient.ObjectGetBulkAsync(payload, "").Result.Resources; foreach (var obj in objects) { stream.Objects[stream.Objects.FindIndex(o => o._id == obj._id)] = obj; } var(toDelete, ToAddOrMod) = DiffStreamStates(previousStream, stream); SpeckleWindow.Dispatcher.Invoke(() => { NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = true, loadingBlurb = "Deleting " + toDelete.Count() + " objects.", objects = stream.Objects })); }, System.Windows.Threading.DispatcherPriority.Background); // DELETION OF OLD OBJECTS if (toDelete.Count() > 0) { Queue.Add(new Action(() => { using (Transaction t = new Transaction(CurrentDoc.Document, "Speckle Delete (" + (string)client.streamId + ")")) { t.Start(); foreach (var obj in toDelete) { var myObj = previousStream.Objects.FirstOrDefault(o => o._id == obj._id); if (myObj != null) { var elem = CurrentDoc.Document.GetElement(myObj.Properties["revitUniqueId"] as string); CurrentDoc.Document.Delete(elem.Id); } } t.Commit(); } })); Executor.Raise(); } // ADD/MOD/LEAVE ALONE EXISTING OBJECTS //if the conversion completely fails, it outputs a speckleerror and it's put in here var errors = new List <SpeckleError>(); //this instead will store errors swallowed by the erroreater class Globals.ConversionErrors = new List <SpeckleError>(); var tempList = new List <SpeckleObject>(); Queue.Add(new Action(() => { using (var t = new Transaction(CurrentDoc.Document, "Speckle Bake")) { t.Start(); int i = 0; foreach (var mySpkObj in ToAddOrMod) { SpeckleWindow.Dispatcher.Invoke(() => { NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = true, isLoadingIndeterminate = false, loadingProgress = 1f * i / ToAddOrMod.Count * 100, loadingBlurb = string.Format("Creating/updating objects: {0} / {1}", i, ToAddOrMod.Count) })); }, System.Windows.Threading.DispatcherPriority.Background); object res; var failOpts = t.GetFailureHandlingOptions(); failOpts.SetFailuresPreprocessor(new ErrorEater()); t.SetFailureHandlingOptions(failOpts); try { res = SpeckleCore.Converter.Deserialise(obj: mySpkObj, excludeAssebmlies: new string[] { "SpeckleCoreGeometryDynamo", "SpeckleCoreGeometryRevit" }); // The converter returns either the converted object, or the original speckle object if it failed to deserialise it. // Hence, we need to create a shadow copy of the baked element only if deserialisation was succesful. if (res is Element) { // creates a shadow copy of the baked object to store in our local state. var myObject = new SpeckleObject() { Properties = new Dictionary <string, object>() }; myObject._id = mySpkObj._id; myObject.ApplicationId = mySpkObj.ApplicationId; myObject.Properties["__type"] = mySpkObj.Type; myObject.Properties["revitUniqueId"] = ((Element)res).UniqueId; myObject.Properties["revitId"] = ((Element)res).Id.ToString(); myObject.Properties["userModified"] = false; tempList.Add(myObject); } // TODO: Handle scenario when one object creates more objects. // ie: SpeckleElements wall with a base curve that is a polyline/polycurve if (res is System.Collections.IEnumerable) { int k = 0; var xx = ((IEnumerable <object>)res).Cast <Element>(); foreach (var elm in xx) { var myObject = new SpeckleObject(); myObject._id = mySpkObj._id; myObject.ApplicationId = mySpkObj.ApplicationId; myObject.Properties["__type"] = mySpkObj.Type; myObject.Properties["revitUniqueId"] = ((Element)elm).UniqueId; myObject.Properties["revitId"] = ((Element)elm).Id.ToString(); myObject.Properties["userModified"] = false; myObject.Properties["orderIndex"] = k++; // keeps track of which elm it actually is tempList.Add(myObject); } } //if( res is SpeckleObject || res == null ) failedToBake++; if (res is SpeckleError) { errors.Add(res as SpeckleError); } } catch (Exception e) { //if(e.Message.Contains("missing")) //failedToBake++; errors.Add(new SpeckleError { Message = e.Message }); } i++; } t.Commit(); } })); Executor.Raise(); Queue.Add(new Action(() => { SpeckleWindow.Dispatcher.Invoke(() => { NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = true, isLoadingIndeterminate = true, loadingBlurb = string.Format("Updating shadow state.") })); }, System.Windows.Threading.DispatcherPriority.Background); // set the local state stream's object list, and inject it in the kits, persist it in the doc previousStream.Objects = tempList; InjectStateInKits(); using (var t = new Transaction(CurrentDoc.Document, "Speckle State Save")) { t.Start(); Storage.SpeckleStateManager.WriteState(CurrentDoc.Document, LocalState); t.Commit(); } string errorMsg = ""; int failedToConvert = errors.Count(); //other conversion errors that we are catching var additionalErrors = GetAndClearConversionErrors(); if (additionalErrors != null && additionalErrors.Count > 0) { errors.AddRange(additionalErrors); } errors.AddRange(Globals.ConversionErrors); //remove duplicates errors = errors.GroupBy(x => x.Message).Select(x => x.First()).ToList(); if (errors.Any()) { errorMsg += string.Format("There {0} {1} error{2} ", errors.Count() == 1 ? "is" : "are", errors.Count(), errors.Count() == 1 ? "" : "s"); if (failedToConvert > 0) { errorMsg += string.Format("and {0} objects that failed to convert ", failedToConvert, failedToConvert == 1 ? "" : "s"); } errorMsg += "<nobr>" + Globals.GetRandomSadFace() + "</nobr>"; } //if(errors.Any()) //{ // errorMsg += "" + // //errors += "<v-divider></v-divider>" + // "<v-layout row wrap><v-flex xs12>"; // //"<strong>Missing families:</strong> "; // foreach( var err in errors) // { // errorMsg += $"<code>{err.Message}</code> "; // } // errorMsg += "</v-flex></v-layout>"; //} SpeckleWindow.Dispatcher.Invoke(() => { NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = false, isLoadingIndeterminate = true, loadingBlurb = string.Format("Done."), errorMsg, errors })); }, System.Windows.Threading.DispatcherPriority.Background); })); Executor.Raise(); }
static async Task TestObjects(SpeckleApiClient myClient) { var myPoint = new SpecklePoint() { Value = new List <double>() { 1, 2, 3 } }; var mySecondPoint = new SpecklePoint() { Value = new List <double>() { 23, 33, 12 } }; var myCircle = new SpeckleCircle() { Radius = 21 }; var myPlane = new SpecklePlane() { Origin = new SpecklePoint() { Value = new List <double>() { 12, 12, 12 } } }; var myArc = new SpeckleArc() { Radius = 2, AngleRadians = 2.1, EndAngle = 1, StartAngle = 0 }; myCircle.Properties = new Dictionary <string, object>(); myCircle.Properties.Add("a property", "Hello!"); myCircle.Properties.Add("point", myPoint); List <SpeckleObject> myList = new List <SpeckleObject>(); Console.WriteLine(); try { Console.WriteLine("Creating some objects."); var Response = await myClient.ObjectCreateAsync(new List <SpeckleObject>() { myPoint, myCircle, myArc, myPlane }); Console.WriteLine("OK: Saved " + Response.Resources.Count + " objects"); myList = Response.Resources; } catch (Exception e) { Console.WriteLine(e.Message); } Console.WriteLine(); try { Console.WriteLine("Updating an object"); var Response = await myClient.ObjectUpdateAsync(myList[1]._id, new SpeckleCircle() { Radius = 42 }); Console.WriteLine("OK: Saved " + Response.Message); } catch (Exception e) { Console.WriteLine(e.Message); } Console.WriteLine(); try { Console.WriteLine("Updating an object's properties"); var Response = await myClient.ObjectUpdatePropertiesAsync(myList[1]._id, new { hello = "World", max = 3.14 }); Console.WriteLine("OK: Saved " + Response.Message); } catch (Exception e) { Console.WriteLine(e.Message); } Console.WriteLine(); try { Console.WriteLine("Getting an object"); var Response = await myClient.ObjectGetAsync(myList[1]._id); Console.WriteLine("OK: Got " + Response.Resource.ToJson()); } catch (Exception e) { Console.WriteLine(e.Message); } Console.WriteLine(); try { Console.WriteLine("Getting objects in bulk"); var Response = await myClient.ObjectGetBulkAsync(new string[] { myList[1]._id, myList[0]._id, myList[2]._id }, "fields=properties,radius"); Console.WriteLine("OK: Got " + Response.Resources.Count); } catch (Exception e) { Console.WriteLine(e.Message); } Console.WriteLine(); try { Console.WriteLine("Deleting an object"); var Response = await myClient.ObjectDeleteAsync(myList[0]._id); Console.WriteLine("OK: Got " + Response.Message); } catch (Exception e) { Console.WriteLine(e.Message); } }