Exemplo n.º 1
0
        /// <summary>
        /// Gets a stream and its objects, in bulk. This is NOT recommended for large streams.
        /// </summary>
        /// <param name="_streamId"></param>
        static void GetStream(string _streamId = null)
        {
            Console.WriteLine("Hello Speckle! We will now try and get a stream.");
            var account = LocalContext.GetAccountByEmailAndRestApi("*****@*****.**", "https://hestia.speckle.works/api");

            var streamId = "";

            if (_streamId == null)
            {
                Console.WriteLine("What stream id should we get?");
                streamId = Console.ReadLine();
            }
            else
            {
                streamId = _streamId;
            }

            var client = new SpeckleApiClient(account.RestApi, false, "console_app");

            client.AuthToken = account.Token;

            var stream  = client.StreamGetAsync(streamId, "").Result.Resource;
            var objects = client.StreamGetObjectsAsync(streamId, "fields=hash,type").Result; // restricting to just a few things

            Console.WriteLine("This is the stream:");
            Console.WriteLine(stream.ToJson());
            Console.WriteLine();
            Console.WriteLine("Press any key to continue.");
            Console.ReadLine();
            Console.WriteLine("These are the objects:");
            Console.WriteLine(objects.ToJson());
            Console.WriteLine();
            Console.WriteLine("Press any key to continue.");
            Console.ReadLine();
        }
Exemplo n.º 2
0
        public virtual void UpdateGlobal( )
        {
            var getStream = myReceiver.StreamGetAsync(myReceiver.StreamId, null);

            getStream.Wait();

            NickName = getStream.Result.Resource.Name;
            Layers   = getStream.Result.Resource.Layers.ToList();

            // TODO: Implement cache
            // we can safely omit the displayValue, since this is rhino!
            this.Message = "Getting objects";

            var payload = getStream.Result.Resource.Objects.Where(o => !ObjectCache.ContainsKey(o._id)).Select(obj => obj._id).ToArray();

            myReceiver.ObjectGetBulkAsync(payload, "omit=displayValue").ContinueWith(tres =>
            {
                // add to cache
                foreach (var x in tres.Result.Resources)
                {
                    ObjectCache[x._id] = x;
                }

                // populate real objects
                SpeckleObjects.Clear();
                foreach (var obj in getStream.Result.Resource.Objects)
                {
                    SpeckleObjects.Add(ObjectCache[obj._id]);
                }

                this.Message     = "Converting objects";
                ConvertedObjects = SpeckleCore.Converter.Deserialise(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);
            });
        }
Exemplo n.º 3
0
        public static async Task <SpeckleStream> GetStream(string restApi, string apiToken, string streamId, ISpeckleAppMessenger messenger)
        {
            SpeckleApiClient myClient = new SpeckleApiClient()
            {
                BaseUrl = restApi, AuthToken = apiToken
            };
            var queryString = "fields=streamId,name";

            try
            {
                var response = await myClient.StreamGetAsync(streamId, queryString);

                if (response != null && response.Success.HasValue && response.Success.Value &&
                    response.Resource != null && response.Resource.StreamId.Equals(streamId, StringComparison.InvariantCultureIgnoreCase))
                {
                    return(response.Resource);
                }
            }
            catch (SpeckleException se)
            {
                if (messenger != null)
                {
                    messenger.Message(MessageIntent.Display, MessageLevel.Error, "Unable to access stream information for " + streamId);
                    var context = new List <string>()
                    {
                        "Unable to access stream information for " + streamId,
                        "StatusCode=" + se.StatusCode, "ResponseData=" + se.Response, "Message=" + se.Message, "BaseUrl=" + restApi,
                        "Endpoint=StreamGetAsync", "QueryString=\"" + queryString + "\""
                    };
                    if (se is SpeckleException <ResponseBase> && ((SpeckleException <ResponseBase>)se).Result != null)
                    {
                        var responseJson = ((SpeckleException <ResponseBase>)se).Result.ToJson();
                        context.Add("ResponseJson=" + responseJson);
                    }
                    messenger.Message(MessageIntent.TechnicalLog, MessageLevel.Error, se, context.ToArray());
                }
            }
            catch (Exception ex)
            {
                if (messenger != null)
                {
                    messenger.Message(MessageIntent.Display, MessageLevel.Error, "Unable to access stream information for " + streamId);
                    messenger.Message(MessageIntent.TechnicalLog, MessageLevel.Error, ex, "Unable to access stream information",
                                      "BaseUrl=" + restApi, "StreamId" + streamId);
                }
            }
            return(null);
        }
Exemplo n.º 4
0
        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;
            }
        }
Exemplo n.º 5
0
    //Initialize receiver
    IEnumerator InitAsync(string inStreamID, string URL)
    {
        Client = new SpeckleApiClient(URL);

        //Assign events
        Client.OnReady     += Client_OnReady;
        Client.OnLogData   += Client_OnLogData;
        Client.OnWsMessage += Client_OnWsMessage;
        Client.OnError     += Client_OnError;

        //make sure convereter is loaded
        var hack = new ConverterHack();

        SpeckleObjects = new List <SpeckleObject>();

        StreamID = inStreamID;
        Client.IntializeReceiver(StreamID, "UnityTest", "Unity", "UnityGuid", authToken);

        var streamGetResponse = Client.StreamGetAsync(StreamID, null);

        while (!streamGetResponse.IsCompleted)
        {
            yield return(null);
        }

        Client.Stream = streamGetResponse.Result.Resource;

        if (rootGameObject == null)
        {
            rootGameObject = new GameObject(Client.Stream.Name);
        }

        //call event on SpeckleManager to allow users to do their own thing when a stream is created
        transform.GetComponent <UnitySpeckle>().OnReceiverCreated.Invoke(this);

        UpdateGlobal();
    }
Exemplo n.º 6
0
        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);
        }
Exemplo n.º 7
0
        /// <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>&nbsp;&nbsp;";

                //  foreach( var err in errors)
                //  {
                //    errorMsg += $"<code>{err.Message}</code>&nbsp;";
                //  }

                //  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();
        }
Exemplo n.º 8
0
        /// <summary>
        /// Initializes sender.
        /// </summary>
        /// <param name="streamID">Stream ID of stream. If no stream ID is given, a new stream is created.</param>
        /// <param name="streamName">Stream name</param>
        /// <returns>Task</returns>
        public async Task InitializeSender(string streamID = "", string clientID = "", string streamName = "")
        {
            apiClient.AuthToken = apiToken;

            if (string.IsNullOrEmpty(clientID))
            {
                HelperFunctions.tryCatchWithEvents(() =>
                {
                    var streamResponse = apiClient.StreamCreateAsync(new SpeckleStream()).Result;
                    apiClient.Stream   = streamResponse.Resource;
                    apiClient.StreamId = streamResponse.Resource.StreamId;
                },
                                                   "", "Unable to create stream on the server");

                HelperFunctions.tryCatchWithEvents(() =>
                {
                    var clientResponse = apiClient.ClientCreateAsync(new AppClient()
                    {
                        DocumentName = Path.GetFileNameWithoutExtension(GSA.GsaApp.gsaProxy.FilePath),
                        DocumentType = "GSA",
                        Role         = "Sender",
                        StreamId     = this.StreamID,
                        Online       = true,
                    }).Result;
                    apiClient.ClientId = clientResponse.Resource._id;
                }, "", "Unable to create client on the server");
            }
            else
            {
                HelperFunctions.tryCatchWithEvents(() =>
                {
                    var streamResponse = apiClient.StreamGetAsync(streamID, null).Result;

                    apiClient.Stream   = streamResponse.Resource;
                    apiClient.StreamId = streamResponse.Resource.StreamId;
                }, "", "Unable to get stream response");

                HelperFunctions.tryCatchWithEvents(() =>
                {
                    var clientResponse = apiClient.ClientUpdateAsync(clientID, new AppClient()
                    {
                        DocumentName = Path.GetFileNameWithoutExtension(GSA.GsaApp.gsaProxy.FilePath),
                        Online       = true,
                    }).Result;

                    apiClient.ClientId = clientID;
                }, "", "Unable to update client on the server");
            }

            apiClient.Stream.Name = streamName;

            HelperFunctions.tryCatchWithEvents(() =>
            {
                apiClient.SetupWebsocket();
            }, "", "Unable to set up web socket");

            HelperFunctions.tryCatchWithEvents(() =>
            {
                apiClient.JoinRoom("stream", streamID);
            }, "", "Uable to join web socket");
        }
Exemplo n.º 9
0
        static async Task TestStreams(SpeckleApiClient myClient)
        {
            string streamId       = "lol";
            string secondStreamId = "hai";

            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
            };


            myPoint.Properties = new Dictionary <string, object>();
            myPoint.Properties.Add("Really", mySecondPoint);

            myCircle.Properties = new Dictionary <string, object>();
            myCircle.Properties.Add("a property", "Hello!");
            myCircle.Properties.Add("point", myPoint);

            SpeckleStream myStream = new SpeckleStream()
            {
                Name    = "Hello World My Little Stream",
                Objects = new List <SpeckleObject>()
                {
                    myCircle, myPoint
                }
            };

            SpeckleStream secondStream = new SpeckleStream()
            {
                Name    = "Second Little Stream",
                Objects = new List <SpeckleObject>()
                {
                    myCircle, mySecondPoint
                }
            };

            Console.WriteLine();
            try
            {
                Console.WriteLine("Creating a stream.");
                var Response = await myClient.StreamCreateAsync(myStream);

                Console.WriteLine("OK: " + Response.Resource.ToJson());

                streamId = Response.Resource.StreamId;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine();
            try
            {
                Console.WriteLine("Creating a second stream.");
                var Response = await myClient.StreamCreateAsync(secondStream);

                Console.WriteLine("OK: " + Response.Resource.ToJson());

                secondStreamId = Response.Resource.StreamId;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }


            Console.WriteLine();
            try
            {
                Console.WriteLine("Diffing two streams!");
                var Response = await myClient.StreamDiffAsync(streamId, secondStreamId);

                Console.WriteLine("OK: " + Response.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine();
            try
            {
                Console.WriteLine("Getting a stream.");
                var Response = await myClient.StreamGetAsync(streamId, null);

                Console.WriteLine("OK: " + Response.Resource.ToJson());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine();
            try
            {
                Console.WriteLine("Getting a stream's objects.");
                var Response = await myClient.StreamGetObjectsAsync(streamId, null);

                Console.WriteLine("OK: " + Response.Resources.Count);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine();
            try
            {
                Console.WriteLine("Updating a stream.");
                var Response = await myClient.StreamUpdateAsync(streamId, new SpeckleStream()
                {
                    Name = "I hate api testing", ViewerLayers = new List <object>()
                    {
                        new { test = "test" }
                    }
                });

                Console.WriteLine("OK: " + Response.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine();
            try
            {
                Console.WriteLine("Getting a stream field.");
                var Response = await myClient.StreamGetAsync(streamId, "fields=viewerLayers,name,owner");

                Console.WriteLine("OK: " + Response.Resource.ToJson());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine();
            try
            {
                Console.WriteLine("Getting all users's streams.");
                var Response = await myClient.StreamsGetAllAsync();

                Console.WriteLine("OK: " + Response.Resources.Count);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }


            Console.WriteLine();
            try
            {
                Console.WriteLine("Cloning a stream.");
                var Response = await myClient.StreamCloneAsync(streamId);

                Console.WriteLine("OK: " + Response.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine();
            try
            {
                Console.WriteLine("Deleting a stream: " + streamId);
                var Response = await myClient.StreamDeleteAsync(streamId);

                Console.WriteLine("OK: " + Response.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }