public override void UpdateSender(string args)
        {
            var client = JsonConvert.DeserializeObject <dynamic>(args);
            var index  = ClientListWrapper.clients.FindIndex(cl => (string)cl._id == (string)client._id);

            ClientListWrapper.clients[index] = client;

            var myStream = LocalState.FirstOrDefault(st => st.StreamId == (string)client.streamId);

            myStream.Name = (string)client.name;

            Queue.Add(new Action(() =>
            {
                using (Transaction t = new Transaction(CurrentDoc.Document, "Update Speckle Sender"))
                {
                    t.Start();
                    SpeckleStateManager.WriteState(CurrentDoc.Document, LocalState);
                    SpeckleClientsStorageManager.WriteClients(CurrentDoc.Document, ClientListWrapper);
                    t.Commit();
                }
            }));
            Executor.Raise();

            ISelectionFilter filter = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(client.filter), GetFilterType(client.filter.Type.ToString()));

            GetSelectionFilterObjects(filter, client._id.ToString(), client.streamId.ToString());

            SpeckleTelemetry.RecordStreamUpdated("Revit");
        }
        public override void AddSelectionToSender(string args)
        {
            var client = JsonConvert.DeserializeObject <dynamic>(args);

            var selectionIds = CurrentDoc.Selection.GetElementIds().Select(id => CurrentDoc.Document.GetElement(id).UniqueId);

            // LOCAL STATE management
            var spkObjectsToAdd = selectionIds.Select(id =>
            {
                var temp = new SpeckleObject();
                temp.Properties["revitUniqueId"] = id;
                temp.Properties["__type"]        = "Sent Object";
                return(temp);
            });

            var myStream = LocalState.FirstOrDefault(st => st.StreamId == (string)client.streamId);
            var added    = 0;

            foreach (var obj in spkObjectsToAdd)
            {
                var ind = myStream.Objects.FindIndex(o => (string)o.Properties["revitUniqueId"] == (string)obj.Properties["revitUniqueId"]);
                if (ind == -1)
                {
                    myStream.Objects.Add(obj);
                    added++;
                }
            }

            var myClient = ClientListWrapper.clients.FirstOrDefault(cl => (string)cl._id == (string)client._id);

            myClient.objects = JsonConvert.DeserializeObject <dynamic>(JsonConvert.SerializeObject(myStream.Objects));

            // Persist state and clients to revit file
            Queue.Add(new Action(() =>
            {
                using (Transaction t = new Transaction(CurrentDoc.Document, "Adding Speckle Receiver"))
                {
                    t.Start();
                    SpeckleStateManager.WriteState(CurrentDoc.Document, LocalState);
                    SpeckleClientsStorageManager.WriteClients(CurrentDoc.Document, ClientListWrapper);
                    t.Commit();
                }
            }));
            Executor.Raise();

            if (added != 0)
            {
                NotifyUi("update-client", JsonConvert.SerializeObject(new
                {
                    _id     = client._id,
                    expired = true,
                    objects = myClient.objects,
                    message = String.Format("You have added {0} objects from this sender.", added)
                }));
            }
            //throw new NotImplementedException();
        }
        public override void RemoveSelectionFromSender(string args)
        {
            var client   = JsonConvert.DeserializeObject <dynamic>(args);
            var myStream = LocalState.FirstOrDefault(st => st.StreamId == (string)client.streamId);
            var myClient = ClientListWrapper.clients.FirstOrDefault(cl => (string)cl._id == (string)client._id);

            var selectionIds = CurrentDoc.Selection.GetElementIds().Select(id => CurrentDoc.Document.GetElement(id).UniqueId);
            var removed      = 0;

            foreach (var revitUniqueId in selectionIds)
            {
                var index = myStream.Objects.FindIndex(o => (string)o.Properties["revitUniqueId"] == revitUniqueId);
                if (index == -1)
                {
                    continue;
                }
                myStream.Objects.RemoveAt(index);
                removed++;
            }

            myClient.objects = JsonConvert.DeserializeObject <dynamic>(JsonConvert.SerializeObject(myStream.Objects));

            // Persist state and clients to revit file
            Queue.Add(new Action(() =>
            {
                using (Transaction t = new Transaction(CurrentDoc.Document, "Adding Speckle Receiver"))
                {
                    t.Start();
                    SpeckleStateManager.WriteState(CurrentDoc.Document, LocalState);
                    SpeckleClientsStorageManager.WriteClients(CurrentDoc.Document, ClientListWrapper);
                    t.Commit();
                }
            }));
            Executor.Raise();

            if (removed != 0)
            {
                NotifyUi("update-client", JsonConvert.SerializeObject(new
                {
                    _id     = client._id,
                    expired = true,
                    objects = myClient.objects,
                    message = String.Format("You have removed {0} objects from this sender.", removed)
                }));
            }
        }
        public override void AddSender(string args)
        {
            var client = JsonConvert.DeserializeObject <dynamic>(args);

            ClientListWrapper.clients.Add(client);

            // TODO: Add stream to LocalState (do we actually need to??? hm...).
            var myStream = new SpeckleStream()
            {
                StreamId = (string)client.streamId, Objects = new List <SpeckleObject>()
            };

            //foreach( dynamic obj in client.objects )
            //{
            //  var SpkObj = new SpeckleObject() { };
            //  SpkObj.Properties[ "revitUniqueId" ] = obj.id.ToString();
            //  SpkObj.Properties[ "__type" ] = "Sent Object";
            //  myStream.Objects.Add( SpkObj );
            //}

            LocalState.Add(myStream);

            Queue.Add(new Action(() =>
            {
                using (Transaction t = new Transaction(CurrentDoc.Document, "Adding Speckle Sender"))
                {
                    t.Start();
                    SpeckleStateManager.WriteState(CurrentDoc.Document, LocalState);
                    SpeckleClientsStorageManager.WriteClients(CurrentDoc.Document, ClientListWrapper);
                    t.Commit();
                }
            }));
            Executor.Raise();


            ISelectionFilter filter = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(client.filter), GetFilterType(client.filter.Type.ToString()));

            GetSelectionFilterObjects(filter, client._id.ToString(), client.streamId.ToString());

            SpeckleTelemetry.RecordStreamCreated("Revit");
        }
        /// <summary>
        /// Given the filter in use by a stream returns the document elements that match it
        /// </summary>
        /// <returns></returns>
        private IEnumerable <SpeckleObject> GetSelectionFilterObjects(ISelectionFilter filter, string clientId, string streamId)
        {
            var doc = CurrentDoc.Document;
            IEnumerable <SpeckleObject> objects = new List <SpeckleObject>();

            var selectionIds = new List <string>();

            if (filter.Name == "Selection")
            {
                var selFilter = filter as ElementsSelectionFilter;
                selectionIds = selFilter.Selection;
            }
            else if (filter.Name == "Category")
            {
                var catFilter  = filter as ListSelectionFilter;
                var bics       = new List <BuiltInCategory>();
                var categories = Globals.GetCategories(doc);
                IList <ElementFilter> elementFilters = new List <ElementFilter>();

                foreach (var cat in catFilter.Selection)
                {
                    elementFilters.Add(new ElementCategoryFilter(categories[cat].Id));
                }
                LogicalOrFilter categoryFilter = new LogicalOrFilter(elementFilters);

                selectionIds = new FilteredElementCollector(doc)
                               .WhereElementIsNotElementType()
                               .WhereElementIsViewIndependent()
                               .WherePasses(categoryFilter)
                               .Select(x => x.UniqueId).ToList();
            }
            else if (filter.Name == "View")
            {
                var viewFilter = filter as ListSelectionFilter;

                var views = new FilteredElementCollector(doc)
                            .WhereElementIsNotElementType()
                            .OfClass(typeof(View))
                            .Where(x => viewFilter.Selection.Contains(x.Name));

                foreach (var view in views)
                {
                    var ids = new FilteredElementCollector(doc, view.Id)
                              .WhereElementIsNotElementType()
                              .WhereElementIsViewIndependent()
                              .Where(x => x.IsPhysicalElement())
                              .Select(x => x.UniqueId).ToList();

                    selectionIds = selectionIds.Union(ids).ToList();
                }
            }
            else if (filter.Name == "Parameter")
            {
                try
                {
                    var propFilter = filter as PropertySelectionFilter;
                    var query      = new FilteredElementCollector(doc)
                                     .WhereElementIsNotElementType()
                                     .WhereElementIsNotElementType()
                                     .WhereElementIsViewIndependent()
                                     .Where(x => x.IsPhysicalElement())
                                     .Where(fi => fi.LookupParameter(propFilter.PropertyName) != null);

                    propFilter.PropertyValue = propFilter.PropertyValue.ToLowerInvariant();

                    switch (propFilter.PropertyOperator)
                    {
                    case "equals":
                        query = query.Where(fi => GetStringValue(fi.LookupParameter(propFilter.PropertyName)) == propFilter.PropertyValue);
                        break;

                    case "contains":
                        query = query.Where(fi => GetStringValue(fi.LookupParameter(propFilter.PropertyName)).Contains(propFilter.PropertyValue));
                        break;

                    case "is greater than":
                        query = query.Where(fi => UnitUtils.ConvertFromInternalUnits(
                                                fi.LookupParameter(propFilter.PropertyName).AsDouble(),
                                                fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) > double.Parse(propFilter.PropertyValue));
                        break;

                    case "is less than":
                        query = query.Where(fi => UnitUtils.ConvertFromInternalUnits(
                                                fi.LookupParameter(propFilter.PropertyName).AsDouble(),
                                                fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) < double.Parse(propFilter.PropertyValue));
                        break;

                    default:
                        break;
                    }

                    selectionIds = query.Select(x => x.UniqueId).ToList();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            // LOCAL STATE management
            objects = selectionIds.Select(id =>
            {
                var temp = new SpeckleObject();
                temp.Properties["revitUniqueId"] = id;
                temp.Properties["__type"]        = "Sent Object";
                return(temp);
            });


            var myStream = LocalState.FirstOrDefault(st => st.StreamId == streamId);

            myStream.Objects.Clear();
            myStream.Objects.AddRange(objects);

            var myClient = ClientListWrapper.clients.FirstOrDefault(cl => (string)cl._id == (string)clientId);

            myClient.objects = JsonConvert.DeserializeObject <dynamic>(JsonConvert.SerializeObject(myStream.Objects));

            // Persist state and clients to revit file
            Queue.Add(new Action(() =>
            {
                using (Transaction t = new Transaction(CurrentDoc.Document, "Update local storage"))
                {
                    t.Start();
                    SpeckleStateManager.WriteState(CurrentDoc.Document, LocalState);
                    SpeckleClientsStorageManager.WriteClients(CurrentDoc.Document, ClientListWrapper);
                    t.Commit();
                }
            }));
            Executor.Raise();
            var plural = objects.Count() == 1 ? "" : "s";

            if (objects.Count() != 0)
            {
                NotifyUi("update-client", JsonConvert.SerializeObject(new
                {
                    _id     = clientId,
                    expired = true,
                    objects = myClient.objects,
                    //message = $"You have added {objects.Count()} object{plural} to this sender."
                }));
            }

            return(objects);
        }
Exemple #6
0
        public string ProcessRequest(string sRequest)
        {
            Response response;

            try
            {
                response = new Response();
                var request = JsonConvert.DeserializeObject <Request>(sRequest);
                switch (request.Operation)
                {
                case Operation.GetAllLines:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        response.Data = GetLinesAsString();
                    });

                    response.StatusCode = 200;
                    break;

                case Operation.GetAllLineIds:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        response.Data = GetLineIdsAsJSON();
                    });

                    response.StatusCode = 200;
                    break;

                case Operation.GetAllArcIds:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        response.Data = GetArcIdsAsJSON();
                    });

                    response.StatusCode = 200;
                    break;

                case Operation.GetAllPolylineIds:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        response.Data = GetPolylineIdsAsJSON();
                    });

                    response.StatusCode = 200;
                    break;

                case Operation.GetObject:
                    response.Operation = request.Operation;
                    Action a = () =>
                    {
                        response.Data = GetObjectAsJSON(Convert.ToInt64(request.Data));
                    };

                    if (ProcessingMode == 1)
                    {
                        waitingAction = a;
                        requestWaitingSignal.Set();
                        requestCompletedSignal.WaitOne(-1);
                    }
                    else
                    {
                        waitingAction = null;
                        pr.ReportProgress(a);
                    }

                    response.StatusCode = 200;
                    break;

                case Operation.GetFileName:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        response.Data = BoundDocument.Name;
                    });

                    response.StatusCode = 200;
                    break;

                case Operation.LoadClientState:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        response.Data = SpeckleStateManager.ReadState(BoundDocument, Constants.SpeckleAutoCADClientsKey);
                    });
                    response.StatusCode = 200;
                    break;

                case Operation.SaveClientState:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        SpeckleStateManager.WriteState(BoundDocument, Constants.SpeckleAutoCADClientsKey, request.Data);
                    });
                    response.StatusCode = 200;
                    break;

                case Operation.GetDocumentLocation:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        response.Data = BoundDocument.Database.Filename;
                    });

                    response.StatusCode = 200;
                    break;

                case Operation.LoadStreamState:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        response.Data = SpeckleStateManager.ReadState(BoundDocument, Constants.SpeckleAutoCADStreamsKey);
                    });
                    response.StatusCode = 200;
                    break;

                case Operation.SaveStreamState:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        SpeckleStateManager.WriteState(BoundDocument, Constants.SpeckleAutoCADStreamsKey, request.Data);
                    });
                    response.StatusCode = 200;
                    break;

                case Operation.GetSelectionCount:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        response.Data = GetSelectionCountAsJSON();
                    });
                    response.StatusCode = 200;
                    break;

                case Operation.GetSelectedIds:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        response.Data = GetSelectedIdsAsJSON();
                    });
                    response.StatusCode = 200;
                    break;

                case Operation.GetAllAlignmentIds:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        response.Data = GetObjectHandlesAsJSON(typeof(ACD.Alignment));
                    });

                    response.StatusCode = 200;
                    break;

                case Operation.GetAllAlignmentProfileIds:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        response.Data = GetAlignmentProfileIdsAsJSON();
                    });

                    response.StatusCode = 200;
                    break;

                case Operation.GetLengthUnit:
                    response.Operation = request.Operation;
                    pr.ReportProgress(() =>
                    {
                        response.Data = GetLengthUnitAsJSON();
                    });

                    response.StatusCode = 200;
                    break;

                default:
                    response.Data       = string.Empty;
                    response.StatusCode = 400;
                    break;
                }
            }
            catch (System.Exception ex)
            {
                response = new Response
                {
                    Data       = ex.Message.ToString(),
                    StatusCode = 500
                };
            }

            var sResponse = JsonConvert.SerializeObject(response);

            return(sResponse);
        }