Example #1
0
        public BatchConverter()
        {
            var kit = KitManager.GetDefaultKit();

            if (kit == null)
            {
                throw new SpeckleException("Cannot find the Objects Kit. Has it been copied to the Kits folder?");
            }

            if (Globals.RevitDocument != null)
            {
                _converter = kit.LoadConverter(Applications.DynamoRevit);
            }
            else
            {
                _converter = kit.LoadConverter(Applications.DynamoSandbox);
            }

            if (_converter == null)
            {
                throw new SpeckleException("Cannot find the Dynamo converter. Has it been copied to the Kits folder?");
            }

            // if in Revit, we have a doc, injected by the Extension
            if (Globals.RevitDocument != null)
            {
                _converter.SetContextDocument(Globals.RevitDocument);
            }
        }
Example #2
0
        public BatchConverter()
        {
            var kit = KitManager.GetDefaultKit();

            _converter = kit.LoadConverter(Applications.Dynamo);
            if (_converter == null)
            {
                throw new Exception("Cannot find the Dynamo converter, has it been copied to the Kit folder?");
            }
#if REVIT
            _converter.SetContextDocument(Globals.RevitDocument);
#endif
        }
Example #3
0
 private void SetDefaultKitAndConverter()
 {
     Kit = KitManager.GetDefaultKit();
     try
     {
         Converter = Kit.LoadConverter(Applications.Rhino);
         Converter.SetContextDocument(RhinoDoc.ActiveDoc);
     }
     catch
     {
         AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine.");
     }
 }
Example #4
0
 public ExtendSpeckleObjectAsync() : base("Extend Speckle Object Async", "ESOA",
                                          "Extend a current object with key/value pairs", "Speckle 2 Dev", "Async Object Management")
 {
     Kit = KitManager.GetDefaultKit();
     try
     {
         Converter  = Kit.LoadConverter(Applications.Rhino);
         BaseWorker = new ExtendSpeckleObjectWorker(this, Converter);
         Message    = $"{Kit.Name} Kit";
     }
     catch
     {
         AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine.");
     }
 }
Example #5
0
        public void Setup()
        {
            var kits = KitManager.GetDefaultKit();

            converter = (ConverterETABS)kits.LoadConverter(Applications.ETABSv18);
            cOAPI myETABSObject;

            //Can't figure out how to start the program automatically get a port problem ~ so have to start at least one program
            myETABSObject = (ETABSv1.cOAPI)Interaction.GetObject(Class: "CSI.ETABS.API.ETABSObject");
            //cHelper myHelper = new Helper();
            //myETABSObject = myHelper.CreateObjectProgID("CSI.ETABS.API.ETABSObject");
            //myETABSObject.ApplicationStart();
            Model = myETABSObject.SapModel;
            converter.SetContextDocument(Model);
        }
Example #6
0
 public GetObjectValueByKeyAsync() : base("Speckle Object Value by Key Async", "Object K/V A",
                                          "Gets the value of a specific key in a Speckle object.", "Speckle 2 Dev", "Async Object Management")
 {
     Kit = KitManager.GetDefaultKit();
     try
     {
         Converter  = Kit.LoadConverter(Applications.Rhino);
         BaseWorker = new GetObjectValueByKeyWorker(this, Converter);
         Message    = $"{Kit.Name} Kit";
     }
     catch
     {
         AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine.");
     }
 }
Example #7
0
 public CreateSpeckleObjectAsync() : base("Create Speckle Object Async", "CSOA",
                                          "Allows you to create a Speckle object by setting its keys and values.",
                                          "Speckle 2 Dev", "Async Object Management")
 {
     Kit = KitManager.GetDefaultKit();
     try
     {
         Converter  = Kit.LoadConverter(Applications.Rhino);
         BaseWorker = new CreateSpeckleObjectWorker(this, Converter);
         Message    = $"{Kit.Name} Kit";
     }
     catch
     {
         AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine.");
     }
 }
Example #8
0
 public CreateSpeckleObject()
     : base("Create Speckle Object", "CSO",
            "Allows you to create a Speckle object by setting its keys and values.\nIn each individual parameter, you can select between 'item' and 'list' access type via the right-click menu.\n",
            "Speckle 2", "Object Management")
 {
     Kit = KitManager.GetDefaultKit();
     try
     {
         Converter = Kit.LoadConverter(Applications.Rhino);
         Message   = $"{Kit.Name} Kit";
     }
     catch
     {
         AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine.");
     }
 }
 public ExpandSpeckleObjectAsync() : base("Expand Speckle Object Async", "ESOA",
                                          "Allows you to decompose a Speckle object in its constituent parts.",
                                          "Speckle 2 Dev", "Async Object Management")
 {
     Kit = KitManager.GetDefaultKit();
     try
     {
         Converter  = Kit.LoadConverter(Applications.Rhino);
         BaseWorker = new ExpandSpeckleObjectWorker(this, Converter);
         Message    = $"{Kit.Name} Kit";
     }
     catch
     {
         AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine.");
     }
 }
Example #10
0
        public CreateSchemaObject() : base("Create Schema Object", "CsO",
                                           "Allows you to create a Speckle object from a schema class.",
                                           ComponentCategories.PRIMARY_RIBBON, ComponentCategories.OBJECTS)
        {
            Kit = KitManager.GetDefaultKit();
            try
            {
                Converter = Kit.LoadConverter(Applications.Rhino);
                Message   = $"{Kit.Name} Kit";
            }
            catch
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine.");
            }

            Seed = GenerateSeed();
        }
 private void SetDefaultKitAndConverter()
 {
     try
     {
         Kit       = KitManager.GetDefaultKit();
         Converter = Kit.LoadConverter(Applications.Rhino6);
         Converter.SetConverterSettings(SpeckleGHSettings.MeshSettings);
         SpeckleGHSettings.OnMeshSettingsChanged +=
             (sender, args) => Converter.SetConverterSettings(SpeckleGHSettings.MeshSettings);
         Converter.SetContextDocument(RhinoDoc.ActiveDoc);
         foundKit = true;
     }
     catch
     {
         AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No default kit found on this machine.");
         foundKit = false;
     }
 }
Example #12
0
        public override async Task SendStream(StreamState state, ProgressViewModel progress)
        {
            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(Utils.BentleyAppName);
            var streamId  = state.StreamId;
            var client    = state.Client;

            if (Control.InvokeRequired)
            {
                Control.Invoke(new SetContextDelegate(converter.SetContextDocument), new object[] { Session.Instance });
            }
            else
            {
                converter.SetContextDocument(Session.Instance);
            }

            var selectedObjects = new List <Object>();

            if (state.Filter != null)
            {
                if (Control.InvokeRequired)
                {
                    state.SelectedObjectIds = (List <string>)Control.Invoke(new GetObjectsFromFilterDelegate(GetObjectsFromFilter), new object[] { state.Filter, converter, progress });
                }
                else
                {
                    state.SelectedObjectIds = GetObjectsFromFilter(state.Filter, converter, progress);
                }
            }

            if (state.SelectedObjectIds.Count == 0 && !ExportGridLines)
            {
                progress.Report.LogOperationError(new Exception("Zero objects selected; send stopped. Please select some objects, or check that your filter can actually select something."));
                return;
            }

            var commitObj = new Base();

            var units = Units.GetUnitsFromString(ModelUnits).ToLower();

            commitObj["units"] = units;

            var conversionProgressDict = new ConcurrentDictionary <string, int>();

            conversionProgressDict["Conversion"]      = 0;
            Execute.PostToUIThread(() => progress.Max = state.SelectedObjectIds.Count());
            int convertedCount = 0;

            // grab elements from active model
            var objs = new List <Element>();

#if (OPENROADS || OPENRAIL)
            bool convertCivilObject = false;
            var  civObjs            = new List <NamedModelEntity>();

            if (civilElementKeys.Count(x => state.SelectedObjectIds.Contains(x)) > 0)
            {
                if (Control.InvokeRequired)
                {
                    civObjs = (List <NamedModelEntity>)Control.Invoke(new GetCivilObjectsDelegate(GetCivilObjects), new object[] { state });
                }
                else
                {
                    civObjs = GetCivilObjects(state);
                }

                objs = civObjs.Select(x => x.Element).ToList();
                convertCivilObject = true;
            }
            else
            {
                objs = state.SelectedObjectIds.Select(x => Model.FindElementById((ElementId)Convert.ToUInt64(x))).ToList();
            }
#else
            objs = state.SelectedObjectIds.Select(x => Model.FindElementById((ElementId)Convert.ToUInt64(x))).ToList();
#endif

#if (OPENBUILDINGS)
            if (ExportGridLines)
            {
                var converted = ConvertGridLines(converter, progress);

                if (converted == null)
                {
                    progress.Report.LogConversionError(new Exception($"Failed to convert Gridlines."));
                }
                else
                {
                    var containerName = "Grid Systems";

                    if (commitObj[$"@{containerName}"] == null)
                    {
                        commitObj[$"@{containerName}"] = new List <Base>();
                    }
                    ((List <Base>)commitObj[$"@{containerName}"]).Add(converted);

                    // not sure this makes much sense here
                    conversionProgressDict["Conversion"]++;
                    progress.Update(conversionProgressDict);

                    convertedCount++;
                }
            }
#endif

            foreach (var obj in objs)
            {
                if (progress.CancellationTokenSource.Token.IsCancellationRequested)
                {
                    return;
                }

                if (obj == null)
                {
                    progress.Report.Log($"Skipped not found object.");
                    continue;
                }

                var objId   = obj.ElementId.ToString();
                var objType = obj.ElementType;

                if (!converter.CanConvertToSpeckle(obj))
                {
                    progress.Report.Log($"Skipped not supported type: ${objType}. Object ${objId} not sent.");
                    continue;
                }

                // convert obj
                Base   converted     = null;
                string containerName = string.Empty;
                try
                {
                    var levelCache = Model.GetFileLevelCache();
                    var objLevel   = levelCache.GetLevel(obj.LevelId);
                    var layerName  = "Unknown";
                    if (objLevel != null)
                    {
                        layerName = objLevel.Name;
                    }

#if (OPENROADS || OPENRAIL)
                    if (convertCivilObject)
                    {
                        var civilObj = civObjs[objs.IndexOf(obj)];
                        if (Control.InvokeRequired)
                        {
                            converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { civilObj });
                            Control.Invoke((Action)(() => { containerName = civilObj.Name == "" ? "Unnamed" : civilObj.Name; }));
                        }
                        else
                        {
                            converted     = converter.ConvertToSpeckle(civilObj);
                            containerName = civilObj.Name == "" ? "Unnamed" : civilObj.Name;
                        }
                    }
                    else
                    {
                        if (Control.InvokeRequired)
                        {
                            converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { obj });
                        }
                        else
                        {
                            converted = converter.ConvertToSpeckle(obj);
                        }
                        containerName = layerName;
                    }
#else
                    if (Control.InvokeRequired)
                    {
                        converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { obj });
                    }
                    else
                    {
                        converted = converter.ConvertToSpeckle(obj);
                    }

                    containerName = layerName;
#endif
                    if (converted == null)
                    {
                        progress.Report.LogConversionError(new Exception($"Failed to convert object {objId} of type {objType}."));
                        continue;
                    }
                }
                catch
                {
                    progress.Report.LogConversionError(new Exception($"Failed to convert object {objId} of type {objType}."));
                    continue;
                }

                /* TODO: adding the feature data and properties per object
                 * foreach (var key in obj.ExtensionDictionary)
                 * {
                 * converted[key] = obj.ExtensionDictionary.GetUserString(key);
                 * }
                 */

                if (commitObj[$"@{containerName}"] == null)
                {
                    commitObj[$"@{containerName}"] = new List <Base>();
                }
                ((List <Base>)commitObj[$"@{containerName}"]).Add(converted);

                conversionProgressDict["Conversion"]++;
                progress.Update(conversionProgressDict);

                converted.applicationId = objId;

                convertedCount++;
            }

            progress.Report.Merge(converter.Report);

            if (progress.Report.OperationErrorsCount != 0)
            {
                return;
            }

            if (convertedCount == 0)
            {
                progress.Report.LogOperationError(new SpeckleException("Zero objects converted successfully. Send stopped.", false));
                return;
            }

            if (progress.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return;
            }

            Execute.PostToUIThread(() => progress.Max = convertedCount);

            var transports = new List <ITransport>()
            {
                new ServerTransport(client.Account, streamId)
            };

            var commitObjId = await Operations.Send(
                commitObj,
                progress.CancellationTokenSource.Token,
                transports,
                onProgressAction : dict => progress.Update(dict),
                onErrorAction : (err, exception) =>
            {
                progress.Report.LogOperationError(exception);
                progress.CancellationTokenSource.Cancel();
            },
                disposeTransports : true
                );

            var actualCommit = new CommitCreateInput
            {
                streamId          = streamId,
                objectId          = commitObjId,
                branchName        = state.BranchName,
                message           = state.CommitMessage != null ? state.CommitMessage : $"Pushed {convertedCount} elements from {Utils.AppName}.",
                sourceApplication = Utils.BentleyAppName
            };

            if (state.PreviousCommitId != null)
            {
                actualCommit.parents = new List <string>()
                {
                    state.PreviousCommitId
                };
            }

            try
            {
                var commitId = await client.CommitCreate(actualCommit);

                state.PreviousCommitId = commitId;
            }
            catch (Exception e)
            {
                progress.Report.LogOperationError(e);
            }
        }
Example #13
0
        public override async Task <StreamState> ReceiveStream(StreamState state, ProgressViewModel progress)
        {
            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(Utils.BentleyAppName);
            var transport = new ServerTransport(state.Client.Account, state.StreamId);
            var stream    = await state.Client.StreamGet(state.StreamId);

            var previouslyReceivedObjects = state.ReceivedObjects;

            if (converter == null)
            {
                throw new Exception("Could not find any Kit!");
            }

            if (Control.InvokeRequired)
            {
                Control.Invoke(new SetContextDelegate(converter.SetContextDocument), new object[] { Session.Instance });
            }
            else
            {
                converter.SetContextDocument(Session.Instance);
            }

            if (progress.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            /*
             * if (Doc == null)
             * {
             * progress.Report.LogOperationError(new Exception($"No Document is open."));
             * progress.CancellationTokenSource.Cancel();
             * }
             */

            //if "latest", always make sure we get the latest commit when the user clicks "receive"
            Commit commit = null;

            if (state.CommitId == "latest")
            {
                var res = await state.Client.BranchGet(progress.CancellationTokenSource.Token, state.StreamId, state.BranchName, 1);

                commit = res.commits.items.FirstOrDefault();
            }
            else
            {
                commit = await state.Client.CommitGet(progress.CancellationTokenSource.Token, state.StreamId, state.CommitId);
            }
            string referencedObject = commit.referencedObject;

            var commitObject = await Operations.Receive(
                referencedObject,
                progress.CancellationTokenSource.Token,
                transport,
                onProgressAction : dict => progress.Update(dict),
                onTotalChildrenCountKnown : num => Execute.PostToUIThread(() => progress.Max = num),
                onErrorAction : (message, exception) =>
            {
                progress.Report.LogOperationError(exception);
                progress.CancellationTokenSource.Cancel();
            },
                disposeTransports : true
                );

            try
            {
                await state.Client.CommitReceived(new CommitReceivedInput
                {
                    streamId          = stream?.id,
                    commitId          = commit?.id,
                    message           = commit?.message,
                    sourceApplication = Utils.BentleyAppName
                });
            }
            catch
            {
                // Do nothing!
            }
            if (progress.Report.OperationErrorsCount != 0)
            {
                return(state);
            }

            // invoke conversions on the main thread via control
            var flattenedObjects = FlattenCommitObject(commitObject, converter);
            List <ApplicationPlaceholderObject> newPlaceholderObjects;

            if (Control.InvokeRequired)
            {
                newPlaceholderObjects = (List <ApplicationPlaceholderObject>)Control.Invoke(new NativeConversionAndBakeDelegate(ConvertAndBakeReceivedObjects), new object[] { flattenedObjects, converter, state, progress });
            }
            else
            {
                newPlaceholderObjects = ConvertAndBakeReceivedObjects(flattenedObjects, converter, state, progress);
            }

            if (newPlaceholderObjects == null)
            {
                converter.Report.ConversionErrors.Add(new Exception("fatal error: receive cancelled by user"));
                return(null);
            }

            DeleteObjects(previouslyReceivedObjects, newPlaceholderObjects);

            state.ReceivedObjects = newPlaceholderObjects;

            progress.Report.Merge(converter.Report);

            if (progress.Report.OperationErrorsCount != 0)
            {
                return(null); // the commit is being rolled back
            }
            try
            {
                //await state.RefreshStream();
                WriteStateToFile();
            }
            catch (Exception e)
            {
                progress.Report.OperationErrors.Add(e);
            }

            return(state);
        }
        /// <summary>
        /// Receives a stream and bakes into the existing revit file.
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>
        public override async Task <StreamState> ReceiveStream(StreamState state)
        {
            ConversionErrors.Clear();
            OperationErrors.Clear();

            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(ConnectorRevitUtils.RevitAppName);

            converter.SetContextDocument(CurrentDoc.Document);
            var previouslyReceiveObjects = state.ReceivedObjects;

            var transport = new ServerTransport(state.Client.Account, state.Stream.id);

            string referencedObject = state.Commit.referencedObject;

            if (state.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            //if "latest", always make sure we get the latest commit when the user clicks "receive"
            if (state.Commit.id == "latest")
            {
                var res = await state.Client.BranchGet(state.CancellationTokenSource.Token, state.Stream.id, state.Branch.name, 1);

                referencedObject = res.commits.items.FirstOrDefault().referencedObject;
            }

            var commit = state.Commit;



            var commitObject = await Operations.Receive(
                referencedObject,
                state.CancellationTokenSource.Token,
                transport,
                onProgressAction : dict => UpdateProgress(dict, state.Progress),
                onErrorAction : (s, e) =>
            {
                OperationErrors.Add(e);
                state.Errors.Add(e);
                state.CancellationTokenSource.Cancel();
            },
                onTotalChildrenCountKnown : count => Execute.PostToUIThread(() => state.Progress.Maximum = count)
                );

            if (OperationErrors.Count != 0)
            {
                Globals.Notify("Failed to get commit.");
                return(state);
            }

            if (state.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }



            // Bake the new ones.
            Queue.Add(() =>
            {
                using (var t = new Transaction(CurrentDoc.Document, $"Baking stream {state.Stream.name}"))
                {
                    var failOpts = t.GetFailureHandlingOptions();
                    failOpts.SetFailuresPreprocessor(new ErrorEater(converter));
                    failOpts.SetClearAfterRollback(true);
                    t.SetFailureHandlingOptions(failOpts);

                    t.Start();
                    var flattenedObjects = FlattenCommitObject(commitObject, converter);
                    // needs to be set for editing to work
                    converter.SetPreviousContextObjects(previouslyReceiveObjects);
                    // needs to be set for openings in floors and roofs to work
                    converter.SetContextObjects(flattenedObjects.Select(x => new ApplicationPlaceholderObject {
                        applicationId = x.applicationId, NativeObject = x
                    }).ToList());
                    var newPlaceholderObjects = ConvertReceivedObjects(flattenedObjects, converter, state);
                    // receive was cancelled by user
                    if (newPlaceholderObjects == null)
                    {
                        converter.ConversionErrors.Add(new Exception("fatal error: receive cancelled by user"));
                        t.RollBack();
                        return;
                    }

                    DeleteObjects(previouslyReceiveObjects, newPlaceholderObjects);

                    state.ReceivedObjects = newPlaceholderObjects;

                    t.Commit();

                    state.Errors.AddRange(converter.ConversionErrors);
                }
            });

            Executor.Raise();

            while (Queue.Count > 0)
            {
                //wait to let queue finish
            }

            if (converter.ConversionErrors.Any(x => x.Message.Contains("fatal error")))
            {
                // the commit is being rolled back
                return(null);
            }

            try
            {
                await state.RefreshStream();

                WriteStateToFile();
            }
            catch (Exception e)
            {
                WriteStateToFile();
                state.Errors.Add(e);
                Globals.Notify($"Receiving done, but failed to update stream from server.\n{e.Message}");
            }

            return(state);
        }
        public override async Task <StreamState> ReceiveStream(StreamState state)
        {
            Exceptions.Clear();

            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(Utils.AutocadAppName);
            var transport = new ServerTransport(state.Client.Account, state.Stream.id);

            var stream = await state.Client.StreamGet(state.Stream.id);

            if (state.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            string referencedObject = state.Commit.referencedObject;
            string id = state.Commit.id;

            //if "latest", always make sure we get the latest commit when the user clicks "receive"
            if (id == "latest")
            {
                var res = await state.Client.BranchGet(state.CancellationTokenSource.Token, state.Stream.id, state.Branch.name, 1);

                referencedObject = res.commits.items.FirstOrDefault().referencedObject;
                id = res.id;
            }

            //var commit = state.Commit;

            var commitObject = await Operations.Receive(
                referencedObject,
                state.CancellationTokenSource.Token,
                transport,
                onProgressAction : d => UpdateProgress(d, state.Progress),
                onTotalChildrenCountKnown : num => Execute.PostToUIThread(() => state.Progress.Maximum = num),
                onErrorAction : (message, exception) => { Exceptions.Add(exception); }
                );

            if (Exceptions.Count != 0)
            {
                RaiseNotification($"Encountered error: {Exceptions.Last().Message}");
            }

            using (DocumentLock l = Doc.LockDocument())
            {
                using (AcadDb.Transaction tr = Doc.Database.TransactionManager.StartTransaction())
                {
                    // set the context doc for conversion - this is set inside the transaction loop because the converter retrieves this transaction for all db editing when the context doc is set!
                    converter.SetContextDocument(Doc);

                    // keep track of conversion progress here
                    var conversionProgressDict = new ConcurrentDictionary <string, int>();
                    conversionProgressDict["Conversion"] = 0;
                    Execute.PostToUIThread(() => state.Progress.Maximum = state.SelectedObjectIds.Count());
                    Action updateProgressAction = () =>
                    {
                        conversionProgressDict["Conversion"]++;
                        UpdateProgress(conversionProgressDict, state.Progress);
                    };

                    // keep track of any layer name changes for notification here
                    bool changedLayerNames = false;

                    // create a commit layer prefix: all nested layers will be concatenated with this
                    var layerPrefix = DesktopUI.Utils.Formatting.CommitLayer(stream.name, state.Branch.name, id);

                    // delete existing commit layers
                    try
                    {
                        DeleteLayersWithPrefix(layerPrefix, tr);
                    }
                    catch
                    {
                        RaiseNotification($"could not remove existing layers starting with {layerPrefix} before importing new geometry.");
                        state.Errors.Add(new Exception($"could not remove existing layers starting with {layerPrefix} before importing new geometry."));
                    }

                    // flatten the commit object to retrieve children objs
                    var commitObjs = FlattenCommitObject(commitObject, converter, layerPrefix, state);

                    foreach (var commitObj in commitObjs)
                    {
                        // create the object's bake layer if it doesn't already exist
                        Base   obj       = commitObj.Item1;
                        string layerName = commitObj.Item2;

                        if (GetOrMakeLayer(layerName, tr, out string cleanName))
                        {
                            // record if layer name has been modified
                            if (!cleanName.Equals(layerName))
                            {
                                changedLayerNames = true;
                            }

                            // convert obj and add to doc
                            // try catch to prevent memory access violation crash in case a conversion goes wrong
                            try
                            {
                                var converted = converter.ConvertToNative(obj) as AcadDb.Entity;
                                if (converted != null)
                                {
                                    converted.Append(cleanName, tr);
                                }
                                else
                                {
                                    state.Errors.Add(new Exception($"Failed to convert object {obj.id} of type {obj.speckle_type}."));
                                }
                            }
                            catch
                            {
                                state.Errors.Add(new Exception($"Failed to convert object {obj.id} of type {obj.speckle_type}."));
                            }
                        }
                        else
                        {
                            RaiseNotification($"could not create layer {layerName} to bake objects into.");
                            state.Errors.Add(new Exception($"could not create layer {layerName} to bake objects into."));
                        }
                    }

                    // raise any warnings from layer name modification
                    if (changedLayerNames)
                    {
                        state.Errors.Add(new Exception($"Layer names were modified: one or more layers contained invalid characters {Utils.invalidChars}"));
                    }

                    tr.Commit();
                }
            }

            return(state);
        }
Example #16
0
        public override async Task <StreamState> ReceiveStream(StreamState state, ProgressViewModel progress)
        {
            Tracker.TrackPageview(Tracker.RECEIVE);
            Exceptions.Clear();

            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(ConnectorETABSUtils.ETABSAppName);

            converter.SetContextDocument(Model);
            //var previouslyRecieveObjects = state.ReceivedObjects;

            if (converter == null)
            {
                throw new Exception("Could not find any Kit!");
                //RaiseNotification($"Could not find any Kit!");
                progress.CancellationTokenSource.Cancel();
                //return null;
            }


            Tracker.TrackPageview(Tracker.STREAM_GET);
            var stream = await state.Client.StreamGet(state.StreamId);

            if (progress.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            var transport = new ServerTransport(state.Client.Account, state.StreamId);

            Exceptions.Clear();

            Commit commit = null;

            if (state.CommitId == "latest")
            {
                var res = await state.Client.BranchGet(progress.CancellationTokenSource.Token, state.StreamId, state.BranchName, 1);

                commit = res.commits.items.FirstOrDefault();
            }
            else
            {
                commit = await state.Client.CommitGet(progress.CancellationTokenSource.Token, state.StreamId, state.CommitId);
            }
            string referencedObject = commit.referencedObject;

            var commitObject = await Operations.Receive(
                referencedObject,
                progress.CancellationTokenSource.Token,
                transport,
                onProgressAction : dict => progress.Update(dict),
                onErrorAction : (Action <string, Exception>)((s, e) =>
            {
                progress.Report.LogOperationError(e);
                progress.CancellationTokenSource.Cancel();
            }),
                //onTotalChildrenCountKnown: count => Execute.PostToUIThread(() => state.Progress.Maximum = count),
                disposeTransports : true
                );

            if (progress.Report.OperationErrorsCount != 0)
            {
                return(state);
            }

            try
            {
                await state.Client.CommitReceived(new CommitReceivedInput
                {
                    streamId          = stream?.id,
                    commitId          = commit?.id,
                    message           = commit?.message,
                    sourceApplication = ConnectorETABSUtils.ETABSAppName
                });
            }
            catch
            {
                // Do nothing!
            }


            if (progress.Report.OperationErrorsCount != 0)
            {
                return(state);
            }

            if (progress.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            var conversionProgressDict = new ConcurrentDictionary <string, int>();

            conversionProgressDict["Conversion"] = 0;
            //Execute.PostToUIThread(() => state.Progress.Maximum = state.SelectedObjectIds.Count());

            Action updateProgressAction = () =>
            {
                conversionProgressDict["Conversion"]++;
                progress.Update(conversionProgressDict);
            };


            var commitObjs = FlattenCommitObject(commitObject, converter);

            foreach (var commitObj in commitObjs)
            {
                BakeObject(commitObj, state, converter);
                updateProgressAction?.Invoke();
            }



            try
            {
                //await state.RefreshStream();
                WriteStateToFile();
            }
            catch (Exception e)
            {
                progress.Report.LogOperationError(e);
                WriteStateToFile();
                //state.Errors.Add(e);
                //Globals.Notify($"Receiving done, but failed to update stream from server.\n{e.Message}");
            }
            progress.Report.Merge(converter.Report);
            return(state);
        }
Example #17
0
        public override async Task SendStream(StreamState state, ProgressViewModel progress)
        {
            //throw new NotImplementedException();
            var kit = KitManager.GetDefaultKit();
            //var converter = new ConverterETABS();
            var converter = kit.LoadConverter(ConnectorETABSUtils.ETABSAppName);

            converter.SetContextDocument(Model);
            Exceptions.Clear();

            var commitObj = new Base();
            int objCount  = 0;

            if (state.Filter != null)
            {
                state.SelectedObjectIds = GetSelectionFilterObjects(state.Filter);
            }

            var totalObjectCount = state.SelectedObjectIds.Count();

            if (totalObjectCount == 0)
            {
                progress.Report.LogOperationError(new SpeckleException("Zero objects selected; send stopped. Please select some objects, or check that your filter can actually select something.", false));
                return;
            }

            var conversionProgressDict = new ConcurrentDictionary <string, int>();

            conversionProgressDict["Conversion"] = 0;
            progress.Update(conversionProgressDict);


            //if( commitObj["@Stories"] == null)
            //{
            //    commitObj["@Stories"] = converter.ConvertToSpeckle(("Stories", "ETABS"));
            //}

            foreach (var applicationId in state.SelectedObjectIds)
            {
                if (progress.CancellationTokenSource.Token.IsCancellationRequested)
                {
                    return;
                }

                Base   converted     = null;
                string containerName = string.Empty;


                var selectedObjectType = ConnectorETABSUtils.ObjectIDsTypesAndNames
                                         .Where(pair => pair.Key == applicationId)
                                         .Select(pair => pair.Value.Item1).FirstOrDefault();

                if (!converter.CanConvertToSpeckle(selectedObjectType))
                {
                    progress.Report.Log($"Skipped not supported type:  ${selectedObjectType} are not supported");
                    continue;
                }

                Tracker.TrackPageview(Tracker.CONVERT_TOSPECKLE);

                var typeAndName = ConnectorETABSUtils.ObjectIDsTypesAndNames
                                  .Where(pair => pair.Key == applicationId)
                                  .Select(pair => pair.Value).FirstOrDefault();

                converted = converter.ConvertToSpeckle(typeAndName);

                if (converted == null)
                {
                    var exception = new Exception($"Failed to convert object ${applicationId} of type ${selectedObjectType}.");
                    progress.Report.LogConversionError(exception);
                    continue;
                }


                //if (converted != null)
                //{
                //    if (commitObj[selectedObjectType] == null)
                //    {
                //        commitObj[selectedObjectType] = new List<Base>();
                //    }
                //             ((List<Base>)commitObj[selectedObjectType]).Add(converted);
                //}

                //objCount++;
                conversionProgressDict["Conversion"]++;
                progress.Update(conversionProgressDict);
            }

            Base ElementCount = converter.ConvertToSpeckle(("ElementsCount", "ETABS"));

            if (ElementCount.applicationId != null)
            {
                objCount = Convert.ToInt32(ElementCount.applicationId);
            }
            else
            {
                objCount = 0;
            }


            if (commitObj["@Model"] == null)
            {
                commitObj["@Model"] = converter.ConvertToSpeckle(("Model", "ETABS"));
            }

            if (commitObj["AnalysisResults"] == null)
            {
                commitObj["AnalysisResults"] = converter.ConvertToSpeckle(("AnalysisResults", "ETABS"));
            }

            progress.Report.Merge(converter.Report);

            if (objCount == 0)
            {
                progress.Report.LogOperationError(new SpeckleException("Zero objects converted successfully. Send stopped.", false));
                return;
            }

            if (progress.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return;
            }

            var streamId = state.StreamId;
            var client   = state.Client;

            var transports = new List <SCT.ITransport>()
            {
                new SCT.ServerTransport(client.Account, streamId)
            };

            var objectId = await Operations.Send(
                @object : commitObj,
                cancellationToken : progress.CancellationTokenSource.Token,
                transports : transports,
                onProgressAction : dict => progress.Update(dict),
                onErrorAction : (Action <string, Exception>)((s, e) =>
            {
                progress.Report.LogOperationError(e);
                progress.CancellationTokenSource.Cancel();
            }),
                disposeTransports : true
                );


            if (progress.Report.OperationErrorsCount != 0)
            {
                //RaiseNotification($"Failed to send: \n {Exceptions.Last().Message}");
                return;
            }

            var actualCommit = new CommitCreateInput
            {
                streamId          = streamId,
                objectId          = objectId,
                branchName        = state.BranchName,
                message           = state.CommitMessage != null ? state.CommitMessage : $"Pushed {objCount} elements from ETABS.",
                sourceApplication = ConnectorETABSUtils.ETABSAppName
            };

            if (state.PreviousCommitId != null)
            {
                actualCommit.parents = new List <string>()
                {
                    state.PreviousCommitId
                };
            }

            try
            {
                var commitId = await client.CommitCreate(actualCommit);

                //await state.RefreshStream();
                state.PreviousCommitId = commitId;

                //PersistAndUpdateStreamInFile(state);
                //RaiseNotification($"{objCount} objects sent to {state.Stream.name}. 🚀");
            }
            catch (Exception e)
            {
                //Globals.Notify($"Failed to create commit.\n{e.Message}");
                progress.Report.LogOperationError(e);
            }

            //return state;
        }
Example #18
0
        public override async Task <StreamState> SendStream(StreamState state)
        {
            ConversionErrors.Clear();
            OperationErrors.Clear();

            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(Utils.BentleyAppName);

            if (Control.InvokeRequired)
            {
                Control.Invoke(new SetContextDelegate(converter.SetContextDocument), new object[] { Session.Instance });
            }
            else
            {
                converter.SetContextDocument(Session.Instance);
            }

            var streamId = state.Stream.id;
            var client   = state.Client;

            var selectedObjects = new List <Object>();

            if (state.Filter != null)
            {
                if (Control.InvokeRequired)
                {
                    state.SelectedObjectIds = (List <string>)Control.Invoke(new GetObjectsFromFilterDelegate(GetObjectsFromFilter), new object[] { state.Filter, converter });
                }
                else
                {
                    state.SelectedObjectIds = GetObjectsFromFilter(state.Filter, converter);
                }
            }

            if (state.SelectedObjectIds.Count == 0 && !ExportGridLines)
            {
                RaiseNotification("Zero objects selected; send stopped. Please select some objects, or check that your filter can actually select something.");
                return(state);
            }

            var commitObj = new Base();

            var units = Units.GetUnitsFromString(ModelUnits).ToLower();

            commitObj["units"] = units;

            var conversionProgressDict = new ConcurrentDictionary <string, int>();

            conversionProgressDict["Conversion"] = 0;
            Execute.PostToUIThread(() => state.Progress.Maximum = state.SelectedObjectIds.Count());
            int convertedCount = 0;

            // grab elements from active model
            var objs = new List <Element>();

#if (OPENROADS || OPENRAIL)
            bool convertCivilObject = false;
            var  civObjs            = new List <NamedModelEntity>();

            if (civilElementKeys.Count(x => state.SelectedObjectIds.Contains(x)) > 0)
            {
                if (Control.InvokeRequired)
                {
                    civObjs = (List <NamedModelEntity>)Control.Invoke(new GetCivilObjectsDelegate(GetCivilObjects), new object[] { state });
                }
                else
                {
                    civObjs = GetCivilObjects(state);
                }

                objs = civObjs.Select(x => x.Element).ToList();
                convertCivilObject = true;
            }
            else
            {
                objs = state.SelectedObjectIds.Select(x => Model.FindElementById((ElementId)Convert.ToUInt64(x))).ToList();
            }
#else
            objs = state.SelectedObjectIds.Select(x => Model.FindElementById((ElementId)Convert.ToUInt64(x))).ToList();
#endif

#if (OPENBUILDINGS)
            if (ExportGridLines)
            {
                // grab grid lines
                ITFApplication appInst = new TFApplicationList();

                if (0 == appInst.GetProject(0, out ITFLoadableProjectList projList) && projList != null)
                {
                    ITFLoadableProject proj = projList.AsTFLoadableProject;
                    if (null == proj)
                    {
                        return(null);
                    }

                    ITFDrawingGrid drawingGrid = null;
                    if (Control.InvokeRequired)
                    {
                        Control.Invoke((Action)(() => { proj.GetDrawingGrid(false, 0, out drawingGrid); }));
                    }
                    else
                    {
                        proj.GetDrawingGrid(false, 0, out drawingGrid);
                    }

                    if (null == drawingGrid)
                    {
                        return(null);
                    }

                    Base converted;
                    if (Control.InvokeRequired)
                    {
                        converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { drawingGrid });
                    }
                    else
                    {
                        converted = converter.ConvertToSpeckle(drawingGrid);
                    }

                    if (converted != null)
                    {
                        var containerName = "Grid Systems";

                        if (commitObj[$"@{containerName}"] == null)
                        {
                            commitObj[$"@{containerName}"] = new List <Base>();
                        }
                        ((List <Base>)commitObj[$"@{containerName}"]).Add(converted);

                        // not sure this makes much sense here
                        conversionProgressDict["Conversion"]++;
                        UpdateProgress(conversionProgressDict, state.Progress);

                        //gridLine.applicationId = ??;

                        convertedCount++;
                    }
                }
            }
#endif

            foreach (var obj in objs)
            {
                if (state.CancellationTokenSource.Token.IsCancellationRequested)
                {
                    return(null);
                }

                if (obj == null)
                {
                    state.Errors.Add(new Exception($"Failed to find local object."));
                    continue;
                }

                var objId   = obj.ElementId.ToString();
                var objType = obj.ElementType;

                if (!converter.CanConvertToSpeckle(obj))
                {
                    state.Errors.Add(new Exception($"Objects of type ${objType} are not supported"));
                    continue;
                }

                // convert obj
                // try catch to prevent memory access violation crash in case a conversion goes wrong
                Base   converted     = null;
                string containerName = string.Empty;
                try
                {
                    var levelCache = Model.GetFileLevelCache();
                    var objLevel   = levelCache.GetLevel(obj.LevelId);
                    var layerName  = "Unknown";
                    if (objLevel != null)
                    {
                        layerName = objLevel.Name;
                    }

#if (OPENROADS || OPENRAIL)
                    if (convertCivilObject)
                    {
                        var civilObj = civObjs[objs.IndexOf(obj)];
                        if (Control.InvokeRequired)
                        {
                            converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { civilObj });
                            Control.Invoke((Action)(() => { containerName = civilObj.Name == "" ? "Unnamed" : civilObj.Name; }));
                        }
                        else
                        {
                            converted     = converter.ConvertToSpeckle(civilObj);
                            containerName = civilObj.Name == "" ? "Unnamed" : civilObj.Name;
                        }
                    }
                    else
                    {
                        if (Control.InvokeRequired)
                        {
                            converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { obj });
                        }
                        else
                        {
                            converted = converter.ConvertToSpeckle(obj);
                        }
                        containerName = layerName;
                    }
#else
                    if (Control.InvokeRequired)
                    {
                        converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { obj });
                    }
                    else
                    {
                        converted = converter.ConvertToSpeckle(obj);
                    }

                    containerName = layerName;
#endif
                    if (converted == null)
                    {
                        state.Errors.Add(new Exception($"Failed to convert object ${objId} of type ${objType}."));
                        continue;
                    }
                }
                catch
                {
                    state.Errors.Add(new Exception($"Failed to convert object {objId} of type {objType}."));
                    continue;
                }

                /* TODO: adding the feature data and properties per object
                 * foreach (var key in obj.ExtensionDictionary)
                 * {
                 * converted[key] = obj.ExtensionDictionary.GetUserString(key);
                 * }
                 */

                if (commitObj[$"@{containerName}"] == null)
                {
                    commitObj[$"@{containerName}"] = new List <Base>();
                }
                ((List <Base>)commitObj[$"@{containerName}"]).Add(converted);

                conversionProgressDict["Conversion"]++;
                UpdateProgress(conversionProgressDict, state.Progress);

                converted.applicationId = objId;

                convertedCount++;
            }

            Execute.PostToUIThread(() => state.Progress.Maximum = convertedCount);

            var transports = new List <ITransport>()
            {
                new ServerTransport(client.Account, streamId)
            };

            var commitObjId = await Operations.Send(
                commitObj,
                state.CancellationTokenSource.Token,
                transports,
                onProgressAction : dict => UpdateProgress(dict, state.Progress),
                onErrorAction : (err, exception) => { Exceptions.Add(exception); }
                );

            if (Exceptions.Count != 0)
            {
                RaiseNotification($"Failed to send: \n {Exceptions.Last().Message}");
                return(null);
            }

            if (convertedCount > 0)
            {
                var actualCommit = new CommitCreateInput
                {
                    streamId          = streamId,
                    objectId          = commitObjId,
                    branchName        = state.Branch.name,
                    message           = state.CommitMessage != null ? state.CommitMessage : $"Pushed {convertedCount} elements from {Utils.AppName}.",
                    sourceApplication = Utils.BentleyAppName
                };

                if (state.PreviousCommitId != null)
                {
                    actualCommit.parents = new List <string>()
                    {
                        state.PreviousCommitId
                    };
                }

                try
                {
                    var commitId = await client.CommitCreate(actualCommit);

                    await state.RefreshStream();

                    state.PreviousCommitId = commitId;

                    try
                    {
                        PersistAndUpdateStreamInFile(state);
                    }
                    catch (Exception e)
                    {
                    }
                    RaiseNotification($"{convertedCount} objects sent to {state.Stream.name}.");
                }
                catch (Exception e)
                {
                    Globals.Notify($"Failed to create commit.\n{e.Message}");
                    state.Errors.Add(e);
                }
            }
            else
            {
                Globals.Notify($"Did not create commit: no objects could be converted.");
            }

            return(state);
        }
Example #19
0
        public override async Task <StreamState> ReceiveStream(StreamState state)
        {
            ConversionErrors.Clear();
            OperationErrors.Clear();

            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(Utils.BentleyAppName);

            if (converter == null)
            {
                RaiseNotification($"Could not find any Kit!");
                state.CancellationTokenSource.Cancel();
                return(null);
            }

            if (Control.InvokeRequired)
            {
                Control.Invoke(new SetContextDelegate(converter.SetContextDocument), new object[] { Session.Instance });
            }
            else
            {
                converter.SetContextDocument(Session.Instance);
            }

            var previouslyReceiveObjects = state.ReceivedObjects;

            var transport = new ServerTransport(state.Client.Account, state.Stream.id);

            string referencedObject = state.Commit.referencedObject;

            if (state.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            //if "latest", always make sure we get the latest commit when the user clicks "receive"
            if (state.Commit.id == "latest")
            {
                var res = await state.Client.BranchGet(state.CancellationTokenSource.Token, state.Stream.id, state.Branch.name, 1);

                referencedObject = res.commits.items.FirstOrDefault().referencedObject;
            }

            var commit = state.Commit;

            var commitObject = await Operations.Receive(
                referencedObject,
                state.CancellationTokenSource.Token,
                transport,
                onProgressAction : dict => UpdateProgress(dict, state.Progress),
                onErrorAction : (s, e) =>
            {
                OperationErrors.Add(e);
                state.Errors.Add(e);
                state.CancellationTokenSource.Cancel();
            },
                onTotalChildrenCountKnown : count => Execute.PostToUIThread(() => state.Progress.Maximum = count)
                );

            if (OperationErrors.Count != 0)
            {
                Globals.Notify("Failed to get commit.");
                return(state);
            }

            if (state.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            var flattenedObjects = FlattenCommitObject(commitObject, converter);

            List <ApplicationPlaceholderObject> newPlaceholderObjects;

            if (Control.InvokeRequired)
            {
                newPlaceholderObjects = (List <ApplicationPlaceholderObject>)Control.Invoke(new NativeConversionAndBakeDelegate(ConvertAndBakeReceivedObjects), new object[] { flattenedObjects, converter, state });
            }
            else
            {
                newPlaceholderObjects = ConvertAndBakeReceivedObjects(flattenedObjects, converter, state);
            }

            // receive was cancelled by user
            if (newPlaceholderObjects == null)
            {
                converter.Report.ConversionErrors.Add(new Exception("fatal error: receive cancelled by user"));
                return(null);
            }

            DeleteObjects(previouslyReceiveObjects, newPlaceholderObjects);

            state.ReceivedObjects = newPlaceholderObjects;

            state.Errors.AddRange(converter.Report.ConversionErrors);

            if (converter.Report.ConversionErrors.Any(x => x.Message.Contains("fatal error")))
            {
                // the commit is being rolled back
                return(null);
            }

            try
            {
                await state.RefreshStream();

                WriteStateToFile();
            }
            catch (Exception e)
            {
                WriteStateToFile();
                state.Errors.Add(e);
                Globals.Notify($"Receiving done, but failed to update stream from server.\n{e.Message}");
            }

            return(state);
        }
        public override async Task <StreamState> ReceiveStream(StreamState state)
        {
            if (Doc == null)
            {
                state.Errors.Add(new Exception($"No Document is open."));
                return(null);
            }

            Exceptions.Clear();

            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(Utils.AutocadAppName);
            var transport = new ServerTransport(state.Client.Account, state.Stream.id);

            var stream = await state.Client.StreamGet(state.Stream.id);

            if (state.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            string referencedObject = state.Commit.referencedObject;

            var commitId  = state.Commit.id;
            var commitMsg = state.Commit.message;

            //if "latest", always make sure we get the latest commit when the user clicks "receive"
            if (commitId == "latest")
            {
                var res = await state.Client.BranchGet(state.CancellationTokenSource.Token, state.Stream.id, state.Branch.name, 1);

                var commit = res.commits.items.FirstOrDefault();
                commitId         = commit.id;
                commitMsg        = commit.message;
                referencedObject = commit.referencedObject;
            }

            var commitObject = await Operations.Receive(
                referencedObject,
                state.CancellationTokenSource.Token,
                transport,
                onProgressAction : d => UpdateProgress(d, state.Progress),
                onTotalChildrenCountKnown : num => Execute.PostToUIThread(() => state.Progress.Maximum = num),
                onErrorAction : (message, exception) => { Exceptions.Add(exception); },
                disposeTransports : true
                );

            try
            {
                await state.Client.CommitReceived(new CommitReceivedInput
                {
                    streamId          = stream.id,
                    commitId          = commitId,
                    message           = commitMsg,
                    sourceApplication = Utils.AutocadAppName
                });
            }
            catch
            {
                // Do nothing!
            }
            if (Exceptions.Count != 0)
            {
                RaiseNotification($"Encountered error: {Exceptions.Last().Message}");
            }

            // invoke conversions on the main thread via control
            if (Control.InvokeRequired)
            {
                Control.Invoke(new ConversionDelegate(ConvertCommit), new object[] { commitObject, converter, state, stream, commitId });
            }
            else
            {
                ConvertCommit(commitObject, converter, state, stream, commitId);
            }

            return(state);
        }
    /// <summary>
    /// Converts the Revit elements that have been added to the stream by the user, sends them to
    /// the Server and the local DB, and creates a commit with the objects.
    /// </summary>
    /// <param name="state">StreamState passed by the UI</param>
    public override async Task<StreamState> SendStream(StreamState state)
    {
      ConversionErrors.Clear();
      OperationErrors.Clear();

      var kit = KitManager.GetDefaultKit();
      var converter = kit.LoadConverter(ConnectorRevitUtils.RevitAppName);
      converter.SetContextDocument(CurrentDoc.Document);

      var streamId = state.Stream.id;
      var client = state.Client;

      var convertedObjects = new List<Base>();

      if (state.Filter != null)
      {
        state.Objects = GetSelectionFilterObjects(state.Filter);
      }

      if (state.Objects.Count == 0)
      {
        state.Errors.Add(new Exception("There are zero objects to send. Please create a filter, or set some via selection."));
        return state;
      }

      var commitObject = new Base();

      var conversionProgressDict = new ConcurrentDictionary<string, int>();
      conversionProgressDict["Conversion"] = 0;
      Execute.PostToUIThread(() => state.Progress.Maximum = state.Objects.Count());
      var convertedCount = 0;

      var placeholders = new List<Base>();

      converter.SetContextObjects(state.Objects.Select(obj => new ApplicationPlaceholderObject { applicationId = obj.applicationId }).ToList());
      foreach (var obj in state.Objects)
      {
        try
        {
          RevitElement revitElement = null;
          if (obj.applicationId != null)
          {
            revitElement = CurrentDoc.Document.GetElement(obj.applicationId);
          }

          if (revitElement == null)
          {
            continue;
          }

          if (!converter.CanConvertToSpeckle(revitElement))
          {
            state.Errors.Add(new Exception($"Skipping {revitElement.GetType()}, not supported"));
            continue;
          }



          var conversionResult = converter.ConvertToSpeckle(revitElement);

          conversionProgressDict["Conversion"]++;
          UpdateProgress(conversionProgressDict, state.Progress);

          placeholders.Add(new ApplicationPlaceholderObject { applicationId = obj.applicationId, ApplicationGeneratedId = obj.applicationId });

          convertedCount++;



          //hosted elements will be returned as `null` by the ConvertToSpeckle method 
          //since they are handled when converting their parents
          if (conversionResult != null)
          {
            var category = $"@{revitElement.Category.Name}";
            if (commitObject[category] == null)
            {
              commitObject[category] = new List<Base>();
            }
             ((List<Base>)commitObject[category]).Add(conversionResult);
          }

        }
        catch (Exception e)
        {
          state.Errors.Add(e);
        }

        //var level = (Level) CurrentDoc.Document.GetElement(revitElement.LevelId);

        //if(commitObject[$"@{level.Name}"] == null)
        //{
        //  commitObject[$"@{level.Name}"] = new Base
        //  {
        //    ["@objects"] = new List<Base>(),
        //    ["elevation"] = level.Elevation, // TODO Cast! 
        //  };
        //}

      }

      if (converter.ConversionErrors.Count != 0)
      {
        // TODO: Get rid of the custom Error class. It's not needed.
        ConversionErrors.AddRange(converter.ConversionErrors.Select(x => new Exception($"{x.Message}\n{x.details}")));
        state.Errors.AddRange(converter.ConversionErrors.Select(x => new Exception($"{x.Message}\n{x.details}")));
      }

      if (convertedCount == 0)
      {
        Globals.Notify("Failed to convert any objects. Push aborted.");
        return state;
      }

      Execute.PostToUIThread(() => state.Progress.Maximum = (int)commitObject.GetTotalChildrenCount());

      if (state.CancellationTokenSource.Token.IsCancellationRequested)
      {
        return state;
      }

      var transports = new List<ITransport>() { new ServerTransport(client.Account, streamId) };

      var objectId = await Operations.Send(
        @object: commitObject,
        cancellationToken: state.CancellationTokenSource.Token,
        transports: transports,
        onProgressAction: dict => UpdateProgress(dict, state.Progress),
        onErrorAction: (s, e) =>
        {
          OperationErrors.Add(e); // TODO!
          state.Errors.Add(e);
          state.CancellationTokenSource.Cancel();
        }
        );

      if (OperationErrors.Count != 0)
      {
        Globals.Notify("Failed to send.");
        state.Errors.AddRange(OperationErrors);
        return state;
      }

      if (state.CancellationTokenSource.Token.IsCancellationRequested)
      {
        return null;
      }

      var actualCommit = new CommitCreateInput()
      {
        streamId = streamId,
        objectId = objectId,
        branchName = state.Branch.name,
        message = state.CommitMessage != null ? state.CommitMessage : $"Sent {convertedCount} objects from {ConnectorRevitUtils.RevitAppName}."
      };

      if (state.PreviousCommitId != null) { actualCommit.previousCommitIds = new List<string>() { state.PreviousCommitId }; }

      try
      {
        var res = await client.CommitCreate(actualCommit);

        var updatedStream = await client.StreamGet(streamId);
        state.Branches = updatedStream.branches.items;
        state.Stream.name = updatedStream.name;
        state.Stream.description = updatedStream.description;

        WriteStateToFile();
        RaiseNotification($"{convertedCount} objects sent to Speckle 🚀");
      }
      catch (Exception e)
      {
        state.Errors.Add(e);
        Globals.Notify($"Failed to create commit.\n{e.Message}");
      }

      return state;
    }
Example #22
0
        public override async Task SendStream(StreamState state, ProgressViewModel progress)
        {
            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(Utils.AutocadAppName);
            var streamId  = state.StreamId;
            var client    = state.Client;

            if (state.Filter != null)
            {
                state.SelectedObjectIds = GetObjectsFromFilter(state.Filter, converter);
            }

            // remove deleted object ids
            var deletedElements = new List <string>();

            foreach (var handle in state.SelectedObjectIds)
            {
                if (Doc.Database.TryGetObjectId(Utils.GetHandle(handle), out ObjectId id))
                {
                    if (id.IsErased || id.IsNull)
                    {
                        deletedElements.Add(handle);
                    }
                }
            }
            state.SelectedObjectIds = state.SelectedObjectIds.Where(o => !deletedElements.Contains(o)).ToList();

            if (state.SelectedObjectIds.Count == 0)
            {
                progress.Report.LogOperationError(new Exception("Zero objects selected; send stopped. Please select some objects, or check that your filter can actually select something."));
                return;
            }

            var commitObj = new Base();

            var units = Units.GetUnitsFromString(Doc.Database.Insunits.ToString());

            commitObj["units"] = units;

            var conversionProgressDict = new ConcurrentDictionary <string, int>();

            conversionProgressDict["Conversion"]      = 0;
            Execute.PostToUIThread(() => progress.Max = state.SelectedObjectIds.Count());
            int convertedCount = 0;

            bool renamedlayers = false;

            using (Transaction tr = Doc.Database.TransactionManager.StartTransaction())
            {
                // set the context doc for conversion - this is set inside the transaction loop because the converter retrieves this transaction for all db editing when the context doc is set!
                converter.SetContextDocument(Doc);

                foreach (var autocadObjectHandle in state.SelectedObjectIds)
                {
                    if (progress.CancellationTokenSource.Token.IsCancellationRequested)
                    {
                        return;
                    }

                    // get the db object from id
                    Handle   hn  = Utils.GetHandle(autocadObjectHandle);
                    DBObject obj = hn.GetObject(out string type, out string layer);

                    if (obj == null)
                    {
                        progress.Report.Log($"Skipped not found object: ${autocadObjectHandle}.");
                        continue;
                    }

                    if (!converter.CanConvertToSpeckle(obj))
                    {
                        progress.Report.Log($"Skipped not supported type: ${type}. Object ${obj.Id} not sent.");
                        continue;
                    }

                    // convert obj
                    Base   converted     = null;
                    string containerName = string.Empty;
                    converted = converter.ConvertToSpeckle(obj);
                    if (converted == null)
                    {
                        progress.Report.LogConversionError(new Exception($"Failed to convert object {autocadObjectHandle} of type {type}."));
                        continue;
                    }

                    /* TODO: adding the extension dictionary / xdata per object
                     * foreach (var key in obj.ExtensionDictionary)
                     * {
                     * converted[key] = obj.ExtensionDictionary.GetUserString(key);
                     * }
                     */

                    if (obj is BlockReference)
                    {
                        containerName = "Blocks";
                    }
                    else
                    {
                        // remove invalid chars from layer name
                        string cleanLayerName = Utils.RemoveInvalidDynamicPropChars(layer);
                        containerName = cleanLayerName;
                        if (!cleanLayerName.Equals(layer))
                        {
                            renamedlayers = true;
                        }
                    }

                    if (commitObj[$"@{containerName}"] == null)
                    {
                        commitObj[$"@{containerName}"] = new List <Base>();
                    }
                    ((List <Base>)commitObj[$"@{containerName}"]).Add(converted);

                    conversionProgressDict["Conversion"]++;
                    progress.Update(conversionProgressDict);

                    converted.applicationId = autocadObjectHandle;

                    convertedCount++;
                }
                tr.Commit();
            }

            progress.Report.Merge(converter.Report);

            if (convertedCount == 0)
            {
                progress.Report.LogOperationError(new SpeckleException("Zero objects converted successfully. Send stopped.", false));
                return;
            }

            if (renamedlayers)
            {
                progress.Report.Log("Replaced illegal chars ./ with - in one or more layer names.");
            }

            if (progress.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return;
            }

            Execute.PostToUIThread(() => progress.Max = convertedCount);

            var transports = new List <ITransport>()
            {
                new ServerTransport(client.Account, streamId)
            };

            var commitObjId = await Operations.Send(
                commitObj,
                progress.CancellationTokenSource.Token,
                transports,
                onProgressAction : dict => progress.Update(dict),
                onErrorAction : (err, exception) =>
            {
                progress.Report.LogOperationError(exception);
                progress.CancellationTokenSource.Cancel();
            },
                disposeTransports : true
                );

            if (progress.Report.OperationErrorsCount != 0)
            {
                return;
            }

            var actualCommit = new CommitCreateInput
            {
                streamId          = streamId,
                objectId          = commitObjId,
                branchName        = state.BranchName,
                message           = state.CommitMessage != null ? state.CommitMessage : $"Pushed {convertedCount} elements from {Utils.AppName}.",
                sourceApplication = Utils.AutocadAppName
            };

            if (state.PreviousCommitId != null)
            {
                actualCommit.parents = new List <string>()
                {
                    state.PreviousCommitId
                };
            }

            try
            {
                var commitId = await client.CommitCreate(actualCommit);

                state.PreviousCommitId = commitId;
            }
            catch (Exception e)
            {
                progress.Report.LogOperationError(e);
            }
        }
Example #23
0
        public override async Task <StreamState> ReceiveStream(StreamState state, ProgressViewModel progress)
        {
            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(Utils.AutocadAppName);

            if (converter == null)
            {
                throw new Exception("Could not find any Kit!");
            }
            var transport = new ServerTransport(state.Client.Account, state.StreamId);

            var stream = await state.Client.StreamGet(state.StreamId);

            if (progress.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            if (Doc == null)
            {
                progress.Report.LogOperationError(new Exception($"No Document is open."));
                progress.CancellationTokenSource.Cancel();
            }

            //if "latest", always make sure we get the latest commit when the user clicks "receive"
            Commit commit = null;

            if (state.CommitId == "latest")
            {
                var res = await state.Client.BranchGet(progress.CancellationTokenSource.Token, state.StreamId, state.BranchName, 1);

                commit = res.commits.items.FirstOrDefault();
            }
            else
            {
                commit = await state.Client.CommitGet(progress.CancellationTokenSource.Token, state.StreamId, state.CommitId);
            }
            string referencedObject = commit.referencedObject;

            var commitObject = await Operations.Receive(
                referencedObject,
                progress.CancellationTokenSource.Token,
                transport,
                onProgressAction : dict => progress.Update(dict),
                onTotalChildrenCountKnown : num => Execute.PostToUIThread(() => progress.Max = num),
                onErrorAction : (message, exception) =>
            {
                progress.Report.LogOperationError(exception);
                progress.CancellationTokenSource.Cancel();
            },
                disposeTransports : true
                );

            try
            {
                await state.Client.CommitReceived(new CommitReceivedInput
                {
                    streamId          = stream?.id,
                    commitId          = commit?.id,
                    message           = commit?.message,
                    sourceApplication = Utils.AutocadAppName
                });
            }
            catch
            {
                // Do nothing!
            }
            if (progress.Report.OperationErrorsCount != 0)
            {
                return(state);
            }

            // invoke conversions on the main thread via control
            if (Control.InvokeRequired)
            {
                Control.Invoke(new ConversionDelegate(ConvertCommit), new object[] { commitObject, converter, state, progress, stream, commit.id });
            }
            else
            {
                ConvertCommit(commitObject, converter, state, progress, stream, commit.id);
            }

            return(state);
        }
Example #24
0
        /// <summary>
        /// Converts the Revit elements that have been added to the stream by the user, sends them to
        /// the Server and the local DB, and creates a commit with the objects.
        /// </summary>
        /// <param name="state">StreamState passed by the UI</param>
        public override async Task SendStream(StreamState state, ProgressViewModel progress)
        {
            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(ConnectorRevitUtils.RevitAppName);

            converter.SetContextDocument(CurrentDoc.Document);

            var streamId = state.StreamId;
            var client   = state.Client;

            var selectedObjects = GetSelectionFilterObjects(state.Filter);

            state.SelectedObjectIds = selectedObjects.Select(x => x.UniqueId).ToList();



            if (!selectedObjects.Any())
            {
                progress.Report.LogOperationError(new Exception("There are zero objects to send. Please use a filter, or set some via selection."));
                return;
            }

            converter.SetContextObjects(selectedObjects.Select(x => new ApplicationPlaceholderObject {
                applicationId = x.UniqueId
            }).ToList());

            var commitObject = new Base();

            var conversionProgressDict = new ConcurrentDictionary <string, int>();

            conversionProgressDict["Conversion"] = 0;

            progress.Max = selectedObjects.Count();
            var convertedCount = 0;

            var placeholders = new List <Base>();

            foreach (var revitElement in selectedObjects)
            {
                try
                {
                    if (revitElement == null)
                    {
                        continue;
                    }

                    if (!converter.CanConvertToSpeckle(revitElement))
                    {
                        progress.Report.Log($"Skipped not supported type: {revitElement.GetType()}, name {revitElement.Name}");
                        continue;
                    }

                    if (progress.CancellationTokenSource.Token.IsCancellationRequested)
                    {
                        return;
                    }

                    var conversionResult = converter.ConvertToSpeckle(revitElement);

                    conversionProgressDict["Conversion"]++;
                    progress.Update(conversionProgressDict);


                    placeholders.Add(new ApplicationPlaceholderObject {
                        applicationId = revitElement.UniqueId, ApplicationGeneratedId = revitElement.UniqueId
                    });

                    convertedCount++;

                    //hosted elements will be returned as `null` by the ConvertToSpeckle method
                    //since they are handled when converting their parents
                    if (conversionResult != null)
                    {
                        var category = $"@{revitElement.Category.Name}";
                        if (commitObject[category] == null)
                        {
                            commitObject[category] = new List <Base>();
                        }
                        ((List <Base>)commitObject[category]).Add(conversionResult);
                    }
                }
                catch (Exception e)
                {
                    progress.Report.LogConversionError(e);
                }
            }


            progress.Report.Merge(converter.Report);


            if (convertedCount == 0)
            {
                progress.Report.LogConversionError(new Exception("Zero objects converted successfully. Send stopped."));
                return;
            }

            if (progress.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return;
            }

            var transports = new List <ITransport>()
            {
                new ServerTransport(client.Account, streamId)
            };

            var objectId = await Operations.Send(
                @object : commitObject,
                cancellationToken : progress.CancellationTokenSource.Token,
                transports : transports,
                onProgressAction : dict => progress.Update(dict),
                onErrorAction : (s, e) =>
            {
                progress.Report.LogOperationError(e);
                progress.CancellationTokenSource.Cancel();
            },
                disposeTransports : true
                );

            if (progress.Report.OperationErrorsCount != 0)
            {
                return;
            }

            if (progress.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return;
            }

            var actualCommit = new CommitCreateInput()
            {
                streamId          = streamId,
                objectId          = objectId,
                branchName        = state.BranchName,
                message           = state.CommitMessage != null ? state.CommitMessage : $"Sent {convertedCount} objects from {ConnectorRevitUtils.RevitAppName}.",
                sourceApplication = ConnectorRevitUtils.RevitAppName,
            };

            if (state.PreviousCommitId != null)
            {
                actualCommit.parents = new List <string>()
                {
                    state.PreviousCommitId
                };
            }

            try
            {
                var commitId = await client.CommitCreate(actualCommit);

                //await state.RefreshStream();
                state.PreviousCommitId = commitId;
            }
            catch (Exception e)
            {
                progress.Report.LogOperationError(e);
            }

            //return state;
        }
        /// <summary>
        /// Converts the Revit elements that have been added to the stream by the user, sends them to
        /// the Server and the local DB, and creates a commit with the objects.
        /// </summary>
        /// <param name="state">StreamState passed by the UI</param>
        public override async Task <StreamState> SendStream(StreamState state)
        {
            ConversionErrors.Clear();
            OperationErrors.Clear();

            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(ConnectorRevitUtils.RevitAppName);

            converter.SetContextDocument(CurrentDoc.Document);

            var streamId = state.Stream.id;
            var client   = state.Client;

            var selectedObjects = new List <Element>();

            if (state.Filter != null)
            {
                selectedObjects         = GetSelectionFilterObjects(state.Filter, converter);
                state.SelectedObjectIds = selectedObjects.Select(x => x.UniqueId).ToList();
            }
            else //selection was by cursor
            {
                // TODO: update state by removing any deleted or null object ids
                selectedObjects = state.SelectedObjectIds.Select(x => CurrentDoc.Document.GetElement(x)).Where(x => x != null).ToList();
            }


            if (!selectedObjects.Any())
            {
                state.Errors.Add(new Exception("There are zero objects to send. Please use a filter, or set some via selection."));
                return(state);
            }

            converter.SetContextObjects(selectedObjects.Select(x => new ApplicationPlaceholderObject {
                applicationId = x.UniqueId
            }).ToList());

            var commitObject = new Base();

            var conversionProgressDict = new ConcurrentDictionary <string, int>();

            conversionProgressDict["Conversion"] = 0;
            Execute.PostToUIThread(() => state.Progress.Maximum = selectedObjects.Count());
            var convertedCount = 0;

            var placeholders = new List <Base>();

            foreach (var revitElement in selectedObjects)
            {
                try
                {
                    if (revitElement == null)
                    {
                        continue;
                    }

                    if (!converter.CanConvertToSpeckle(revitElement))
                    {
                        state.Errors.Add(new Exception($"Skipping not supported type: {revitElement.GetType()}, name {revitElement.Name}"));
                        continue;
                    }

                    var conversionResult = converter.ConvertToSpeckle(revitElement);

                    conversionProgressDict["Conversion"]++;
                    UpdateProgress(conversionProgressDict, state.Progress);

                    placeholders.Add(new ApplicationPlaceholderObject {
                        applicationId = revitElement.UniqueId, ApplicationGeneratedId = revitElement.UniqueId
                    });

                    convertedCount++;

                    //hosted elements will be returned as `null` by the ConvertToSpeckle method
                    //since they are handled when converting their parents
                    if (conversionResult != null)
                    {
                        var category = $"@{revitElement.Category.Name}";
                        if (commitObject[category] == null)
                        {
                            commitObject[category] = new List <Base>();
                        }
                        ((List <Base>)commitObject[category]).Add(conversionResult);
                    }
                }
                catch (Exception e)
                {
                    state.Errors.Add(e);
                }
            }

            if (converter.Report.ConversionErrorsCount != 0)
            {
                // TODO: Get rid of the custom Error class. It's not needed.
                ConversionErrors.AddRange(converter.Report.ConversionErrors);
                state.Errors.AddRange(converter.Report.ConversionErrors);
            }

            if (convertedCount == 0)
            {
                Globals.Notify("Zero objects converted successfully. Send stopped.");
                return(state);
            }

            Execute.PostToUIThread(() => state.Progress.Maximum = (int)commitObject.GetTotalChildrenCount());

            if (state.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(state);
            }

            var transports = new List <ITransport>()
            {
                new ServerTransport(client.Account, streamId)
            };

            var objectId = await Operations.Send(
                @object : commitObject,
                cancellationToken : state.CancellationTokenSource.Token,
                transports : transports,
                onProgressAction : dict => UpdateProgress(dict, state.Progress),
                onErrorAction : (s, e) =>
            {
                OperationErrors.Add(e); // TODO!
                state.Errors.Add(e);
                state.CancellationTokenSource.Cancel();
            },
                disposeTransports : true
                );

            if (OperationErrors.Count != 0)
            {
                Globals.Notify("Failed to send.");
                state.Errors.AddRange(OperationErrors);
                return(state);
            }

            if (state.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            var actualCommit = new CommitCreateInput()
            {
                streamId          = streamId,
                objectId          = objectId,
                branchName        = state.Branch.name,
                message           = state.CommitMessage != null ? state.CommitMessage : $"Sent {convertedCount} objects from {ConnectorRevitUtils.RevitAppName}.",
                sourceApplication = ConnectorRevitUtils.RevitAppName,
            };

            if (state.PreviousCommitId != null)
            {
                actualCommit.parents = new List <string>()
                {
                    state.PreviousCommitId
                };
            }

            try
            {
                var commitId = await client.CommitCreate(actualCommit);

                await state.RefreshStream();

                state.PreviousCommitId = commitId;

                WriteStateToFile();
                RaiseNotification($"{convertedCount} objects sent to Speckle 🚀");
            }
            catch (Exception e)
            {
                state.Errors.Add(e);
                Globals.Notify($"Failed to create commit.\n{e.Message}");
            }

            return(state);
        }
    /// <summary>
    /// Receives a stream and bakes into the existing revit file.
    /// </summary>
    /// <param name="state"></param>
    /// <returns></returns>
    public override async Task<StreamState> ReceiveStream(StreamState state)
    {
      ConversionErrors.Clear();
      OperationErrors.Clear();

      var kit = KitManager.GetDefaultKit();
      var converter = kit.LoadConverter(ConnectorRevitUtils.RevitAppName);
      converter.SetContextDocument(CurrentDoc.Document);
      var previouslyReceiveObjects = state.ReceivedObjects;

      var transport = new ServerTransport(state.Client.Account, state.Stream.id);

      string referencedObject = state.Commit.referencedObject;

      //if "latest", always make sure we get the latest commit when the user clicks "receive"
      if (state.Commit.id == "latest")
      {
        var res = await state.Client.BranchGet(state.CancellationTokenSource.Token, state.Stream.id, state.Branch.name, 1);
        referencedObject = res.commits.items.FirstOrDefault().referencedObject;
      }

      var commit = state.Commit;

      if (state.CancellationTokenSource.Token.IsCancellationRequested)
      {
        return null;
      }

      var commitObject = await Operations.Receive(
          referencedObject,
          state.CancellationTokenSource.Token,
          transport,
          onProgressAction: dict => UpdateProgress(dict, state.Progress),
          onErrorAction: (s, e) =>
          {
            OperationErrors.Add(e);
            state.Errors.Add(e);
            state.CancellationTokenSource.Cancel();
          },
          onTotalChildrenCountKnown: count => Execute.PostToUIThread(() => state.Progress.Maximum = count)
          );

      if (OperationErrors.Count != 0)
      {
        Globals.Notify("Failed to get commit.");
        return state;
      }

      if (state.CancellationTokenSource.Token.IsCancellationRequested)
      {
        return null;
      }

      UpdateProgress(new ConcurrentDictionary<string, int>() { ["Converting"] = 1 }, state.Progress);

      // Bake the new ones.
      Queue.Add(() =>
      {
        using (var t = new Transaction(CurrentDoc.Document, $"Baking stream {state.Stream.name}"))
        {
          t.Start();

          var flattenedObjects = FlattenCommitObject(commitObject, converter);
          // needs to be set for editing to work 
          converter.SetPreviousContextObjects(previouslyReceiveObjects);
          // needs to be set for openings in floors and roofs to work
          converter.SetContextObjects(flattenedObjects.Select(x => new ApplicationPlaceholderObject { applicationId = x.applicationId, NativeObject = x }).ToList());
          var newPlaceholderObjects = ConvertReceivedObjects(flattenedObjects, converter, state);

          DeleteObjects(previouslyReceiveObjects, newPlaceholderObjects);

          state.ReceivedObjects = newPlaceholderObjects;
          state.Errors.AddRange(converter.ConversionErrors.Select(e => new Exception($"{e.message}: {e.details}")));

          t.Commit();
        }
      });

      Executor.Raise();

      try
      {
        var updatedStream = await state.Client.StreamGet(state.Stream.id);
        state.Branches = updatedStream.branches.items;
        state.Stream.name = updatedStream.name;
        state.Stream.description = updatedStream.description;

        WriteStateToFile();
      }
      catch (Exception e)
      {
        WriteStateToFile();
        state.Errors.Add(e);
        Globals.Notify($"Receiving done, but failed to update stream from server.\n{e.Message}");
      }

      return state;
    }
        public override async Task <StreamState> SendStream(StreamState state)
        {
            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(Utils.AutocadAppName);

            converter.SetContextDocument(Doc);

            var streamId = state.Stream.id;
            var client   = state.Client;

            if (state.Filter != null)
            {
                state.SelectedObjectIds = GetObjectsFromFilter(state.Filter);
            }
            if (state.SelectedObjectIds.Count == 0)
            {
                RaiseNotification("Zero objects selected; send stopped. Please select some objects, or check that your filter can actually select something.");
                return(state);
            }

            var commitObj = new Base();

            var units = Units.GetUnitsFromString(Doc.Database.Insunits.ToString());

            commitObj["units"] = units;

            var conversionProgressDict = new ConcurrentDictionary <string, int>();

            conversionProgressDict["Conversion"] = 0;
            Execute.PostToUIThread(() => state.Progress.Maximum = state.SelectedObjectIds.Count());
            int  convertedCount = 0;
            bool renamedlayers  = false;

            foreach (var autocadObjectHandle in state.SelectedObjectIds)
            {
                if (state.CancellationTokenSource.Token.IsCancellationRequested)
                {
                    return(null);
                }

                // get the db object from id
                AcadDb.Handle   hn             = new AcadDb.Handle(Convert.ToInt64(autocadObjectHandle, 16));
                AcadDb.DBObject obj            = hn.GetObject(out string type, out string layer);
                string          cleanLayerName = Utils.RemoveInvalidDynamicPropChars(layer);
                if (!cleanLayerName.Equals(layer))
                {
                    renamedlayers = true;
                }

                if (obj == null)
                {
                    state.Errors.Add(new Exception($"Failed to find local object ${autocadObjectHandle}."));
                    continue;
                }

                if (!converter.CanConvertToSpeckle(obj))
                {
                    state.Errors.Add(new Exception($"Objects of type ${type} are not supported"));
                    continue;
                }

                // convert geo to speckle base
                if (!converter.CanConvertToSpeckle(obj))
                {
                    state.Errors.Add(new Exception($"Skipping object {autocadObjectHandle}, {obj.GetType()} type not supported"));
                    continue;
                }
                Base converted = converter.ConvertToSpeckle(obj);

                if (converted == null)
                {
                    state.Errors.Add(new Exception($"Failed to convert object ${autocadObjectHandle} of type ${type}."));
                    continue;
                }

                conversionProgressDict["Conversion"]++;
                UpdateProgress(conversionProgressDict, state.Progress);

                converted.applicationId = autocadObjectHandle;

                /* TODO: adding the extension dictionary / xdata per object
                 * foreach (var key in obj.ExtensionDictionary)
                 * {
                 * converted[key] = obj.ExtensionDictionary.GetUserString(key);
                 * }
                 */

                if (commitObj[$"@{cleanLayerName}"] == null)
                {
                    commitObj[$"@{cleanLayerName}"] = new List <Base>();
                }

                ((List <Base>)commitObj[$"@{cleanLayerName}"]).Add(converted);
                convertedCount++;
            }

            if (renamedlayers)
            {
                RaiseNotification("Replaced illegal chars ./ with - in one or more layer names.");
            }

            if (state.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            Execute.PostToUIThread(() => state.Progress.Maximum = convertedCount);

            var transports = new List <ITransport>()
            {
                new ServerTransport(client.Account, streamId)
            };

            var commitObjId = await Operations.Send(
                commitObj,
                state.CancellationTokenSource.Token,
                transports,
                onProgressAction : dict => UpdateProgress(dict, state.Progress),
                onErrorAction : (err, exception) => { Exceptions.Add(exception); }
                );

            if (Exceptions.Count != 0)
            {
                RaiseNotification($"Failed to send: \n {Exceptions.Last().Message}");
                return(null);
            }

            var actualCommit = new CommitCreateInput
            {
                streamId          = streamId,
                objectId          = commitObjId,
                branchName        = state.Branch.name,
                message           = state.CommitMessage != null ? state.CommitMessage : $"Pushed {convertedCount} elements from AutoCAD.",
                sourceApplication = Utils.AutocadAppName
            };

            if (state.PreviousCommitId != null)
            {
                actualCommit.parents = new List <string>()
                {
                    state.PreviousCommitId
                };
            }

            try
            {
                var commitId = await client.CommitCreate(actualCommit);

                await state.RefreshStream();

                state.PreviousCommitId = commitId;

                PersistAndUpdateStreamInFile(state);
                RaiseNotification($"{convertedCount} objects sent to {state.Stream.name}.");
            }
            catch (Exception e)
            {
                Globals.Notify($"Failed to create commit.\n{e.Message}");
                state.Errors.Add(e);
            }

            return(state);
        }
Example #28
0
        /// <summary>
        /// Receives a stream and bakes into the existing revit file.
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>
        public override async Task <StreamState> ReceiveStream(StreamState state, ProgressViewModel progress)
        {
            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(ConnectorRevitUtils.RevitAppName);

            converter.SetContextDocument(CurrentDoc.Document);
            var previouslyReceiveObjects = state.ReceivedObjects;

            var transport = new ServerTransport(state.Client.Account, state.StreamId);

            var stream = await state.Client.StreamGet(state.StreamId);

            if (progress.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            Commit myCommit = null;

            //if "latest", always make sure we get the latest commit when the user clicks "receive"
            if (state.CommitId == "latest")
            {
                var res = await state.Client.BranchGet(progress.CancellationTokenSource.Token, state.StreamId, state.BranchName, 1);

                myCommit = res.commits.items.FirstOrDefault();
            }
            else
            {
                myCommit = await state.Client.CommitGet(progress.CancellationTokenSource.Token, state.StreamId, state.CommitId);
            }
            string referencedObject = myCommit.referencedObject;

            var commitObject = await Operations.Receive(
                referencedObject,
                progress.CancellationTokenSource.Token,
                transport,
                onProgressAction : dict => progress.Update(dict),
                onErrorAction : (s, e) =>
            {
                progress.Report.LogOperationError(e);
                progress.CancellationTokenSource.Cancel();
            },
                onTotalChildrenCountKnown : count => { progress.Max = count; },
                disposeTransports : true
                );

            try
            {
                await state.Client.CommitReceived(new CommitReceivedInput
                {
                    streamId          = stream?.id,
                    commitId          = myCommit?.id,
                    message           = myCommit?.message,
                    sourceApplication = ConnectorRevitUtils.RevitAppName
                });
            }
            catch
            {
                // Do nothing!
            }

            if (progress.Report.OperationErrorsCount != 0)
            {
                return(state);
            }

            if (progress.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }



            await RevitTask.RunAsync(app =>
            {
                using (var t = new Transaction(CurrentDoc.Document, $"Baking stream {state.StreamId}"))
                {
                    var failOpts = t.GetFailureHandlingOptions();
                    failOpts.SetFailuresPreprocessor(new ErrorEater(converter));
                    failOpts.SetClearAfterRollback(true);
                    t.SetFailureHandlingOptions(failOpts);

                    t.Start();
                    var flattenedObjects = FlattenCommitObject(commitObject, converter);
                    // needs to be set for editing to work
                    converter.SetPreviousContextObjects(previouslyReceiveObjects);
                    // needs to be set for openings in floors and roofs to work
                    converter.SetContextObjects(flattenedObjects.Select(x => new ApplicationPlaceholderObject {
                        applicationId = x.applicationId, NativeObject = x
                    }).ToList());
                    var newPlaceholderObjects = ConvertReceivedObjects(flattenedObjects, converter, state, progress);
                    // receive was cancelled by user
                    if (newPlaceholderObjects == null)
                    {
                        progress.Report.LogConversionError(new Exception("fatal error: receive cancelled by user"));
                        t.RollBack();
                        return;
                    }

                    DeleteObjects(previouslyReceiveObjects, newPlaceholderObjects);

                    state.ReceivedObjects = newPlaceholderObjects;

                    t.Commit();
                    progress.Report.Merge(converter.Report);
                }
            });



            if (converter.Report.ConversionErrors.Any(x => x.Message.Contains("fatal error")))
            {
                // the commit is being rolled back
                return(null);
            }


            return(state);
        }
        public override async Task <StreamState> SendStream(StreamState state)
        {
            var kit       = KitManager.GetDefaultKit();
            var converter = kit.LoadConverter(Utils.AutocadAppName);

            var streamId = state.Stream.id;
            var client   = state.Client;

            if (state.Filter != null)
            {
                state.SelectedObjectIds = GetObjectsFromFilter(state.Filter, converter);
            }

            // remove deleted object ids
            var deletedElements = new List <string>();

            foreach (var handle in state.SelectedObjectIds)
            {
                if (Doc.Database.TryGetObjectId(Utils.GetHandle(handle), out AcadDb.ObjectId id))
                {
                    if (id.IsErased || id.IsNull)
                    {
                        deletedElements.Add(handle);
                    }
                }
            }
            state.SelectedObjectIds = state.SelectedObjectIds.Where(o => !deletedElements.Contains(o)).ToList();

            if (state.SelectedObjectIds.Count == 0)
            {
                RaiseNotification("Zero objects selected; send stopped. Please select some objects, or check that your filter can actually select something.");
                return(state);
            }

            var commitObj = new Base();

            /* Deprecated until we decide whether or not commit objs need units. If so, should add UnitsToSpeckle conversion method to connector
             * var units = Units.GetUnitsFromString(Doc.Database.Insunits.ToString());
             * commitObj["units"] = units;
             */

            var conversionProgressDict = new ConcurrentDictionary <string, int>();

            conversionProgressDict["Conversion"] = 0;
            Execute.PostToUIThread(() => state.Progress.Maximum = state.SelectedObjectIds.Count());
            int  convertedCount = 0;
            bool renamedlayers  = false;

            using (Transaction tr = Doc.Database.TransactionManager.StartTransaction())
            {
                converter.SetContextDocument(Doc); // set context doc here to capture transaction prop

                foreach (var autocadObjectHandle in state.SelectedObjectIds)
                {
                    if (state.CancellationTokenSource.Token.IsCancellationRequested)
                    {
                        return(null);
                    }

                    // get the db object from id
                    AcadDb.Handle   hn  = Utils.GetHandle(autocadObjectHandle);
                    AcadDb.DBObject obj = hn.GetObject(out string type, out string layer);

                    if (obj == null)
                    {
                        state.Errors.Add(new Exception($"Failed to find local object ${autocadObjectHandle}."));
                        continue;
                    }

                    if (!converter.CanConvertToSpeckle(obj))
                    {
                        state.Errors.Add(new Exception($"Objects of type ${type} are not supported"));
                        continue;
                    }

                    // convert obj
                    // try catch to prevent memory access violation crash in case a conversion goes wrong
                    Base   converted     = null;
                    string containerName = string.Empty;
                    try
                    {
                        converted = converter.ConvertToSpeckle(obj);
                        if (converted == null)
                        {
                            state.Errors.Add(new Exception($"Failed to convert object ${autocadObjectHandle} of type ${type}."));
                            continue;
                        }
                    }
                    catch
                    {
                        state.Errors.Add(new Exception($"Failed to convert object {autocadObjectHandle} of type {type}."));
                        continue;
                    }

                    /* TODO: adding the extension dictionary / xdata per object
                     * foreach (var key in obj.ExtensionDictionary)
                     * {
                     * converted[key] = obj.ExtensionDictionary.GetUserString(key);
                     * }
                     */

                    if (obj is BlockReference)
                    {
                        containerName = "Blocks";
                    }
                    else
                    {
                        // remove invalid chars from layer name
                        string cleanLayerName = Utils.RemoveInvalidDynamicPropChars(layer);
                        containerName = cleanLayerName;
                        if (!cleanLayerName.Equals(layer))
                        {
                            renamedlayers = true;
                        }
                    }

                    if (commitObj[$"@{containerName}"] == null)
                    {
                        commitObj[$"@{containerName}"] = new List <Base>();
                    }
                    ((List <Base>)commitObj[$"@{containerName}"]).Add(converted);

                    conversionProgressDict["Conversion"]++;
                    UpdateProgress(conversionProgressDict, state.Progress);

                    converted.applicationId = autocadObjectHandle;

                    convertedCount++;
                }

                tr.Commit();
            }

            if (renamedlayers)
            {
                RaiseNotification("Replaced illegal chars ./ with - in one or more layer names.");
            }

            if (state.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return(null);
            }

            Execute.PostToUIThread(() => state.Progress.Maximum = convertedCount);

            var transports = new List <ITransport>()
            {
                new ServerTransport(client.Account, streamId)
            };

            var commitObjId = await Operations.Send(
                commitObj,
                state.CancellationTokenSource.Token,
                transports,
                onProgressAction : dict => UpdateProgress(dict, state.Progress),
                onErrorAction : (err, exception) => { Exceptions.Add(exception); },
                disposeTransports : true
                );

            if (Exceptions.Count != 0)
            {
                RaiseNotification($"Failed to send: \n {Exceptions.Last().Message}");
                return(null);
            }

            if (convertedCount > 0)
            {
                var actualCommit = new CommitCreateInput
                {
                    streamId          = streamId,
                    objectId          = commitObjId,
                    branchName        = state.Branch.name,
                    message           = state.CommitMessage != null ? state.CommitMessage : $"Pushed {convertedCount} elements from {Utils.AppName}.",
                    sourceApplication = Utils.AutocadAppName
                };

                if (state.PreviousCommitId != null)
                {
                    actualCommit.parents = new List <string>()
                    {
                        state.PreviousCommitId
                    };
                }

                try
                {
                    var commitId = await client.CommitCreate(actualCommit);

                    await state.RefreshStream();

                    state.PreviousCommitId = commitId;

                    PersistAndUpdateStreamInFile(state);
                    RaiseNotification($"{convertedCount} objects sent to {state.Stream.name}.");
                }
                catch (Exception e)
                {
                    Globals.Notify($"Failed to create commit.\n{e.Message}");
                    state.Errors.Add(e);
                }
            }
            else
            {
                Globals.Notify($"Did not create commit: no objects could be converted.");
            }

            return(state);
        }