Пример #1
0
        static public void GetEnt()
        {
            AcEd.Editor  ed = AcAp.Application.DocumentManager.MdiActiveDocument.Editor;
            PromptResult rs = ed.GetString("\nВведите метку примитива (в hex-представлении): ");

            if (rs.Status != PromptStatus.OK)
            {
                return;
            }
            System.Int64  l  = System.Int64.Parse(rs.StringResult, System.Globalization.NumberStyles.HexNumber);
            AcDb.Handle   h  = new AcDb.Handle(l);
            AcDb.Database db = AcDb.HostApplicationServices.WorkingDatabase;
            AcDb.ObjectId id = db.GetObjectId(false, h, 0);
            if (!id.IsValid)
            {
                ed.WriteMessage("\nОшибочная метка примитива {0}", h);
                return;
            }
            using (AcAp.DocumentLock doclock = ed.Document.LockDocument())
            {
                using (AcDb.Transaction tr = db.TransactionManager.StartTransaction())
                {
                    AcDb.Entity ent = tr.GetObject(id, AcDb.OpenMode.ForRead) as AcDb.Entity;
                    if (ent != null)
                    {
                        ed.WriteMessage("\nEntity Class: {0}", AcRx.RXClass.GetClass(ent.GetType()).Name);
                        // Ну и так далее - делаешь с примитивом то, что тебе нужно...
                    }
                    else
                    {
                        ed.WriteMessage("\nЭто не примитив!");
                    }
                }
            }
        }
        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);
        }
        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);
        }
Пример #4
0
 public override void WriteHandle(Autodesk.AutoCAD.DatabaseServices.Handle handle)
 {
 }